在Python中将大的不规则网格插入到另一个不规则网格中

时间:2011-10-09 05:38:46

标签: python numpy matplotlib scipy interpolation

我正在尝试使用Python将复杂值从一个不规则网格插入到另一个不规则网格中。网格是2D的,有103,113个数据点。我使用的是Python 2.6.6,Scipy 0.7.2,Numpy 1.3.0,Matplotlib 0.99.3

在Matlab中使用griddata,大约需要5秒钟。

BnGRID2  = griddata(R_GRID1,Z_GRID1,BnGRID1,R_GRID2,Z_GRID2) (MATLAB)

(注意所有阵列都是201 x 513)

但是,如果我尝试使用matplotlib.mlab.griddata,即使我尝试仅使用真实部分,我也会得到一个memoryError:

mlab.griddata(R_GRID1.flatten(),Z_GRID1.flatten(),num.real(BnGRID1.flatten()),R_GRID2.flatten(),Z_GRID2.flatten())

如果我尝试使用interp2d,我会遇到分段错误而Python退出:

a = interp.interp2d(R_GRID1,Z_GRID1,num.real(BnGRID1))

我尝试过使用KDTree,这似乎工作正常,但是,与Matlab的几秒相比,它需要几分钟,但我还没有太多地探讨这个选项。

想知道是否有人有任何想法我怎么能像Matlab一样快地完成这项工作?我注意到Scipy的新版本也有griddata,有没有人知道这是否可以处理大的不规则网格?

1 个答案:

答案 0 :(得分:6)

Scipy的griddata似乎能够毫无问题地处理这种大小的数据集:

import numpy as np
import scipy.interpolate

# old grid
x, y = np.mgrid[0:1:201j, 0:1:513j]
z = np.sin(x*20) * (1j + np.cos(y*3))**2   # some data

# new grid
x2, y2 = np.mgrid[0.1:0.9:201j, 0.1:0.9:513j]

# interpolate onto the new grid
z2 = scipy.interpolate.griddata((x.ravel(), y.ravel()), z.ravel(), (x2, y2), method='cubic')

对于旧的AMD Athlon,griddata步骤大约需要5秒。

如果您的数据在网格上(即,对应于值z [i,j]的坐标是(x [i],y [j])),您可以使用scipy.interpolate.RectBivariateSpline获得更快的速度

z3 = (scipy.interpolate.RectBivariateSpline(x[:,0], y[0,:], z.real)(x2[:,0], y2[0,:])
 + 1j*scipy.interpolate.RectBivariateSpline(x[:,0], y[0,:], z.imag)(x2[:,0], y2[0,:]))

需要0.05秒。它的速度要快得多,因为即使网格间距不规则,只要网格是矩形的,就可以使用更有效的算法。

相关问题