为什么 `scipy.interpolate.griddata` 在只读数组上失败?

4

我有一些数据,想要使用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个回答

4

相关代码是用Cython编写的,当Cython请求输入数组的memoryview时,它总是要求一个可写的, 即使你不需要它。

由于标记为非可写的数组将拒绝提供可写的memoryview,因此即使它在第一次不需要写入数组,代码也会失败。


我明白了——这解释了错误,但我仍然认为scipy中的这个问题是一个bug,因为它没有自己制作副本而是抛出了一个错误。最终,cython可能应该被改变以允许只读内存视图。我已经为scipy打开了一个错误报告(https://github.com/scipy/scipy/issues/6864)。让我们看看那边的人会说些什么。 - David Zwicker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接