From 34fbbf9cae01f9ed5bb950e5080e04ce857212b6 Mon Sep 17 00:00:00 2001 From: "Christopher J. Markiewicz" Date: Wed, 14 Oct 2015 21:40:35 -0400 Subject: [PATCH] BF: Set strided_scalar as not writeable Numpy 1.10 cannot broadcast a strided array that is set as writeable --- nibabel/fileslice.py | 10 ++++++++-- nibabel/tests/test_fileslice.py | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/nibabel/fileslice.py b/nibabel/fileslice.py index 35333bc363..feecc718d4 100644 --- a/nibabel/fileslice.py +++ b/nibabel/fileslice.py @@ -767,9 +767,15 @@ def strided_scalar(shape, scalar=0.): strided_arr : array Array of shape `shape` for which all values == `scalar`, built by setting all strides of `strided_arr` to 0, so the scalar is broadcast - out to the full array `shape`. + out to the full array `shape`. `strided_arr` is flagged as not + `writeable`. + + The array is set read-only to avoid a numpy error when broadcasting - + see https://github.com/numpy/numpy/issues/6491 """ shape = tuple(shape) scalar = np.array(scalar) strides = [0] * len(shape) - return np.lib.stride_tricks.as_strided(scalar, shape, strides) + strided_scalar = np.lib.stride_tricks.as_strided(scalar, shape, strides) + strided_scalar.flags.writeable = False + return strided_scalar diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index 12668e56d9..7ff86c61d0 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -639,8 +639,14 @@ def test_strided_scalar(): assert_equal(observed.shape, shape) assert_equal(observed.dtype, expected.dtype) assert_array_equal(observed.strides, 0) - observed[..., 0] = 99 - assert_array_equal(observed, expected * 0 + 99) + # Strided scalars are set as not writeable + # This addresses a numpy 1.10 breakage of broadcasting a strided + # array without resizing (see GitHub PR #358) + assert_false(observed.flags.writeable) + def setval(x): + x[..., 0] = 99 + # RuntimeError for numpy < 1.10 + assert_raises((RuntimeError, ValueError), setval, observed) # Default scalar value is 0 assert_array_equal(strided_scalar((2, 3, 4)), np.zeros((2, 3, 4)))