Python中具有NaN的数组的2D多项式拟合

时间:2018-08-04 13:09:17

标签: python numpy scipy lmfit

我正在尝试将三阶多项式拟合到包含NaN值的1024x1024图像阵列,到目前为止,lmfit未能返回可靠的拟合。我遇到了需要展平阵列并删除NaN的解决方案,但这会删除我的大部分数据,从而导致不合适。任何建议,将不胜感激。

编辑1:我正在寻找的解决方案看起来像this,但具有NaN。

编辑2:这是我尝试使用lmfit的结果:

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from lmfit import Model, Parameters

noedge_fits = 'fitsfile1.fits' ### 3D cube
mask_fits   = 'fitsfile2.fits' ### 2D image
mw_fits     = 'fitsfile3.fits' ### 3D cube

wholecube = fits.open(noedge_fits)
maskplane = fits.open(mask_fits)
mwcube = fits.open(mw_fits)

whole = wholecube[0].data[0]
mask  = maskplane[0].data[0]
mw    = mwcube[0].data[0]


def poly(x, y, ab0, a1, b1, ab1, a2, b2, ab2, a3, b3, ab3):
    return ab0 + a1*x + b1*y + ab1*x*y + a2*x**2 + b2*y**2 + ab2*x**2*y + ab3*x*y**2 + a3*x**3 + b3*y**3

x0, y0, z0 = whole.shape

arrx = np.arange(y0)
arry = np.arange(z0)

for k in range(x0):
    if not np.isnan(mw[k].any()):
        for i in range(y0):
            for j in range(z0):
                if not np.isnan(mask[i,j]):
                    mw[k,i,j] = np.nan

        pmodel = Model(poly, independent_vars=['x','y'])
        params = pmodel.make_params(ab=0., a1=0., b1=0., a2=0., b2=0., a3=0., b3=0.)

        result = pmodel.fit(mw[k], params, x=arrx, y=arry, nan_policy='propagate')

        print result.best_values

0 个答案:

没有答案