def main(): if len(sys.argv[1:]) <= 5: print ('Missing arguments') print ("Usage: %s [Image] [X] [Y] [MagZpt] [Box Size] [--sky Sky] [--m Mask] " % (sys.argv[0])) print ("Example: %s image.fits 1000 1050 25 50 --sky 0.5 --m mask.fits" % (sys.argv[0])) print ("Example: %s image.fits 1000 1050 25 50 --sky 0.5" % (sys.argv[0])) print ("Example: %s image.fits 1000 1050 25 100 " % (sys.argv[0])) sys.exit() flagsky=False flageven=False flagmask=False imgname= sys.argv[1] maskfile ="none" mgeoutfile="psfmge.txt" sky=0 X = np.float(sys.argv[2]) Y = np.float(sys.argv[3]) mgzpt= sys.argv[4] mgzpt=np.float(mgzpt) boxsize= np.float(sys.argv[5]) boxsize=np.int(np.round(boxsize)) if boxsize % 2 == 0: flageven=True #################################### ##################################### # init values OptionHandleList = ['--sky', '--m'] options = {} for OptionHandle in OptionHandleList: options[OptionHandle[2:]] = sys.argv[sys.argv.index(OptionHandle)] if OptionHandle in sys.argv else None if options['sky'] != None: flagsky=True if options['m'] != None: flagmask=True ################################ if flagsky == True: opt={} OptionHandle="--sky" opt[OptionHandle[2:]] = sys.argv[sys.argv.index(OptionHandle)+1] sky=np.float(opt['sky']) if flagmask == True: opt={} OptionHandle="--m" opt[OptionHandle[2:]] = sys.argv[sys.argv.index(OptionHandle)+1] maskfile=opt['m'] ################################################ #################################### #################################### # exptime= sys.argv[3] # exptime=np.float(exptime) convbox=100 # sky=0.55 fit=1 fitsky=0 Z=0 xpos=367 ypos=357 anglegass=35.8 # scale = 0.0455 # arcsec/pixel scale = 0.68 # arcsec/pixel set to default ################################################### # Create GALFIT input file header to compute sky # ################################################### # imgname = "ngc4342.fits" if imgname.find(".") != -1: (TNAM, trash) = imgname.split(".") else: TNAM=imgname exptime = GetExpTime(imgname) ################## ################# # Here we use an accurate four gaussians MGE PSF for # the HST/WFPC2/F814W filter, taken from Table 3 of # Cappellari et al. (2002, ApJ, 578, 787) # sigmapsf = [0.494, 1.44, 4.71, 13.4] # In PC1 pixels # normpsf = [0.294, 0.559, 0.0813, 0.0657] # total(normpsf)=1 # ang=90-ang ###################### # sky=back ################# hdu = fits.open(imgname) img = hdu[0].data # skylev = 0.55 # counts/pixel minlevel = 0 # counts/pixel # minlevel = 2 # counts/pixel ngauss = 12 plt.clf() # f = find_galaxy(img, fraction=0.04, plot=1) eps,theta,xpeak,ypeak,back=StarSextractor(imgname,X,Y) print("star found at ",xpeak,ypeak) print("Ellipticity, Angle = ",eps,theta) xpos=xpeak ypos=ypeak if flagsky == True: img = img - sky # subtract sky print("Sky = ",sky) else: print("Sky = ",back) sky=back img = img - back # subtract sky # I have to switch x and y coordinates, don't ask me why xtemp=xpeak xpeak=ypeak ypeak=xtemp plt.clf() ################################ ######### Mask ############ if flagmask == True: errmsg="file {} does not exist".format(maskfile) assert os.path.isfile(maskfile), errmsg hdu = fits.open(maskfile) mask = hdu[0].data maskb=np.array(mask,dtype=bool) maskbt=maskb.T hdu.close() else: maskb=None ############################## ############################## # s = sectors_photometry(img, eps, theta, xpeak, ypeak, minlevel=minlevel, plot=1) s = sectors_photometry(img, eps, theta, xpeak, ypeak, badpixels=maskb, minlevel=minlevel,plot=1) # s = sectors_photometry(img, eps, theta, xpeak, ypeak, minlevel=minlevel, plot=1) plt.pause(2) # Allow plot to appear on the screen ########################### # m = mge_fit_sectors(s.radius, s.angle, s.counts, eps, # ngauss=ngauss, sigmapsf=sigmapsf, normpsf=normpsf, # scale=scale, plot=1, bulge_disk=0, linear=0) # m = mge_fit_sectors(s.radius, s.angle, s.counts, eps, # ngauss=ngauss, scale=scale, plot=1, bulge_disk=0, linear=0) plt.clf() m = mge_fit_sectors(s.radius, s.angle, s.counts, eps, ngauss=ngauss, scale=scale, bulge_disk=0, linear=0,plot=1) plt.pause(2) # Allow plot to appear on the screen # print(len(m.sol.T)) # print(len(m.sol)) (counts,sigma,axisrat)=m.sol anglegass = 90 - theta hdu.close() ### print GALFIT files #################### ##################### parfile="psfgas.txt" outname=TNAM rmsname="none" psfname="none" consfile="constraints" T1 = "{}".format(imgname) T2 = outname + "-psf.fits" T3 = "{}".format(rmsname) # xlo=1 # ylo=1 # (xhi,yhi)=GetAxis(imgname) ## computing PSF size if flageven: xlo= xpos - boxsize/2 ylo= ypos - boxsize/2 xhi= xpos + boxsize/2 yhi= ypos + boxsize/2 xlo=np.int(np.round(xlo)) ylo=np.int(np.round(ylo)) xhi=np.int(np.round(xhi)) yhi=np.int(np.round(yhi)) else: xlo= xpeak - boxsize/2 + 0.5 ylo= ypeak - boxsize/2 + 0.5 xhi= xpeak + boxsize/2 + 0.5 yhi= ypeak + boxsize/2 + 0.5 xlo=np.int(np.round(xlo)) ylo=np.int(np.round(ylo)) xhi=np.int(np.round(xhi)) yhi=np.int(np.round(yhi)) # scale = 0.0455 fout1 = open(parfile, "w") fout2 = open(mgeoutfile, "w") PrintHeader(fout1, T1, T2, T3, psfname, 1, maskfile, consfile, xlo, xhi, ylo, yhi, convbox, convbox, mgzpt, scale, scale, "regular", 0, 0) index = 0 outline2 = "# counts Mag Sig(pixels) FWHM(pixels) q angle \n" fout2.write(outline2) # index+=1 while index < len(counts): TotCounts = counts[index] SigPix = sigma[index] qobs = axisrat[index] TotCounts=np.float(TotCounts) SigPix=np.float(SigPix) qobs=np.float(qobs) C0=TotCounts/(2*np.pi*qobs*SigPix**2) Ftot = 2*np.pi*SigPix**2*C0*qobs mgemag = mgzpt + 0.1 + 2.5*np.log10(exptime) - 2.5*np.log10(Ftot) FWHM = 2.35482 * SigPix # mgesb= mgzpt - 2.5*np.log10(mgecount/exptime) + 2.5*np.log10(plate**2) + 0.1 outline = "Counts: {:.2f} Mag: {:.2f} Sig: {:.2f} FWHM: {:.2f} q: {:.2f} angle: {:.2f} \n".format(TotCounts,mgemag, SigPix, FWHM, qobs, anglegass) print(outline) outline2 = "{:.2f} {:.2f} {:.2f} {:.2f} {:.2f} {:.2f} \n".format(TotCounts, mgemag, SigPix, FWHM, qobs, anglegass) fout2.write(outline2) PrintGauss(fout1, index, xpos, ypos, mgemag, FWHM, qobs, anglegass, Z, fit) index+=1 # sky removed as requested by GALFIT PrintSky(fout1, index, sky, 1, fitsky) fout1.close() fout2.close() print("Done. Run GALFIT as : 'galfit -o1 psfgas.txt' to create psf model ") print("or Run GALFIT as : 'galfit psfgas.txt' to adjust the mge psf model ") print("mge parameters are stored in {} ".format(mgeoutfile))
def MulEllipSectors(galpar, params, n_sectors=19, minlevel=0): badpixels = galpar.mask #it's already done #galpar.img = galpar.img - galpar.skylevel #galpar.model = galpar.model - galpar.skylevel fignum = 1 if badpixels is not None: errmsg = "file {} does not exist".format(badpixels) assert os.path.isfile(badpixels), errmsg hdu = fits.open(badpixels) mask = hdu[0].data maskb = np.array(mask, dtype=bool) maskbt = maskb.T hdu.close() else: maskb = None eps = 1 - galpar.q if params.dplot: plt.clf() print("") if params.flagranx[1] == True: (xmin, xmax) = params.ranx.split("-") xmin = np.float(xmin) xmax = np.float(xmax) if params.flagrany[1] == True: (ymin, ymax) = params.rany.split("-") ymin = np.float(ymin) ymax = np.float(ymax) ################### # I have to switch x and y values because they are different axes for # numpy xtemp = galpar.xc galpar.xc = galpar.yc galpar.yc = xtemp angsec = 90 - galpar.ang ###################### sg = sectors_photometry(galpar.img, eps, angsec, galpar.xc, galpar.yc, minlevel=minlevel, plot=False, badpixels=maskb, n_sectors=n_sectors) sm = sectors_photometry(galpar.model, eps, angsec, galpar.xc, galpar.yc, minlevel=minlevel, plot=False, badpixels=maskb, n_sectors=n_sectors) ################################################### stidx = np.argsort(sg.radius) # galaxy mgerad = sg.radius[stidx] mgecount = sg.counts[stidx] mgeangle = sg.angle[stidx] mgeanrad = np.deg2rad(mgeangle) # model stidx = np.argsort(sm.radius) mgemodrad = sm.radius[stidx] mgemodcount = sm.counts[stidx] mgemodangle = sm.angle[stidx] mgemodanrad = np.deg2rad(mgemodangle) # converting to pixels mgerad = mgerad * galpar.scale mgemodrad = mgemodrad * galpar.scale # formula according to cappellary mge manual # galaxy: mgesb = galpar.mgzpt - 2.5 * np.log10( mgecount / galpar.exptime) + 2.5 * np.log10(galpar.scale**2) + 0.1 # Model: mgemodsb = galpar.mgzpt - 2.5 * np.log10( mgemodcount / galpar.exptime) + 2.5 * np.log10(galpar.scale**2) + 0.1 if params.flagsub: wtemp = [] mgesbsub = [] mgeradsub = [] mgeanglesub = [] rsub = [] hdusub = fits.open(params.namesub) subimgs = [] cnt = 0 while (cnt < len(params.Comps)): if params.Comps[cnt] == True: imgsub = hdusub[cnt + 2].data subimgs.append(imgsub) cnt = cnt + 1 hdu.close() ############################### # galaxy: ab = galpar.q ni = 0 while (ni < params.N): subim = subimgs[ni] subcmp = sectors_photometry(subim, eps, angsec, galpar.xc, galpar.yc, minlevel=minlevel, plot=0, badpixels=maskb, n_sectors=n_sectors) subidx = np.argsort(subcmp.radius) temprad = subcmp.radius[subidx] #converting to arcsec temprad = temprad * galpar.scale mgecountsub = subcmp.counts[subidx] tempangle = subcmp.angle[subidx] mgeanradsub = np.deg2rad(tempangle) # formula according to cappellary mge manual tempmge = galpar.mgzpt - 2.5 * np.log10( mgecountsub / galpar.exptime) + 2.5 * np.log10(galpar.scale** 2) + 0.1 mgesbsub.append(tempmge) mgeradsub.append(temprad) mgeanglesub.append(tempangle) ni += 1 minrad = np.min(mgerad) if params.flagranx[1] == False: maxrad = np.max(mgerad) * params.ranx else: maxrad = np.max(mgerad) minsb = np.min(mgesb) maxsb = np.max(mgesb) xran = minrad * (maxrad / minrad)**np.array([-0.02, +1.02]) yran = minsb * (maxsb / minsb)**np.array([+1.05, -0.05]) if params.flagrany[1] == False: yran1 = yran[0] yran2 = yran[1] lyran = yran2 - yran1 yranmid = yran1 + lyran / 2 lyran = lyran * params.rany yran1 = yranmid - lyran / 2 yran2 = yranmid + lyran / 2 yran[0] = yran1 yran[1] = yran2 sectors = np.unique(mgeangle) n = sectors.size dn = int(round(n / 6.)) nrows = (n - 1) // dn + 1 # integer division plt.clf() fig, axsec = plt.subplots(nrows, 2, sharex=True, sharey='col', num=fignum) fig.subplots_adjust(hspace=0.01) if params.flagpix: axpix = axsec[0, 0].twiny() axpix2 = axsec[0, 1].twiny() fig.text(0.04, 0.5, 'Surface brightness', va='center', rotation='vertical') fig.text(0.96, 0.5, 'error (%)', va='center', rotation='vertical') axsec[-1, 0].set_xlabel("radius ('')") axsec[-1, 1].set_xlabel("radius ('')") if params.flaglogx == True: axsec[-1, 0].xaxis.set_major_locator(LogLocator(base=10.0, numticks=15)) if params.flagpix: axpix.set_xscale("log") axpix2.set_xscale("log") else: axsec[-1, 0].xaxis.set_minor_locator(AutoMinorLocator()) axsec[-1, 0].tick_params(which='both', width=2) axsec[-1, 0].tick_params(which='major', length=7) axsec[-1, 0].tick_params(which='minor', length=4, color='r') if params.flaglogx == True: axsec[-1, 0].xaxis.set_major_locator(LogLocator(base=10.0, numticks=15)) else: axsec[-1, 0].xaxis.set_minor_locator(AutoMinorLocator()) axsec[-1, 1].tick_params(which='both', width=2) axsec[-1, 1].tick_params(which='major', length=7) axsec[-1, 1].tick_params(which='minor', length=4, color='r') # row = 7 # old values row = nrows - 1 for j in range(0, n, dn): w = np.nonzero(mgeangle == sectors[j])[0] w = w[np.argsort(mgerad[w])] r = mgerad[w] wmod = np.nonzero(mgemodangle == sectors[j])[0] wmod = wmod[np.argsort(mgemodrad[wmod])] if (len(mgemodrad) < len(mgerad)): r2 = mgemodrad[wmod] else: wmod = w r2 = mgemodrad[wmod] txtang = sectors[j] txt = "$%.f^\circ$" % txtang if params.flagranx[1] == False: axsec[row, 0].set_xlim(xran) else: axsec[row, 0].set_xlim(xmin, xmax) if params.flagrany[1] == False: axsec[row, 0].set_ylim(yran) else: axsec[row, 0].set_ylim(ymax, ymin) #inverted if params.flaglogx == False: axsec[row, 0].plot(r, mgesb[w], 'C3o') axsec[row, 0].plot(r2, mgemodsb[wmod], 'C0-', linewidth=2) else: axsec[row, 0].semilogx(r, mgesb[w], 'C3o') axsec[row, 0].semilogx(r2, mgemodsb[wmod], 'C0-', linewidth=2) if params.flagrid == True: # Customize the major grid axsec[row, 0].grid(which='major', linestyle='-', linewidth='0.7', color='black') # Customize the minor grid axsec[row, 0].grid(which='minor', linestyle=':', linewidth='0.5', color='black') # axsec[row,0].grid(True) if params.flagsub == True: ii = 0 while (ii < params.N): wtemp = np.nonzero(mgeanglesub[ii] == sectors[j])[0] wtemp = wtemp[np.argsort(mgeradsub[ii][wtemp])] rtemp = mgeradsub[ii][wtemp] if params.flaglogx == False: axsec[row, 0].plot(rtemp, mgesbsub[ii][wtemp], '--', color='skyblue', linewidth=2) else: axsec[row, 0].semilogx(rtemp, mgesbsub[ii][wtemp], '--', color='skyblue', linewidth=2) ii += 1 axsec[row, 0].text(0.98, 0.95, txt, ha='right', va='top', transform=axsec[row, 0].transAxes) if (len(mgemodrad) < len(mgerad)): sberr = 1 - mgemodsb[wmod] / mgesb[wmod] axsec[row, 1].plot(r2, sberr * 100, 'C0o') else: sberr = 1 - mgemodsb[w] / mgesb[w] axsec[row, 1].plot(r, sberr * 100, 'C0o') axsec[row, 1].axhline(linestyle='--', color='C1', linewidth=2) axsec[row, 1].yaxis.tick_right() axsec[row, 1].yaxis.set_label_position("right") axsec[row, 1].set_ylim([-19.5, 20]) # axsec[row, 1].set_ylim([-20, 20]) if params.flagranx[1] == False: axsec[row, 1].set_xlim(xran) else: axsec[row, 1].set_xlim(xmin, xmax) axsec[row, 0].yaxis.set_minor_locator(AutoMinorLocator()) axsec[row, 0].tick_params(which='both', width=2) axsec[row, 0].tick_params(which='major', length=7) axsec[row, 0].tick_params(which='minor', length=4, color='r') axsec[row, 1].yaxis.set_minor_locator(AutoMinorLocator()) axsec[row, 1].tick_params(which='both', width=2) axsec[row, 1].tick_params(which='major', length=7) axsec[row, 1].tick_params(which='minor', length=4, color='r') row -= 1 if params.flagpix == True: axpix.set_xlabel("(pixels)") ##x1, x2 = axsec[7,0].get_xlim() if params.flagranx[1] == False: x1 = xran[0] x2 = xran[1] else: x1 = xmin x2 = xmax axpix.set_xlim(x1 / galpar.scale, x2 / galpar.scale) axpix.figure.canvas.draw() axpix2.set_xlabel("(pixels)") axpix2.set_xlim(x1 / galpar.scale, x2 / galpar.scale) axpix2.figure.canvas.draw() ## if params.flaglogx == True: axpix.xaxis.set_major_locator(LogLocator(base=10.0, numticks=15)) else: axpix.xaxis.set_minor_locator(AutoMinorLocator()) axpix.tick_params(which='both', width=2) axpix.tick_params(which='major', length=7) axpix.tick_params(which='minor', length=4, color='r') if params.flaglogx == True: axpix2.xaxis.set_major_locator(LogLocator(base=10.0, numticks=15)) else: axpix2.xaxis.set_minor_locator(AutoMinorLocator()) axpix2.tick_params(which='both', width=2) axpix2.tick_params(which='major', length=7) axpix2.tick_params(which='minor', length=4, color='r')
def EllipSectors(galpar, params, n_sectors=19, minlevel=0): badpixels = galpar.mask # removing background: galpar.img = galpar.img - galpar.skylevel galpar.model = galpar.model - galpar.skylevel xradm = [] ysbm = [] ysberrm = [] if badpixels is not None: errmsg = "file {} does not exist".format(badpixels) assert os.path.isfile(badpixels), errmsg hdu = fits.open(badpixels) mask = hdu[0].data maskb = np.array(mask, dtype=bool) maskbt = maskb.T hdu.close() else: maskb = None eps = 1 - galpar.q if params.dplot: plt.clf() print("") ############ # I have to switch x and y values because they are different axes for # numpy: yctemp = galpar.xc xctemp = galpar.yc # and angle is different as well: angsec = 90 - galpar.ang # angsec=ang ############################### # galaxy: g = sectors_photometry(galpar.img, eps, angsec, xctemp, yctemp, minlevel=minlevel, plot=params.dplot, badpixels=maskb, n_sectors=n_sectors) if params.dplot: plt.pause(1) # Allow plot to appear on the screen plt.savefig(params.namesec) ################################################### stidxg = np.argsort(g.radius) mgerad = g.radius[stidxg] mgecount = g.counts[stidxg] mgeangle = g.angle[stidxg] mgeanrad = np.deg2rad(mgeangle) ab = galpar.q aellabg = mgerad * np.sqrt((np.sin(mgeanrad)**2) / ab**2 + np.cos(mgeanrad)**2) #changing to arc sec aellarcg = aellabg * galpar.scale #### # formula according to cappellary mge manual: mgesbg = galpar.mgzpt - 2.5 * np.log10( mgecount / galpar.exptime) + 2.5 * np.log10(galpar.scale**2) + 0.1 #### stidxq = np.argsort(aellarcg) xarcg = aellarcg[stidxq] ymgeg = mgesbg[stidxq] ############# Function to order SB along X-axis xradq, ysbq, ysberrq = FindSB(xarcg, ymgeg, n_sectors) ################ ############################### # model: m = sectors_photometry(galpar.model, eps, angsec, xctemp, yctemp, minlevel=minlevel, plot=params.dplot, badpixels=maskb, n_sectors=n_sectors) if params.dplot: plt.pause(1) # Allow plot to appear on the screen plt.savefig(params.namemod) ################################################### stidxm = np.argsort(m.radius) mgerad = m.radius[stidxm] mgecount = m.counts[stidxm] mgeangle = m.angle[stidxm] mgeanrad = np.deg2rad(mgeangle) ab = galpar.q aellabm = mgerad * np.sqrt((np.sin(mgeanrad)**2) / ab**2 + np.cos(mgeanrad)**2) aellarcm = aellabm * galpar.scale # formula according to cappellary mge manual mgesbm = galpar.mgzpt - 2.5 * np.log10( mgecount / galpar.exptime) + 2.5 * np.log10(galpar.scale**2) + 0.1 ## stidxq = np.argsort(aellarcm) xarcm = aellarcm[stidxq] ymgem = mgesbm[stidxq] ###### Function to order SB along X-axis xradm, ysbm, ysberrm = FindSB(xarcm, ymgem, n_sectors) ################ Plotting limx, limy, axsec = PlotSB(xradq, ysbq, ysberrq, xradm, ysbm, ysberrm, params, galpar.scale) ### if params.flagout == True: OUTFH = open(params.output, "w") lineout = "# sectors_photometry used with pa={} q={} \n".format( galpar.ang, galpar.q) OUTFH.write(lineout) lineout = "# Galaxy Model \n" OUTFH.write(lineout) lineout = "# rad SB SBerr rad SB SBerr \n" OUTFH.write(lineout) lineout = "# (arcsec) (mag/arcsec) (error) (arcsec) (mag/arcsec) (error) \n" OUTFH.write(lineout) for idx, item in enumerate(xradq): if idx < len(xradm): lineout = "{0:.3f} {1:.3f} {2:.3f} {3:.3f} {4:.3f} {5:.3f} \n".format( xradq[idx], ysbq[idx], ysberrq[idx], xradm[idx], ysbm[idx], ysberrm[idx]) else: lineout = "{0:.3f} {1:.3f} {2:.3f} \n".format( xradq[idx], ysbq[idx], ysberrq[idx]) OUTFH.write(lineout) OUTFH.close() #### Creating Subcomponents images with Galfit params.Comps = [] if params.flagsub: print("running galfit to create subcomponents...") rungal = "galfit -o3 {}".format(params.galfile) errgal = sp.run([rungal], shell=True, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True) runchg = "mv subcomps.fits {}".format(params.namesub) errchg = sp.run([runchg], shell=True, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True) # read number of components params.Comps, params.N = ReadNComp(params.galfile, galpar.xc, galpar.yc) xradq, ysbq, n = SubComp(params.namesub, params.N, params.Comps, galpar.mgzpt, galpar.exptime, galpar.scale, galpar.xc, galpar.yc, galpar.q, galpar.ang, params.flagpix, axsec, skylevel=galpar.skylevel, n_sectors=n_sectors, badpixels=badpixels, minlevel=minlevel) axsec.legend(loc=1) return limx, limy
def SubComp(namesub, N, Comps, mgzpt, exptime, scale, xc, yc, q, ang, flagpix, axsec, skylevel=0, n_sectors=19, badpixels=None, minlevel=0): errmsg = "file {} does not exist".format(namesub) assert os.path.isfile(namesub), errmsg hdu = fits.open(namesub) subimgs = [] cnt = 0 # image =0 do not count while (cnt < len(Comps)): if Comps[cnt] == True: img = hdu[cnt + 2].data subimgs.append(img) cnt = cnt + 1 hdu.close() xradm = [] ysbm = [] ysberrm = [] if badpixels is not None: errmsg = "file {} does not exist".format(badpixels) assert os.path.isfile(badpixels), errmsg hdu = fits.open(badpixels) mask = hdu[0].data maskb = np.array(mask, dtype=bool) maskbt = maskb.T hdu.close() else: maskb = None eps = 1 - q ############ # I have to switch x and y values because they are different axes for # numpy: yctemp = xc xctemp = yc # and angle is different as well: angsec = 90 - ang #################### ab = q n = 0 while (n < N): subim = subimgs[n] scmp = sectors_photometry(subim, eps, angsec, xctemp, yctemp, minlevel=minlevel, plot=0, badpixels=maskb, n_sectors=n_sectors) ################################################### stidxg = np.argsort(scmp.radius) mgerad = scmp.radius[stidxg] mgecount = scmp.counts[stidxg] mgeangle = scmp.angle[stidxg] mgeanrad = np.deg2rad(mgeangle) aellabg = mgerad * np.sqrt((np.sin(mgeanrad)**2) / ab**2 + np.cos(mgeanrad)**2) #converting to arcsec aellarcg = aellabg * scale # formula according to cappellary mge manual mgesbg = mgzpt - 2.5 * np.log10(mgecount / exptime) + 2.5 * np.log10( scale**2) + 0.1 stidxq = np.argsort(aellarcg) xarcg = aellarcg[stidxq] ymgeg = mgesbg[stidxq] xradq, ysbq, ysberrq = FindSB(xarcg, ymgeg, n_sectors) PlotSub(xradq, ysbq, n, axsec) n = n + 1 return xradq, ysbq, n
def main(): if len(sys.argv[1:]) <= 6: print ('Missing arguments') print ("Usage: %s [Image] [X] [Y] [MagZpt] [PSF sigma or File] [Twist 1=yes 0=No] [-sky Sky] [-m Mask] " % (sys.argv[0])) print ("Example: %s image.fits 500 500 25 0.494 0" % (sys.argv[0])) print ("Example: %s image.fits 500 500 25 0.494 1 -sky 0.5 " % (sys.argv[0])) print ("Example: %s image.fits 500 500 25 0.494 1 -sky 0.5 -m mask.fits " % (sys.argv[0])) sys.exit() flagsky=False twist=False flagpsf=False flagconv=True imgname= sys.argv[1] flagmask=False maskfile="mask.fits" mgeoutfile="mgegasregu.txt" sky=0 X = np.float(sys.argv[2]) Y = np.float(sys.argv[3]) ########################################## ############################################ flaglogx=False flagq=False flagpa=False flagsub=False flaginit=False OptionHandleList = ['-m', '-sky'] options = {} for OptionHandle in OptionHandleList: options[OptionHandle[1:]] = sys.argv[sys.argv.index(OptionHandle)] if OptionHandle in sys.argv else None if options['m'] != None: flagmask=True if options['sky'] != None: flagsky=True ################################ if flagsky == True: opt={} OptionHandle="-sky" opt[OptionHandle[1:]] = sys.argv[sys.argv.index(OptionHandle)+1] sky=np.float(opt['sky']) if flagmask == True: opt={} OptionHandle="-m" opt[OptionHandle[1:]] = sys.argv[sys.argv.index(OptionHandle)+1] maskfile=np.str(opt['m']) ###################################### ###################################### if imgname.find(".") != -1: (timg, trash) = imgname.split(".") else: timg=imgname namepng=timg+".png" sectorspng="sectors.png" mgzpt= sys.argv[4] mgzpt=np.float(mgzpt) valpsf= sys.argv[5] # flagpsf = isinstance(valpsf,str) flagpsf=valpsf.replace(".",'',1).isdigit() if flagpsf == True: sigpsf=np.float(valpsf) if (np.abs(sigpsf) < 0.001 ): flagconv=False else: sigpsf,normpsf=ReadMgePsf(valpsf) twist = np.bool(np.int(sys.argv[6])) convbox=100 # sky=0.55 fit=1 skyfit=0 Z=0 xpos=367 ypos=357 anglegass=35.8 # scale = 0.0455 # arcsec/pixel scale = 0.68 # arcsec/pixel set to default ################################################### # Create GALFIT input file header to compute sky # ################################################### # imgname = "ngc4342.fits" if imgname.find(".") != -1: (TNAM, trash) = imgname.split(".") else: TNAM=imgname exptime = GetExpTime(imgname) ################## ################# # Here we use an accurate four gaussians MGE PSF for # the HST/WFPC2/F814W filter, taken from Table 3 of # Cappellari et al. (2002, ApJ, 578, 787) # sigmapsf = [0.494, 1.44, 4.71, 13.4] # In PC1 pixels # normpsf = [0.294, 0.559, 0.0813, 0.0657] # total(normpsf)=1 # ang=90-ang ###################### # Mask file ################# if flagmask: errmsg="file {} does not exist".format(maskfile) assert os.path.isfile(maskfile), errmsg hdu = fits.open(maskfile) mask = hdu[0].data maskb=np.array(mask,dtype=bool) maskbt=maskb.T hdu.close() ###################### # sky=back ################# hdu = fits.open(imgname) img = hdu[0].data img=img.astype(float) # skylev = 0.55 # counts/pixel minlevel = 15 # counts/pixel ngauss = 12 plt.clf() # f = find_galaxy(img, fraction=0.04, plot=1) # sextractor eps,theta,xpeak,ypeak,back=Sextractor(imgname,X,Y) print("galaxy found at ",xpeak,ypeak) print("Ellipticity, Angle = ",eps,theta) if flagsky == True: print("Sky = ",sky) else: print("Sky = ",back) sky=back # print(eps,theta,xpeak,ypeak) img -= sky # subtract sky # I have to switch x and y coordinates, don't ask me why xtemp=xpeak xpeak=ypeak ypeak=xtemp plt.clf() if twist: # Perform galaxy photometry if flagmask: s = sectors_photometry_twist(img, theta, xpeak, ypeak, minlevel=minlevel, badpixels=maskb ,plot=1) else: s = sectors_photometry_twist(img, theta, xpeak, ypeak, minlevel=minlevel, plot=1) plt.savefig(sectorspng) plt.pause(1) # Allow plot to appear on the screen plt.clf() # m = mge_fit_sectors_twist(s.radius, s.angle, s.counts, eps, ngauss=ngauss, # sigmapsf=sigmapsf,normpsf=normpsf, scale=scale, plot=1) if flagpsf == True: if flagconv: m = mge_fit_sectors_twist(s.radius, s.angle, s.counts, eps, ngauss=ngauss, sigmapsf=sigpsf, scale=scale, plot=1) else: print("No convolution") m = mge_fit_sectors_twist(s.radius, s.angle, s.counts, eps, ngauss=ngauss, scale=scale, plot=1) else: m = mge_fit_sectors_twist(s.radius, s.angle, s.counts, eps, ngauss=ngauss, sigmapsf=sigpsf, normpsf=normpsf ,scale=scale, plot=1) plt.pause(1) # Allow plot to appear on the screen plt.savefig(namepng) elif twist == False: if flagmask: s = sectors_photometry(img, eps, theta, xpeak, ypeak, minlevel=minlevel, badpixels=maskb ,plot=1) else: s = sectors_photometry(img, eps, theta, xpeak, ypeak, minlevel=minlevel, plot=1) # s = sectors_photometry(img, eps, theta, xpeak, ypeak, minlevel=minlevel, plot=1) plt.pause(1) # Allow plot to appear on the screen plt.savefig(sectorspng) ########################### # m = mge_fit_sectors(s.radius, s.angle, s.counts, eps, # ngauss=ngauss, sigmapsf=sigmapsf, normpsf=normpsf, # scale=scale, plot=1, bulge_disk=0, linear=0) plt.clf() if flagpsf == True: if flagconv: m = mge_fit_sectors(s.radius, s.angle, s.counts, eps, ngauss=ngauss, sigmapsf=sigpsf, scale=scale, plot=1, bulge_disk=0, linear=0) else: print("No convolution") m = mge_fit_sectors(s.radius, s.angle, s.counts, eps, ngauss=ngauss, scale=scale, plot=1, bulge_disk=0, linear=0) else: m = mge_fit_sectors(s.radius, s.angle, s.counts, eps, ngauss=ngauss, sigmapsf=sigpsf, normpsf=normpsf, scale=scale, plot=1, bulge_disk=0, linear=0) plt.pause(1) # Allow plot to appear on the screen plt.savefig(namepng) # print(len(m.sol.T)) # print(len(m.sol)) if twist: (counts,sigma,axisrat,pa)=m.sol # if flagsky: # alpha1= pa - f.pa # alphaf= 180 - alpha1 # else: theta2=270 -theta alpha1= pa - theta2 alphaf= alpha1 - 90 elif twist == False: (counts,sigma,axisrat)=m.sol # if flagsky: # anglegass = f.pa # - 90 # else: anglegass = 90 - theta # print(counts) # print(counts[0],sigma[0],axisrat[0]) ### print GALFIT files #################### ##################### parfile="MGEGALFITREGU.txt" outname=TNAM rmsname="none" psfname="none" # switch back xtemp=xpeak xpeak=ypeak ypeak=xtemp consfile="constraints" T1 = "{}".format(imgname) T2 = outname + "-mgeregu.fits" T3 = "{}".format(rmsname) xlo=1 ylo=1 (xhi,yhi)=GetAxis(imgname) # scale = 0.0455 fout1 = open(parfile, "w") fout2 = open(mgeoutfile, "w") outline2 = "# Mag Sig(pixels) FWHM(pixels) q angle \n" fout2.write(outline2) PrintHeader(fout1, T1, T2, T3, psfname, 1, maskfile, consfile, xlo, xhi, ylo, yhi, convbox, convbox, mgzpt, scale, scale, "regular", 0, 0) index = 0 # index+=1 while index < len(counts): TotCounts = counts[index] SigPix = sigma[index] qobs = axisrat[index] TotCounts=np.float(TotCounts) SigPix=np.float(SigPix) qobs=np.float(qobs) if twist: anglegass = alphaf[index] #- 90 anglegass=np.float(anglegass) C0=TotCounts/(2*np.pi*qobs*SigPix**2) Ftot = 2*np.pi*SigPix**2*C0*qobs mgemag = mgzpt + 0.1 + 2.5*np.log10(exptime) - 2.5*np.log10(Ftot) FWHM = 2.35482 * SigPix # mgesb= mgzpt - 2.5*np.log10(mgecount/exptime) + 2.5*np.log10(plate**2) + 0.1 outline = "Mag: {:.2f} Sig: {:.2f} FWHM: {:.2f} q: {:.2f} angle: {:.2f} \n".format(mgemag, SigPix, FWHM, qobs, anglegass) print(outline) outline2 = "{:.2f} {:.2f} {:.2f} {:.2f} {:.2f} \n".format(mgemag, SigPix, FWHM, qobs, anglegass) fout2.write(outline2) PrintGauss(fout1, index+1, xpeak, ypeak, mgemag, FWHM, qobs, anglegass, Z, fit) index+=1 PrintSky(fout1, index+1, sky, Z, skyfit) fout1.close() fout2.close() print("Done. Gaussians are stored in {}, and {} for galfit format ".format(mgeoutfile,parfile))