Skip to content

Commit 1c45e0d

Browse files
committed
BUG: Simplify linear ramp padding with linspace
linspace supports non-scalar values since version 1.16. This can simplify construction of the ramp for the pad mode "linear_ramp". This removes a bug in the old implementation where certain edge and end values resulted in an integer underflow for unsigned dtypes (see numpygh-14191). Protect against this regression with a new test for all numeric dtypes.
1 parent 4f641f3 commit 1c45e0d

2 files changed

Lines changed: 49 additions & 37 deletions

File tree

‎numpy/lib/arraypad.py‎

Lines changed: 25 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -244,27 +244,19 @@ def _prepend_ramp(arr, pad_amt, end, axis=-1):
244244
if pad_amt == 0:
245245
return arr
246246

247-
# Generate shape for final concatenated array
248-
padshape = tuple(x if i != axis else pad_amt
249-
for (i, x) in enumerate(arr.shape))
250-
251-
# Generate an n-dimensional array incrementing along `axis`
252-
ramp_arr = _arange_ndarray(arr, padshape, axis,
253-
reverse=True).astype(np.float64)
254-
255-
# Appropriate slicing to extract n-dimensional edge along `axis`
247+
# Slice a chunk from the edge to calculate stats on and extract edge
256248
edge_slice = _slice_first(arr.shape, 1, axis=axis)
249+
edge = arr[edge_slice]
257250

258-
# Extract edge, and extend along `axis`
259-
edge_pad = arr[edge_slice].repeat(pad_amt, axis)
260-
261-
# Linear ramp
262-
slope = (end - edge_pad) / float(pad_amt)
263-
ramp_arr = ramp_arr * slope
264-
ramp_arr += edge_pad
265-
_round_ifneeded(ramp_arr, arr.dtype)
251+
ramp_arr = np.linspace(
252+
start=end,
253+
stop=edge.squeeze(axis),
254+
num=pad_amt,
255+
endpoint=False,
256+
dtype=arr.dtype,
257+
axis=axis
258+
)
266259

267-
# Ramp values will most likely be float, cast them to the same type as arr
268260
return _do_prepend(arr, ramp_arr, axis)
269261

270262

@@ -294,27 +286,23 @@ def _append_ramp(arr, pad_amt, end, axis=-1):
294286
if pad_amt == 0:
295287
return arr
296288

297-
# Generate shape for final concatenated array
298-
padshape = tuple(x if i != axis else pad_amt
299-
for (i, x) in enumerate(arr.shape))
300-
301-
# Generate an n-dimensional array incrementing along `axis`
302-
ramp_arr = _arange_ndarray(arr, padshape, axis,
303-
reverse=False).astype(np.float64)
304-
305-
# Slice a chunk from the edge to calculate stats on
289+
# Slice a chunk from the edge to calculate stats on and extract edge
306290
edge_slice = _slice_last(arr.shape, 1, axis=axis)
291+
edge = arr[edge_slice]
292+
293+
ramp_arr = np.linspace(
294+
start=end,
295+
stop=edge.squeeze(axis),
296+
num=pad_amt,
297+
endpoint=False,
298+
dtype=arr.dtype,
299+
axis=axis
300+
)
301+
# Reverse linear space in appropriate dimension
302+
ramp_arr = ramp_arr[
303+
_slice_at_axis(ramp_arr.shape, slice(None, None, -1), axis)
304+
]
307305

308-
# Extract edge, and extend along `axis`
309-
edge_pad = arr[edge_slice].repeat(pad_amt, axis)
310-
311-
# Linear ramp
312-
slope = (end - edge_pad) / float(pad_amt)
313-
ramp_arr = ramp_arr * slope
314-
ramp_arr += edge_pad
315-
_round_ifneeded(ramp_arr, arr.dtype)
316-
317-
# Ramp values will most likely be float, cast them to the same type as arr
318306
return _do_append(arr, ramp_arr, axis)
319307

320308

‎numpy/lib/tests/test_arraypad.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,30 @@ def test_object_array(self):
679679
])
680680
assert_equal(actual, expected)
681681

682+
@pytest.mark.parametrize("dtype", (
683+
np.sctypes["uint"]
684+
+ np.sctypes["int"]
685+
+ np.sctypes["float"]
686+
+ np.sctypes["complex"]
687+
))
688+
def test_negative_difference(self, dtype):
689+
"""
690+
Check correct behavior of unsigned dtypes if there is a negative
691+
difference between the edge to pad and `end_values`. Check both cases
692+
to be independent of implementation. Test behavior for all other dtypes
693+
in case dtype casting interferes with complex dtypes. See gh-14191.
694+
"""
695+
x = np.array([3], dtype=dtype)
696+
result = np.pad(x, 3, mode="linear_ramp", end_values=0)
697+
expected = np.array([0, 1, 2, 3, 2, 1, 0], dtype=dtype)
698+
assert_equal(result, expected)
699+
700+
x = np.array([0], dtype=dtype)
701+
result = np.pad(x, 3, mode="linear_ramp", end_values=3)
702+
expected = np.array([3, 2, 1, 0, 1, 2, 3], dtype=dtype)
703+
assert_equal(result, expected)
704+
705+
682706

683707
class TestReflect(object):
684708
def test_check_simple(self):

0 commit comments

Comments
 (0)