【问题标题】:How can I use nearest neighbor interpolation only outside of bounds when using RegularGridInterpolator使用RegularGridInterpolator时,如何仅在边界之外使用最近邻插值
【发布时间】:2021-12-09 03:08:57
【问题描述】:

使用RegularGridInterpolator 获取输入数据的外壳(边界)之外的值,可以在外推值或固定值之间进行选择。如何获得船体内部的线性插值和船体外部的最近邻插值?

【问题讨论】:

    标签: python scipy interpolation


    【解决方案1】:

    以下类使用两个插值器。第一个将外壳外的所有值设置为np.nan。第二个插值器仅对那些 nan 值进行最近邻插值。

    class RegularGridInterpolatorNNextrapol:
        def __init__( self, points, values, method='linear' ):
            self.interp = RegularGridInterpolator(points, values, method=method,
                                                  bounds_error=False, fill_value=np.nan)
            self.nearest = RegularGridInterpolator(points, values, method='nearest',
                                               bounds_error=False, fill_value=None)
    
        def __call__( self, xi ):
            vals = self.interp( xi )
            idxs = np.isnan( vals )
            vals[idxs] = self.nearest( xi[idxs] )
            return vals
    

    这是一个导致下图的示例:

    x = np.linspace( -0.5, 0.5, 5 )
    y = np.linspace( -0.5, 0.5, 5 )
    X1, Y1 = np.meshgrid(x, y)
    z = np.hypot(X1, Y1)
    
    interp = RegularGridInterpolatorNNextrapol((x,y), z)
    
    X = np.linspace(min(x)-0.2, max(x)+0.2,40)
    Y = np.linspace(min(y)-0.2, max(y)+0.2,40)
    X, Y = np.meshgrid(X, Y)  # 2D grid for interpolation
    
    pts = np.column_stack((X.flatten(),Y.flatten()))
    Z = interp( pts )
    
    plt.pcolormesh(X, Y, Z.reshape(X.shape), shading='auto')
    plt.plot(X1, Y1, "ok" )
    plt.legend()
    plt.colorbar()
    plt.axis("equal")
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 2016-05-02
      • 2019-02-20
      • 2010-12-21
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多