def del_license(fitsfile, keys): """Delete license information from FITS""" try: for key in keys: pyfits.delval(fitsfile, key) except KeyError: print("License information not found.", file=sys.stderr)
def headerRenameKey2(self, key, newkey): for filename in self._matchingFiles: self._logger.notice('rename %s: %s= %s' % (filename, key, newkey)) try: value = pyfits.getval(filename, key) pyfits.setval(filename, newkey, value) pyfits.delval(filename, key) except: pass
def speccombine(fs=None): iraf.cd('work') if fs is None: fs = glob('trm/sci*c?.fits') if len(fs)==0: print("No flux calibrated images to combine.") iraf.cd('..') return #diagnostic() nsteps = 8001 lamgrid = np.linspace(2000.0, 10000.0, nsteps) nfs = len(fs) # for each aperture # get all of the science images specs = np.zeros((nfs, nsteps)) specerrs = np.zeros((nfs, nsteps)) ap = 0 for i, f in enumerate(fs): hdu = pyfits.open(f) # print ('---hdu.data---') # print (hdu[0].data) w=WCS(f) # print ('-----w-----') # print(w) # get the wavelengths of the pixels npix = hdu[0].data.shape[2] # print('-----npix-----') # print(npix) lam = w.all_pix2world(np.linspace(0, npix - 1, npix), 0, 0, 0)[0] # print('-----lam-----') # print(lam) # interpolate each spectrum onto a comman wavelength scale specs[i] = interp(lamgrid, lam, hdu[0].data[0][ap], left=0.0, right=0.0) # Also calculate the errors. Right now we assume that the variances # interpolate linearly. This is not stricly correct but it should be # close. Also we don't include terms in the variance for the # uncertainty in the wavelength solution. specerrs[i] = interp(lamgrid, lam, hdu[0].data[3][ap] ** 2.0) ** 0.5 #print ('-----specs-----') #print (specs) # minimize the chi^2 given free parameters are multiplicative factors # We could use linear or quadratic, but for now assume constant p0 = np.ones(nfs) results = optimize.minimize(combine_spec_chi2, p0, args=(lamgrid, specs, specerrs), method='Nelder-Mead', options={'maxfev': 1e5, 'maxiter': 1e5}) # write the best fit parameters into the headers of the files # Dump the list of spectra into a string that iraf can handle iraf_filelist = str(fs).replace('[', '').replace(']', '').replace("'", '') # write the best fit results into a file lines = [] for p in results['x']: lines.append('%f\n' % (1.0 / p)) f = open('flx/scales.dat', 'w') f.writelines(lines) f.close() # run scombine after multiplying the spectra by the best fit parameters combfile = 'sci_com.fits' if os.path.exists(combfile): os.remove(combfile) iraf.scombine(iraf_filelist, combfile, scale='@flx/scales.dat', reject='avsigclip', lthreshold=-2e-16) # Remove the other apertures [TBD] # remove the sky and arc bands from the combined spectra. (or add back?? TBD) # remove some header keywords that don't make sense in the combined file delkws = ['GR-ANGLE','FILTER','BANDID2','BANDID3','BANDID4'] for kw in delkws: pyfits.delval(combfile,kw) # combine JD (average), AIRMASS (average), EXPTIME (sum) # we assume there is a c1.fits file for each image c1fs = [f for f in fs if 'c1.fits' in f] avgjd = np.mean([pyfits.getval(f,'JD') for f in c1fs]) pyfits.setval(combfile,'JD',value=avgjd, comment='average of multiple exposures') print "average JD = " + str(avgjd) sumet = np.sum([pyfits.getval(f,'EXPTIME') for f in c1fs]) pyfits.setval(combfile,'EXPTIME',value=sumet,comment='sum of multiple exposures') print "total EXPTIME = " + str(sumet) avgam = np.mean([pyfits.getval(f,'AIRMASS') for f in c1fs]) pyfits.setval(combfile,'AIRMASS',value=avgam,comment='average of multiple exposures') print "avg AIRMASS = " + str(avgam) # update this to used avg jd midpoint of all exposures? print "barycentric velocity correction (km/s) = ", iraf.bcvcorr(spectra=combfile,keytime='UTC-OBS',keywhen='mid', obslong="339:11:16.8",obslat="-32:22:46.2",obsalt='1798',obsname='saao', savebcv='yes',savejd='yes',printmode=2) pyfits.setval(combfile,'UTMID',comment='added by RVSAO task BCVCORR') pyfits.setval(combfile,'GJDN',comment='added by RVSAO task BCVCORR') pyfits.setval(combfile,'HJDN',comment='added by RVSAO task BCVCORR') pyfits.setval(combfile,'BCV',comment='added by RVSAO task BCVCORR (km/s)') pyfits.setval(combfile,'HCV',comment='added by RVSAO task BCVCORR (km/s)') iraf.dopcor(input=combfile,output='',redshift=-iraf.bcvcorr.bcv,isvelocity='yes', add='no',dispersion='yes',flux='no',verbose='yes') pyfits.setval(combfile,'DOPCOR01',comment='barycentric velocity correction applied') iraf.cd('..')
def headerDeleteKey(self, key): for filename in self._matchingFiles: self._logger.notice('delete %s: %s' % (filename, key)) pyfits.delval(filename, key)
def speccombine(fs=None): iraf.cd('work') if fs is None: fs = glob('flx/sci*c?.fits') if len(fs)==0: print("No flux calibrated images to combine.") iraf.cd('..') return nsteps = 8001 lamgrid = np.linspace(2000.0, 10000.0, nsteps) nfs = len(fs) # for each aperture # get all of the science images specs = np.zeros((nfs, nsteps)) specerrs = np.zeros((nfs, nsteps)) ap = 0 for i, f in enumerate(fs): hdu = pyfits.open(f) w = WCS(f) # get the wavelengths of the pixels npix = hdu[0].data.shape[2] lam = w.all_pix2world(np.linspace(0, npix - 1, npix), 0, 0, 0)[0] # interpolate each spectrum onto a comman wavelength scale specs[i] = interp(lamgrid, lam, hdu[0].data[0][ap], left=0.0, right=0.0) # Also calculate the errors. Right now we assume that the variances # interpolate linearly. This is not stricly correct but it should be # close. Also we don't include terms in the variance for the # uncertainty in the wavelength solution. specerrs[i] = interp(lamgrid, lam, hdu[0].data[3][ap] ** 2.0) ** 0.5 # minimize the chi^2 given free parameters are multiplicative factors # We could use linear or quadratic, but for now assume constant p0 = np.ones(nfs) results = optimize.minimize(combine_spec_chi2, p0, args=(lamgrid, specs, specerrs), method='Nelder-Mead', options={'maxfev': 1e5, 'maxiter': 1e5}) # write the best fit parameters into the headers of the files # Dump the list of spectra into a string that iraf can handle iraf_filelist = str(fs).replace('[', '').replace(']', '').replace("'", '') # write the best fit results into a file lines = [] for p in results['x']: lines.append('%f\n' % (1.0 / p)) f = open('flx/scales.dat', 'w') f.writelines(lines) f.close() # run scombine after multiplying the spectra by the best fit parameters combfile = 'sci_com.fits' if os.path.exists(combfile): os.remove(combfile) iraf.scombine(iraf_filelist, combfile, scale='@flx/scales.dat', reject='avsigclip', lthreshold=1e-19) # Remove the other apertures [TBD] # remove the sky and arc bands from the combined spectra. (or add back?? TBD) # remove some header keywords that don't make sense in the combined file delkws = ['GRATING','GR-ANGLE','FILTER','BANDID2','BANDID3','BANDID4'] for kw in delkws: pyfits.delval(combfile,kw) # combine JD (average), AIRMASS (average), EXPTIME (sum) # we assume there is a c1.fits file for each image c1fs = [f for f in fs if 'c1.fits' in f] avgjd = np.mean([pyfits.getval(f,'JD') for f in c1fs]) pyfits.setval(combfile,'JD',value=avgjd) print "average JD = " + str(avgjd) sumet = np.sum([pyfits.getval(f,'EXPTIME') for f in c1fs]) pyfits.setval(combfile,'EXPTIME',value=sumet) print "total EXPTIME = " + str(sumet) avgam = np.mean([pyfits.getval(f,'AIRMASS') for f in c1fs]) pyfits.setval(combfile,'AIRMASS',value=avgam) print "avg AIRMASS = " + str(avgam) iraf.cd('..') return specs
def speccombine(fs=None): iraf.cd('work') if fs is None: fs = glob('flx/sci*c?.fits') if len(fs)==0: print("No flux calibrated images to combine.") iraf.cd('..') return nsteps = 8001 lamgrid = np.linspace(2000.0, 10000.0, nsteps) nfs = len(fs) # for each aperture # get all of the science images specs = np.zeros((nfs, nsteps)) specerrs = np.zeros((nfs, nsteps)) ap = 0 for i, f in enumerate(fs): hdu = pyfits.open(f) w = WCS(f) # get the wavelengths of the pixels npix = hdu[0].data.shape[2] lam = w.all_pix2world(np.linspace(0, npix - 1, npix), 0, 0, 0)[0] # interpolate each spectrum onto a comman wavelength scale specs[i] = interp(lamgrid, lam, hdu[0].data[0][ap], left=0.0, right=0.0) # Also calculate the errors. Right now we assume that the variances # interpolate linearly. This is not stricly correct but it should be # close. Also we don't include terms in the variance for the # uncertainty in the wavelength solution. specerrs[i] = interp(lamgrid, lam, hdu[0].data[3][ap] ** 2.0) ** 0.5 # minimize the chi^2 given free parameters are multiplicative factors # We could use linear or quadratic, but for now assume constant p0 = np.ones(nfs) results = optimize.minimize(combine_spec_chi2, p0, args=(lamgrid, specs, specerrs), method='Nelder-Mead', options={'maxfev': 1e5, 'maxiter': 1e5}) # write the best fit parameters into the headers of the files # Dump the list of spectra into a string that iraf can handle iraf_filelist = str(fs).replace('[', '').replace(']', '').replace("'", '') # write the best fit results into a file lines = [] for p in results['x']: lines.append('%f\n' % (1.0 / p)) f = open('flx/scales.dat', 'w') f.writelines(lines) f.close() # run scombine after multiplying the spectra by the best fit parameters combfile = 'sci_com.fits' if os.path.exists(combfile): os.remove(combfile) iraf.scombine(iraf_filelist, combfile, scale='@flx/scales.dat', reject='avsigclip', lthreshold=-1e-17) # Remove the other apertures [TBD] # remove the sky and arc bands from the combined spectra. (or add back?? TBD) # remove some header keywords that don't make sense in the combined file delkws = ['GR-ANGLE','FILTER','BANDID2','BANDID3','BANDID4'] for kw in delkws: pyfits.delval(combfile,kw) # combine JD (average), AIRMASS (average), EXPTIME (sum) # we assume there is a c1.fits file for each image c1fs = [f for f in fs if 'c1.fits' in f] avgjd = np.mean([pyfits.getval(f,'JD') for f in c1fs]) pyfits.setval(combfile,'JD',value=avgjd) print "average JD = " + str(avgjd) sumet = np.sum([pyfits.getval(f,'EXPTIME') for f in c1fs]) pyfits.setval(combfile,'EXPTIME',value=sumet) print "total EXPTIME = " + str(sumet) avgam = np.mean([pyfits.getval(f,'AIRMASS') for f in c1fs]) pyfits.setval(combfile,'AIRMASS',value=avgam) print "avg AIRMASS = " + str(avgam) iraf.cd('..') return specs