def make_flats(cubename, vrange=[0, 10], noisevrange=[-100, -50], suffix='_sub.fits', out_suffix=""): cubefile = pyfits.open(cubename + suffix) if not os.path.exists(cubename + suffix): raise IOError( "Missing file %s. This may be caused by a lack of starlink." % (cubename + suffix)) cubefile[0].header = _fix_ms_kms_header(cubefile[0].header) flathead = strip_headers.flatten_header(cubefile[0].header) integrated = cubes.integ(cubefile, vrange, zunits='wcs', dvmult=True)[0] if integrated.shape != cubefile[0].data.shape[1:]: raise ValueError( "Cube integrated to incorrect size. Major error. Badness.") flatimg = pyfits.PrimaryHDU(data=integrated, header=flathead) flatimg.writeto(cubename.replace("cube", "integrated") + out_suffix + ".fits", clobber=True) noise = cubes.integ(cubefile, noisevrange, average=np.std, zunits='wcs')[0] flatimg.data = noise flatimg.writeto(cubename.replace("cube", "noise") + out_suffix + ".fits", clobber=True) mincube = cubes.integ(cubefile, vrange, average=np.min, zunits='wcs')[0] flatimg.data = mincube flatimg.writeto(cubename.replace("cube", "min") + out_suffix + ".fits", clobber=True)
def integrate(vrange=vrange,suffix='_integrated.fits'): for fn in ['LimaBean_H2CO11_taucube.fits', 'LimaBean_H2CO11_taucube_claw.fits', 'LimaBean_H2CO22_taucube.fits',]: fn = datapath+fn hdu = fits.open(fn) hdr = hdu[0].header xarr = (np.arange(hdr['NAXIS3'])-hdr['CRPIX3']+1)*hdr['CDELT3']+hdr['CRVAL3'] xr = [np.argmin(np.abs(xarr-x)) for x in vrange] integ = hdu[0].data[xr[0]:xr[1],:,:].sum(axis=0) integ *= hdr['CDELT3'] fhdr = strip_headers.flatten_header(hdr) hdu[0].data = integ hdu[0].header = fhdr hdu.writeto(fn.replace(".fits",suffix),clobber=True)
def make_flats(cubename,vrange=[0,10],noisevrange=[-100,-50],suffix='_sub.fits', out_suffix=""): cubefile = pyfits.open(cubename+suffix) if not os.path.exists(cubename+suffix): raise IOError("Missing file %s. This may be caused by a lack of starlink." % (cubename+suffix)) cubefile[0].header = _fix_ms_kms_header(cubefile[0].header) flathead = strip_headers.flatten_header(cubefile[0].header) integrated = cubes.integ(cubefile,vrange,zunits='wcs',dvmult=True)[0] if integrated.shape != cubefile[0].data.shape[1:]: raise ValueError("Cube integrated to incorrect size. Major error. Badness.") flatimg = pyfits.PrimaryHDU(data=integrated,header=flathead) flatimg.writeto(cubename.replace("cube","integrated")+out_suffix+".fits", clobber=True) noise = cubes.integ(cubefile,noisevrange,average=np.std,zunits='wcs')[0] flatimg.data = noise flatimg.writeto(cubename.replace("cube","noise")+out_suffix+".fits", clobber=True) mincube = cubes.integ(cubefile,vrange,average=np.min,zunits='wcs')[0] flatimg.data = mincube flatimg.writeto(cubename.replace("cube","min")+out_suffix+".fits", clobber=True)
import re from paths import datapath_w51 as datapath from paths import figurepath as figpath from paths import h2co11taufn import paths import os #matplotlib.rc('text', usetex=True) #matplotlib.rcParams['text.latex.preamble'] = [r'\boldmath'] pl.mpl.rc_file(os.path.join(paths.source_root, 'plot_scripts/pubfiguresrc')) h2co11 = fits.open(h2co11taufn) co32 = fits.open(datapath+'w51_bieging_13co32.fits') #hdr = fits.getheader(datapath+'h2co_integ.fits') hdr = flatten_header(h2co11[0].header) cohdr = flatten_header(co32[0].header) h2co_45to55 = h2co11[0].data[95:105,:,:].sum(axis=0) h2co_55to60 = h2co11[0].data[105:110,:,:].sum(axis=0) h2co_60to65 = h2co11[0].data[110:115,:,:].sum(axis=0) h2co_65to75 = h2co11[0].data[115:125,:,:].sum(axis=0) co_45to55 = co32[0].data[31:51,:,:].sum(axis=0) co_55to60 = co32[0].data[51:61,:,:].sum(axis=0) co_60to65 = co32[0].data[61:71,:,:].sum(axis=0) co_65to75 = co32[0].data[71:91,:,:].sum(axis=0) rgb = np.array([h2co_55to60,h2co_60to65,h2co_65to75]) L,H = np.nanmin(rgb),np.nanmax(rgb)
def spectral_grid(cube11=pyspeckit.Cube(datapath+'LimaBean_H2CO11_cube_sub.fits'), h213co11cube=pyspeckit.Cube(datapath+'LimaBean_H213CO_cube_sub.fits'), cube22=pyspeckit.Cube(datapath+'LimaBean_H2CO22_cube_sub_smoothtoCband.fits'), figure=pl.figure(1,figsize=(10,10)), yrange=(-2.1,0.5), nx=6, ny=6, dx=2, dy=2, xc=48, yc=45, xlabel="Velocity", ylabel="$T_A^*$ [K]$", ratio=False): for c in [cube11,h213co11cube,cube22]: c.xarr.convert_to_unit('km/s') def some_plots(xx,yy,dolegend=False): c13 = h213co11cube.get_spectrum(xx,yy) c12 = cube11.get_spectrum(xx,yy) c22 = cube22.get_spectrum(xx,yy) for c in (c12,c13,c22): c.plotter.autorefresh=False c12.baseline(exclude=[-225,200],order=5) c13.baseline(exclude=[-225,200],order=5) c13.plotter(label='H$_{2}$$^{13}$CO 1-1', axis=pl.gca(), color='b', alpha=0.5, refresh=False) c12.plotter(axis=c13.plotter.axis, clear=False, color='k', label="H$_{2}$CO 1-1", alpha=0.8, linewidth=1.5, refresh=False) #(c13*6).plotter(label='6$\\times$H$_{2}$$^{13}$CO',axis=pl.gca(),color='r',clear=False) c22.plotter(axis=c13.plotter.axis,clear=False,color='r',linewidth=2,alpha=0.5, label='H$_2$CO 2-2', refresh=False) if ratio: r = c12.copy() r.data = c22.data/c12.data r.data[(r.data>1)] = np.nan r.data[(r.data<1/13.)] = np.nan r.plotter(axis=c13.plotter.axis,clear=False,color='r', refresh=False) if dolegend: pl.legend(loc='best') pl.gca().set_xlim(-100,100) pl.clf() pl.subplots_adjust(wspace=0,hspace=0,left=0.05,right=0.95,bottom=0.05,top=0.95) #nx,ny = 6,6 #xc,yc = 52,48 # center #xc,yc = 45,42 # bottom left xl = xc - (nx/2.)*dx yl = yc - (ny/2.)*dy w = wcs.WCS(strip_headers.flatten_header(cube11.header)) for ii,(spy,spx) in enumerate(itertools.product(range(nx),range(ny))): sp = pl.subplot(nx,ny,ii+1) sp.zorder = nx-spx+ny*spy some_plots(spx*dx+xl,(ny-spy-1)*dy+yl,dolegend=False) # ,dolegend=(ii==24)) sp.set_ylim(*yrange) if spx > 0: sp.set_yticks([]) else: sp.set_yticks(sp.get_yticks()[1:]) if spy < ny-1: sp.set_xticks([]) else: sp.set_xticks(sp.get_xticks()[1:]) sp.set_xlabel("") sp.set_ylabel("") (l,b), = w.wcs_pix2world([[spx*dx+xl,(ny-spy-1)*dy+yl]],0) sp.annotate('%0.3f %+0.3f' % (l,b),(0.5,0.9),xycoords='axes fraction',fontsize=12, horizontalalignment='center') sp.xaxis.set_tick_params(labelsize=14) sp.yaxis.set_tick_params(labelsize=14) pl.figtext(0.5,0.01,xlabel) pl.figtext(-0.01,0.5,ylabel,rotation='vertical') pl.draw()
ratioF[0].header['BUNIT'] = 'log volume density' ratioF.writeto(datapath+'W51_H2CO11_to_22_logdensity_supersampled_textbg_sigma%0.1f.fits' % sigma, clobber=True) nfin = np.isfinite(ratio).sum(axis=0) ratio[:,nfin < 2] = np.nan from scipy.stats import nanmedian rmax = np.nanmax(ratio, axis=0)[None,:,:] rmin = np.nanmin(ratio, axis=0)[None,:,:] rmid = nanmedian(ratio, axis=0)[None,:,:] densc = fits.getdata(datapath+'W51_H2CO11_to_22_logdensity_supersampled_textbg_sigma%0.1f.fits' % sigma) dens_peak = np.nanmax(densc,axis=0) dens_peakf = fits.PrimaryHDU(data=dens_peak, header=flatten_header(header)) dens_peakf.writeto(datapath+'W51_H2CO_logdensity_textbg_peak.fits',clobber=True) d_rmaxprojection = ratio_to_dens_slow(rmax, cont11, cont22) d_rminprojection = ratio_to_dens_slow(rmin, cont11, cont22) d_rmidprojection = ratio_to_dens_slow(rmid, cont11, cont22) dens_rmaxf = fits.PrimaryHDU(data=d_rmaxprojection, header=flatten_header(header)) dens_rmaxf.writeto(datapath+'W51_H2CO_logdensity_textbg_max_ratio_sigma%0.1f.fits' % sigma,clobber=True) dens_rminf = fits.PrimaryHDU(data=d_rminprojection, header=flatten_header(header)) dens_rminf.writeto(datapath+'W51_H2CO_logdensity_textbg_min_ratio_sigma%0.1f.fits' % sigma,clobber=True) dens_rmidf = fits.PrimaryHDU(data=d_rmidprojection, header=flatten_header(header)) dens_rmidf.writeto(datapath+'W51_H2CO_logdensity_textbg_mid_ratio_sigma%0.1f.fits' % sigma,clobber=True) dens_rmaxf = fits.PrimaryHDU(data=rmax, header=flatten_header(header)) dens_rmaxf.writeto(datapath+'W51_H2CO_max_ratio.fits',clobber=True)
savefig('W51_H2CO_2parfittry11_v1_justdensity%s.png' % extrastr,bbox_inches='tight') dens1.show_markers(np.array(ysos['_Glon'][ysos['Cl1']=='I']), np.array(ysos['_Glat'][ysos['Cl1']=='I']), edgecolor='k',marker='x') dens1.show_markers(np.array(masers['GLON']), np.array(masers['GLAT']), marker='+',edgecolor='k') dens1.show_markers(glon,glat,marker='+',edgecolor='k') dens1.refresh() savefig('W51_H2CO_2parfittry11_v1_justdensity%s_withYSOs.png' % extrastr,bbox_inches='tight') column1 = 10**parcubefile[0].data[1] * parcubefile[0].data[5] column2 = 10**parcubefile[0].data[9] * parcubefile[0].data[13] totalcolumn = np.log10(column1 + column2) totalcolumn[totalcolumn == 0] = np.nan colhdu = fits.PrimaryHDU(data=totalcolumn, header=flatten_header(parcubefile[0].header)) pl.figure(4) pl.clf() tcol = FITSFigure(colhdu, figure=pl.figure(4)) tcol.show_colorscale(cmap=cmhot) tcol.colorbar._colorbar_axes.set_ylabel('log$_{10}$(N(H$_2$) cm$^{-2}$)') savefig('W51_H2CO_2parfittry11_totalcolumn.png', bbox_inches='tight') labels = {'dens':'log$_{10}$(n(H$_2$) cm$^{-3}$)', 'lindens':'n(H$_2$) [cm$^{-3}]$', 'velocity':'Velocity ($V_{LSR}$ km s$^{-1}$)', 'ratio':r'Ratio $\tau_{obs} 1-1 / \tau_{obs} 2-2$', 'width':'Line Width (km s$^{-1}$)', 'column':'log$_{10}$(N(H$_2$) cm$^{-2}$)'}
def spectral_grid(cube11=pyspeckit.Cube(datapath+'W51_H2CO11_taucube_supersampled.fits'), h213co11cube=pyspeckit.Cube(datapath+'W51_H213CO11_taucube_supersampled.fits'), cube22=pyspeckit.Cube(datapath+'W51_H2CO22_pyproc_taucube_lores_supersampled.fits'), figure=pl.figure(1,figsize=(10,10)), yrange=(-2.1,0.5), vrange=(40,80), ratio=False, nx=6, ny=6, dx=4, dy=4, xc=94, yc=75, baseline=False ): for c in [cube11,cube22]: # h213cocube c.xarr.convert_to_unit('km/s') def some_plots(xx,yy,dolegend=False): c13 = h213co11cube.get_spectrum(xx,yy) c12 = cube11.get_spectrum(xx,yy) c22 = cube22.get_spectrum(xx,yy) for c in (c12,c22):# c13, c.plotter.autorefresh=False if baseline: c12.baseline(exclude=[-225,200],order=5) c13.baseline(exclude=[-225,200],order=5) c13.plotter(label='H$_{2}$$^{13}$CO 1-1',axis=pl.gca(),color='b',alpha=0.5) #c12.plotter(axis=c13.plotter.axis,clear=False,color='k',label="H$_{2}$CO 1-1") c12.plotter(axis=pl.gca(),color='k',label="H$_{2}$CO 1-1") #(c13*6).plotter(label='6$\\times$H$_{2}$$^{13}$CO',axis=pl.gca(),color='r',clear=False) c22.plotter(axis=c12.plotter.axis,clear=False,color='r',linewidth=2,alpha=0.8, label='H$_2$CO 2-2') if ratio: r = c12.copy() r.data = c22.data/c12.data r.data[(r.data>1)] = np.nan r.data[(r.data<1/13.)] = np.nan r.plotter(axis=c12.plotter.axis,clear=False,color='r') if dolegend: pl.legend(loc='best') pl.gca().set_xlim(*vrange) pl.clf() pl.subplots_adjust(wspace=0,hspace=0,left=0.05,right=0.95,bottom=0.05,top=0.95) xl = xc - (nx/2.)*dx yl = yc - (ny/2.)*dy w = wcs.WCS(strip_headers.flatten_header(cube11.header)) for ii,(spy,spx) in enumerate(itertools.product(range(nx),range(ny))): sp = pl.subplot(nx,ny,ii+1) sp.zorder = nx-spx+ny*spy some_plots(spx*dx+xl,(ny-spy-1)*dy+yl,dolegend=False)#,dolegend=(ii==24)) sp.set_ylim(*yrange) if spx > 0: sp.set_yticks([]) if spy < ny-1: sp.set_xticks([]) (l,b), = w.wcs_pix2world([[spx*dx+xl,(ny-spy-1)*dy+yl]],0) sp.annotate('%0.3f %+0.3f' % (l,b),(0.5,0.9),xycoords='axes fraction',fontsize=12, horizontalalignment='center') pl.draw()
reg_centers = {} for freq,fn in files.items(): if freq not in fluxes: fluxes[freq] = {} peaks[freq] = {} valleys[freq] = {} cutouts[freq] = {} mpfits[freq] = {} gpars[freq] = {} gparerrs[freq] = {} gfits[freq] = {} reg_centers[freq] = {} data = fits.getdata(fn).squeeze() header = flatten_header(fits.getheader(fn)) wcs = astropy.wcs.WCS(header).sub([astropy.wcs.WCSSUB_CELESTIAL]) beam = radio_beam.Beam.from_fits_header(header) beams[freq] = beam frequencies[freq] = header.get('CRVAL3') or header.get('ACRVAL3') if wcs.wcs.radesys == 'FK4' or wcs.wcs.equinox == 1950: (blx,bly),(tr_x,tr_y) = wcs.wcs_world2pix([(290.35090,14.42627),(290.34560,14.43126),],0) else: (blx,bly),(tr_x,tr_y) = wcs.wcs_world2pix([(290.92445,14.524376),(290.91912,14.529338)],0) error[freq] = data[bly:tr_y,blx:tr_x].std() obsdate[freq] = fits.getheader(fn)['DATE-OBS'] print("file: {0}".format(fn)) for reg in ProgressBar(reglist):