summaryrefslogtreecommitdiff
path: root/numpy/lib/tests/test_arraypad.py
diff options
context:
space:
mode:
authorEric Wieser <wieser.eric@gmail.com>2019-10-15 20:20:20 +0100
committerGitHub <noreply@github.com>2019-10-15 20:20:20 +0100
commit10a7a4a815105e16828fe83fb89778c3bbafe692 (patch)
tree2c73effc6bf4b8404e63564f78661caff034b255 /numpy/lib/tests/test_arraypad.py
parentd0731e118a5c40d866702f1b5da2be4d4f52ded9 (diff)
parent83da5faca3a313c5d37226b86fa781956f8d162b (diff)
downloadnumpy-10a7a4a815105e16828fe83fb89778c3bbafe692.tar.gz
Merge branch 'master' into master
Diffstat (limited to 'numpy/lib/tests/test_arraypad.py')
-rw-r--r--numpy/lib/tests/test_arraypad.py697
1 files changed, 441 insertions, 256 deletions
diff --git a/numpy/lib/tests/test_arraypad.py b/numpy/lib/tests/test_arraypad.py
index e62fccaa0..65593dd29 100644
--- a/numpy/lib/tests/test_arraypad.py
+++ b/numpy/lib/tests/test_arraypad.py
@@ -6,58 +6,140 @@ from __future__ import division, absolute_import, print_function
import pytest
import numpy as np
-from numpy.testing import (assert_array_equal, assert_raises, assert_allclose,
- assert_equal)
-from numpy.lib import pad
+from numpy.testing import assert_array_equal, assert_allclose, assert_equal
+from numpy.lib.arraypad import _as_pairs
+
+
+_numeric_dtypes = (
+ np.sctypes["uint"]
+ + np.sctypes["int"]
+ + np.sctypes["float"]
+ + np.sctypes["complex"]
+)
+_all_modes = {
+ 'constant': {'constant_values': 0},
+ 'edge': {},
+ 'linear_ramp': {'end_values': 0},
+ 'maximum': {'stat_length': None},
+ 'mean': {'stat_length': None},
+ 'median': {'stat_length': None},
+ 'minimum': {'stat_length': None},
+ 'reflect': {'reflect_type': 'even'},
+ 'symmetric': {'reflect_type': 'even'},
+ 'wrap': {},
+ 'empty': {}
+}
+
+
+class TestAsPairs(object):
+ 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_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_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_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 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_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)
class TestConditionalShortcuts(object):
- def test_zero_padding_shortcuts(self):
+ @pytest.mark.parametrize("mode", _all_modes.keys())
+ def test_zero_padding_shortcuts(self, mode):
test = np.arange(120).reshape(4, 5, 6)
- pad_amt = [(0, 0) for axis in test.shape]
- modes = ['constant',
- 'edge',
- 'linear_ramp',
- 'maximum',
- 'mean',
- 'median',
- 'minimum',
- 'reflect',
- 'symmetric',
- 'wrap',
- ]
- for mode in modes:
- assert_array_equal(test, pad(test, pad_amt, mode=mode))
-
- def test_shallow_statistic_range(self):
+ pad_amt = [(0, 0) for _ in test.shape]
+ assert_array_equal(test, np.pad(test, pad_amt, mode=mode))
+
+ @pytest.mark.parametrize("mode", ['maximum', 'mean', 'median', 'minimum',])
+ def test_shallow_statistic_range(self, mode):
test = np.arange(120).reshape(4, 5, 6)
- pad_amt = [(1, 1) for axis in test.shape]
- modes = ['maximum',
- 'mean',
- 'median',
- 'minimum',
- ]
- for mode in modes:
- assert_array_equal(pad(test, pad_amt, mode='edge'),
- pad(test, pad_amt, mode=mode, stat_length=1))
-
- def test_clip_statistic_range(self):
+ pad_amt = [(1, 1) for _ in test.shape]
+ assert_array_equal(np.pad(test, pad_amt, mode='edge'),
+ np.pad(test, pad_amt, mode=mode, stat_length=1))
+
+ @pytest.mark.parametrize("mode", ['maximum', 'mean', 'median', 'minimum',])
+ def test_clip_statistic_range(self, mode):
test = np.arange(30).reshape(5, 6)
- pad_amt = [(3, 3) for axis in test.shape]
- modes = ['maximum',
- 'mean',
- 'median',
- 'minimum',
- ]
- for mode in modes:
- assert_array_equal(pad(test, pad_amt, mode=mode),
- pad(test, pad_amt, mode=mode, stat_length=30))
+ pad_amt = [(3, 3) for _ in test.shape]
+ assert_array_equal(np.pad(test, pad_amt, mode=mode),
+ np.pad(test, pad_amt, mode=mode, stat_length=30))
class TestStatistic(object):
def test_check_mean_stat_length(self):
a = np.arange(100).astype('f')
- a = pad(a, ((25, 20), ), 'mean', stat_length=((2, 3), ))
+ a = np.pad(a, ((25, 20), ), 'mean', stat_length=((2, 3), ))
b = np.array(
[0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
@@ -81,7 +163,7 @@ class TestStatistic(object):
def test_check_maximum_1(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'maximum')
+ a = np.pad(a, (25, 20), 'maximum')
b = np.array(
[99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
@@ -105,7 +187,7 @@ class TestStatistic(object):
def test_check_maximum_2(self):
a = np.arange(100) + 1
- a = pad(a, (25, 20), 'maximum')
+ a = np.pad(a, (25, 20), 'maximum')
b = np.array(
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
@@ -129,7 +211,7 @@ class TestStatistic(object):
def test_check_maximum_stat_length(self):
a = np.arange(100) + 1
- a = pad(a, (25, 20), 'maximum', stat_length=10)
+ a = np.pad(a, (25, 20), 'maximum', stat_length=10)
b = np.array(
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
@@ -153,7 +235,7 @@ class TestStatistic(object):
def test_check_minimum_1(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'minimum')
+ a = np.pad(a, (25, 20), 'minimum')
b = np.array(
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -177,7 +259,7 @@ class TestStatistic(object):
def test_check_minimum_2(self):
a = np.arange(100) + 2
- a = pad(a, (25, 20), 'minimum')
+ a = np.pad(a, (25, 20), 'minimum')
b = np.array(
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
@@ -201,7 +283,7 @@ class TestStatistic(object):
def test_check_minimum_stat_length(self):
a = np.arange(100) + 1
- a = pad(a, (25, 20), 'minimum', stat_length=10)
+ a = np.pad(a, (25, 20), 'minimum', stat_length=10)
b = np.array(
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -225,7 +307,7 @@ class TestStatistic(object):
def test_check_median(self):
a = np.arange(100).astype('f')
- a = pad(a, (25, 20), 'median')
+ a = np.pad(a, (25, 20), 'median')
b = np.array(
[49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,
49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,
@@ -249,7 +331,7 @@ class TestStatistic(object):
def test_check_median_01(self):
a = np.array([[3, 1, 4], [4, 5, 9], [9, 8, 2]])
- a = pad(a, 1, 'median')
+ a = np.pad(a, 1, 'median')
b = np.array(
[[4, 4, 5, 4, 4],
@@ -263,7 +345,7 @@ class TestStatistic(object):
def test_check_median_02(self):
a = np.array([[3, 1, 4], [4, 5, 9], [9, 8, 2]])
- a = pad(a.T, 1, 'median').T
+ a = np.pad(a.T, 1, 'median').T
b = np.array(
[[5, 4, 5, 4, 5],
@@ -279,7 +361,7 @@ class TestStatistic(object):
a = np.arange(100).astype('f')
a[1] = 2.
a[97] = 96.
- a = pad(a, (25, 20), 'median', stat_length=(3, 5))
+ a = np.pad(a, (25, 20), 'median', stat_length=(3, 5))
b = np.array(
[ 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
@@ -303,7 +385,7 @@ class TestStatistic(object):
def test_check_mean_shape_one(self):
a = [[4, 5, 6]]
- a = pad(a, (5, 7), 'mean', stat_length=2)
+ a = np.pad(a, (5, 7), 'mean', stat_length=2)
b = np.array(
[[4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],
[4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6],
@@ -325,7 +407,7 @@ class TestStatistic(object):
def test_check_mean_2(self):
a = np.arange(100).astype('f')
- a = pad(a, (25, 20), 'mean')
+ a = np.pad(a, (25, 20), 'mean')
b = np.array(
[49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,
49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5, 49.5,
@@ -348,7 +430,7 @@ class TestStatistic(object):
assert_array_equal(a, b)
@pytest.mark.parametrize("mode", [
- pytest.param("mean", marks=pytest.mark.xfail(reason="gh-11216")),
+ "mean",
"median",
"minimum",
"maximum"
@@ -361,11 +443,65 @@ class TestStatistic(object):
a = np.pad(a, (1, 1), mode)
assert_equal(a[0], a[-1])
+ @pytest.mark.parametrize("mode", ["mean", "median", "minimum", "maximum"])
+ @pytest.mark.parametrize(
+ "stat_length", [-2, (-2,), (3, -1), ((5, 2), (-2, 3)), ((-4,), (2,))]
+ )
+ def test_check_negative_stat_length(self, mode, stat_length):
+ arr = np.arange(30).reshape((6, 5))
+ match = "index can't contain negative values"
+ with pytest.raises(ValueError, match=match):
+ np.pad(arr, 2, mode, stat_length=stat_length)
+
+ def test_simple_stat_length(self):
+ a = np.arange(30)
+ a = np.reshape(a, (6, 5))
+ a = np.pad(a, ((2, 3), (3, 2)), mode='mean', stat_length=(3,))
+ b = np.array(
+ [[6, 6, 6, 5, 6, 7, 8, 9, 8, 8],
+ [6, 6, 6, 5, 6, 7, 8, 9, 8, 8],
+
+ [1, 1, 1, 0, 1, 2, 3, 4, 3, 3],
+ [6, 6, 6, 5, 6, 7, 8, 9, 8, 8],
+ [11, 11, 11, 10, 11, 12, 13, 14, 13, 13],
+ [16, 16, 16, 15, 16, 17, 18, 19, 18, 18],
+ [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],
+ [26, 26, 26, 25, 26, 27, 28, 29, 28, 28],
+
+ [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],
+ [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],
+ [21, 21, 21, 20, 21, 22, 23, 24, 23, 23]]
+ )
+ assert_array_equal(a, b)
+
+ @pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning")
+ @pytest.mark.filterwarnings(
+ "ignore:invalid value encountered in (true_divide|double_scalars):"
+ "RuntimeWarning"
+ )
+ @pytest.mark.parametrize("mode", ["mean", "median"])
+ def test_zero_stat_length_valid(self, mode):
+ arr = np.pad([1., 2.], (1, 2), mode, stat_length=0)
+ expected = np.array([np.nan, 1., 2., np.nan, np.nan])
+ assert_equal(arr, expected)
+
+ @pytest.mark.parametrize("mode", ["minimum", "maximum"])
+ def test_zero_stat_length_invalid(self, mode):
+ match = "stat_length of 0 yields no value for padding"
+ with pytest.raises(ValueError, match=match):
+ np.pad([1., 2.], 0, mode, stat_length=0)
+ with pytest.raises(ValueError, match=match):
+ np.pad([1., 2.], 0, mode, stat_length=(1, 0))
+ with pytest.raises(ValueError, match=match):
+ np.pad([1., 2.], 1, mode, stat_length=0)
+ with pytest.raises(ValueError, match=match):
+ np.pad([1., 2.], 1, mode, stat_length=(1, 0))
+
class TestConstant(object):
def test_check_constant(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'constant', constant_values=(10, 20))
+ a = np.pad(a, (25, 20), 'constant', constant_values=(10, 20))
b = np.array(
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
@@ -389,7 +525,7 @@ class TestConstant(object):
def test_check_constant_zeros(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'constant')
+ a = np.pad(a, (25, 20), 'constant')
b = np.array(
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@@ -415,7 +551,7 @@ class TestConstant(object):
# If input array is int, but constant_values are float, the dtype of
# the array to be padded is kept
arr = np.arange(30).reshape(5, 6)
- test = pad(arr, (1, 2), mode='constant',
+ test = np.pad(arr, (1, 2), mode='constant',
constant_values=1.1)
expected = np.array(
[[ 1, 1, 1, 1, 1, 1, 1, 1, 1],
@@ -436,7 +572,7 @@ class TestConstant(object):
# the array to be padded is kept - here retaining the float constants
arr = np.arange(30).reshape(5, 6)
arr_float = arr.astype(np.float64)
- test = pad(arr_float, ((1, 2), (1, 2)), mode='constant',
+ test = np.pad(arr_float, ((1, 2), (1, 2)), mode='constant',
constant_values=1.1)
expected = np.array(
[[ 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1],
@@ -454,7 +590,7 @@ class TestConstant(object):
def test_check_constant_float3(self):
a = np.arange(100, dtype=float)
- a = pad(a, (25, 20), 'constant', constant_values=(-1.1, -1.2))
+ a = np.pad(a, (25, 20), 'constant', constant_values=(-1.1, -1.2))
b = np.array(
[-1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1,
-1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1, -1.1,
@@ -478,7 +614,7 @@ class TestConstant(object):
def test_check_constant_odd_pad_amount(self):
arr = np.arange(30).reshape(5, 6)
- test = pad(arr, ((1,), (2,)), mode='constant',
+ test = np.pad(arr, ((1,), (2,)), mode='constant',
constant_values=3)
expected = np.array(
[[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
@@ -535,10 +671,16 @@ class TestConstant(object):
assert_array_equal(arr, expected)
+ def test_pad_empty_dimension(self):
+ arr = np.zeros((3, 0, 2))
+ result = np.pad(arr, [(0,), (2,), (1,)], mode="constant")
+ assert result.shape == (3, 4, 4)
+
+
class TestLinearRamp(object):
def test_check_simple(self):
a = np.arange(100).astype('f')
- a = pad(a, (25, 20), 'linear_ramp', end_values=(4, 5))
+ a = np.pad(a, (25, 20), 'linear_ramp', end_values=(4, 5))
b = np.array(
[4.00, 3.84, 3.68, 3.52, 3.36, 3.20, 3.04, 2.88, 2.72, 2.56,
2.40, 2.24, 2.08, 1.92, 1.76, 1.60, 1.44, 1.28, 1.12, 0.96,
@@ -562,7 +704,7 @@ class TestLinearRamp(object):
def test_check_2d(self):
arr = np.arange(20).reshape(4, 5).astype(np.float64)
- test = pad(arr, (2, 2), mode='linear_ramp', end_values=(0, 0))
+ test = np.pad(arr, (2, 2), mode='linear_ramp', end_values=(0, 0))
expected = np.array(
[[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0.5, 1., 1.5, 2., 1., 0.],
@@ -593,11 +735,37 @@ class TestLinearRamp(object):
])
assert_equal(actual, expected)
+ def test_end_values(self):
+ """Ensure that end values are exact."""
+ a = np.pad(np.ones(10).reshape(2, 5), (223, 123), mode="linear_ramp")
+ assert_equal(a[:, 0], 0.)
+ assert_equal(a[:, -1], 0.)
+ assert_equal(a[0, :], 0.)
+ assert_equal(a[-1, :], 0.)
+
+ @pytest.mark.parametrize("dtype", _numeric_dtypes)
+ def test_negative_difference(self, dtype):
+ """
+ Check correct behavior of unsigned dtypes if there is a negative
+ difference between the edge to pad and `end_values`. Check both cases
+ to be independent of implementation. Test behavior for all other dtypes
+ in case dtype casting interferes with complex dtypes. See gh-14191.
+ """
+ x = np.array([3], dtype=dtype)
+ result = np.pad(x, 3, mode="linear_ramp", end_values=0)
+ expected = np.array([0, 1, 2, 3, 2, 1, 0], dtype=dtype)
+ assert_equal(result, expected)
+
+ x = np.array([0], dtype=dtype)
+ result = np.pad(x, 3, mode="linear_ramp", end_values=3)
+ expected = np.array([3, 2, 1, 0, 1, 2, 3], dtype=dtype)
+ assert_equal(result, expected)
+
class TestReflect(object):
def test_check_simple(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'reflect')
+ a = np.pad(a, (25, 20), 'reflect')
b = np.array(
[25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
15, 14, 13, 12, 11, 10, 9, 8, 7, 6,
@@ -621,7 +789,7 @@ class TestReflect(object):
def test_check_odd_method(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'reflect', reflect_type='odd')
+ a = np.pad(a, (25, 20), 'reflect', reflect_type='odd')
b = np.array(
[-25, -24, -23, -22, -21, -20, -19, -18, -17, -16,
-15, -14, -13, -12, -11, -10, -9, -8, -7, -6,
@@ -645,7 +813,7 @@ class TestReflect(object):
def test_check_large_pad(self):
a = [[4, 5, 6], [6, 7, 8]]
- a = pad(a, (5, 7), 'reflect')
+ a = np.pad(a, (5, 7), 'reflect')
b = np.array(
[[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
@@ -668,7 +836,7 @@ class TestReflect(object):
def test_check_shape(self):
a = [[4, 5, 6]]
- a = pad(a, (5, 7), 'reflect')
+ a = np.pad(a, (5, 7), 'reflect')
b = np.array(
[[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
@@ -689,30 +857,49 @@ class TestReflect(object):
assert_array_equal(a, b)
def test_check_01(self):
- a = pad([1, 2, 3], 2, 'reflect')
+ a = np.pad([1, 2, 3], 2, 'reflect')
b = np.array([3, 2, 1, 2, 3, 2, 1])
assert_array_equal(a, b)
def test_check_02(self):
- a = pad([1, 2, 3], 3, 'reflect')
+ a = np.pad([1, 2, 3], 3, 'reflect')
b = np.array([2, 3, 2, 1, 2, 3, 2, 1, 2])
assert_array_equal(a, b)
def test_check_03(self):
- a = pad([1, 2, 3], 4, 'reflect')
+ a = np.pad([1, 2, 3], 4, 'reflect')
b = np.array([1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3])
assert_array_equal(a, b)
- def test_check_padding_an_empty_array(self):
- a = pad(np.zeros((0, 3)), ((0,), (1,)), mode='reflect')
- b = np.zeros((0, 5))
- assert_array_equal(a, b)
+
+class TestEmptyArray(object):
+ """Check how padding behaves on arrays with an empty dimension."""
+
+ @pytest.mark.parametrize(
+ # Keep parametrization ordered, otherwise pytest-xdist might believe
+ # that different tests were collected during parallelization
+ "mode", sorted(_all_modes.keys() - {"constant", "empty"})
+ )
+ def test_pad_empty_dimension(self, mode):
+ match = ("can't extend empty axis 0 using modes other than 'constant' "
+ "or 'empty'")
+ with pytest.raises(ValueError, match=match):
+ np.pad([], 4, mode=mode)
+ with pytest.raises(ValueError, match=match):
+ np.pad(np.ndarray(0), 4, mode=mode)
+ with pytest.raises(ValueError, match=match):
+ np.pad(np.zeros((0, 3)), ((1,), (0,)), mode=mode)
+
+ @pytest.mark.parametrize("mode", _all_modes.keys())
+ def test_pad_non_empty_dimension(self, mode):
+ result = np.pad(np.ones((2, 0, 2)), ((3,), (0,), (1,)), mode=mode)
+ assert result.shape == (8, 0, 4)
class TestSymmetric(object):
def test_check_simple(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'symmetric')
+ a = np.pad(a, (25, 20), 'symmetric')
b = np.array(
[24, 23, 22, 21, 20, 19, 18, 17, 16, 15,
14, 13, 12, 11, 10, 9, 8, 7, 6, 5,
@@ -736,7 +923,7 @@ class TestSymmetric(object):
def test_check_odd_method(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'symmetric', reflect_type='odd')
+ a = np.pad(a, (25, 20), 'symmetric', reflect_type='odd')
b = np.array(
[-24, -23, -22, -21, -20, -19, -18, -17, -16, -15,
-14, -13, -12, -11, -10, -9, -8, -7, -6, -5,
@@ -760,7 +947,7 @@ class TestSymmetric(object):
def test_check_large_pad(self):
a = [[4, 5, 6], [6, 7, 8]]
- a = pad(a, (5, 7), 'symmetric')
+ a = np.pad(a, (5, 7), 'symmetric')
b = np.array(
[[5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],
[5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],
@@ -784,7 +971,7 @@ class TestSymmetric(object):
def test_check_large_pad_odd(self):
a = [[4, 5, 6], [6, 7, 8]]
- a = pad(a, (5, 7), 'symmetric', reflect_type='odd')
+ a = np.pad(a, (5, 7), 'symmetric', reflect_type='odd')
b = np.array(
[[-3, -2, -2, -1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6],
[-3, -2, -2, -1, 0, 0, 1, 2, 2, 3, 4, 4, 5, 6, 6],
@@ -807,7 +994,7 @@ class TestSymmetric(object):
def test_check_shape(self):
a = [[4, 5, 6]]
- a = pad(a, (5, 7), 'symmetric')
+ a = np.pad(a, (5, 7), 'symmetric')
b = np.array(
[[5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],
[5, 6, 6, 5, 4, 4, 5, 6, 6, 5, 4, 4, 5, 6, 6],
@@ -828,17 +1015,17 @@ class TestSymmetric(object):
assert_array_equal(a, b)
def test_check_01(self):
- a = pad([1, 2, 3], 2, 'symmetric')
+ a = np.pad([1, 2, 3], 2, 'symmetric')
b = np.array([2, 1, 1, 2, 3, 3, 2])
assert_array_equal(a, b)
def test_check_02(self):
- a = pad([1, 2, 3], 3, 'symmetric')
+ a = np.pad([1, 2, 3], 3, 'symmetric')
b = np.array([3, 2, 1, 1, 2, 3, 3, 2, 1])
assert_array_equal(a, b)
def test_check_03(self):
- a = pad([1, 2, 3], 6, 'symmetric')
+ a = np.pad([1, 2, 3], 6, 'symmetric')
b = np.array([1, 2, 3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1, 2, 3])
assert_array_equal(a, b)
@@ -846,7 +1033,7 @@ class TestSymmetric(object):
class TestWrap(object):
def test_check_simple(self):
a = np.arange(100)
- a = pad(a, (25, 20), 'wrap')
+ a = np.pad(a, (25, 20), 'wrap')
b = np.array(
[75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
@@ -871,7 +1058,7 @@ class TestWrap(object):
def test_check_large_pad(self):
a = np.arange(12)
a = np.reshape(a, (3, 4))
- a = pad(a, (10, 12), 'wrap')
+ a = np.pad(a, (10, 12), 'wrap')
b = np.array(
[[10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10, 11, 8, 9, 10,
11, 8, 9, 10, 11, 8, 9, 10, 11],
@@ -929,12 +1116,12 @@ class TestWrap(object):
assert_array_equal(a, b)
def test_check_01(self):
- a = pad([1, 2, 3], 3, 'wrap')
+ a = np.pad([1, 2, 3], 3, 'wrap')
b = np.array([1, 2, 3, 1, 2, 3, 1, 2, 3])
assert_array_equal(a, b)
def test_check_02(self):
- a = pad([1, 2, 3], 4, 'wrap')
+ a = np.pad([1, 2, 3], 4, 'wrap')
b = np.array([3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1])
assert_array_equal(a, b)
@@ -943,35 +1130,25 @@ class TestWrap(object):
b = np.pad(a, (0, 5), mode="wrap")
assert_array_equal(a, b[:-5, :-5])
+ def test_repeated_wrapping(self):
+ """
+ Check wrapping on each side individually if the wrapped area is longer
+ than the original array.
+ """
+ a = np.arange(5)
+ b = np.pad(a, (12, 0), mode="wrap")
+ assert_array_equal(np.r_[a, a, a, a][3:], b)
-class TestStatLen(object):
- def test_check_simple(self):
- a = np.arange(30)
- a = np.reshape(a, (6, 5))
- a = pad(a, ((2, 3), (3, 2)), mode='mean', stat_length=(3,))
- b = np.array(
- [[6, 6, 6, 5, 6, 7, 8, 9, 8, 8],
- [6, 6, 6, 5, 6, 7, 8, 9, 8, 8],
-
- [1, 1, 1, 0, 1, 2, 3, 4, 3, 3],
- [6, 6, 6, 5, 6, 7, 8, 9, 8, 8],
- [11, 11, 11, 10, 11, 12, 13, 14, 13, 13],
- [16, 16, 16, 15, 16, 17, 18, 19, 18, 18],
- [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],
- [26, 26, 26, 25, 26, 27, 28, 29, 28, 28],
-
- [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],
- [21, 21, 21, 20, 21, 22, 23, 24, 23, 23],
- [21, 21, 21, 20, 21, 22, 23, 24, 23, 23]]
- )
- assert_array_equal(a, b)
+ a = np.arange(5)
+ b = np.pad(a, (0, 12), mode="wrap")
+ assert_array_equal(np.r_[a, a, a, a][:-3], b)
class TestEdge(object):
def test_check_simple(self):
a = np.arange(12)
a = np.reshape(a, (4, 3))
- a = pad(a, ((2, 3), (3, 2)), 'edge')
+ a = np.pad(a, ((2, 3), (3, 2)), 'edge')
b = np.array(
[[0, 0, 0, 0, 1, 2, 2, 2],
[0, 0, 0, 0, 1, 2, 2, 2],
@@ -991,56 +1168,123 @@ class TestEdge(object):
# Check a pad_width of the form ((1, 2),).
# Regression test for issue gh-7808.
a = np.array([1, 2, 3])
- padded = pad(a, ((1, 2),), 'edge')
+ padded = np.pad(a, ((1, 2),), 'edge')
expected = np.array([1, 1, 2, 3, 3, 3])
assert_array_equal(padded, expected)
a = np.array([[1, 2, 3], [4, 5, 6]])
- padded = pad(a, ((1, 2),), 'edge')
- expected = pad(a, ((1, 2), (1, 2)), 'edge')
+ padded = np.pad(a, ((1, 2),), 'edge')
+ expected = np.pad(a, ((1, 2), (1, 2)), 'edge')
assert_array_equal(padded, expected)
a = np.arange(24).reshape(2, 3, 4)
- padded = pad(a, ((1, 2),), 'edge')
- expected = pad(a, ((1, 2), (1, 2), (1, 2)), 'edge')
+ padded = np.pad(a, ((1, 2),), 'edge')
+ expected = np.pad(a, ((1, 2), (1, 2), (1, 2)), 'edge')
assert_array_equal(padded, expected)
-class TestZeroPadWidth(object):
- def test_zero_pad_width(self):
- arr = np.arange(30)
- arr = np.reshape(arr, (6, 5))
- for pad_width in (0, (0, 0), ((0, 0), (0, 0))):
- assert_array_equal(arr, pad(arr, pad_width, mode='constant'))
+class TestEmpty(object):
+ def test_simple(self):
+ arr = np.arange(24).reshape(4, 6)
+ result = np.pad(arr, [(2, 3), (3, 1)], mode="empty")
+ assert result.shape == (9, 10)
+ assert_equal(arr, result[2:-3, 3:-1])
+ def test_pad_empty_dimension(self):
+ arr = np.zeros((3, 0, 2))
+ result = np.pad(arr, [(0,), (2,), (1,)], mode="empty")
+ assert result.shape == (3, 4, 4)
-class TestLegacyVectorFunction(object):
- def test_legacy_vector_functionality(self):
- def _padwithtens(vector, pad_width, iaxis, kwargs):
- vector[:pad_width[0]] = 10
- vector[-pad_width[1]:] = 10
- return vector
- a = np.arange(6).reshape(2, 3)
- a = pad(a, 2, _padwithtens)
- b = np.array(
- [[10, 10, 10, 10, 10, 10, 10],
- [10, 10, 10, 10, 10, 10, 10],
+def test_legacy_vector_functionality():
+ def _padwithtens(vector, pad_width, iaxis, kwargs):
+ vector[:pad_width[0]] = 10
+ vector[-pad_width[1]:] = 10
- [10, 10, 0, 1, 2, 10, 10],
- [10, 10, 3, 4, 5, 10, 10],
+ a = np.arange(6).reshape(2, 3)
+ a = np.pad(a, 2, _padwithtens)
+ b = np.array(
+ [[10, 10, 10, 10, 10, 10, 10],
+ [10, 10, 10, 10, 10, 10, 10],
- [10, 10, 10, 10, 10, 10, 10],
- [10, 10, 10, 10, 10, 10, 10]]
- )
- assert_array_equal(a, b)
+ [10, 10, 0, 1, 2, 10, 10],
+ [10, 10, 3, 4, 5, 10, 10],
+ [10, 10, 10, 10, 10, 10, 10],
+ [10, 10, 10, 10, 10, 10, 10]]
+ )
+ assert_array_equal(a, b)
-class TestNdarrayPadWidth(object):
- def test_check_simple(self):
+
+def test_unicode_mode():
+ a = np.pad([1], 2, mode=u'constant')
+ b = np.array([0, 0, 1, 0, 0])
+ assert_array_equal(a, b)
+
+
+@pytest.mark.parametrize("mode", ["edge", "symmetric", "reflect", "wrap"])
+def test_object_input(mode):
+ # Regression test for issue gh-11395.
+ a = np.full((4, 3), fill_value=None)
+ pad_amt = ((2, 3), (3, 2))
+ b = np.full((9, 8), fill_value=None)
+ assert_array_equal(np.pad(a, pad_amt, mode=mode), b)
+
+
+class TestPadWidth(object):
+ @pytest.mark.parametrize("pad_width", [
+ (4, 5, 6, 7),
+ ((1,), (2,), (3,)),
+ ((1, 2), (3, 4), (5, 6)),
+ ((3, 4, 5), (0, 1, 2)),
+ ])
+ @pytest.mark.parametrize("mode", _all_modes.keys())
+ def test_misshaped_pad_width(self, pad_width, mode):
+ arr = np.arange(30).reshape((6, 5))
+ match = "operands could not be broadcast together"
+ with pytest.raises(ValueError, match=match):
+ np.pad(arr, pad_width, mode)
+
+ @pytest.mark.parametrize("mode", _all_modes.keys())
+ def test_misshaped_pad_width_2(self, mode):
+ arr = np.arange(30).reshape((6, 5))
+ match = ("input operand has more dimensions than allowed by the axis "
+ "remapping")
+ with pytest.raises(ValueError, match=match):
+ np.pad(arr, (((3,), (4,), (5,)), ((0,), (1,), (2,))), mode)
+
+ @pytest.mark.parametrize(
+ "pad_width", [-2, (-2,), (3, -1), ((5, 2), (-2, 3)), ((-4,), (2,))])
+ @pytest.mark.parametrize("mode", _all_modes.keys())
+ def test_negative_pad_width(self, pad_width, mode):
+ arr = np.arange(30).reshape((6, 5))
+ match = "index can't contain negative values"
+ with pytest.raises(ValueError, match=match):
+ np.pad(arr, pad_width, mode)
+
+ @pytest.mark.parametrize("pad_width", [
+ "3",
+ "word",
+ None,
+ object(),
+ 3.4,
+ ((2, 3, 4), (3, 2)), # dtype=object (tuple)
+ complex(1, -1),
+ ((-2.1, 3), (3, 2)),
+ ])
+ @pytest.mark.parametrize("mode", _all_modes.keys())
+ def test_bad_type(self, pad_width, mode):
+ arr = np.arange(30).reshape((6, 5))
+ match = "`pad_width` must be of integral type."
+ with pytest.raises(TypeError, match=match):
+ np.pad(arr, pad_width, mode)
+ with pytest.raises(TypeError, match=match):
+ np.pad(arr, np.array(pad_width), mode)
+
+ def test_pad_width_as_ndarray(self):
a = np.arange(12)
a = np.reshape(a, (4, 3))
- a = pad(a, np.array(((2, 3), (3, 2))), 'edge')
+ a = np.pad(a, np.array(((2, 3), (3, 2))), 'edge')
b = np.array(
[[0, 0, 0, 0, 1, 2, 2, 2],
[0, 0, 0, 0, 1, 2, 2, 2],
@@ -1056,121 +1300,62 @@ class TestNdarrayPadWidth(object):
)
assert_array_equal(a, b)
-
-class TestUnicodeInput(object):
- def test_unicode_mode(self):
- constant_mode = u'constant'
- a = np.pad([1], 2, mode=constant_mode)
- b = np.array([0, 0, 1, 0, 0])
- assert_array_equal(a, b)
-
-
-class TestObjectInput(object):
- def test_object_input(self):
- # Regression test for issue gh-11395.
- a = np.full((4, 3), None)
- pad_amt = ((2, 3), (3, 2))
- b = np.full((9, 8), None)
- modes = ['edge',
- 'symmetric',
- 'reflect',
- 'wrap',
- ]
- for mode in modes:
- assert_array_equal(pad(a, pad_amt, mode=mode), b)
-
-
-class TestValueError1(object):
- def test_check_simple(self):
- arr = np.arange(30)
- arr = np.reshape(arr, (6, 5))
- kwargs = dict(mode='mean', stat_length=(3, ))
- assert_raises(ValueError, pad, arr, ((2, 3), (3, 2), (4, 5)),
- **kwargs)
-
- def test_check_negative_stat_length(self):
- arr = np.arange(30)
- arr = np.reshape(arr, (6, 5))
- kwargs = dict(mode='mean', stat_length=(-3, ))
- assert_raises(ValueError, pad, arr, ((2, 3), (3, 2)),
- **kwargs)
-
- def test_check_negative_pad_width(self):
- arr = np.arange(30)
- arr = np.reshape(arr, (6, 5))
- kwargs = dict(mode='mean', stat_length=(3, ))
- assert_raises(ValueError, pad, arr, ((-2, 3), (3, 2)),
- **kwargs)
-
- def test_check_empty_array(self):
- assert_raises(ValueError, pad, [], 4, mode='reflect')
- assert_raises(ValueError, pad, np.ndarray(0), 4, mode='reflect')
- assert_raises(ValueError, pad, np.zeros((0, 3)), ((1,), (0,)),
- mode='reflect')
-
-
-class TestValueError2(object):
- def test_check_negative_pad_amount(self):
- arr = np.arange(30)
- arr = np.reshape(arr, (6, 5))
- kwargs = dict(mode='mean', stat_length=(3, ))
- assert_raises(ValueError, pad, arr, ((-2, 3), (3, 2)),
- **kwargs)
-
-
-class TestValueError3(object):
- def test_check_kwarg_not_allowed(self):
- arr = np.arange(30).reshape(5, 6)
- assert_raises(ValueError, pad, arr, 4, mode='mean',
- reflect_type='odd')
-
- def test_mode_not_set(self):
- arr = np.arange(30).reshape(5, 6)
- assert_raises(TypeError, pad, arr, 4)
-
- def test_malformed_pad_amount(self):
- arr = np.arange(30).reshape(5, 6)
- assert_raises(ValueError, pad, arr, (4, 5, 6, 7), mode='constant')
-
- def test_malformed_pad_amount2(self):
- arr = np.arange(30).reshape(5, 6)
- assert_raises(ValueError, pad, arr, ((3, 4, 5), (0, 1, 2)),
- mode='constant')
-
- def test_pad_too_many_axes(self):
- arr = np.arange(30).reshape(5, 6)
-
- # Attempt to pad using a 3D array equivalent
- bad_shape = (((3,), (4,), (5,)), ((0,), (1,), (2,)))
- assert_raises(ValueError, pad, arr, bad_shape,
- mode='constant')
-
-
-class TestTypeError1(object):
- def test_float(self):
- arr = np.arange(30)
- assert_raises(TypeError, pad, arr, ((-2.1, 3), (3, 2)))
- assert_raises(TypeError, pad, arr, np.array(((-2.1, 3), (3, 2))))
-
- def test_str(self):
- arr = np.arange(30)
- assert_raises(TypeError, pad, arr, 'foo')
- assert_raises(TypeError, pad, arr, np.array('foo'))
-
- def test_object(self):
- class FooBar(object):
- pass
- arr = np.arange(30)
- assert_raises(TypeError, pad, arr, FooBar())
-
- def test_complex(self):
- arr = np.arange(30)
- assert_raises(TypeError, pad, arr, complex(1, -1))
- assert_raises(TypeError, pad, arr, np.array(complex(1, -1)))
-
- def test_check_wrong_pad_amount(self):
- arr = np.arange(30)
- arr = np.reshape(arr, (6, 5))
- kwargs = dict(mode='mean', stat_length=(3, ))
- assert_raises(TypeError, pad, arr, ((2, 3, 4), (3, 2)),
- **kwargs)
+ @pytest.mark.parametrize("pad_width", [0, (0, 0), ((0, 0), (0, 0))])
+ @pytest.mark.parametrize("mode", _all_modes.keys())
+ def test_zero_pad_width(self, pad_width, mode):
+ arr = np.arange(30).reshape(6, 5)
+ assert_array_equal(arr, np.pad(arr, pad_width, mode=mode))
+
+
+@pytest.mark.parametrize("mode", _all_modes.keys())
+def test_kwargs(mode):
+ """Test behavior of pad's kwargs for the given mode."""
+ allowed = _all_modes[mode]
+ not_allowed = {}
+ for kwargs in _all_modes.values():
+ if kwargs != allowed:
+ not_allowed.update(kwargs)
+ # Test if allowed keyword arguments pass
+ np.pad([1, 2, 3], 1, mode, **allowed)
+ # Test if prohibited keyword arguments of other modes raise an error
+ for key, value in not_allowed.items():
+ match = "unsupported keyword arguments for mode '{}'".format(mode)
+ with pytest.raises(ValueError, match=match):
+ np.pad([1, 2, 3], 1, mode, **{key: value})
+
+
+def test_constant_zero_default():
+ arr = np.array([1, 1])
+ assert_array_equal(np.pad(arr, 2), [0, 0, 1, 1, 0, 0])
+
+
+@pytest.mark.parametrize("mode", [1, "const", object(), None, True, False])
+def test_unsupported_mode(mode):
+ match= "mode '{}' is not supported".format(mode)
+ with pytest.raises(ValueError, match=match):
+ np.pad([1, 2, 3], 4, mode=mode)
+
+
+@pytest.mark.parametrize("mode", _all_modes.keys())
+def test_non_contiguous_array(mode):
+ arr = np.arange(24).reshape(4, 6)[::2, ::2]
+ result = np.pad(arr, (2, 3), mode)
+ assert result.shape == (7, 8)
+ assert_equal(result[2:-3, 2:-3], arr)
+
+
+@pytest.mark.parametrize("mode", _all_modes.keys())
+def test_memory_layout_persistence(mode):
+ """Test if C and F order is preserved for all pad modes."""
+ x = np.ones((5, 10), order='C')
+ assert np.pad(x, 5, mode).flags["C_CONTIGUOUS"]
+ x = np.ones((5, 10), order='F')
+ assert np.pad(x, 5, mode).flags["F_CONTIGUOUS"]
+
+
+@pytest.mark.parametrize("dtype", _numeric_dtypes)
+@pytest.mark.parametrize("mode", _all_modes.keys())
+def test_dtype_persistence(dtype, mode):
+ arr = np.zeros((3, 2, 1), dtype=dtype)
+ result = np.pad(arr, 1, mode=mode)
+ assert result.dtype == dtype