如何修复赋值前引用的变量问题

时间:2018-03-23 12:28:34

标签: python matplotlib physics astronomy

我对此代码存在一些问题,因为最后一行似乎导致了一个问题:

from astropy.io import fits

import matplotlib.pyplot as plt
import numpy as np
import glob  
import pdb #to debug

filelist=glob.glob('5/img/*.fit') #reads in all fits files

hdu = fits.open('MCtest_C1.fits')
hdu[0].header
coeff=hdu[0].data #added in [1].data
print(coeff.shape)
hdu.close()


def make_cube(filelist,x0,x1,y0,y1):
    exptime= np.zeros(len(filelist))
    n=np.zeros(len(filelist))
    jd= np.zeros(len(filelist))
    #pdb.set_trace() #- used to debug

    for i,name in enumerate(filelist):
        hdu=fits.open(name)
        img=hdu[1].data
        nonlin = coeff[:,:,0]*img**3 + coeff[:,:,1]*img**2 + coeff[:,:,2]*img**1 + coeff[:,:,3]*img**0
        exptime[i]=hdu[0].header['EXPTIME']
        n[i]=int( (hdu[0].header['RUNSET'].split(':') )[0] )
        jd[i]=hdu[0].header['JD']
        hdu.close()
        img=img[x0:x1,y0:y1] #makes cutout
        idx=(n>3) #added 13/10/17
        if (i==0):
            cube=img.copy()
        else:
            cube=np.dstack((cube,img))
        print (n[i],i,cube.shape)

    print(n,cube.shape)
    idx=(n>3)
    hdu=fits.PrimaryHDU(cube[:,:,idx])
    hdu.writeto(  ('cube_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1)  ) ,overwrite=True )
    hdu=fits.PrimaryHDU(exptime[idx])
    hdu.writeto(  ('exptime_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1)  ) ,overwrite=True )
    hdu=fits.PrimaryHDU(jd[idx])
    hdu.writeto(  ('jd_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1)  ) ,overwrite=True )
    hdu=fits.PrimaryHDU(nonlin[idx])
    hdu.writeto(  ('nonlin_corrected_%i_%i_%i_%i.fits' % (x0,x1,y0,y1)  ), overwrite=True)

make_cube(filelist, 0, 512, 0, 512)

错误如下:UnboundLocalError: local variable 'cube' referenced before assignment

我尝试了最后一行的不同缩进,并且它以不同的缩进方式运行,但它没有正确运行代码。

我也查找了与此错误相关的其他问题,但我还没有看到任何可以帮助我的事情。

任何帮助都会很棒!谢谢:))

0 个答案:

没有答案