为什么`scipy.interpolate.griddata`对于只读数组失败了?

时间:2016-12-16 20:21:27

标签: python numpy scipy

我有一些数据,我尝试使用scipy.interpolate.griddata进行插值。在我的用例中,我将一些numpy数组标记为只读,这显然打破了插值:

import numpy as np
from scipy import interpolate

x0 = 10 * np.random.randn(100, 2)
y0 = np.random.randn(100)
x1 = np.random.randn(3, 2)

x0.flags.writeable = False
# x1.flags.writeable = False

interpolate.griddata(x0, y0, x1)

产生以下异常:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-a6e09dbdd371> in <module>()
      6 # x1.flags.writeable = False
      7 
----> 8 interpolate.griddata(x0, y0, x1)

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/interpolate/ndgriddata.pyc in griddata(points, values, xi, method, fill_value, rescale)
    216         ip = LinearNDInterpolator(points, values, fill_value=fill_value,
    217                                   rescale=rescale)
--> 218         return ip(xi)
    219     elif method == 'cubic' and ndim == 2:
    220         ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,

scipy/interpolate/interpnd.pyx in scipy.interpolate.interpnd.NDInterpolatorBase.__call__ (scipy/interpolate/interpnd.c:3930)()

scipy/interpolate/interpnd.pyx in scipy.interpolate.interpnd.LinearNDInterpolator._evaluate_double (scipy/interpolate/interpnd.c:5267)()

scipy/interpolate/interpnd.pyx in scipy.interpolate.interpnd.LinearNDInterpolator._do_evaluate (scipy/interpolate/interpnd.c:6006)()

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/interpolate/interpnd.so in View.MemoryView.memoryview_cwrapper (scipy/interpolate/interpnd.c:17829)()

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/interpolate/interpnd.so in View.MemoryView.memoryview.__cinit__ (scipy/interpolate/interpnd.c:14104)()

ValueError: buffer source array is read-only

显然,插值函数不喜欢数组被写保护。但是,我不明白他们为什么要改变它 - 我当然不希望通过调用插值函数来改变我的输入,据我所知,这在文档中也没有提到。为什么函数会像这样?

请注意,只设置x1而不是x0会导致类似的错误。

1 个答案:

答案 0 :(得分:2)

relevant code是用Cython编写的,当Cython请求输入数组的内存视图it always asks for a writeable one时,即使你不需要它。

由于标记为不可写的数组将拒绝提供可写的内存视图,因此代码会失败,即使它首先不需要写入数组。