Skip to content

Commit d34a3f0

Browse files
committed
BUG: ensure integer shape, strides for as_strided
1 parent 300ee75 commit d34a3f0

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/matplotlib/mlab.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,6 +590,19 @@ def stride_windows(x, n, noverlap=None, axis=0):
590590
if n > x.size:
591591
raise ValueError('n cannot be greater than the length of x')
592592

593+
# as_strided can lead to memory out of bound access for non
594+
# integer noverlap or n
595+
if not isinstance(noverlap, (int, long)):
596+
warnings.warn("Using a non integer 'noverlap' instead of an integer "
597+
"will result in an error in the future",
598+
cbook.mplDeprecation)
599+
noverlap = int(round(noverlap))
600+
if not isinstance(n, (int, long)):
601+
warnings.warn("Using a non integer 'n' instead of an integer "
602+
"will result in an error in the future",
603+
cbook.mplDeprecation)
604+
n = int(round(n))
605+
593606
step = n - noverlap
594607
if axis == 0:
595608
shape = (n, (x.shape[-1]-noverlap)//step)
@@ -642,6 +655,14 @@ def stride_repeat(x, n, axis=0):
642655
if n < 1:
643656
raise ValueError('n cannot be less than 1')
644657

658+
# as_strided might lead to memory out of bound access for non
659+
# integer n
660+
if not isinstance(n, (int, long)):
661+
warnings.warn("Using a non integer 'n' instead of an integer "
662+
"will result in an error in the future",
663+
cbook.mplDeprecation)
664+
n = int(round(n))
665+
645666
if axis == 0:
646667
shape = (n, x.size)
647668
strides = (0, x.strides[0])

lib/matplotlib/tests/test_mlab.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import six
55

66
import tempfile
7+
import warnings
78

89
from numpy.testing import assert_allclose, assert_array_equal
910
import numpy.ma.testutils as matest
@@ -283,6 +284,22 @@ def test_stride_windows_n32_noverlap0_axis1_unflatten(self):
283284
assert_equal(y.shape, x1.shape)
284285
assert_array_equal(y, x1)
285286

287+
def test_stride_ensure_integer_type(self):
288+
N = 1000
289+
n_sin_periods = 10
290+
x = np.empty(3*N, dtype='f4')
291+
x.fill(np.NaN)
292+
y = x[N:2*N]
293+
y[:] = np.sin(np.arange(N)/N * 2 * np.pi * n_sin_periods)
294+
with warnings.catch_warnings():
295+
warnings.simplefilter('ignore', cbook.mplDeprecation)
296+
y_strided = mlab.stride_windows(y, n=330, noverlap=0.6)
297+
assert_equal(sum(np.isnan(y_strided.flat[:])), 0)
298+
y_strided = mlab.stride_windows(y, n=333.3, noverlap=0)
299+
assert_equal(sum(np.isnan(y_strided.flat[:])), 0)
300+
y_strided = mlab.stride_repeat(y, n=33.815)
301+
assert_equal(sum(np.isnan(y_strided.flat[:])), 0)
302+
286303

287304
class csv_testcase(CleanupTestCase):
288305
def setUp(self):

0 commit comments

Comments
 (0)