python中三维样条插值

2024-04-25 12:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在搜索等效的Matlab命令

Vq = interp3(X,Y,Z,V,Xq,Yq,Zq)

在Python中。在Matlab中,我可以使用“样条”插值方法,这是我在python中找不到的3D数据。存在scipy.interpolate.griddata,但它没有三维数据的样条线选项。

我要插值的数据是一个3D矩阵(51x51x51),它在3D网格上有规律地分布。

scipy.interpolate.Rbf可能是一个选项,但我不能让它工作:

xi = yi = zi = np.linspace(1, 132651, 132651) interp = scipy.interpolate.Rbf(xi, yi, zi, data, function='cubic')

导致内存错误。

编辑: 我想要的一个最小的例子(没有插值): Matlab代码

v=rand([51,51,51]);
isosurface (v, 0.3);

为了简单起见,我在这个例子中使用随机数据。我想做等值面图(特别是费米面图)。由于某些结构非常小,因此需要51x51x51的高网格分辨率。

进一步说明:矩阵中的数据集彼此独立,z(或第三个分量)不是x和y的函数


Tags: 数据网格选项矩阵scipy例子样条插值
1条回答
网友
1楼 · 发布于 2024-04-25 12:09:21

3+维的样条插值可以使用scipy.interpolate.Rbf完成,如您所述。为了绘图,您可以使用较小的分辨率(1000点是一个很好的经验法则),当您想要计算样条曲线时,您可以在大于132000点的点上进行插值,而不会出现问题(请参见下面的示例)。

你能在matlab中添加一个Minimal, Complete, and Verifiable example来做你想做的事情吗?这将解释为什么需要创建分辨率为132000点的栅格空间。另外,请注意,有一个维度诅咒。Matlab使用的cubic spline or a piecewise polynomial可能由于过度拟合而变得危险。我建议您使用一种更理智的方法来培训51个数据点,并应用到132000多个数据点。This是多项式曲线拟合和模型选择的一个很好的例子。

示例:

生成数据:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

%matplotlib inline
import random
# set seed to reproducible
random.seed(1)
data_size = 51
max_value_range = 132651
x = np.array([random.random()*max_value_range for p in range(0,data_size)])
y = np.array([random.random()*max_value_range for p in range(0,data_size)])
z = 2*x*x*x + np.sqrt(y)*y + random.random()
fig = plt.figure(figsize=(10,6))
ax = axes3d.Axes3D(fig)
ax.scatter3D(x,y,z, c='r')

enter image description here

拟合样条曲线并插值

x_grid = np.linspace(0, 132651, 1000*len(x))
y_grid = np.linspace(0, 132651, 1000*len(y))
B1, B2 = np.meshgrid(x_grid, y_grid, indexing='xy')
Z = np.zeros((x.size, z.size))

import scipy as sp
import scipy.interpolate
spline = sp.interpolate.Rbf(x,y,z,function='thin_plate',smooth=5, episilon=5)

Z = spline(B1,B2)
fig = plt.figure(figsize=(10,6))
ax = axes3d.Axes3D(fig)
ax.plot_wireframe(B1, B2, Z)
ax.plot_surface(B1, B2, Z,alpha=0.2)
ax.scatter3D(x,y,z, c='r')

enter image description here

在大数据上拟合样条曲线

predict_data_size = 132000
x_predict = np.array([random.random()*max_value_range for p in range(0,predict_data_size)])
y_predict = np.array([random.random()*max_value_range for p in range(0,predict_data_size)])
z_predict = spline(x_predict, y_predict)
fig = plt.figure(figsize=(10,6))
ax = axes3d.Axes3D(fig)
ax.plot_wireframe(B1, B2, Z)
ax.plot_surface(B1, B2, Z,alpha=0.2)
ax.scatter3D(x_predict,y_predict,z_predict, c='r')

enter image description here

相关问题 更多 >