def get_wcs(self, warnings_filter='ignore'): ''' return wcs of input image ''' import warnings from astropy.wcs import WCS as wcs fhead=self.get_input_head() with warnings.catch_warnings(): warnings.simplefilter(warnings_filter) return wcs(fhead)
def get_pixscale(self): ''' get pixel scale of initial fits in unit of arcsec/pixel ''' fhead = self.get_fitsHead() with warnings.catch_warnings(): warnings.simplefilter("ignore") w = wcs(fhead) return np.average(pixel_scales(w)) * 3600 # arcsec/pixel
# scale of the datacube when plotting, e.g., [min, max], default is None colormap=None # colormap when plotting, e.g., 'rainbow', default is None row_col=[3, 3] # rows and columns of the panels in the figure, default is [3, 3] outfig=fitsfile # output eps file without suffix, default is fitsfile.pdf dat, hdr=ft.getdata(fitsfile+'.fits', header=True) hdr['NAXIS']=2 del hdr['NAXIS3'], hdr['PC3_1'], hdr['PC3_2'], hdr['PC1_3'], hdr['PC2_3'], hdr['PC3_3'] del hdr['CTYPE3'], hdr['CRVAL3'], hdr['CDELT3'], hdr['CRPIX3'], hdr['CUNIT3'] distance=1*1e3*u.pc # distance to the source, unit is 1e3*u.pc pixsz=np.mean(pixsc(wcs(hdr)))*u.deg # pixel size of the datacube, unit is u.deg """ import figure and subplot """ fig=plt.figure(figsize=figsize) for pltid in range(dat.shape[0]): ax=plt.subplot(row_col[0], row_col[1], pltid+1, projection=wcs(hdr)) plt.subplots_adjust(wspace=0, hspace=0) xaxis, yaxis, xyaxis=ax.coords[0], ax.coords[1], ax.coords """ axis labels and tick labels """ show=True if pltid==(row_col[0]-1)*row_col[1] else False xax_vis, yax_vis=show, show # whether to display the axis labels or not, defaut is True xtk_vis, ytk_vis=show, show # whether to display the tick labels or not, defaut is True
hdr = ft.getheader(fitsfile + '.fits') unit = [hdr['cunit1'], hdr['cunit2'], hdr['cunit3']] for i in range(len(unit)): if unit[i] == 'km/s' or unit[i] == 'm/s': inax = i fac = 1e3 if unit[i] == 'km/s' else 1 else: inax = False if inax: dim[inax] = [i * 1e3 for i in dim[inax]] for i in range(len(dim)): if dim[i] != []: world = [hdr['crval1'], hdr['crval2'], hdr['crval3']] if inax: world[inax] = world[inax] * fac world[i] = dim[i] pixel = wcs(hdr).wcs_world2pix(world[0], world[1], world[2], 0) dim[i] = [int(round(pixel[i][0])), int(round(pixel[i][1]))] dim[i].sort() else: dim[i] = [0, hdr['naxis' + str(i + 1)] - 1] """ clip the new datacube """ if not olshow: dim.reverse() shape = [i[1] - i[0] + 1 for i in dim] dlpix = [i[0] for i in dim] subdat = np.zeros(tuple(shape)) dat = ft.getdata(fitsfile + '.fits') for i in range(shape[0]): for j in range(shape[1]): for k in range(shape[2]): subdat[i, j, k] = dat[i + dlpix[0], j + dlpix[1], k + dlpix[2]]
import numpy as np from astropy.io import fits as ft from spectral_cube import SpectralCube as sc from astropy.wcs import WCS as wcs fitsfile='' # without suffix spec=[] # in km/s nchan= # in channel rms=0 # in Jy/beam, default is 0 nexc=3 # pixels with value < -next*rms are excluded when doing moment0, default is 3/1.5 ncut=3 # pixel with value < ncut*integrated rms are set to be zero after doing moment0, default is 3/5 """ input normalization """ spec=[i*1e3 for i in spec] dat, hdr=ft.getdata(fitsfile+'.fits', header=True) pixel=wcs(hdr).wcs_world2pix(hdr['crval1'], hdr['crval2'], spec, 0) chans=[round(pixel[2][0]), round(pixel[2][1])] dchan=round(abs(chans[1]-chans[0])/nchan) for i in range(nchan): chans.insert(i+1, chans[i]+dchan) chans.pop() """ print information """ world=wcs(hdr).wcs_pix2world(hdr['crpix1'], hdr['crpix2'], chans, 0) spec=[i/1e3 for i in world[2]] dvelo=dchan*hdr['cdelt3'] print('Extraction of %i channels from %f km/s to %f km/s.' %(nchan, spec[0], spec[-1])) print('The width of each channel is %f km/s (%i times of spectral resolution).' %(dvelo, dchan)) print('The ranges of each channel are:') for i in range(len(spec)-1): print('%f km/s to %f km/s' %(spec[i], spec[i+1]))
fitsfile = '' # fitsfile without suffix figsize = None # size of the figure, e.g., [6.4, 4.8]/[8.0, 6.0], default is None scale = None # scale of the datacube when plotting, e.g., [min, max], default is None colormap = None # colormap when plotting, e.g., 'rainbow', default is None outfig = fitsfile # output figure file without suffix, default is fitsfile.pdf dat, hdr = ft.getdata(fitsfile + '.fits', header=True) distance = 1 * 1e3 * u.pc # distance to the source, unit is 1e3*u.pc pixsz = np.mean(pixsc(wcs(hdr))) * u.deg # pixel size of the datacube, unit is u.deg """ import figure and subplot """ fig = plt.figure(figsize=figsize) ax = plt.subplot(1, 1, 1, projection=wcs(hdr)) xaxis, yaxis, xyaxis = ax.coords[0], ax.coords[1], ax.coords """ axis labels and tick labels """ xax_vis, yax_vis = True, True # whether to display the axis labels or not, defaut is True xtk_vis, ytk_vis = True, True # whether to display the tick labels or not, defaut is True xpad, ypad = 1.0, 1.0 # distance between axis labels and tick labels, defaut is 1.0 xsize, ysize = 'medium', 'medium' # size of the labels, e.g., 'x-small'/'small'/'medium'/'large'/'x-large', defaut is 'medium' xweit, yweit = 'normal', 'normal'
fitfunc = None # fitting function, 'Plummer', 'Gaussian' or 'Both', default is None bgdegree = 0 # polynomial order used in background subtraction, 0 or 1, default is 0 bgdist = None # radial range used in background subtraction, like (0.3,0.5), unit is pc, default is None fitdist_pm = 0.1 # radial range in which to fit the profile using 'Plummer', unit is pc, default is 0.1 fitdist_gs = 0.1 # radial range in which to fit the profile using 'Gaussian', unit is pc, default is 0.1 """ inputs """ fil_image, fil_header = ft.getdata(fitsfile + '.fits', header=True) if fits_err is not None: err_image, err_header = ft.getdata(fits_err + '.fits', header=True) fil_path = ascii.read(pathfile + '.path', format='fixed_width', names=['x', 'y']) fil_path_x, fil_path_y = [i for i in fil_path['x']], [j for j in fil_path['y']] path_pixel = wcs(fil_header).wcs_world2pix(fil_path_x, fil_path_y, 0) fil_path = np.zeros_like(fil_image) for i in range(path_pixel[0].shape[0]): fil_path[int(round(path_pixel[1][i])), int(round(path_pixel[0][i]))] = 1.0 fil_path = fil_path.astype(bool) major_fwhm = fil_header['bmaj'] * 3600 minor_fwhm = fil_header['bmin'] * 3600 beam_fwhm = np.sqrt(major_fwhm * minor_fwhm) """ mask and sample """ radobjmk = radfil_class.radfil(fil_image, filspine=fil_path, header=fil_header, beamwidth=beam_fwhm, distance=distance * 1e3) radobjmk.build_profile(samp_int=step, cutdist=width * radobjmk.imgscale.value)
def clus_get_xid(maps, cats, savemap=0, simmap=0, verbose=1, confusionerrors=1): err = False thresh = 3.0 mf = 1.0 mJy2Jy = 1000.0 / mf catfile = config.CLUSDATA + 'placeholder' #this doesn't actually seem to do anything in the xid code, # but you need something for this for some reason. #Old code not used anymore # print('Retrieving data from cats') # inra = [] # indec = [] # for i in range(len(cats)): # for j in range(len(cats[i]['ra'])): # if cats[i]['ra'][j] not in inra and cats[i]['dec'][j] not in indec: # inra.append(cats[i]['ra'][j]) # indec.append(cats[i]['dec'][j]) # print('Done retrieving data from cats') inra = np.array(cats['ra']) indec = np.array(cats['dec']) ra = inra * u.deg dec = indec * u.deg c = SkyCoord(ra, dec, unit='deg') plt.scatter(ra, dec, c=cats['flux'], alpha=0.5) plt.show() print(inra) #initializing data containers. pinds = [] files = [] primary_hdus = [] noise_maps = [] data_maps = [] headers = [] pixsizes = [] prf_sizes = [] priors = [] prfs = [] for i in range(len(maps)): bands = [18, 25, 36] #units of arcseconds fwhm = bands[i] / maps[i]['pixsize'] #converts to arcseconds/pixel pixs = maps[i]['pixsize'] size = pixs * 5 moc = pymoc.util.catalog.catalog_to_moc(c, size, 15) #getting data from the fits files files.append(maps[i]['file']) hdul = fits.open(files[i]) headers.append(hdul[1].header) primary_hdus.append(hdul[0].header) img = hdul[1].data data_maps.append(img) noise_maps.append(hdul[2].data) pixsizes.append(maps[i]['pixsize']) prf_sizes.append(get_spire_beam_fwhm(maps[i]['band'])) pinds.append(np.arange(0, 101, 1) * 1.0 / pixsizes[i]) # print(maps[i]['file']) # print(pixsizes[i]) #setting up priors prior = xidplus.prior(data_maps[i], noise_maps[i], primary_hdus[i], headers[i], moc=moc) prior.prior_cat(inra, indec, catfile, moc=moc) prior.prior_bkg(-5.0, 5) #setting up prfs. # This prf doesnt quite look correct # In previous set up we needed to rebin to accuratly describe our beam sizes prf = Gaussian2DKernel( bands[i] / 2.355, x_size=101, y_size=101) #maybe x_size and y_size need to change. prf.normalize(mode='peak') prfs.append(prf.array) # print(prfs) exit() #appending prf to prior and setting point matrix prior.set_prf(prfs[i], pinds[i], pinds[i]) #prfs, xpinds, ypinds prior.get_pointing_matrix() prior.upper_lim_map() #appending prior to priors list. priors.append(prior) print('fitting %s sources' % (priors[0].nsrc)) print('using %s %s %s pixels' % (priors[0].snpix, priors[1].snpix, priors[2].snpix)) fit = SPIRE.all_bands( priors[0], priors[1], priors[2], iter=1000 ) #number of iterations should be at least 100 just set lower for testing. posterior = xidplus.posterior_stan(fit, [priors[0], priors[1], priors[2]]) # figs, fig = xidplus.plots.plot_Bayes_pval_map(priors, posterior) # print(type(figs)) #figs is list. # print(figs) #fig is matplotlib.figure.figure object. # print(type(fig)) # cols = ['PSW', 'PMW', 'PLW'] # counter = 0 # for figure in figs: # figure.save('xid_%s.png' %(cols[counter])) # counter += 1 # plt.imshow(figs) spire_cat = cat.create_SPIRE_cat(posterior, priors[0], priors[1], priors[2]) # spire_cat.writeto('xid_model_2_%s.fits' % (maps[0]['name'])) xid_data = spire_cat[1].data xid = [] #in units of mJy for fluxes and degrees for RA/DEC xid1 = { 'band': 'PSW', 'sra': xid_data.field('RA'), 'sdec': xid_data.field('DEC'), 'sflux': xid_data.field('F_SPIRE_250'), 'serr': xid_data.field( 'FErr_SPIRE_250_u' ), #there was also FErr_SPIRE_250_l don't know which to use. 'pflux': xid_data.field('F_SPIRE_250'), 'perr': xid_data.field('FErr_SPIRE_250_u'), 'model': None, 'mf': mf } #idk if perr and pflux is right there may be a conversion needed for pflux. #in mikes code it has pflux = output from xid / mJy2Jy. xid2 = { 'band': 'PMW', 'sra': xid_data.field('RA'), 'sdec': xid_data.field('DEC'), 'sflux': xid_data.field('F_SPIRE_350'), 'serr': xid_data.field('FErr_SPIRE_350_u'), 'pflux': xid_data.field('F_SPIRE_350'), 'perr': xid_data.field('FErr_SPIRE_350_u'), 'model': None, 'mf': mf } xid3 = { 'band': 'PLW', 'sra': xid_data.field('RA'), 'sdec': xid_data.field('DEC'), 'sflux': xid_data.field('F_SPIRE_500'), 'serr': xid_data.field('FErr_SPIRE_500_u'), 'pflux': xid_data.field('F_SPIRE_500'), 'perr': xid_data.field('FErr_SPIRE_500_u'), 'model': None, 'mf': mf } #there was another term in the dictionary sflux, pflux and sflux looked like maybe the same thing, but I'm not sure. #I left it out so if there are issues with that then it is because that is gone. xid.append(xid1) xid.append(xid2) xid.append(xid3) # models = create_model(maps, xid) # for i in range(len(xid)): # xid[i]['model'] = models[i] # # only look at data with a flux lower than 0.0 # for i in range(len(xid)): # whpl = [] # for j in range(xid[i]['model'].shape[0]): # for k in range(xid[i]['model'].shape[1]): # if xid[i]['pflux'][j] >= 0.0: # whpl.append(j) # whpl = np.array(whpl) # # xid[i]['sra'] = xid[i]['sra'][whpl] # xid[i]['sdec'] = xid[i]['sdec'][whpl] # xid[i]['x'] = xid[i]['x'][whpl] # xid[i]['y'] = xid[i]['y'][whpl] # xid[i]['sflux'] = xid[i]['sflux'][whpl] # xid[i]['serr'] = xid[i]['serr'][whpl] for i in range(len(xid)): ra = xid[i]['sra'] * u.deg dec = xid[i]['sdec'] * u.deg c = SkyCoord(ra, dec) #initializing w class. hdul = fits.open(maps[i]['file']) w = wcs(hdul[1].header) #converting ra/dec to pixel coords. px, py = skycoord_to_pixel(c, w) xid[i]['x'] = px xid[i]['y'] = py xid[i]['sra'] = xid[i]['sra'].tolist() xid[i]['sdec'] = xid[i]['sdec'].tolist() xid[i]['sflux'] = xid[i]['sflux'].tolist() xid[i]['serr'] = xid[i]['serr'].tolist() xid[i]['pflux'] = xid[i]['pflux'].tolist() xid[i]['perr'] = xid[i]['perr'].tolist() xid[i]['x'] = xid[i]['x'].tolist() xid[i]['y'] = xid[i]['y'].tolist() #saving to json file for further analysis. with open('xid_a0370_take_9_%s.json' % (xid[i]['band']), 'w') as f: #code for saving output to a file. json.dump(xid[i], f) #model = image_model(x,y, sflux, maps[i]['astr']['NAXIS'][0], maps[i]['astr']['NAXIS'][1], #maps[i]['psf']) #need to finish converting model over to python. # # if savemap: # outfile = config.CLUSSBOX + 'clus_get_xid_model_' + maps[i]['band'] + '.fit' # writefits(outfile, data=model, header_dict=maps[i]['shead']) return xid, err
box=','.join(box) else: ra=[0, ohdr['NAXIS1']-1] dec=[0, ohdr['NAXIS2']-1] box='' """ integrated range retrieval """ if axis=='ra': inax=1 elif axis=='dec': inax=2 elif axis=='spec': inax=3 dim=[ra,dec,spec] pixel=[ohdr['CRPIX1'], ohdr['CRPIX2'], ohdr['CRPIX3']] pixel[inax-1]=dim[inax-1] rlpix=pixel[inax-1] rlval=wcs(ohdr).wcs_pix2world(pixel[0], pixel[1], pixel[2], 0) rlval[2]=rlval[2]/1e3 rlval=list(rlval[inax-1]) """ moment """ importfits(fitsfile+'.fits', fitsfile+'.im', zeroblanks=True, overwrite=True) if os.path.isdir('./'+fitsfile+'_mom.im'): os.system('rm -f '+fitsfile+'_mom.im') immoments(fitsfile+'.im', moments=moment, axis=axis, chans=chans, box=box, includepix=inpix, excludepix=expix, outfile=fitsfile+'_mom.im') """ export and header fix """ exportfits(fitsfile+'_mom.im', fitsfile+'_mom.fits', velocity=True, dropstokes=True, stokeslast=False, overwrite=True) tdat, thdr=ft.getdata(fitsfile+'_mom.fits', header=True) if thdr['CUNIT3']=='m/s':