def credit(frameid): if os.path.exists(frameid + '.cr_org.fits'): print(frameid + '.cr_org.fits exists. ' + 'No need to backup the original file.') else: print('Copying ' + frameid + '.cr.fits to ' + frameid + '.cr_org.fits') shutil.copy(frameid + '.cr.fits', frameid + '.cr_org.fits') if os.path.exists(frameid + '.mask_org.fits'): print(frameid + '.mask_org.fits exists. ' + 'No need to backup the original file.') else: print('Copying ' + frameid + '.mask.fits to ' + frameid + '.mask_org.fits') shutil.copy(frameid + '.mask.fits', frameid + '.mask_org.fits') iraf.set(stdimage='imt8192') iraf.imedit( frameid + '.cr.fits', command='display $image 1 erase=$erase fill=no order=0 >& dev$null') data_ov = fits.getdata(frameid + '.ov.fits') data_cr = fits.getdata(frameid + '.cr.fits') hdl_mask = fits.open(frameid + '.mask.fits', mode='update') data_temp = data_ov - data_cr np.seterr(invalid='ignore') # ignore RuntimeWarning in dividing 0 by 0. hdl_mask[0].data = np.nan_to_num(data_temp / data_temp) hdl_mask.close() return
def maskImages(filename): #Read in the full width half maximum from the input file imageHeader = fits.open(filename+".fits")[0] fwhm = imageHeader.header['SEEING'] ######CONFIG STUFF###### z1_default=-12 #Change this value to alter the low end of the image display z2_default=1000 #Change this value to alter the high end of the image display ztrans_default='log' #Change this to 'log' to use a logarithmic intensity plot in the display of the R image iraf.imedit.radius=3.0*fwhm #Change this value to change imedit's default radius. ######################## #Determine if a masked R image exists; create one if it does not. maskedExists=False try: with open(filename+'Masked.fits'):maskedExists=True except IOError: print 'The masked file does not exist. Creating masked file...' mask = fits.getdata(filename+'MaskReversed.fits') base = fits.getdata(filename+'.fits') result = np.multiply(base,mask) hdu=fits.PrimaryHDU(result) hdulist = fits.HDUList([hdu]) hdulist.writeto(filename+'Masked.fits') print 'Masked file written as testDataMasked.fits' #Display the image's Ha counterpart iraf.display(filename+'_Ha.fits',2) #Set the display parameters for the R image iraf.display.z1=z1_default iraf.display.z2=z2_defulat iraf.display.ztrans=ztrans_default iraf.imedit.command="display $image 1 erase=$erase fill=no order=0 >& dev$null" #Determine if a handmasked image exists handmaskedExists=False try: with open(filename+'_Handmasked.fits'):handmaskedExists=True print 'Handmasked image detected, loading it for further editing...' except IOError: print 'Creating new handmask image...' #Print some useful commands print 'Here are some pertinent commands used in imedit\ne Fill circles with constant value\n+/- increase/decrease radius\nk Fill circles with input data (spot healing, essentially)\nu Undo the last change\nq Finish editing the image and write the output\nQ Finish editing without writing output\ni Reset editor to initial loaded image' #if a handmasked image does not exist, load the R image for editing otherwise load the handmask to edit it. iraf.display.zscale='no' iraf.display.zrange='no' if (not handmaskedExists): iraf.imedit(filename+'Masked.fits',filename+'_Handmasked.fits') else: iraf.imedit(filename+'_Handmasked.fits','') #Repeat the process for Ha. print 'Mask Ha. Same commands apply' haHandmaskedExists=False iraf.display.zscale='yes' iraf.display.zrange='yes'
#Repeat the process for Ha. print 'Mask Ha. Same commands apply' haHandmaskedExists=False iraf.display.zscale='yes' iraf.display.zrange='yes' try: with open(filename+'_HaHandmasked.fits'):haHandmaskedExists=True print 'Ha handmasked image detected, loading it for further editing...' except IOError: print 'Creating new Ha handmask image...' iraf.display(filename+'Masked.fits',2) if (haHandmaskedExists): iraf.imedit(filename+'_HaHandmasked.fits','') else: iraf.imedit(filename+'_Ha.fits',filename+'_HaHandmasked.fits') #This reads through a handmasked set of R and Ha images and extracts the #masks from it, writing it as (filename)handmask.fits and (filename #)_HaHandmask.fits def getMasks(filename): #Delete the old masks, if any exist. iraf.imdelete(filename+'_Handmask.fits') iraf.imdelete(filename+'_HaHandmask.fits') #Extract the mask from the masked R image, using a handmasked image if one exists otherwise using the masked image maskValue = 0.0 try: maskedRImage = fits.getdata(filename+'_Handmasked.fits') except IOError:
def runellipse(files, xcenter, ycenter, minr, initialr, maxr, nframe=1): for i in range(len(files)): #for i in range(5): mfile = files[i] repeatflag = 1 while (repeatflag > 0.1): iraf.display(mfile, frame=nframe, fill='yes') outfile1 = 'm' + mfile print mfile print 'Running imedit to mask out other sources in the field:' print 'Enter b to mask out a circular region' print 'Enter a to mark the corners of a rectangle' print 'Enter q when finished' try: os.remove(outfile1) except OSError: print 'everything is ok' print 'running imedit ', mfile, outfile1 iraf.imedit(mfile, outfile1) t = mfile.split('.') efile = t[0] + '.tab' print 'Running ellipse to fit isophotes to galaxy:' print 'Enter h to continue fitting' try: os.remove(efile) except OSError: print 'everything is ok' iraf.ellipse(input=outfile1, output=efile, x0=xcenter, y0=ycenter, hcenter='yes', sma0=initialr, minsma=minr, maxsma=maxr) print 'Displaying isophotes. Hit q to quit' iraf.isoexam(table=efile) # try: # iraf.ellipse(input=outfile1,output=efile,x0=xcenter,y0=ycenter,hcenter='yes',sma0=initialr,minsma=minr,maxsma=maxr) # except: # print efile," already exists so I am deleting it. Hit Cntrl-c if you don't want to delete" # s='rm '+efile # os.system(s) # iraf.ellipse(input=outfile1,output=efile,x0=xcenter,y0=ycenter,hcenter='yes',sma0=initialr,minsma=minr,maxsma=maxr) flag = str( raw_input('Are you happy with the fit? y=yes n=no x=quit ')) flag = str(flag) print 'this is what I think you typed ', flag if flag.find('y') > -1: s = 'mv *' + t[0] + '* Finished/' os.system(s) repeatflag = 0 print 'i think repeatflag = 0', repeatflag if flag.find('n') > -1: s = 'rm *' + t[0] + '*.tab' os.system(s) s = 'rm m' + t[0] + '*.fits' os.system(s) repeatflag = 1 print 'i think repeatflag = 1', repeatflag if flag.find('x') > -1: repeatflag = 0 print 'i think repeatflag = 0', repeatflag return print 'repeatflag = ', repeatflag
def runimedit(mfile, outfile1, nframe): continueWithProgram = 1 continueWithObject = 1 repeatflag = 1 while (repeatflag > 0.1): iraf.display(mfile, frame=nframe, fill='yes') print mfile print 'Running imedit to mask out other sources in the field:' print 'Enter b to mask out a circular region' print 'Enter a to mark the corners of a rectangle' print 'Enter q when finished' try: os.remove(outfile1) except OSError: print 'everything is ok' print 'running imedit ', mfile, outfile1 iraf.imedit(mfile, outfile1) flag = str( raw_input( 'Are you happy with the editing? n=no x=quit y (or any other key) = yes ' )) flag = str(flag) print 'this is what I think you typed ', flag if flag.find('n') > -1: flag2 = str( raw_input( 'What is wrong? r=redo masking, o=nearby object, p=partial image, x=quit ' )) if flag2.find('r') > -1: s = 'rm ' + outfile1 os.system(s) repeatflag = 1 print 'i think repeatflag = 1 ', repeatflag elif flag2.find('o') > -1: s = 'rm ' + outfile1 os.system(s) s = 'mv ' + isomfile + ' NearbyObjects/' os.system(s) continueWithObject = 0 return continueWithProgram, continueWithObject elif flag2.find('p') > -1: s = 'rm ' + outfile1 os.system(s) s = 'mv ' + mfile + ' PartialImages/' os.system(s) continueWithObject = 0 return continueWithProgram, continueWithObject elif flag2.find('x') > -1: continueWithProgram = 0 repeatflag = 0 print 'i think repeatflag = 0', repeatflag return continueWithProgram, continueWithObject else: repeatflag = 0 elif flag.find('x') > -1: print 'i think you want to exit' continueWithProgram = 0 repeatflag = 0 return continueWithProgram, continueWithObject else: repeatflag = 0 return continueWithProgram, continueWithObject
def runimedit(mfile,outfile1,nframe): continueWithProgram=1 continueWithObject=1 repeatflag=1 while (repeatflag > 0.1): iraf.display(mfile,frame=nframe, fill='yes') print mfile print 'Running imedit to mask out other sources in the field:' print 'Enter b to mask out a circular region' print 'Enter a to mark the corners of a rectangle' print 'Enter q when finished' try: os.remove(outfile1) except OSError: print 'everything is ok' print 'running imedit ',mfile, outfile1 iraf.imedit(mfile,outfile1) flag=str(raw_input('Are you happy with the editing? n=no x=quit y (or any other key) = yes ')) flag=str(flag) print 'this is what I think you typed ',flag if flag.find('n') > -1: flag2=str(raw_input('What is wrong? r=redo masking, o=nearby object, p=partial image, x=quit ')) if flag2.find('r') > -1: s='rm '+outfile1 os.system(s) repeatflag=1 print 'i think repeatflag = 1 ', repeatflag elif flag2.find('o') > -1: s='rm '+outfile1 os.system(s) s='mv '+mfile+' NearbyObjects/' os.system(s) continueWithObject=0 return continueWithProgram,continueWithObject elif flag2.find('p') > -1: s='rm '+outfile1 os.system(s) s='mv '+mfile+' PartialImages/' os.system(s) continueWithObject=0 return continueWithProgram,continueWithObject elif flag2.find('x') > -1: continueWithProgram=0 repeatflag=0 print 'i think repeatflag = 0', repeatflag return continueWithProgram,continueWithObject else: repeatflag=0 elif flag.find('x') > -1: print 'i think you want to exit' continueWithProgram=0 repeatflag=0 return continueWithProgram,continueWithObject else: repeatflag=0 return continueWithProgram,continueWithObject
def maskStars(imageName): #read in the fits data and header imageHeader = fits.open(imageName+".fits")[0] #Read in the skysigma, skyv, and seeing (fwhm) from the header and set up other relevant values sigma = imageHeader.header['SKYSIGMA'] threshold = 3.0 * sigma skyv = imageHeader.header['SKY'] fwhm = imageHeader.header['SEEING'] aper = 3.0 * fwhm annul = 5 * fwhm #Read in the galcut file galcut = open("galcut.file") galcutString = file.read(galcut) galcut.close() #Parse the galcut file into its variables galList = galcutString.split(' ') xCenter = float(galList[0]) yCenter = float(galList[1]) a = float(galList[2]) #Semimajor Axis eccent = float(galList[3]) #Eccentricity posAngle = float(galList[4]) #Position angle posAngleRad = (posAngle+90)*3.14159/180 b = a * eccent #Semiminor Axis na = -1*a nb = -1*b #Create a version of the r image with the sky added back in for the daofind procedure iraf.imdelete("withsky") iraf.imarith(imageName,'+',skyv,"withsky") # Load daophot package iraf.digiphot() iraf.daophot() print("A. Find stars using daofind") #DAOFIND searches the IRAF images image for local density maxima, # with a full-width half-maxima of datapars.fwhmpsf, and a peak # amplitude greater than findpars.threshold * datapars.sigma above # the local background, and writes a list of detected objects in the # file output. # Here we set the fwhm and sigma equal to those listed in the header. # We set the datamin to -3*sigma = -1*threshold defined above # The findpars.threshold is set to 4.5*sigma by default. You may have # to alter this value for images where too few/many stars are found. #Configure 'datapars', 'findpars', and 'daofind' iraf.datapars.fwhmpsf=fwhm iraf.datapars.sigma=sigma iraf.datapars.datamax='indef' iraf.datapars.datamin=(-1)*threshold iraf.datapars.ccdread='RDNOISE' iraf.datapars.gain="GAIN" iraf.datapars.exposure="EXPTIME" iraf.datapars.airmass="AIRMASS" iraf.datapars.filter="FILTER" iraf.datapars.obstime="TIME-OBS" iraf.findpars.threshold=4.5 iraf.findpars.roundhi=3 iraf.findpars.roundlo=-3 iraf.daofind.verify='no' iraf.daofind.verbose='no' #create the variable for the coordinate file allStars = imageName+'.coo' #Remove a previous coordinate file if one exists silentDelete(imageName+'.coo') #Find the stars in the aligned R image iraf.daofind("withsky",allStars) print("The file containing the data of the stars in the aligned R-image is ",allStars) print(" ") if os.path.getsize(allStars) > 2239 : print("B. Separate stars inside and outside galaxy") #Delete existing files for f in ("temp.file","maskfile","maskfile.sat"): silentDelete(f) #Extract the coordinates from the allStars file, redirecting stdout to do so sys.stdout=open("temp.file","w") iraf.pdump(allStars,"xcenter,ycenter",'yes') sys.stdout = sys.__stdout__ #Read the file to get the xy coordinate pairs in a list coords = open("temp.file") coordList = list(coords) countout=0 #Create strings of xy pairs to write to files outGalString = "" for pair in coordList: #for each entry in the list, parse it into xy value integer pairs values = pair.split(" ") x = float(values[0]) y = float(values[1]) #Determine if the star lies within the galaxy-centered ellipse inGalaxy = False deltaX = x - xCenter deltaY = y - yCenter cdx = abs(deltaX) cdy = abs(deltaY) if (cdx < a and cdy < a): xt=(deltaX*math.cos(posAngleRad))+(deltaY*math.sin(posAngleRad)) yt=(deltaY*math.cos(posAngleRad))-(deltaX*math.sin(posAngleRad)) if(xt <= a and xt >= na and yt <= b and yt >= nb): inGalaxy = True if (not inGalaxy): outGalString += str(x) + " " + str(y) + "\n" countout=countout+1 #Write the coordinate list to a file mask = open("maskfile","w") mask.write(outGalString) mask.close() print('') print(" ",countout," stars found outside galaxy") print('') if countout!=0 : print("C. Do photometry to find saturated stars") for f in ("maskfile.mag","maskfile.satmag","maskfile.sat"): silentDelete(f) #Configure 'centerpars', 'fitskypars','photpars' iraf.datapars.datamax=150000 iraf.datapars.datamin='indef' iraf.centerpars.calgorithm="none" iraf.fitskypars.salgorithm="mode" iraf.fitskypars.annulus=annul iraf.fitskypars.dannulus=10 iraf.photpars.apertures=fwhm iraf.phot.verify='no' iraf.phot.verbose='no' #Call 'phot' to get the data of the stars iraf.phot (imageName,"maskfile","maskfile.mag") boexpr="PIER==305" iraf.pselect("maskfile.mag","maskfile.satmag",boexpr) sys.stdout=open("maskfile.sat","w") iraf.pdump("maskfile.satmag","xcenter,ycenter","yes") sys.stdout = sys.__stdout__ print("D. Make mask of stars outside galaxy") #Delete the rmask if one exists silentDelete("rmask.fits") #Configure 'imedit' iraf.imedit.cursor="maskfile" iraf.imedit.display='no' iraf.imedit.autodisplay='no' iraf.imedit.aperture="circular" iraf.imedit.value=-1000 iraf.imedit.default="e" #Replace the pixel values near the star coordinates with value -1000 using imedit iraf.imedit(imageName,"redit",radius=aper) iraf.imcopy.verbose='no' #Do the same for the saturated stars, but with larger apertures satMaskSize = os.path.getsize("maskfile.sat") if satMaskSize < 1 : print(" No saturated stars found") if (satMaskSize!=0): iraf.imedit.cursor="maskfile.sat" iraf.imedit.radius=2*aper iraf.imedit("redit","rmask") else: iraf.imcopy("redit","rmask") #Replace good pixels with value 0 in 'rmask' iraf.imreplace.lower=-999 iraf.imreplace.upper='indef' iraf.imreplace("rmask",0) #Replace bad pixels with value 1 in 'rmask' iraf.imreplace.lower='indef' iraf.imreplace.upper=-1000 iraf.imreplace("rmask",1) #Remove the mask file if one already exists silentDelete(imageName+"mask.fits") iraf.imcopy("rmask",imageName+"mask") print(" ") print("The mask image is ",imageName+"mask") print("The masked image is ",imageName+"Masked") print(" ") else : print("No stars found outside galaxy, no mask created.") if os.path.getsize(allStars) < 2314 : print("No stars found, no mask created.") #Delete intermediate images for f in ("rmask.fits","redit.fits","maskimage.fits","maskfile.mag","maskfile.satmag","temp.file","withsky.fits","mask.fits"): silentDelete(f)
def maskStars(imageName): #read in the fits data and header imageHeader = fits.open(imageName + ".fits")[0] #Read in the skysigma, skyv, and seeing (fwhm) from the header and set up other relevant values sigma = imageHeader.header['SKYSIGMA'] threshold = 3.0 * sigma skyv = imageHeader.header['SKY'] fwhm = imageHeader.header['SEEING'] aper = 3.0 * fwhm annul = 5 * fwhm #Read in the galcut file galcut = open("galcut.file") galcutString = file.read(galcut) galcut.close() #Parse the galcut file into its variables galList = galcutString.split(' ') xCenter = float(galList[0]) yCenter = float(galList[1]) a = float(galList[2]) #Semimajor Axis eccent = float(galList[3]) #Eccentricity posAngle = float(galList[4]) #Position angle posAngleRad = (posAngle + 90) * 3.14159 / 180 b = a * eccent #Semiminor Axis na = -1 * a nb = -1 * b #Create a version of the r image with the sky added back in for the daofind procedure iraf.imdelete("withsky") iraf.imarith(imageName, '+', skyv, "withsky") # Load daophot package iraf.digiphot() iraf.daophot() print("A. Find stars using daofind") #DAOFIND searches the IRAF images image for local density maxima, # with a full-width half-maxima of datapars.fwhmpsf, and a peak # amplitude greater than findpars.threshold * datapars.sigma above # the local background, and writes a list of detected objects in the # file output. # Here we set the fwhm and sigma equal to those listed in the header. # We set the datamin to -3*sigma = -1*threshold defined above # The findpars.threshold is set to 4.5*sigma by default. You may have # to alter this value for images where too few/many stars are found. #Configure 'datapars', 'findpars', and 'daofind' iraf.datapars.fwhmpsf = fwhm iraf.datapars.sigma = sigma iraf.datapars.datamax = 'indef' iraf.datapars.datamin = (-1) * threshold iraf.datapars.ccdread = 'RDNOISE' iraf.datapars.gain = "GAIN" iraf.datapars.exposure = "EXPTIME" iraf.datapars.airmass = "AIRMASS" iraf.datapars.filter = "FILTER" iraf.datapars.obstime = "TIME-OBS" iraf.findpars.threshold = 4.5 iraf.findpars.roundhi = 3 iraf.findpars.roundlo = -3 iraf.daofind.verify = 'no' iraf.daofind.verbose = 'no' #create the variable for the coordinate file allStars = imageName + '.coo' #Remove a previous coordinate file if one exists silentDelete(imageName + '.coo') #Find the stars in the aligned R image iraf.daofind("withsky", allStars) print( "The file containing the data of the stars in the aligned R-image is ", allStars) print(" ") if os.path.getsize(allStars) > 2239: print("B. Separate stars inside and outside galaxy") #Delete existing files for f in ("temp.file", "maskfile", "maskfile.sat"): silentDelete(f) #Extract the coordinates from the allStars file, redirecting stdout to do so sys.stdout = open("temp.file", "w") iraf.pdump(allStars, "xcenter,ycenter", 'yes') sys.stdout = sys.__stdout__ #Read the file to get the xy coordinate pairs in a list coords = open("temp.file") coordList = list(coords) countout = 0 #Create strings of xy pairs to write to files outGalString = "" for pair in coordList: #for each entry in the list, parse it into xy value integer pairs values = pair.split(" ") x = float(values[0]) y = float(values[1]) #Determine if the star lies within the galaxy-centered ellipse inGalaxy = False deltaX = x - xCenter deltaY = y - yCenter cdx = abs(deltaX) cdy = abs(deltaY) if (cdx < a and cdy < a): xt = (deltaX * math.cos(posAngleRad)) + (deltaY * math.sin(posAngleRad)) yt = (deltaY * math.cos(posAngleRad)) - (deltaX * math.sin(posAngleRad)) if (xt <= a and xt >= na and yt <= b and yt >= nb): inGalaxy = True if (not inGalaxy): outGalString += str(x) + " " + str(y) + "\n" countout = countout + 1 #Write the coordinate list to a file mask = open("maskfile", "w") mask.write(outGalString) mask.close() print('') print(" ", countout, " stars found outside galaxy") print('') if countout != 0: print("C. Do photometry to find saturated stars") for f in ("maskfile.mag", "maskfile.satmag", "maskfile.sat"): silentDelete(f) #Configure 'centerpars', 'fitskypars','photpars' iraf.datapars.datamax = 150000 iraf.datapars.datamin = 'indef' iraf.centerpars.calgorithm = "none" iraf.fitskypars.salgorithm = "mode" iraf.fitskypars.annulus = annul iraf.fitskypars.dannulus = 10 iraf.photpars.apertures = fwhm iraf.phot.verify = 'no' iraf.phot.verbose = 'no' #Call 'phot' to get the data of the stars iraf.phot(imageName, "maskfile", "maskfile.mag") boexpr = "PIER==305" iraf.pselect("maskfile.mag", "maskfile.satmag", boexpr) sys.stdout = open("maskfile.sat", "w") iraf.pdump("maskfile.satmag", "xcenter,ycenter", "yes") sys.stdout = sys.__stdout__ print("D. Make mask of stars outside galaxy") #Delete the rmask if one exists silentDelete("rmask.fits") #Configure 'imedit' iraf.imedit.cursor = "maskfile" iraf.imedit.display = 'no' iraf.imedit.autodisplay = 'no' iraf.imedit.aperture = "circular" iraf.imedit.value = -1000 iraf.imedit.default = "e" #Replace the pixel values near the star coordinates with value -1000 using imedit iraf.imedit(imageName, "redit", radius=aper) iraf.imcopy.verbose = 'no' #Do the same for the saturated stars, but with larger apertures satMaskSize = os.path.getsize("maskfile.sat") if satMaskSize < 1: print(" No saturated stars found") if (satMaskSize != 0): iraf.imedit.cursor = "maskfile.sat" iraf.imedit.radius = 2 * aper iraf.imedit("redit", "rmask") else: iraf.imcopy("redit", "rmask") #Replace good pixels with value 0 in 'rmask' iraf.imreplace.lower = -999 iraf.imreplace.upper = 'indef' iraf.imreplace("rmask", 0) #Replace bad pixels with value 1 in 'rmask' iraf.imreplace.lower = 'indef' iraf.imreplace.upper = -1000 iraf.imreplace("rmask", 1) #Remove the mask file if one already exists silentDelete(imageName + "mask.fits") iraf.imcopy("rmask", imageName + "mask") print(" ") print("The mask image is ", imageName + "mask") print("The masked image is ", imageName + "Masked") print(" ") else: print("No stars found outside galaxy, no mask created.") if os.path.getsize(allStars) < 2314: print("No stars found, no mask created.") #Delete intermediate images for f in ("rmask.fits", "redit.fits", "maskimage.fits", "maskfile.mag", "maskfile.satmag", "temp.file", "withsky.fits", "mask.fits"): silentDelete(f)