def plot_sky_projection_healpy_count(Sliced_Halo_data,nside): HEALPix_mode = read_data_bool(tag_name = 'HEALPix_Cartesian',file_name = 'parameters/Output_Parameters.xml') HEALPix_grat = read_data_bool(tag_name = 'HEALPix_Graticule',file_name = 'parameters/Output_Parameters.xml') fdir = './Output/plots/HEALPix/' Sl_n = len(Sliced_Halo_data) Z_max = max(Sliced_Halo_data[Sl_n-1].Z_red[:]) rc('text',usetex=True) for k in range(Sl_n): pix = zeros(12*nside**2) n = len(Sliced_Halo_data[k].RA[:]) for i in range(n): j = hp.ang2pix(nside,DtoR*(90.0-Sliced_Halo_data[k].DEC[i]),DtoR*Sliced_Halo_data[k].RA[i]) pix[j] += 1 clf() if (HEALPix_mode): hp.cartview(pix) else: hp.mollview(pix) if (HEALPix_grat): hp.graticule() fname = 'sky_projection_HEALPix_Count_%i_%i.pdf'%(nside,(k+1)) title(r'sky projection for redshift between %0.2f and %0.2f'%(Sliced_Halo_data[k].z_min,Sliced_Halo_data[k].z_max),fontsize = 20) print 'Saving plot', fname savefig(fdir+fname,bbox_inches='tight') rc('text',usetex=False) close() return 0
def plot_model1(qu, QU, mod, R_mod, mask, lab=''): plt.figure() plt.title('Data vs model {}'.format(lab)) plt.scatter(qu[0, mask], QU[0, mask], c='grey', marker='^', label='data') plt.scatter(qu[1, mask], QU[1, mask], c='skyblue', marker='^') plt.scatter(qu[0, mask], mod[0, mask], c='k', marker='.', label='model') plt.scatter(qu[1, mask], mod[1, mask], c='b', marker='.') plt.legend() plt.xlabel(r'$q, u$') plt.ylabel(r'$Q, U$ [MJy/sr]') plt.title('Plot data vs model') plt.savefig('Figures/Sampling/model_vs_data_sampler.png') # Residuals: res = residual(QU, mod, mask) print(np.shape(res)) hp.gnomview(res[0,:], title=r'Residuals, $\frac{Q_s - Q_m}{|Q_s|}$',\ cmap='bwr', min=-1, max=1, rot=[104,22.2], xsize=150) hp.graticule() plt.savefig('Figures/Sampling/Q_residuals.png') hp.gnomview(res[1,:], title=r'Residuals, $\frac{U_s - U_m}{|U_s|}$',\ cmap='bwr', min=-1, max=1, rot=[104, 22.2], xsize=150) hp.graticule() plt.savefig('Figures/Sampling/U_residuals.png')
def plot_zoom_sky(Output_Para,pix,pix_bool): rc('font',family='serif') from XCat_Objects import DtoR if (pix_bool): lon = Read_Float_Input("Please enter long (-180<long<180) : ") lat = Read_Float_Input("Please enter lati (-90<long<90) : ") rot = Read_Float_Input("Please enter rot (0<rot<360) : ") res = Read_Float_Input("Please enter resolution (in arcmin) : ") else: print "Please, first load a HEALPix map file ." raw_input("Press enter to continue ... ") return 0 plt.clf() hp.gnomview(pix, fig = 1, rot=(lon,lat,rot),reso = res) hp.graticule() plt.show() plt.close() save_ques = Read_YN_Input("Do you want to save its picture (please enter Y, y, N, or n)? ") if save_ques : rc('text',usetex=True) plt.clf() hp.gnomview(pix, fig = 1, rot=(lon,lat,rot),reso = res) hp.graticule() print 'Saving plot', fname plt.savefig(fdir+fname+'_zoom.pdf',bbox_inches='tight') # plt.savefig(fdir+fname+'.pdf') rc('text',usetex=False) plt.close()
def animation_path(sched,rot,title,*args, **kwargs): vid_title = "videos/"+title + ".mp4" hpy.mollview(title=title,rot=rot) hpy.graticule(verbose=0) points = hpy.projscatter(np.pi/2-sched[:,1],sched[:,0],lonlat=False,cmap="hsv",c=np.arange(np.size(sched,0)),*args, **kwargs) offto = points.get_offsets() arrayto = points.get_array() climto = points.get_clim() cmapto = points.get_cmap() plt.clf() hpy.mollview(title=title,rot=rot) hpy.graticule(verbose=0) points = hpy.projscatter([],[],lonlat=False,*args, **kwargs) fig = points.get_figure() points.set_clim(climto) points.set_cmap(cmapto) def animate(i,data,color): start_data = max(0,i-300) # start_data = 0 points.set_offsets(data[start_data:i,:]) points.set_array(color[start_data:i]) return points, anim = animation.FuncAnimation(fig, animate,fargs=(offto,arrayto),frames=np.size(offto,0), interval=20, blit=True) anim.save(vid_title)
def plot_mask(ra, dec, nside=2**10): pix = hp.pixelfunc.ang2pix(nside, dec, dec, lonlat=True) hp.visufunc.mollview(map=np.bincount(pix,minlength=hp.nside2npix(nside)), cbar=False, notext=True, max=1, min=0, title="", cmap="binary") hp.graticule() plt.show()
def draw_function(l, b, value, max, folder=None, title=None): ## s310, t211, v nside = 8 if folder is not None: folder = f"{folder}/{nside}" pix = compute_pixel(nside, np.degrees(l.values), np.degrees(b.values)) npix = hp.nside2npix(nside) bin_means, bin_edges, binnumber = scipy.stats.binned_statistic( pix, value, bins=npix, statistic='median') # hist, _ = np.histogram(bin_means, range=(0, npix), bins=(npix)) plt.clf() hp.mollview(bin_means, title=title, unit='медианное значение в пикселе', coord='G', min=-max, max=+max) hp.graticule() if folder is not None and title is not None: Path(folder).mkdir(parents=True, exist_ok=True) plt.savefig(f'{folder}/{title}.png') else: plt.show()
def plot(self, title='MOC', coord='C'): """ plot current instance using matplotlib coord can be 'C', 'G' or 'E' (respectively celestial, galactic or ecliptic) """ from matplotlib import pyplot as plt import healpy as hp # degrade to NORDER 8 if norder is greater if self.max_order > 8: plotted_moc = self.degrade_to_order(8) else: plotted_moc = self m = {} # partial HEALPix map for val in plotted_moc.best_res_pixels_iterator(): m[val] = 1 # ensure the map is at the correct nside max_ipix = hp.nside2npix(2**plotted_moc.max_order) - 1 if not max_ipix in m: m[max_ipix] = hp.pixelfunc.UNSEEN hp.mollview(m, nest=True, coord=['C', coord], title=title, cbar=False) hp.graticule() plt.show()
def test_calc_healpixels_for_region(): ahp = HEALPix(nside=NSIDE, order='ring', frame=TETE()) NPIX = hp.nside2npix(NSIDE) map = np.zeros(NPIX) test_regions = [NGC288_params] for region in test_regions: r = generate_sky_maps.CelestialRegion(region) r.calc_healpixels_for_region(ahp) map[r.pixels] += 1.0 # Approximate test: Compare the combined area of the HEALpixels to the # minimum (cartesian) area that the region should cover. # True area will always be greater. min_expected_area = np.pi * (NGC288_params['l_width'] * u.deg / 2.0)**2 healpix_area = len(r.pixels) * ahp.pixel_area assert healpix_area > min_expected_area.to(u.steradian) fig = plt.figure(1, (10, 10)) hp.mollview(map, title='Test of HEALpix regions') hp.graticule() plt.tight_layout() plt.savefig('test_cone_search_regions.png') plt.close(1)
def compute_visibility(self): # coord=SkyCoord(ra.flatten(),dec.flatten(),unit=u.deg) # m=Visibility().for_time("2016-10-09T17:31:06",coord=coord) # figure(figsize=(20,10)) # scatter(ra,dec,s=100,c=m,lw=0,alpha=0.4) visibility = Visibility() gwm = healpy.read_map(rootd + "/" + self.skymap) nsides = healpy.npix2nside(gwm.shape[0]) vmap = visibility.for_time(self.utc, nsides=nsides) healpy.mollview( gwm * (vmap * 2 - 1), title="visibility for INTEGRAL due to sun constrains\n" + self.utc) healpy.projscatter(self.ra, self.dec, lonlat=True) healpy.graticule() plot.plot(self.dir + "/visibility.png") healpy.write_map(self.dir + "/visibility.fits", vmap) source_theta = (90 - self.dec) / 180 * pi source_phi = (self.ra) / 180 * pi visibility = dict(probability_visible=sum(gwm * vmap), source_visible=vmap[healpy.ang2pix( nsides, source_theta, source_phi)]) json.dump(visibility, open(self.dir + "/visibility.json", "w"))
def display_stacked_image(self, smoothing_kernel_sigma=0.5): """ Display a map with all active analysis bins stacked together. :param smoothing_kernel_sigma: sigma for the Gaussian smoothing kernel to apply :return: a matplotlib.Figure instance """ # This is the resolution (i.e., the size of one pixel) of the image in arcmin resolution = 3.0 # The image is going to cover the diameter plus 20% padding xsize = self._get_optimal_xsize(resolution) active_planes_bins = [self._maptree[x] for x in self._active_planes] # Get the center of the projection for this plane this_ra, this_dec = self._roi.ra_dec_center # Healpix uses longitude between -180 and 180, while R.A. is between 0 and 360. We need to fix that: longitude = ra_to_longitude(this_ra) # Declination is already between -90 and 90 latitude = this_dec total = None for i, data_analysis_bin in enumerate(active_planes_bins): # Plot data background_map = data_analysis_bin.background_map.as_dense() this_data = data_analysis_bin.observation_map.as_dense( ) - background_map idx = np.isnan(this_data) # this_data[idx] = hp.UNSEEN if i == 0: total = this_data else: # Sum only when there is no UNSEEN, so that the UNSEEN pixels will stay UNSEEN total[~idx] += this_data[~idx] delta_coord = (self._roi.data_radius.to("deg").value * 2.0) / 15.0 fig, sub = plt.subplots(1, 1) proj = self._represent_healpix_map(fig, total, longitude, latitude, xsize, resolution, smoothing_kernel_sigma) cax = sub.imshow(proj, origin='lower') fig.colorbar(cax) sub.axis('off') hp.graticule(delta_coord, delta_coord) return fig
def plot_zoom(scan, ra, dec, title, reso=3, var="pVal", range=[0, 6], cmap=None): if cmap is None: pdf_palette = sns.color_palette("Blues", 500) cmap = mpl.colors.ListedColormap(pdf_palette) hp.gnomview(scan, rot=(np.degrees(ra), np.degrees(dec), 0), cmap=cmap, max=max(scan), reso=reso, title=title, notext=True, cbar=False #unit=r"" ) plt.plot(4.95 / 3. * reso * np.radians([-1, 1, 1, -1, -1]), 4.95 / 3. * reso * np.radians([1, 1, -1, -1, 1]), color="k", ls="-", lw=3) hp.graticule(verbose=False) plot_labels(dec, ra, reso)
def make_healpix_image(plt, img, title, num_bins, source_json=None): """ Writes out an image as a healpy image """ nside = hp.pixelfunc.get_min_valid_nside(num_bins*num_bins*3/4) npix = hp.nside2npix(nside) pixels = np.arange(npix) m = np.zeros(npix) + hp.UNSEEN window_d = np.degrees(hp.nside2resol(nside)) for i in pixels: theta, phi = hp.pix2ang(nside, i) if (theta < np.pi / 2): el = np.degrees(np.pi/2 - theta) az = np.degrees(phi) s = elaz.ElAz(el, az) x_min, x_max, y_min, y_max, area = s.get_px_window(num_bins, window_deg=window_d) s_px = img[y_min:y_max, x_min:x_max] m[i] = np.sum(s_px)/area hp.orthview(m, rot=(0, 90, 180), title=title, xsize=3000, cbar=False, half_sky=True) hp.graticule() if source_json is not None: src_list = elaz.from_json(source_json, el_limit=20.0, jy_limit=1e4) output_list = [] for s in src_list: l, m = s.get_lm() output_list.append(plt.Circle([-l, m], 0.03, color=(0.9, 0.2, 0.3), fill=False)) ax = plt.gca() for circle in output_list: ax.add_artist(circle)
def _generatePlot(self, table): coords, proj = self.__getCoordinatesAndProjection() fignum = 1 self.Plot.figure(num = fignum, tight_layout = True) pixels = self.__getPixelsData(table) #pixels = self.__getMaskedPixels(pixels) cmap = self.Plot.get_cmap(self.Configuration.getValueOf(ChartHealpixOptions.COLOURMAP, "jet")) cmap.set_under('w') healpy.mollview(pixels, fig = fignum, coord = [coords, proj], unit = 'mas', title = "", min = self.__Min, max = self.__Max, flip = 'astro', cbar = False, cmap = cmap, norm = self.__getNormalization(), nest = self.__nestedPixels()) healpy.graticule(dpar = 30, dmer = 30, coord = proj, local = None, linestyle = ':', color = 'white') healpy.projtext(0, 90, "90", lonlat = True, coord = proj, verticalalignment = 'bottom', horizontalalignment = 'center', fontsize = 12) healpy.projtext(0, 270, "-90", lonlat = True, coord = proj, verticalalignment = 'top', horizontalalignment = 'center', linespacing = 2.0, fontsize = 12) healpy.projtext( 179, 0, "180 ", lonlat = True, coord = proj, verticalalignment = 'center', horizontalalignment = 'right', fontsize = 12) healpy.projtext(-179, 0, " -180", lonlat = True, coord = proj, verticalalignment = 'center', horizontalalignment = 'left', fontsize = 12)
def mollview(hp_map, filename=None, lim=None, coord='C', verbose=True, return_projected_map=False, xsize=1200, grat_deg=None, **kwargs): ''' mollview plot for healpix wrapper ''' import healpy as hp if lim is None: cmin = cmax = None elif type(lim) is list or type(lim) is tuple: cmin, cmax = lim else: cmin = -lim cmax = lim retimg = hp.mollview(hp_map, min=cmin, max=cmax, coord=coord, return_projected_map=return_projected_map, xsize=xsize, **kwargs) if grat_deg is not None: hp.graticule(dpar=grat_deg, dmer=grat_deg, coord=coord) if filename is not None: plt.savefig(filename) if verbose: cprint("Saved healpix plot to " + filename, color="g") if return_projected_map: return retimg
def graphtargets(info, targets, skymap): "Generate a graph with the targets generated over the sky map" import healpy as hp from io import BytesIO import matplotlib.pyplot as plt aligo_banana = hp.read_map(skymap) numfig = 1 fig = plt.figure(numfig, figsize=(10, 5)) graph_title = "{} -{}-{}\nBayestar Prob. Sky Map with Targets".format( info["graceid"], info["pkt_ser_num"], info["alerttype"]) hp.mollview( aligo_banana, title=graph_title, flip="astro", unit="$\Delta$", fig=numfig, cmap=plt.cm.gist_heat_r, ) fig.axes[1].texts[0].set_fontsize(8) for obs in targets: ra_pointings = np.array(obs["targets"]["RA"]) dec_pointings = np.array(obs["targets"]["Dec"]) hp.projscatter(ra_pointings, dec_pointings, lonlat=True, color="green", marker=".") hp.graticule() graphIO = BytesIO() plt.savefig(graphIO) return graphIO.getvalue()
def tsmaps(self): """TS maps for the spectral templates Each has 12*512**2 = 3.2M pixels. The following table has the number of pixels above the TS value labeling the column. %(tsmap_info)s """ z = dict() cuts = (10, 16, 25, 100) keys = self.keys for key in keys: z[key] = [np.sum(self.tables[key] > x) for x in cuts] df = pd.DataFrame(z, index=cuts).T self.tsmap_info = html_table( df, href=False, ) fig, axx = plt.subplots(2, 3, figsize=(18, 15)) plt.subplots_adjust(hspace=-0.4, wspace=0.05, left=0.05) for ax, key in zip(axx.flatten(), keys): plt.sca(ax) healpy.mollview(self.tables[key], hold=True, min=10, max=25, title=key, cbar=True, cmap=plt.get_cmap('YlOrRd')) healpy.graticule(dmer=180, dpar=90, color='lightgrey') axx[1, 2].set_visible(False) return fig
def plot_tsfile(file,skiprows=32,column=22): data = np.loadtxt(file,skiprows=skiprows,unpack=True) print len(data[0]) nside=int(round(mt.sqrt(len(data[9])/12))) tsarray=np.zeros(nside*nside*12) index=np.array(data[0]).astype(int) ''' data2=np.transpose(0*data) data2[index]=np.transpose(data) data2=np.transpose(data2) print(data2[0]) print(data2[10]) return ''' tsarray[index]=data[column] tsarray_s = hp.sphtfunc.smoothing(tsarray,sigma = 1.023/nside) hp.mollview(tsarray,coord=['C','G'], title='TS Map', unit='prob',xsize = 2048) hp.graticule() plt.savefig("%s_c%d.png" % (file,column)) plt.show() hp.mollview(tsarray_s,coord=['C','G'], title='TS Map Smoothed', unit='prob',xsize = 2048) hp.graticule() plt.savefig("%s_c%d__s.png" % (file,column)) plt.show()
def plot_sky_projection_healpy_simple_zoom(Sliced_Halo_data,Output_Para): rc('font',family='serif') fdir = './Output/plots/HEALPixZoom/' nside = Output_Para.nside Sl_n = len(Sliced_Halo_data) Z_max = max(Sliced_Halo_data[Sl_n-1].Z_red[:]) ques = True while (ques): k = Read_Integer_Input("We have %i redshift slice which one you want exctract the halo ? "%Sl_n) k = int(k) - 1 while(k > (Sl_n-1) or k < 0 ): print "Invalid Number." k = Read_Integer_Input("Please choose an integer between 1 and %i : "%Sl_n) k = int(k) - 1 pix = zeros(12*nside**2) n = len(Sliced_Halo_data[k].RA[:]) if (n == 0): print "There is no halo in this piece of redshift, please choos another one ..." raw_input("Press enter to continue ... ") break for i in range(n): j = hp.ang2pix(nside,DtoR*(90.0-Sliced_Halo_data[k].DEC[i]),DtoR*(Sliced_Halo_data[k].RA[i])) pix[j] += 10.0**Sliced_Halo_data[k].lgFx[i] halo_n = Read_Integer_Input("We have %i halos in this slice which one you want to exctract ? "%n) halo_n = halo_n - 1 while(halo_n > (n-1) or halo_n < 0 ): print "Invalid Number." halo_n = Read_Integer_Input("Please choose an integer between 1 and %i : "%n) halo_n = halo_n - 1 clf() hp.gnomview(pix, fig = 1 ,rot=(Sliced_Halo_data[k].RA[halo_n],Sliced_Halo_data[k].DEC[halo_n],0.0) , xsize=Output_Para.xsize , reso=Output_Para.resolution , degree=Output_Para.resol_degree) hp.graticule() show() close() save_ques = Read_YN_Input("Do you want to save its picture (please enter Y, y, N, or n)? ") if save_ques : rc('text',usetex=True) clf() hp.gnomview(pix, fig=1 , rot=(Sliced_Halo_data[k].RA[halo_n],Sliced_Halo_data[k].DEC[halo_n],0.0) , xsize=Output_Para.xsize , reso=Output_Para.resolution , degree=Output_Para.resol_degree) hp.graticule() fname = 'sky_projection_HEALPix_Simple_%i_%i_%i.pdf'%(nside,(halo_n+1),(k+1)) title(r'Redshift is between %0.2f and %0.2f'%(Sliced_Halo_data[k].z_min,Sliced_Halo_data[k].z_max),fontsize = 20) print 'Saving plot', fname # savefig(fdir+fname,bbox_inches='tight') savefig(fdir+fname) rc('text',usetex=False) close() ques = False return 0
def plots(maps, surveys, clf=True, save=True, title=None, pure_noise=True): import pylab as pl from utils import latexify latexify(columns=2, equal=False, fontsize=10, ratio=None, ggplot=True) for kk, survey in enumerate(surveys): if survey in ['Planck', 'SO', 'AdvACT']: fmap = 1.e6 * cmb_map(survey, pure_noise=pure_noise) else: fmap = np.ones_like(maps[kk]) if clf: pl.clf() ## C equates to equatorial. ## min=-150., max=150. hp.visufunc.mollview(maps[kk] * fmap, coord=['C', 'C'], flip='astro', rot=(0., 0., 0.), hold=False, format='%.1lf', cbar=True,\ unit=r'$\mu K$', cmap='RdBu_r') hp.graticule(dpar=15., dmer=30.) if save: if title is None: pl.title('%s in Mollweide' % survey) pl.savefig('plots/footprint/%s.pdf' % survey) else: pl.title('%s' % title) pl.savefig('plots/footprint/%s.pdf' % ('_' + title))
def plot(self, title='MOC', coord='C'): """ plot current instance using matplotlib coord can be 'C', 'G' or 'E' (respectively celestial, galactic or ecliptic) """ from matplotlib import pyplot as plt import healpy as hp # degrade to NORDER 8 if norder is greater if self.max_order > 8: plotted_moc = self.degrade_to_order(8) else: plotted_moc = self m = np.zeros(hp.nside2npix(2**plotted_moc.max_order)) for val in plotted_moc.best_res_pixels_iterator(): m[val] = 1 from matplotlib.colors import LinearSegmentedColormap cmap = LinearSegmentedColormap.from_list('w2r', ['#ffffff', '#ff0000']) cmap.set_under('w') cmap.set_bad('gray') hp.mollview(m, nest=True, coord=['C', coord], title=title, cbar=False, cmap=cmap) hp.graticule() plt.show()
def plot_healpix(file_name="ALL_SKY.FITS", field=0, max_v=60, min_v=0): #file_names = glob.glob("*_healpix.fits") haslam = hp.read_map(file_name, field=field) for x in xrange(len(haslam)): if np.allclose(haslam[x], 0.0): haslam[x] = hp.UNSEEN #print "haslam = ",haslam cmap = cm.jet cmap.set_over(cmap(1.0)) cmap.set_under('w') cmap.set_bad('gray') proj_map = hp.mollview(haslam, coord=['C'], xsize=2000, return_projected_map=True, title='', max=max_v, min=min_v, cmap=cmap) #max=0.4 #proj_map = hp.mollview(haslam,coord=['C'], xsize=2000,return_projected_map=True,title='',cmap=cmap) hp.graticule() f = file_name[:-5] plt.savefig(f + str(field) + ".png") plt.show()
def parse_patches(args): # Parse the patch definitions patches = [] total_weight = 0 for patch_def in args.patch: parts = patch_def.split(',') name = parts[0] weight = float(parts[1]) total_weight += weight print('Adding patch "{}" {} '.format(name, weight), end='') if len(parts[2:]) == 3: corners = parse_patch_center_and_width(args, parts) elif len(parts[2:]) == 4: corners = parse_patch_rectangular(args, parts) else: corners = parse_patch_explicit(args, parts) print('') patches.append([name, weight, corners]) if args.debug: import matplotlib.pyplot as plt import healpy as hp plt.figure(figsize=[18, 12]) for iplot, coord in enumerate('CEG'): hp.mollview(np.zeros(12), coord=coord, cbar=False, title='Patch locations', sub=[2, 2, 1 + iplot]) hp.graticule(30) for name, weight, corners in patches: lon = [corner._ra / degree for corner in corners] lat = [corner._dec / degree for corner in corners] lon.append(lon[0]) lat.append(lat[0]) print('{} corners:\n lon = {}\n lat= {}'.format( name, lon, lat), flush=True) hp.projplot(lon, lat, 'r-', threshold=1, lonlat=True, coord='C', lw=2) hp.projtext(lon[0], lat[0], name, lonlat=True, coord='C', fontsize=14) plt.savefig('patches.png') plt.close() # Normalize the weights for i in range(len(patches)): patches[i][1] /= total_weight return patches
def main(argv): _path = '/home/tiago/Develop/SMAPs/' file15 = 'smpas_obstime_15.fits' file2 = 'smpas_obstime_2.fits' extMapFile = 'extintion_at3800.fits' map15 = H.read_map(os.path.join(_path,file15)) map2 = H.read_map(os.path.join(_path,file2)) extMap = H.read_map(os.path.join(_path,extMapFile)) fig = py.figure(1,figsize=(8,3)) H.mollview(map2*10**(-extMap),fig=1,coord=['G','E'],title='secz < 2.0',sub=(1,2,1),max=1296,cbar=False,notext=True)#,unit='hours z < 1.3') H.graticule() H.mollview(map15*10**(-extMap),fig=1,coord=['G','E'],title='secz < 1.5',sub=(1,2,2),max=1296,cbar=False,notext=True)#,unit='hours z < 1.3') H.graticule() #H.write_map(os.path.join(_path,'dcorr_'+file15),map15*10**(-extMap)) #H.write_map(os.path.join(_path,'dcorr_'+file2),map2*10**(-extMap)) #H.write_map(os.path.join(_path,'dcorr_'+file3),map3*10**(-extMap)) py.savefig(os.path.join(_path,'Figures/fig2.png')) py.show()
def plot(self, plt, src_list): """ Modified plot to deal with the reduced number of pixels """ all_npix = hp.nside2npix(self.nside) all_pixels = np.zeros(all_npix) + hp.UNSEEN all_pixels[self.pixel_indices] = self.pixels rot = (0, 90, 0) plt.figure() # (figsize=(6,6)) logger.info("self.pixels: {}".format(self.pixels.shape)) if True: hp.orthview(all_pixels, rot=rot, xsize=1000, cbar=True, half_sky=True, hold=False) hp.graticule(verbose=False) else: hp.mollview(all_pixels, rot=rot, xsize=1000, cbar=True) hp.graticule(verbose=True) if src_list is not None: for s in src_list: self.plot_x(plt, s.el_r, s.az_r)
def _grid(self, **kwargs): """generate background grids for figure Parameters ---------- Healpix graticule Parameters """ hp.graticule(**self.getkeys(kwargs, 'graticule'))
def main(): """ This is the main routine. """ h_nside=512 # The same value a bayesstar.fits smoothing=0.01 # Smooth the resulting map to 0.01 radians with a Gaussian hubbleconstant=72 speedoflight=3E5 filenameCat = 'XSC_Completed.tbl.gz' RA,DEC,JMAG,HMAG,KMAG = np.loadtxt(filenameCat,skiprows= 50, usecols = (0,1,3,4,5), dtype=[('f0',float), ('f1',float), ('f2',float), ('f3',float), ('f4',float)], unpack = True) MK_Star = -24.0 DIST = np.power(10,(KMAG-MK_Star)/5)*1E-05 REDSHIFT = (DIST*hubbleconstant)/speedoflight print("Interval of K MAG = ",min(KMAG)," - ",max(KMAG)) print("Interval of distances [Mpc] = ",min(DIST)," - ",max(DIST)) print("Interval of redshift = ",min(REDSHIFT)," - ",max(REDSHIFT)) # Select Galaxies by redshift under the assumption of MK=MK_Star for rmin in np.arange(4)*0.01: rmax=rmin+0.01 if rmin == 0: kmin=0 else: kmin=5*np.log10(rmin/hubbleconstant*speedoflight*1E5)+MK_Star kmax=5*np.log10(rmax/hubbleconstant*speedoflight*1E5)+MK_Star galpixels_Range= np.zeros(hp.nside2npix(h_nside)) include_me = np.logical_and((REDSHIFT > rmin), np.logical_and((REDSHIFT<rmax), (KMAG != 0.0))) ra_Range = RA[include_me] dec_Range = DEC[include_me] pix_num_Range = (DeclRaToIndex(dec_Range,ra_Range,h_nside)) galpixels_Range[pix_num_Range]+=1 print("Number of objects with %g < z < %g : %d" % (rmin,rmax,len(ra_Range))) map = hp.sphtfunc.smoothing(galpixels_Range,sigma = smoothing) hp.write_map("%g-%g_raw.fits" % (rmin,rmax),galpixels_Range) hp.write_map("%g-%g.fits" % (rmin,rmax),map) hp.mollview(map,coord='C',rot = [0,0.3], title='Relative Surface Density of Galaxies: %0.1f < K < %0.1f (%g < z < %g)' % (kmin,kmax,rmin,rmax), unit='prob',xsize = 2048) hp.graticule() plt.savefig("%g-%g.png" % (rmin,rmax)) plt.show()
def plot_Single_Halo_Surface_Brightness(Halo_data,Input_Para,Output_Para): from XCat_Objects import DtoR, RtoD rc('font',family='serif') fdir = './Output/plots/HEALPixSurfaceBrightness/' nside = Output_Para.nside Sl_n = len(Halo_data) k = Read_Integer_Input("We have %i redshift slice which one you want exctract the halo ? "%Sl_n) k = int(k) - 1 while(k > (Sl_n-1) or k < 0 ): print "Invalid Number." k = Read_Integer_Input("Please choose an integer between 1 and %i : "%Sl_n) k = int(k) - 1 n = len(Halo_data[k].RA[:]) if (n == 0): print "There is no halo in this piece of redshift, please choos another one ..." raw_input("Press enter to continue ... ") return halo_n = Read_Integer_Input("We have %i halos in this slice which one you want to exctract ? "%n) halo_n = halo_n - 1 from XCat_Objects import Halo_Brightness_Surface_Sample_Object Halo_Sample = Halo_Brightness_Surface_Sample_Object(Halo_data[k],Input_Para,Output_Para,halo_n) pix = zeros(12*nside**2) for i in range(len(Halo_Sample.sRA[:])): j = hp.ang2pix(nside,DtoR*(90.0-Halo_Sample.sDEC[i]),DtoR*(Halo_Sample.sRA[i])) pix[j] += Halo_Sample.sSB[i] if (Output_Para.log_scale): pix_min = max(pix[:])/10.0**4 pix = log10((pix+pix_min)*4.0*pi/(12.0*nside**2)) else: pix = pix/(12.0*nside**2) plt.clf() hp.gnomview(pix, fig=1 ,rot=(Halo_Sample.RA,Halo_Sample.DEC,0.0), xsize=Output_Para.xsize , reso=Output_Para.resolution , degree=Output_Para.resol_degree) hp.graticule() plt.show() plt.close() save_ques = Read_YN_Input("Do you want to save its picture (please enter Y, y, N, or n)? ") if save_ques : rc('text',usetex=True) plt.clf() hp.gnomview(pix, fig=1 , rot=(Halo_Sample.RA,Halo_Sample.DEC,0.0) , xsize=Output_Para.xsize , reso=Output_Para.resolution , degree=Output_Para.resol_degree) hp.graticule() if (Output_Para.log_scale): fname = 'sky_projection_HEALPix_Surface_Brightness_Profile_log_%i_%i_%i.pdf'%(nside,(halo_n+1),(k+1)) else: fname = 'sky_projection_HEALPix_Surface_Brightness_Profile_%i_%i_%i.pdf'%(nside,(halo_n+1),(k+1)) plt.title(r'Surface Brightness Profile',fontsize = 20) print 'Saving plot', fname # savefig(fdir+fname,bbox_inches='tight') plt.savefig(fdir+fname) rc('text',usetex=False) plt.close()
def PlotMap(Map, NsideMap, MapName): hp.mollview(Map, coord='C', rot=[0, 0.3], title='Histogram-Equalized Probability Density Map', unit='prob', xsize=NsideMap) hp.graticule() plt.savefig(MapName)
def draw_map(m, cmap=pl.cm.jet, filename=None): mm = m.copy() mm[mm <= 0] = hp.UNSEEN cmap.set_under('w') hp.mollview(mm, nest=True, cmap=cmap) hp.graticule() if filename is not None: fig = pl.gcf() fig.savefig(filename + '.png', bbox_inches='tight')
def plot_map_data(map, file_name, range=None): fig = plt.figure(1,(10,10)) if range == None: hp.mollview(map) else: hp.mollview(map, min=range[0], max=range[1]) hp.graticule() plt.tight_layout() plt.savefig(file_name) plt.close(1)
def plot_skymap(skymap, smooth=None, decmax=None, scale=None, color_bins=40, color_palette='viridis', symmetric=False, cbar_min=None, cbar_max=None, cbar_title='Skymap', llabel=None, polar=False, fig=None, sub=None): cpalette = sns.color_palette(color_palette, color_bins) cmap = ListedColormap(cpalette.as_hex()) cmap.set_under('white') cmap.set_bad('gray') # if cbar_max and cbar_max and symmetric and (cbar_max != -cbar_min): # raise ValueError('The max/min colorbar values can\'t be symmetric') # elif cbar_max and cbar_max: # pass # elif: # skymap_min = skymap.min() # skymap_max = skymap.max() # maximum = np.max(np.abs([skymap_min, skymap_max])) # cbar_min = np.sign(skymap_min) * maximum # cbar_max = np.sign(skymap_max) * maximum # else: # cbar_min = cbar_min if cbar_min else skymap.min() # cbar_max = cbar_max if cbar_max else skymap.max() if polar: shrink = 0.6 rot = [0,-90,180] hp.orthview(skymap, half_sky=True, rot=rot, coord='C', title='', min=cbar_min, max=cbar_max, cbar=False, cmap=cmap, fig=fig, sub=sub) else: shrink = 1.0 hp.mollview(skymap, rot=180, coord='C', title='', min=cbar_min, max=cbar_max, cbar=False, cmap=cmap, fig=fig, sub=sub) hp.graticule(verbose=False) fig = plt.gcf() ax = plt.gca() image = ax.get_images()[0] cbar = fig.colorbar(image, orientation='horizontal', aspect=50, pad=0.01, fraction=0.1, ax=ax, format=FormatStrFormatter('%g'), shrink=shrink) if cbar_title: cbar.set_label(cbar_title, size=14) if not polar: ax.set_ylim(-1, 0.005) ax.annotate('0$^\circ$', xy=(1.8, -0.75), size=14) ax.annotate('360$^\circ$', xy=(-1.99, -0.75), size=14) if llabel: ax.annotate(llabel, xy=(-1.85,-0.24), size=20, color='white') return fig, ax
def plotMap(map, unit, title): min_map = max(0., np.min(map)) max_map = np.max(map) hp.mollview(map, min=min_map, max=max_map, cmap=plt.cm.rainbow, norm="hist", title=title, unit=unit) hp.graticule()
def plot_efield_beams(xt,xp,yt,yp,rot=[0,0],minv = [-1,-1,-1,-1],maxv=[1,1,1,1],figno=1): A = [xt,xp,yt,yp] plt.figure(figno) plt.clf() for a in range(4): hp.orthview(A[a],half_sky=True,sub=(2,2,a+1),min=minv[a],max=maxv[a],rot=rot) #plt.title(beam_labels[a,b]) hp.graticule() # plt.show() return
def plot_footprint_object(self, footprint_obj): """sfd is what footprint_wSFD() returns""" temp = np.log10(footprint_obj.temp) temp[footprint_obj.ipix_legsurvey] = 2. hp.mollview(temp, nest=True, flip='geo', title='Mollweide Projection, Galactic Coordinates', unit='', max=-0.5) hp.graticule(c='k', lw=1) plt.savefig('footprint_wSFD.png', dpi=150)
def add_edges(): hp.graticule(verbose=False) plt.grid(True) lons = np.arange(-150.0, 180, 30.0) lats = np.zeros(lons.shape) for lon, lat in zip(lons, lats): hp.projtext(lon, lat, "%.0f" % lon, lonlat=True) lats = np.arange(-60.0, 90, 30.0) lons = np.zeros(lons.shape) for lon, lat in zip(lons, lats): hp.projtext(lon, lat, "%.0f" % lat, lonlat=True)
def plot_zoom(ind, LLH=False, reso=1., cmap=None, draw_contour=True, ax=None): """Plot skymap of an alert event Args: ind (int): Alert event index LLH (bool, default=False): plot LLH vs. scaled probs. """ skymap, header = hp.read_map(skymap_files[ind], h=True, verbose=False, dtype=None) header = {name: val for name, val in header} nside = hp.get_nside(skymap) area = np.count_nonzero(skymap < 64.2) * hp.nside2pixarea(nside) * 180.**2. / (np.pi**2.) reso *= int(np.sqrt(area)) reso = np.max([reso, 1.]) original_LLH = None if not LLH: original_LLH = np.copy(skymap) skymap = np.exp(-1. * skymap / 2.) skymap = np.where(skymap > 1e-20, skymap, 0.0) skymap = skymap / np.sum(skymap) ra = np.radians(header['RA']) dec = np.radians(header['DEC']) title = skymap_files[ind][l_ind:r_ind].replace('Run', 'Run ').replace('_', ', Event ') if cmap is None: pdf_palette = sns.color_palette("Blues", 500) cmap = mpl.colors.ListedColormap(pdf_palette) max_color = 100 if LLH else max(skymap) hp.gnomview(skymap, rot=(np.degrees(ra), np.degrees(dec), 0), cmap=cmap, max=max_color, min=0, reso=reso, title=title, notext=True, cbar=False #unit=r"" ) plt.plot(4.95/3.*reso*np.radians([-1, 1, 1, -1, -1]), 4.95/3.*reso*np.radians([1, 1, -1, -1, 1]), color="k", ls="-", lw=3) hp.graticule(verbose=False) plot_labels(dec, ra, reso) original_LLH = skymap if original_LLH is None else original_LLH con_nside = 256 if area < 5. else 128 if draw_contour: sample_points = np.array(hp.pix2ang(nside,np.arange(len(original_LLH)))).T msk = original_LLH < 110. contours = plot_contours(None, original_LLH[msk], sample_points[msk], levels=[22.2, 64.2]) #, nside = con_nside) for contour in np.array(contours).T: hp.projplot(contour[0],contour[1],linewidth=1.5,c='k') col_label=r'$-2\Delta \mathrm{LLH}$' if LLH else "Prob." plot_color_bar(cmap = cmap, labels = [0, max_color], col_label = col_label)
def plot_skymap(ind, LLH=True): """Plot skymap of an alert event Args: ind (int): Alert event index LLH (bool, default=False): plot LLH vs. scaled probs. """ skymap, header = hp.read_map(skymap_files[ind], h=True, verbose=False, dtype=None) header = {name: val for name, val in header} original_LLH = None if not LLH: original_LLH = np.copy(skymap) skymap = np.exp(-1. * skymap / 2.) skymap = np.where(skymap > 1e-20, skymap, 0.0) skymap = skymap / np.sum(skymap) if LLH: inf_msk = np.isinf(skymap) other_max = np.max(skymap[~inf_msk]) skymap[inf_msk] = other_max pdf_palette = sns.color_palette("Blues", 500) cmap = mpl.colors.ListedColormap(pdf_palette) hp.mollview(skymap, title="", cbar=True, notext=True, rot=180, hold=False, cmap=cmap, unit = r'$-2 \Delta \mathrm{LLH}$') hp.graticule() # add some labels plt.text(2.0,0., r"$0^\circ$", ha="left", va="center") plt.text(1.9,0.45, r"$30^\circ$", ha="left", va="center") plt.text(1.4,0.8, r"$60^\circ$", ha="left", va="center") plt.text(1.9,-0.45, r"$-30^\circ$", ha="left", va="center") plt.text(1.4,-0.8, r"$-60^\circ$", ha="left", va="center") plt.text(2.0, -0.15, r"$0\,\mathrm{h}$", ha="center", va="center") plt.text(1.333, -0.15, r"$4\,\mathrm{h}$", ha="center", va="center") plt.text(.666, -0.15, r"$8\,\mathrm{h}$", ha="center", va="center") plt.text(0.0, -0.15, r"$12\,\mathrm{h}$", ha="center", va="center") plt.text(-.666, -0.15, r"$16\,\mathrm{h}$", ha="center", va="center") plt.text(-1.333, -0.15, r"$20\,\mathrm{h}$", ha="center", va="center") plt.text(-2.0, -0.15, r"$0\,\mathrm{h}$", ha="center", va="center") original_LLH = skymap if original_LLH is None else original_LLH try: sample_points = np.array(hp.pix2ang(nside,np.arange(len(original_LLH)))).T msk = original_LLH < 110. contours = plot_contours(None, original_LLH[msk], sample_points[msk], levels=[22.2, 64.2]) for contour in np.array(contours).T: hp.projplot(contour[0],contour[1],linewidth=1.5,c='k') except: pass
def plot(self, plt, sphere, src_list): rot = (0, 90, 0) plt.figure() # (figsize=(6,6)) logger.info('sphere.pixels: {}'.format(sphere.pixels.shape)) if True: hp.orthview(sphere.pixels, rot=rot, xsize=1000, cbar=True, half_sky=True, hold=True) hp.graticule(verbose=False) plt.tight_layout() else: hp.mollview(sphere.pixels, rot=rot, xsize=1000, cbar=True) hp.graticule(verbose=True) if src_list is not None: for s in src_list: sphere.plot_x(s.el_r, s.az_r)
def draw_map(self, fig, norm=None): print("Data type are:") for i, key in enumerate(self.data_type): print("{}: {}".format(i, key)) dtype = int(input("Which data do you want to show? ")) hp.mollview(self.data[dtype], coord='G', title=self.data_type[dtype], norm=norm, fig=fig, xsize=8192) hp.graticule() logger.info("Sky map created, field loaded: {}".format( self.data_type[dtype]))
def main(argv): _path = os.path.expanduser('~/Develop/SMAPs/') nna_file = os.path.expanduser('~/Documents/SMAPs/norpointT80.dat') nsa_file = os.path.expanduser('~/Documents/SMAPs/surpointT80.dat') sna_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/smaps_pointT80norte.dat') ssa_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/smaps_pointsulT80.dat') nna_pt = np.loadtxt(nna_file,unpack=True,usecols=(4,5)) nsa_pt = np.loadtxt(nsa_file,unpack=True,usecols=(4,5)) sna_pt = np.loadtxt(sna_file,unpack=True,usecols=(4,5)) ssa_pt = np.loadtxt(ssa_file,unpack=True,usecols=(4,5)) file1 = 'lambda_sfd_ebv.fits' file2 = 'smpas_obstime_2.fits' file3 = 'smpas_obstime_15.fits' extMapFile = 'extintion_at3800.fits' map1 = H.read_map(os.path.join(_path,file1)) map2 = H.read_map(os.path.join(_path,file2)) map3 = H.read_map(os.path.join(_path,file3)) extMap = H.read_map(os.path.join(_path,extMapFile)) H.mollview(map1,fig=1,coord=['G','E'],max=1.0,title='',sub=(2,2,3),cbar=False,notext=True)#,unit='hours z < 1.3') H.projplot((90-nna_pt[1])*np.pi/180.,nna_pt[0]*np.pi/180.,'r.')#,coord=['E','G']) H.projplot((90-nsa_pt[1])*np.pi/180.,nsa_pt[0]*np.pi/180.,'r.')#,coord=['E','G']) H.projplot((90-sna_pt[1])*np.pi/180.,sna_pt[0]*np.pi/180.,'w.')#,coord=['E','G']) H.projplot((90-ssa_pt[1])*np.pi/180.,ssa_pt[0]*np.pi/180.,'w.')#,coord=['E','G']) H.graticule() H.mollview(map2,fig=1,coord=['G','E'],title='',sub=(2,2,1),cbar=False,notext=True,max=1800) #,unit='hours z < 1.3') H.graticule() H.mollview(map3,fig=1,coord='G',title='',sub=(2,2,2),cbar=False,notext=True,max=1800)#,unit='hours z < 1.3') H.graticule() H.mollview(map2*10**(-extMap),fig=1,coord='G',title='',sub=(2,2,4),cbar=False,notext=True)#,unit='hours z < 1.3') H.graticule() py.savefig(os.path.join(_path,'Figures/fig1.png')) py.show()
def main(): """ This is the main routine. """ ''' # Parse the command line. parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_option('-q','--quiet',dest='quiet',action='store_true', default=False,help='quiet output') parser.add_option('-v','--verbose',dest='verbose',action='store_true', default=False,help='verbose output') (options,args) = parser.parse_args() nargs = len(args) ''' filenameCat = '/Users/Elisa/c/EAntolini/Healpix/NedMAP/NED_z_0.1_0.11.txt' RA,DEC = np.loadtxt(filenameCat,skiprows= 26,usecols = (2,3), delimiter = '|',dtype=[('f0',float),('f1',float)], unpack = True) pix = DeclRaToIndex(DEC,RA,512) galpixels= np.zeros(hp.nside2npix(512)) galpixels[pix]=galpixels[pix]+1 print(len(pix)) print(hp.npix2nside(len(pix))) #print(hp.nside2npix(64)) hp.mollview(galpixels,coord='C',rot = [0,0.3], title='Histogram equalized Ecliptic', unit='prob',xsize = 64) hp.graticule() plt.show() # Generate my own Map '''
def plot_leakage_beams(nom_vis,rot=[0,0],mn=-2,mx=0,log=True,figno=2): if log: nom_vis_to_plot = np.log10(np.abs(nom_vis.copy())) else: nom_vis_to_plot = nom_vis.copy() fig = plt.figure(figno) plt.clf() for a in range(4): for b in range(4): if (a==b) and (not log): mn_plot = 0 mx_plot = 1 else: mn_plot = mn mx_plot = mx print mn_plot, mx_plot hp.orthview(nom_vis_to_plot[a,b,:],half_sky=True,title='',sub=(4,4,4*a+b+1),min=mn_plot,max=mx_plot,rot=rot)#,margins=[0.1,0.9,0.9,0.1]) hp.graticule() #fig.tight_layout() # plt.show() return
def visualize_beam(args): angpos = hputil.ang_positions(args.nside) zenith = latlon_to_sphpol([args.lat, args.lon]) beamx_resp = beamx(args.feed, args.freq, angpos, zenith, args.dish_width) beamy_resp = beamy(args.feed, args.freq, angpos, zenith, args.dish_width) # Create output image file name if args.outfile: out_file = args.outfile else: freq = ('%s'%args.freq).replace('.', '_') diameter = ('%s'%args.dish_width).replace('.', '_') out_file = 'beam_resp_%s__%s.%s'%(freq, diameter, args.figfmt) # Plot and save image fig = plt.figure(1, figsize=(args.figlength, args.figwidth)) title1 = 'X beam pattern, f= %sMHz, d = %sm'%(args.freq, args.dish_width) healpy.mollview(beamx_resp[:, 1], fig=1, sub=121, title=title1, min=args.min, max=args.max) title2 = 'Y beam pattern, f= %sMHz, d = %sM'%(args.freq, args.dish_width) healpy.mollview(beamy_resp[:, 0], fig=1, sub=122, title=title2, min=args.min, max=args.max) if args.grid: healpy.graticule() fig.savefig(out_file) fig.clf()
def plot_full_sky_cart(Output_Para,pix,pix_bool): rc('font',family='serif') if (pix_bool): plt.clf() hp.cartview(pix, fig = 1) hp.graticule() plt.show() plt.close() else: print "Please, first load a HEALPix map file ." raw_input("Press enter to continue ... ") return 0 save_ques = Read_YN_Input("Do you want to save its picture (please enter Y, y, N, or n)? ") if save_ques : rc('text',usetex=True) plt.clf() hp.cartview(pix, fig = 1) hp.graticule() print 'Saving plot', fname plt.savefig(fdir+fname+'_cart.pdf',bbox_inches='tight') # plt.savefig(fdir+fname+'.pdf') rc('text',usetex=False) plt.close()
def view(self, inclination=90*u.deg, phase=0.0, what='fluxes', projection='mollweide', cmap='magma', savefig=False, filename='star_surface.png', dlat=30, dlon=30, **kwargs): rot = (360*phase, 90-inclination.to(u.deg).value, 0) if what == 'fluxes': vals = self.tile_fluxes * self.tile_scales vals = vals / vals.max() elif what == 'areas': vals = self.tile_areas / self.tile_areas.max() if 'mollweide'.find(projection) == 0: hp.mollview(vals, rot=rot, cmap=cmap, **kwargs) elif 'cartesian'.find(projection) == 0: hp.cartview(vals, rot=rot, cmap=cmap, **kwargs) elif 'orthographic'.find(projection) == 0: hp.orthview(vals, rot=rot, cmap=cmap, **kwargs) else: raise ValueError('Unrecognised projection') hp.graticule(dlat, dlon) if savefig: plt.savefig(filename) else: plt.show()
phi = l*deg2rad pix = hp.ang2pix(nside, theta, phi, nest=False) val = ir_map[pix] print src, l,b,pix, val hp.projplot(l, b, 'bo', lonlat=True, coord='G') # hp.projtext(l, b, src+','+str(l)+','+str(b), lonlat=True, coord='G') if (b<60): hp.projtext(l, b, src, lonlat=True, coord='G', fontsize=13, weight='bold') else: hp.projtext(l, b, src, lonlat=True, coord='G', fontsize=13, color='r', weight='bold') if(src == '3C109'): hp.projtext(l, b, src, lonlat=True, coord='G', fontsize=13, color='b', weight='bold') mpl.rcParams.update({'font.size':30}) hp.graticule() plt.grid() plt.show() l = 51.641648 b = -9.6750019 # Plot cartview a/o mollview # ll = l if (l>180): ll = ll-360. offset = 1. lonr = [51.25, 52.0] latr = [-10., -9.35] m = hp.cartview(ir_map, title='IRIS 100micron', coord='G', unit='MJy/sr', min=0.,max=26.,
sys.exit() # ==================================================================== # To make Table.3 and associated fig.7; run it three times with inc_haze/inc_bubbles on/off from onestep_fit_flux import onestep_fit_flux onestep_fit_flux( write_png=False, inc_disc=False, inc_haze=True, inc_bubbles=True, raw_sync=False, mfile='ebvh_mask_top-half_disc_40_ns0128.fits', model_list=['12132h'], plot_moll=False ) sys.exit() # ==================================================================== maskfile = 'ebvh_mask_ns0128.fits' mask = hp.read_map( dir + maskfile ) mask[mask == 0.] = hp.UNSEEN hp.mollview(mask, cbar=False, title='Galactic mask') hp.graticule(dpar=20,dmer=20) reg_maskfile = 'south_haze_ptsrc_mask_ns0128.fits' reg_mask = hp.read_map( dir + reg_maskfile ) reg_mask[reg_mask == 0.] = hp.UNSEEN hp.mollview(reg_mask, title='Southern region mask') hp.graticule(dpar=20,dmer=20) pl.show() sys.exit() # ==================================================================== raw_sync = True files = {} files['cmb'] = dir + 'planck_hfi_ilc_ns'+snside+'_1deg_mK.fits'
def almPlots(path, outDir, bundle, nside=128, lmax=500, filterband='i', raRange=[-50,50], decRange=[-65,5], subsetsToConsider=[[130,165], [240, 300]], showPlots=True): """ Plot the skymaps/cartview plots corresponding to alms with specified l-ranges. Automatically creates the output directories and saves the plots. Required Parameters ------------------- * path: str: path to the main directory where output directory is saved * outDir: str: name of the main output directory * bundle: metricBundle object. Optional Parameters ------------------- * nside: int: HEALpix resolution parameter. Default: 128 * lmax: int: upper limit on the multipole. Default: 500 * filterBand: str: any one of 'u', 'g', 'r', 'i', 'z', 'y'. Default: 'i' * raRange: float array: range of right ascention (in degrees) to consider in cartview plot; only useful when cartview= True. Default: [-50,50] * decRange: float array: range of declination (in degrees) to consider in cartview plot; only useful when cartview= True. Default: [-65,5] * subsetsToConsider: array of int arrays: l-ranges to consider, e.g. use [[50, 100]] to consider 50<l<100. Currently built to handle five subsets (= number of colors built in). Default: [[130,165], [240, 300]] * showPlots: boolean: set to True if want to show figures. Default: True """ # set up the output directory outDir2 = 'almAnalysisPlots_%s<RA<%s_%s<Dec<%s'%(raRange[0], raRange[1], decRange[0], decRange[1]) if not os.path.exists('%s%s/%s'%(path, outDir, outDir2)): os.makedirs('%s%s/%s'%(path, outDir, outDir2)) outDir3 = 'almSkymaps' if not os.path.exists('%s%s/%s/%s'%(path, outDir, outDir2, outDir3)): os.makedirs('%s%s/%s/%s'%(path, outDir, outDir2, outDir3)) outDir4 = 'almCartviewMaps' if not os.path.exists('%s%s/%s/%s'%(path, outDir, outDir2, outDir4)): os.makedirs('%s%s/%s/%s'%(path, outDir, outDir2, outDir4)) # ------------------------------------------------------------------------ # In order to consider the out-of-survey area as with data=0, assign the masked region of the # skymaps the median of the in-survey data, and then subtract the median off the entire survey. # Add the median back later. This gets rid of the massive fake monopole and allows reconstructing # the full skymap from components. surveyMedianDict = {} surveyStdDict = {} for dither in bundle: inSurvey = np.where(bundle[dither].metricValues.mask == False)[0] outSurvey = np.where(bundle[dither].metricValues.mask == True)[0] bundle[dither].metricValues.mask[outSurvey] = False # data pixels surveyMedian = np.median(bundle[dither].metricValues.data[inSurvey]) surveyStd = np.std(bundle[dither].metricValues.data[inSurvey]) # assign data[outOfSurvey]= medianData[inSurvey] bundle[dither].metricValues.data[outSurvey] = surveyMedian # subtract median off bundle[dither].metricValues.data[:] = bundle[dither].metricValues.data[:]-surveyMedian # save median for later use surveyMedianDict[dither] = surveyMedian surveyStdDict[dither] = surveyStd # ------------------------------------------------------------------------ # now find the alms correponding to the map. for dither in bundle: array = hp.anafast(bundle[dither].metricValues.filled(bundle[dither].slicer.badval), alm=True, lmax=500) cl = array[0] alm = array[1] l = np.arange(len(cl)) lsubsets = {} colorArray = ['y', 'r', 'g', 'm', 'c'] color = {} for case in range(len(subsetsToConsider)): lsubsets[case] = ((l>subsetsToConsider[case][0]) & (l<subsetsToConsider[case][1])) color[case] = colorArray[case] # ------------------------------------------------------------------------ # plot things out plt.clf() plt.plot(l, (cl*l*(l+1))/(2.0*np.pi), color='b') for key in list(lsubsets.keys()): plt.plot(l[lsubsets[key]], (cl[lsubsets[key]]*l[lsubsets[key]]*(l[lsubsets[key]]+1))/(2.0*np.pi), color=color[key]) plt.title(dither) plt.xlabel('$\ell$') plt.ylabel(r'$\ell(\ell+1)C_\ell/(2\pi)$') filename = 'cls_%s.png'%(dither) plt.savefig('%s%s/%s/%s'%(path, outDir, outDir2, filename), format='png', bbox_inches='tight') if showPlots: plt.show() else: plt.close() surveyMedian = surveyMedianDict[dither] surveyStd = surveyStdDict[dither] # ------------------------------------------------------------------------ # plot full-sky-alm plots first nTicks = 5 colorMin = surveyMedian-1.5*surveyStd colorMax = surveyMedian+1.5*surveyStd increment = (colorMax-colorMin)/float(nTicks) ticks = np.arange(colorMin+increment, colorMax, increment) # full skymap hp.mollview(hp.alm2map(alm, nside=nside, lmax=lmax)+surveyMedian, flip='astro', rot=(0,0,0), min=colorMin, max=colorMax, title='', cbar=False) hp.graticule(dpar=20, dmer=20, verbose=False) plt.title('Full Map') ax = plt.gca() im = ax.get_images()[0] fig = plt.gcf() cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04]) # [left, bottom, width, height] cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes) cb.set_label('$%s$-band Coadded Depth'%filterband) filename = 'alm_FullMap_%s.png'%(dither) plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir3, filename), format='png', bbox_inches='tight') # full cartview hp.cartview(hp.alm2map(alm, nside=nside, lmax=lmax)+surveyMedian, lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title='', cbar=False) hp.graticule(dpar=20, dmer=20, verbose=False) plt.title('Full Map') ax = plt.gca() im = ax.get_images()[0] fig= plt.gcf() cbaxes = fig.add_axes([0.1, -0.05, 0.8, 0.04]) # [left, bottom, width, height] cb = plt.colorbar(im, orientation='horizontal', format='%.2f', ticks=ticks, cax=cbaxes) cb.set_label('$%s$-band Coadded Depth'%filterband) filename = 'alm_Cartview_FullMap_%s.png'%(dither) plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir4, filename), format='png', bbox_inches='tight') # prepare for the skymaps for l-range subsets colorMin = surveyMedian-0.1*surveyStd colorMax = surveyMedian+0.1*surveyStd increment = (colorMax-colorMin)/float(nTicks) increment = 1.15*increment ticks = np.arange(colorMin+increment, colorMax, increment) # ------------------------------------------------------------------------ # consider each l-range for case in list(lsubsets.keys()): index = [] lowLim = subsetsToConsider[case][0] upLim = subsetsToConsider[case][1] for ll in np.arange(lowLim, upLim+1): for mm in np.arange(0,ll+1): index.append(hp.Alm.getidx(lmax=lmax, l=ll, m=mm)) alms1 = alm.copy() alms1.fill(0) alms1[index] = alm[index] # an unmasked array # plot the skymap hp.mollview(hp.alm2map(alms1, nside=nside, lmax=lmax)+surveyMedian, flip='astro', rot=(0,0,0), min=colorMin, max=colorMax, title='', cbar=False) hp.graticule(dpar=20, dmer=20, verbose=False) plt.title('%s<$\ell$<%s'%(lowLim, upLim)) ax = plt.gca() im = ax.get_images()[0] fig= plt.gcf() cbaxes = fig.add_axes([0.1, 0.015, 0.8, 0.04]) # [left, bottom, width, height] cb = plt.colorbar(im, orientation='horizontal',format='%.3f', ticks=ticks, cax = cbaxes) cb.set_label('$%s$-band Coadded Depth'%filterband) filename = 'almSkymap_%s<l<%s_%s.png'%(lowLim, upLim, dither) plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir3, filename), format='png', bbox_inches='tight') # plot cartview hp.cartview(hp.alm2map(alms1, nside=nside, lmax=lmax)+surveyMedian, lonra=raRange, latra=decRange, flip='astro', min=colorMin, max=colorMax, title='',cbar=False) hp.graticule(dpar=20, dmer=20, verbose=False) plt.title('%s<$\ell$<%s'%(lowLim, upLim)) ax = plt.gca() im = ax.get_images()[0] fig= plt.gcf() cbaxes = fig.add_axes([0.1, -0.05, 0.8, 0.04]) # [left, bottom, width, height] cb = plt.colorbar(im, orientation='horizontal',format='%.3f', ticks=ticks, cax=cbaxes) cb.set_label('$%s$-band Coadded Depth'%filterband) filename = 'almCartview_%s<l<%s_%s.png'%(lowLim, upLim, dither) plt.savefig('%s%s/%s/%s/%s'%(path, outDir, outDir2, outDir4, filename), format='png', bbox_inches='tight') if showPlots: plt.show() else: plt.close('all')
def __init__(self, background, nside=None, fignum=None, projection='mollweide', coord_bg='G', coord_plot='C', partialmap=False, config='footprint.cfg', map_path=None, download_config=False, title='Survey Footprints', cbar=None, min=1.0, max=5000.0, log=True, unit='', **kwds): self.fig = pl.figure(fignum) self.coord_plot = coord_plot self.partialmap = partialmap self.kwds = kwds self.cbs = [] if projection == 'mollweide': self.mapview = H.mollview self.mapcontour = vf.mollcontour elif projection == 'cartesian': self.mapview = H.cartview self.mapcontour = vf.cartcontour elif projection == 'orthographic': self.mapview = H.orthview self.mapcontour = vf.orthcontour elif projection == 'gnomonic': self.mapview = H.gnomview self.mapcontour = vf.gnomcontour if map_path is None: full_path = inspect.getfile(inspect.currentframe()) abs_path = os.path.split(full_path)[0] map_path = os.path.join(abs_path, 'maps/') self.config = ConfigHandler(config, map_path, nside=nside, download_config=download_config) # Could also just call load_survey which will call get_background if isinstance(background, str): bgmap, coord_bg, unit2 = self.config.load_survey(background, get_unit=True) background = bgmap[0] if unit2 is not None: unit = unit2 if nside is None: nside = H.npix2nside(len(background)) self.nside = nside coord = [coord_bg, coord_plot] cm.Greys.set_under(alpha=0.0) if log: min = np.log(min) max = np.log(max) unit = r'$\log($' + unit + r'$)$' background = np.log(background) if self.partialmap: sub = (1, 1, 1) margins = (0.01, 0.025, 0.01, 0.03) H.cartview(background, title=title, coord=coord, fig=self.fig.number, cmap=cm.Greys, notext=True, flip='astro', min=min, max=max, sub=sub, margins=margins, **kwds) self.fig.delaxes(self.fig.axes[-1]) else: self.mapview(background, title=title, coord=coord, fig=self.fig.number, cmap=cm.Greys, min=min, max=max, notext=True, cbar=True, flip='astro', unit=unit, **kwds) if not cbar: self.fig.delaxes(self.fig.axes[-1]) H.graticule(dpar=30.0, dmer=30.0, coord='C', verbose=False)
#!/usr/local/bin/python3
def run_final_mcmc( model=None, dir = '/global/scratch2/sd/dpietrob/DM-haze/data/maps/ns0128/', mfile = 'south_haze_ptsrc_mask_ns0128.fits', # mask used for the region fit sig_scaling = 8, haze_fit_mask = 'fit_mask_p-20_20_t-10-35_ns0128.fits', fix_cmb = True, fix_ff = False, # Does/does not assign freefree parameter inc_disc = False, ## inc_bubbles = True, ## :DP May 2015 to get Col.4 of Tab.3 running with no bubbles inc_bubbles = False, inc_mono = True, inc_dipo = True, plot_gnom = False, seed=0, regression = 0, tag = '', nsamples = 750000 ): if model == None: info_message( 'ERROR: dm_model not provided. Stop' ) sys.exit() tag = tag + '_' + model + '_2stp_'+str(sig_scaling).zfill(2)+'x' tag = tag + '_' + str(seed) print tag print model # --- Templates converted to mK_CMB fname = dir + 'haze_model_54_'+model+'_ns0128_K_norm.fits' if not os.path.isfile(fname): info_message( ' >>> making DM model templates...' ) make_dmhaze_templates( model=model ) # # # # --- Making a more suitable mask --- # 30 deg radius from [0,-22.5] # radius = -1 # if False: # m = hp.read_map( dir + 'south_haze_ptsrc_mask_ns0128.fits' ) # # hp.mollview(m) # print np.sum(m)/len(m) # # x,y,z = hp.ang2vec(np.pi/2+22.5/180.*np.pi ,0.) # d = make_disc(128, radius, direction=[x,y,z]) # # hp.mollview(d) # # hp.mollview(d*m) # print np.sum(m*d)/len(m) # # hp.write_map( dir + 'south'+str(radius)+'_haze_ptsrc_mask_ns0128.fits', d*m*ptsrc*ptsrc1 ) # hp.gnomview( d*m*ptsrc*ptsrc1, rot=[0,-22.5], reso=25, min=-1, max=1) # hp.graticule(dpar=5,dmer=5) # # hp.gnomview( ptsrc, rot=[0,-22.5], reso=25, min=-1, max=1) # # hp.graticule(dpar=5,dmer=5) # # m = hp.read_map( dir + 'fit_mask_p-35_35_t-10-35_ns0128.fits' ) # # hp.mollview(m) # print np.sum(m)/len(m) # # pl.show() # # sys.exit() # # if radius>0: # tag = 'southern'+str(radius) # mfile = 'south'+str(radius)+'_haze_ptsrc_mask_ns0128.fits' # else: # tag = 'southern' # mfile = 'south_haze_ptsrc_mask_ns0128.fits' # # # tag = tag + '_2stp' # # tag = tag + '_2stp_10x' # sig_scaling = 10 # # tag = tag + '_2stp_6freq_fxFF_'+str(sig_scaling).zfill(2)+'x' mask = hp.read_map( dir + mfile ) mask_npix = np.sum( mask ) fsky = np.sum( mask ) / len(mask) gpix = np.array( (mask == 1.) ) bpix = np.array( (mask == 0.) ) # --- Define haze flux computation region d = hp.read_map( dir + haze_fit_mask ) haze_region = (mask*d == 1) not_haze_region = (mask*d == 0) # --- What to do find_minimum = True run_mcmc = True # ------ plot_min_sed = False do_write = False # ------ Run MCMC ------ # setup = Data( DMmodel=model, maskfile='ebvh_mask_ns0128.fits', raw_sync=True ) # setup = Data( DMmodel=model, maskfile=mfile, raw_sync=True ) setup = Data( DMmodel=model, maskfile=mfile, raw_sync=True ) data = setup.data gmodel = setup.gmodel freq_min = OrderedDict() # --- Set parameter values from full sky for some components --- if find_minimum: info_message( 'Running regression' ) fx_mnpnt = OrderedDict() fx_mnpnt_er = OrderedDict() mnpnt = OrderedDict() mnpnt_er = OrderedDict() chisq = [] fx_c2 = 0. c2 = 0. flux = {} cfreq = data.cfreq mKt2cgs = conversionfactor( cfreq, option='mKthermo2cgs' ) haze_flux = [] haze_flux_er = [] haze_templ_flux = [] haze_templ_flux_er = [] # --- Find minimum for each frequency for ifreq, freq in enumerate( data.frequencies ): h = getattr( gmodel.haze, 'f'+freq ) # --- Full run for starting point determination # Thin disc component removed: chisq gets worse, but global fit does # not change drmatically. # tfiles = [ gmodel.galaxy.cmb.filename, gmodel.galaxy.dust.filename, gmodel.galaxy.freefree.filename, tfiles = [ gmodel.galaxy.cmb.filename, gmodel.galaxy.dust.filename, gmodel.galaxy.freefree.filename, gmodel.galaxy.sync.filename, h.filename ] icmb = 0 idust = 1 iff = 2 isync = 3 ihaze = 4 if inc_mono: tfiles.append( dir+'map_monopole_ns0128.fits' ) imono = len(tfiles)-1 if inc_dipo: tfiles.append( dir+'map_xdipole_ns0128.fits' ) idipox = len(tfiles)-1 tfiles.append( dir+'map_ydipole_ns0128.fits' ) idipoy = len(tfiles)-1 tfiles.append( dir+'map_zdipole_ns0128.fits' ) idipoz = len(tfiles)-1 if inc_disc: tfiles.append( gmodel.galaxy.disc.filename ) idisc = len(tfiles)-1 if inc_bubbles: tfiles.append( gmodel.galaxy.bubbles.filename ) ibubbles = len(tfiles)-1 map = getattr( data, 'f'+freq ) r = map_regression( map.imap.map, tfiles, rms=map.irms.map, maskfile=dir+'ebvh_mask_ns0128.fits', return_res=True, return_chi2=True ) # maskfile=dir+'map_monopole_ns0128.fits', return_res=True, return_chi2=True ) chisq.append( str("%.3f" % r[3]) ) fx_c2 += r[3] # hp.mollview( r[2], title='FS '+freq, min=-0.3, max=0.3) fx_mnpnt['f'+freq+'_cmb'] = r[0][icmb] fx_mnpnt['f'+freq+'_dust'] = r[0][idust] fx_mnpnt['f'+freq+'_freefree'] = r[0][iff] fx_mnpnt['f'+freq+'_sync'] = r[0][isync] fx_mnpnt['f'+freq+'_haze'] = r[0][ihaze] if inc_mono: fx_mnpnt['f'+freq+'_monopole'] = r[0][imono] if inc_dipo: fx_mnpnt['f'+freq+'_dipole_x'] = r[0][idipox] fx_mnpnt['f'+freq+'_dipole_y'] = r[0][idipoy] fx_mnpnt['f'+freq+'_dipole_z'] = r[0][idipoz] if inc_disc: fx_mnpnt['f'+freq+'_disc'] = r[0][idisc] if inc_bubbles: fx_mnpnt['f'+freq+'_bubbles'] = r[0][ibubbles] fx_mnpnt_er['f'+freq+'_cmb'] = r[1][icmb] fx_mnpnt_er['f'+freq+'_dust'] = r[1][idust] fx_mnpnt_er['f'+freq+'_freefree'] = r[1][iff] fx_mnpnt_er['f'+freq+'_sync'] = r[1][isync] fx_mnpnt_er['f'+freq+'_haze'] = r[1][ihaze] if inc_mono: fx_mnpnt_er['f'+freq+'_monopole'] = r[1][imono] if inc_dipo: fx_mnpnt_er['f'+freq+'_dipole_x'] = r[1][idipox] fx_mnpnt_er['f'+freq+'_dipole_z'] = r[1][idipoz] fx_mnpnt_er['f'+freq+'_dipole_y'] = r[1][idipoy] if inc_disc: fx_mnpnt_er['f'+freq+'_disc'] = r[1][idisc] if inc_bubbles: fx_mnpnt_er['f'+freq+'_bubbles'] = r[1][ibubbles] # --- Remove monopole, dipole and CMB from the map if inc_mono: flat_comp = r[0][imono] if inc_dipo: flat_comp += gmodel.galaxy.dipole_x.map * r[0][idipox] + \ gmodel.galaxy.dipole_y.map * r[0][idipoy] + \ gmodel.galaxy.dipole_z.map * r[0][idipoz] if fix_cmb: flat_comp += gmodel.galaxy.cmb.map * r[0][icmb] # gmodel.galaxy.freefree.map * r[0][2] # --- Run on small patch after flat component removed tfiles = [ gmodel.galaxy.dust.filename, gmodel.galaxy.sync.filename, h.filename, gmodel.galaxy.freefree.filename ] if inc_disc: tfiles.append( gmodel.galaxy.disc.filename ) idisc = len( tfiles ) -1 if inc_bubbles: tfiles.append( gmodel.galaxy.bubbles.filename ) ibubbles = len( tfiles ) -1 if not fix_cmb: tfiles.append( gmodel.galaxy.cmb.filename ) icmb = len( tfiles ) -1 #if inc_mono: # tfiles.append( dir+'map_monopole_ns0128.fits' ) # imono = len( tfiles ) -1 # map = getattr( data, 'f'+freq ) # --- Setting up the smaller mask in the southern region imap = getattr( map, 'imap' ) setattr(imap, 'map', map.imap.map-flat_comp ) setattr(map, 'imap', imap ) r = map_regression( map.imap.map, tfiles, rms=map.irms.map, maskfile=dir+mfile, return_res=True, return_chi2=True ) chisq.append( str("%.3f" % r[3]) ) c2 += r[3] # --- Plot gnomview projections if plot_gnom: ccc = map.imap.map ccc[ bpix] = -1.6375e30 hp.gnomview( ccc, title=freq, rot=[0,-22.5], reso=25 ) hp.graticule(dpar=5,dmer=5) if freq == '070': ccc = gmodel.galaxy.cmb.map ccc[ bpix] = -1.6375e30 hp.gnomview( ccc, min=-0.3, max=0.3, title='CMB', rot=[0,-22.5], reso=25 ) hp.graticule(dpar=5,dmer=5) if freq == 'K': ccc = gmodel.galaxy.sync.map ccc[ bpix] = -1.6375e30 hp.gnomview( ccc, title='Sync', rot=[0,-22.5], reso=25 ) hp.graticule(dpar=5,dmer=5) ccc = gmodel.galaxy.dust.map ccc[ bpix] = -1.6375e30 hp.gnomview( ccc, title='Dust', rot=[0,-22.5], reso=25 ) hp.graticule(dpar=5,dmer=5) ccc = gmodel.galaxy.freefree.map ccc[ bpix] = -1.6375e30 hp.gnomview( ccc, title='FF', rot=[0,-22.5], reso=25 ) hp.graticule(dpar=5,dmer=5) ccc = r[2]*mask ccc[ bpix] = -1.6375e30 hp.gnomview( ccc, min=-0.05, max=0.05, title='Residuals: '+freq, rot=[0,-22.5], reso=25 ) hp.graticule(dpar=5,dmer=5) ccc = (r[2]+r[0][2]*h.map)*mask ccc[ bpix] = -1.6375e30 hp.gnomview( ccc, title='Haze: '+freq, rot=[0,-22.5], reso=25 ) hp.graticule(dpar=5,dmer=5) # ccc = (r[0][2]*h.map)*mask # ccc[ bpix] = -1.6375e30 # hp.gnomview( ccc, min=0., title='Haze template: '+freq, rot=[0,-22.5], reso=25 ) # hp.graticule(dpar=5,dmer=5) pl.show() # --- Flux with residuals # haze_flux.append( np.mean( (r[2] + r[0][2]*h.map )[gpix] ) * mKt2cgs[ifreq] ) haze_flux.append( np.mean( (r[2] + r[0][2]*h.map )[haze_region] ) * mKt2cgs[ifreq] ) # haze_flux_er.append( np.std( (r[2] + r[0][2]*h.map)[gpix] ) * mKt2cgs[ifreq] ) # --- Trying to be independent of the haze template # haze_flux_er.append( np.std( r[2][gpix] ) * mKt2cgs[ifreq] ) haze_flux_er.append( np.sqrt( np.var( r[2][haze_region] ) + (haze_flux[-1]*r[1][2])**2)* mKt2cgs[ifreq] ) freq_min[ freq ] = r mnpnt['f'+freq+'_dust'] = r[0][0] mnpnt['f'+freq+'_sync'] = r[0][1] mnpnt['f'+freq+'_haze'] = r[0][2] mnpnt['f'+freq+'_freefree'] = r[0][3] if inc_disc: mnpnt['f'+freq+'_disc'] = r[0][idisc] if inc_bubbles: mnpnt['f'+freq+'_bubbles'] = r[0][ibubbles] if not fix_cmb: mnpnt['f'+freq+'_cmb'] = r[0][icmb] #if inc_mono: # mnpnt['f'+freq+'_monopole'] = r[0][imono] mnpnt_er['f'+freq+'_dust'] = r[1][0] mnpnt_er['f'+freq+'_sync'] = r[1][1] mnpnt_er['f'+freq+'_haze'] = r[1][2] mnpnt_er['f'+freq+'_freefree'] = r[1][3] if inc_disc: mnpnt_er['f'+freq+'_disc'] = r[1][idisc] if inc_bubbles: mnpnt_er['f'+freq+'_bubbles'] = r[1][ibubbles] if not fix_cmb: mnpnt_er['f'+freq+'_cmb'] = r[1][icmb] #if inc_mono: # mnpnt_er['f'+freq+'_monopole'] = r[1][imono] flux[model+'_haze'] = ( np.array( haze_flux )*1.e20, np.array( haze_flux_er )*1.e20 ) if do_write: figtag = '../sed_dm_' + model + '_2step_' + tag if fix_cmb: figtag = figtag + '_fixCMB' if not inc_disc: figtag = figtag + '_noDISC' if inc_mono: figtag = figtag + '_MONO' file = open(figtag + '.txt', 'w') file.write( '# cfreq, res_haze, res_haze err\n' ) for ifreq,freq in enumerate(data.cfreq): # print ifreq, freq file.write( '%f \t %f \t %f \n' %(freq, flux[model+'_haze'][0][ifreq], flux[model+'_haze'][1][ifreq] ) ) file.close() # print flux info_message(' total chi2 = '+str(c2)+','+str(c2*np.sum(mask))) sed = get_sed( mnpnt ) sed_er = get_sed( mnpnt_er ) fx_sed = get_sed( fx_mnpnt ) fx_sed_er = get_sed( fx_mnpnt_er ) if plot_min_sed: f = data.cfreq cv = conversionfactor( f, option='antenna2thermo' ) fig = plt.figure(30+imodel,(18,7.5), dpi=80) # --- SED plot based on regression coefficients ax = plt.subplot(121) plt.errorbar( f, sed['dust'], yerr=sed_er['dust'], label='dust', color='b', fmt='s:' ) plt.errorbar( f, sed['sync'], yerr=sed_er['sync'], label='sync', color='g', fmt='s:' ) plt.errorbar( f, sed['haze'], yerr=sed_er['haze'], label='haze', color='m', fmt='s:' ) plt.errorbar( f, sed['freefree'], yerr=sed_er['freefree'], label='freefree', color='r', fmt='s:' ) if not fix_cmb: plt.errorbar( f, sed['cmb'], yerr=sed_er['cmb'], label='cmb', color='k', fmt='s:' ) if inc_disc: plt.errorbar( f, sed['disc'], yerr=sed_er['disc'], label='disc', color='y', fmt='s:' ) plt.errorbar( f, fx_sed['cmb'], yerr=fx_sed_er['cmb'], label='cmb FS', color='k', fmt='.-' ) plt.errorbar( f, fx_sed['dust'], yerr=fx_sed_er['dust'], label='dust FS', color='b', fmt='.-' ) plt.errorbar( f, fx_sed['sync'], yerr=fx_sed_er['sync'], label='sync FS', color='g', fmt='.-' ) plt.errorbar( f, fx_sed['haze'], yerr=fx_sed_er['haze'], label='haze FS', color='m', fmt='.-' ) plt.errorbar( f, fx_sed['freefree'], yerr=fx_sed_er['freefree'], label='freefree FS', color='r', fmt='.-' ) if inc_disc: plt.errorbar( f, fx_sed['disc'], yerr=fx_sed_er['disc'], label='disc FS', color='y', fmt='s-' ) plt.plot( f, (f/f[0])**(-3.1)*cv*fx_sed['sync'][0], ':', label='-3.1', color='g' ) plt.plot( f, (f/f[0])**(-2.15)*cv*fx_sed['freefree'][0], ':', label='-2.15', color='r' ) plt.plot( f, f*0.+sed['haze'][0], ':', color='m', label='same amplitude' ) plt.title('Dark matter model: '+model) plt.xlabel(r'$\nu$ [GHz]') plt.ylabel('Template amplitudes') ax.set_yscale('log') ax.set_xscale('log') ax.set_ylim([5e-3,10]) ax.set_xlim([8,100]) plt.legend( loc='upper left',prop={'size':10}) # --- Monopole dipole plot # ax = plt.subplot(122) # # plt.errorbar( f, sed['monopole'], yerr=sed_er['monopole'], label='monopole', color='k' ) # plt.errorbar( f, sed['dipole_x'], yerr=sed_er['dipole_x'], label='dipole_x', color='b' ) # plt.errorbar( f, sed['dipole_y'], yerr=sed_er['dipole_y'], label='dipole_y', color='r' ) # plt.errorbar( f, sed['dipole_z'], yerr=sed_er['dipole_z'], label='dipole_z', color='m' ) # plt.plot( f, f*0., '--', color='g' ) # plt.errorbar( f, sed_noh['monopole'], yerr=sed_er_noh['monopole'], label='monopole no-haze', color='k', fmt='--' ) # plt.errorbar( f, sed_noh['dipole_x'], yerr=sed_er_noh['dipole_x'], label='dipole_x no-haze', color='b', fmt='--' ) # plt.errorbar( f, sed_noh['dipole_y'], yerr=sed_er_noh['dipole_y'], label='dipole_y no-haze', color='r', fmt='--' ) # plt.errorbar( f, sed_noh['dipole_z'], yerr=sed_er_noh['dipole_z'], label='dipole_z no-haze', color='m', fmt='--' ) # # plt.errorbar( f, sed_nod['monopole'], yerr=sed_er_nod['monopole'], label='monopole no-disc', color='k', fmt='s-' ) # plt.errorbar( f, sed_nod['dipole_x'], yerr=sed_er_nod['dipole_x'], label='dipole_x no-disc', color='b', fmt='s-' ) # plt.errorbar( f, sed_nod['dipole_y'], yerr=sed_er_nod['dipole_y'], label='dipole_y no-disc', color='r', fmt='s-' ) # plt.errorbar( f, sed_nod['dipole_z'], yerr=sed_er_nod['dipole_z'], label='dipole_z no-disc', color='m', fmt='s-' ) # # plt.title(r'$^{\rm red}\chi^2=$'+', '.join(chisq)+r'$\pm0.0028$'+' vs \n'+', '.join(chisq_noh)+' vs \n'+', '.join(chisq_nod), fontsize=12) # # plt.title('Dark matter model: '+model+' - Southern region') # plt.xlabel(r'$\nu$ [GHz]') # plt.ylabel(r'Mono/dipole amplitudes [mK_CMB]') # # ax.set_xlim([10,100]) # ax.set_xscale('log') # hd = np.reshape([sed['monopole'],sed['dipole_x'],sed['dipole_y'],sed['dipole_z'],sed_noh['monopole'],sed_noh['dipole_x'],sed_noh['dipole_y'],sed_noh['dipole_z']], 8*len(sed['monopole']) ) # thrs = 1.1 * np.max( abs( hd ) ) # ax.set_ylim([-thrs,thrs]) # plt.legend( loc='lower right',prop={'size':10}) # --- SED plot based on average flux in the region. # Mind, this is region dependent!!! ax = plt.subplot(122) plt.errorbar( f, flux[model+'_haze'][0], yerr=flux[model+'_haze'][1], label='Haze flux', color='m', fmt='s-' ) plt.plot( f, f*0., '--', color='k') ax.set_ylim([-.75,2]) ax.set_xlim([8,100]) plt.xlabel(r'$\nu$ [GHz]') plt.ylabel(r'Haze flux [erg/(cm$^2$ s Hz sr)] $\times 10^{20}$') plt.legend( loc='upper left',prop={'size':10}) ax.annotate(', '.join(data.frequencies), xy=(10, -0.5) ) ax.annotate(', '.join([ str("%0.3f" %s) for s in flux[model+'_haze'][0] ]), xy=(10, -0.6) ) ax.annotate(r'$\pm$'+', '.join([ str("%0.3f" %s) for s in flux[model+'_haze'][1] ]), xy=(10, -0.7) ) figtag = '../sed_dm_'+model+'_2step_'+tag if fix_cmb: figtag = figtag + '_fixCMB' if not inc_disc: figtag = figtag + '_noDISC' if inc_mono: figtag = figtag + '_MONO' fig.savefig(figtag + '.png') pl.show() # --- Setting starting point p = OrderedDict() limits = {} limits['dust'] = (0.,11.) limits['freefree'] = (0.,50) limits['sync'] = (0.,50) limits['cmb'] = (0.97,1.03) # limits['monopole'] = (-0.06,0.06) # limits['disc'] = (0,100) # limits['monopole'] = (-0.06,0.06) limits['disc'] = (0.,1) limits['bubbles'] = (0.,10.) #This is actually the Haze, not DM # sig_scaling = 6. # p['global_haze'] = {'center_value':np.min( sed['haze'] ), 'sigma':np.min(sed_er['haze'])/sig_scaling, 'min':0., 'max':1000} p['global_haze'] = {'center_value':sed['haze'][0], 'sigma':np.min(sed_er['haze'])/sig_scaling, 'min':0., 'max':1000.} for ifreq, freq in enumerate( data.frequencies ): m = getattr( data, 'f'+freq ) # hp.mollview( m.imap.map ) r = freq_min[ freq ] if not fix_cmb: p['f'+freq+'_cmb'] = {'center_value':np.max( np.array([0.,sed['cmb'][ifreq]])), 'sigma':np.min(sed_er['cmb'])/sig_scaling, 'min':limits['cmb'][0], 'max':limits['cmb'][1]} p['f'+freq+'_dust'] = {'center_value':np.max( np.array([0.,sed['dust'][ifreq]])), 'sigma':np.min(sed_er['dust'])/sig_scaling, 'min':limits['dust'][0], 'max':limits['dust'][1]} if not fix_ff: p['f'+freq+'_freefree'] = {'center_value':np.max( np.array([0.,sed['freefree'][ifreq]])), 'sigma':np.min(sed_er['freefree'])/sig_scaling, 'min':limits['freefree'][0], 'max':limits['freefree'][1]} p['f'+freq+'_sync'] = {'center_value':np.max( np.array([0.,sed['sync'][ifreq]])), 'sigma':np.min(sed_er['sync'])/sig_scaling, 'min':limits['sync'][0], 'max':limits['sync'][1]} # p['f'+freq+'_monopole'] = {'center_value':r[0][5], 'sigma':np.min(sed_er['monopole'])/sig_scaling, 'min':limits['monopole'][0], 'max':limits['monopole'][1]} # p['f'+freq+'_dipole_x'] = {'center_value':r[0][6], 'sigma':np.min(sed_er['dipole_x'])/sig_scaling, 'min':limits['monopole'][0], 'max':limits['monopole'][1]} # p['f'+freq+'_dipole_y'] = {'center_value':r[0][7], 'sigma':np.min(sed_er['dipole_y'])/sig_scaling, 'min':limits['monopole'][0], 'max':limits['monopole'][1]} # p['f'+freq+'_dipole_z'] = {'center_value':r[0][8], 'sigma':np.min(sed_er['dipole_z'])/sig_scaling, 'min':limits['monopole'][0], 'max':limits['monopole'][1]} if inc_disc: p['f'+freq+'_disc'] = {'center_value':np.max( np.array([0.,r[0][9]])), 'sigma':np.min(sed_er['disc'])/sig_scaling, 'min':limits['disc'][0], 'max':limits['disc'][1]} if inc_bubbles: p['f'+freq+'_bubbles'] = {'center_value':np.max( np.array([0.,sed['bubbles'][ifreq]])), 'sigma':np.min(sed_er['bubbles'])/sig_scaling, 'min':limits['bubbles'][0], 'max':limits['bubbles'][1]} ppp = {} for key in p.keys(): print key, '\t', p[key]['center_value'], '\t', p[key]['sigma'] ppp[key] = p[key]['center_value'] info_message( 'Starting point chi2: '+str(setup.fg_chisq(ppp) ) ) # sys.exit() # ------ Run MCMC ------ mcmc = MCMC() if run_mcmc: bf, ch = mcmc.sampler( p, setup.fg_chisq, nsamples=nsamples, seed=seed, output_tag=tag, temperature=1., accept_first=False, update_covmat=False )
def visualize_map(args): """Visualize sky maps in hdf5 files. Arguments --------- args : argparse namespace. """ import numpy as np import h5py import healpy # import hpvisual import matplotlib matplotlib.use('Agg') try: # for new version matplotlib import matplotlib.style as mstyle mstyle.use('classic') except ImportError: pass from matplotlib import pyplot as plt # Read in maps data hpmap = None for mapname in args.mapfiles: with h5py.File(mapname, 'r') as f: if hpmap is None: hpmap = f['map'][:] else: hpmap += f['map'][:] # Check args validity if args.ifreq < -(hpmap.shape)[0] or args.ifreq >= (hpmap.shape)[0]: raise Exception('Invalid frequency channel %d, should be in range(-%d, %d).'%(args.ifreq, (hpmap.shape)[0], (hpmap.shape)[0])) else: ifreq = args.ifreq if args.ifreq >= 0 else args.ifreq + (hpmap.shape)[0] if args.pol >= (hpmap.shape)[1]: raise Exception('Invalid frequency channel %d, should be in range(0, %d).'%(args.pol, (hpmap.shape)[1])) if args.figlength <= 0: raise Exception('Figure length figlength (= %f) must greater than 0'%args.figlength) if args.figwidth <= 0: raise Exception('Figure width figwidth (= %f) must greater than 0'%args.figwidth) # Create output image file name if args.outfile: out_file = args.outfile else: out_file = ((args.mapfiles[0].split('/')[-1]).split('.')[0] + '_' + str(ifreq) + '_{' + str(args.pol) + '}' + '.' + args.figfmt).format('T', 'Q', 'U', 'V') # Plot and save image if args.view == 'o': fig = plt.figure(1, figsize=(8, 6)) else: fig = plt.figure(1, figsize=(args.figlength,args.figwidth)) map_data = hpmap[ifreq][args.pol] if args.sqrt: map_data = map_data / np.sqrt(np.abs(map_data)) map_data = map_data / np.sqrt(np.abs(map_data)) # map_data = map_data / np.sqrt(np.abs(map_data)) # smoothing the map with a Gaussian symmetric beam if args.fwhm is not None: fwhm = np.radians(args.fwhm) map_data = healpy.smoothing(map_data, fwhm=fwhm) if args.view == 'm': # set color map if args.cmap is None: cmap = None else: if args.cmap == 'jet09': import colormap cmap = colormap.jet09 else: from pylab import cm # cmap = cm.hot cmap = getattr(cm, args.cmap) cmap.set_under('w') if args.abs: healpy.mollview(np.abs(map_data), fig=1, title='', unit=args.unit, cmap=cmap, min=args.min, max=args.max) else: healpy.mollview(map_data, fig=1, title='', unit=args.unit, cmap=cmap, min=args.min, max=args.max) # plot NVSS sources if args.nvss is not None: import aipy as a flux = args.nvss frequency = 750 # MHz catalog = 'nvss' # catalog = 'wenss' src = '%f/%f' % (flux, frequency / 1.0e3) srclist, cutoff, catalogs = a.scripting.parse_srcs(src, catalog) cat = a.src.get_catalog(srclist, cutoff, catalogs) nsrc = len(cat) # number of sources in cat ras = [ np.degrees(cat.values()[i]._ra) for i in range(nsrc) ] decs = [ np.degrees(cat.values()[i]._dec) for i in range(nsrc) ] jys = [ cat.values()[i].get_jys() for i in range(nsrc) ] # select sources inds = np.where(np.array(decs)>-15.0)[0] ras = np.array(ras)[inds] decs = np.array(decs)[inds] jys = np.array(jys)[inds] # healpy.projscatter(ras, decs, lonlat=True, s=jys, facecolors='none', edgecolors='w', alpha=1.0, linewidth=1.0) healpy.projscatter(ras, decs, lonlat=True, s=150, facecolors='none', edgecolors='w', alpha=1.0, linewidth=1.0) elif args.view == 'c': healpy.cartview(map_data, fig=1, title='', unit=args.unit, min=args.min, max=args.max) elif args.view == 'o': healpy.orthview(map_data, rot=(0, 90, 0), fig=1, title='', unit=args.unit, min=args.min, max=args.max, half_sky=True) # rot to make NCP at the center # fig = plt.figure() # ax = fig.add_axes() # cbar.solids.set_rasterized(True) if args.grid: healpy.graticule() if args.tight: fig.savefig(out_file, bbox_inches='tight') else: fig.savefig(out_file) fig.clf()
parser.add_option('-t','--targets',default=None) parser.add_option('-c','--coord',default='GAL') parser.add_option('-p','--proj',default='MOL',choices=['MOL','CAR']) parser.add_option('-f','--field',default='LOG_LIKELIHOOD') (opts, args) = parser.parse_args() nside = pyfits.open(args[0])[1].header['NSIDE'] map = healpy.UNSEEN * numpy.ones( healpy.nside2npix(nside) ) pix,vals = ugali.utils.skymap.readSparseHealpixMap(args[0],opts.field,construct_map=False) map[pix] = vals[0] if opts.coord.upper() == "GAL": coord = 'G' elif opts.coord.upper() == "CEL": coord = 'GC' if opts.proj.upper() == "MOL": healpy.mollview(map,coord=coord,xsize=1000) elif opts.proj.upper() == "CAR": healpy.cartview(map,coord=coord,xsize=1000) else: raise Exception("...") healpy.graticule() if opts.targets: data = numpy.loadtxt(opts.targets,unpack=True,dtype='str') coord = 'CG' # For RA/DEC input healpy.projscatter(data[1].astype(float),data[2].astype(float), lonlat=True,coord=coord,marker='o',c='w') plt.savefig(opts.outfile)
def go(mcFile, npix, ntrials, plottrial=0, plotlog=False, olddisks=False): #healpixTable = open(mcFile, 'rb') nside = healpy.npix2nside(npix) #healpix = healpixTable[:,plottrial] #hp = healpixTable.read() #healpix = np.fromstring(hp, dtype=np.float64) #start_arr = plottrial*npix #end_arr = plottrial*npix+npix #healpix = healpix[start_arr:end_arr] healpix = np.fromfile(mcFile, dtype=float) healpix = healpix.reshape((ntrials, npix)) healpix = healpix[plottrial] if plotlog == True: healpix = np.log(healpix) # all sky pixels sorted with highest pixels first idx = (np.argsort(healpix))[::-1] sortHP = healpix[idx] # Cumulatively sum up the pixels cumHP = np.cumsum(sortHP) totHP = sortHP.sum() # Make contours pixIdx = np.arange(npix) theta, phi = healpy.pix2ang(nside, pixIdx) # Peak disk value peakPixVal = healpix.max() peakPixIdx = healpix.argmax() peakIncl = np.degrees(theta[peakPixIdx]) peakOmeg = np.degrees(phi[peakPixIdx]) print 'Disk candidate at i = %6.2f, O = %6.2f' % (peakIncl, peakOmeg) # Determine the background (avg and stddev) avgiter = 2 idx = np.arange(len(healpix)) for ii in range(avgiter): avgval = healpix[idx].mean() stddev = healpix[idx].std() hicut = avgval + 5.0 * stddev locut = avgval - 5.0 * stddev idx = np.where((healpix > locut) & (healpix < hicut))[0] print 'BKG: iter = %d, rejecting %d out of %d pixels' % \ (ii, (npix - len(idx)), npix) print '' print 'Background mean = %f, stddev = %f' % (avgval, stddev) print 'Peak = %f, significance = %f' % \ (healpix.max(), (healpix.max() - avgval) / stddev) # Find pixels 1, 2, 3 sigma below the peak idx1 = np.where(healpix > (peakPixVal - (1.0 * stddev)))[0] idx2 = np.where(healpix > (peakPixVal - (2.0 * stddev)))[0] idx3 = np.where(healpix > (peakPixVal - (3.0 * stddev)))[0] cnt1 = len(idx1) cnt2 = len(idx2) cnt3 = len(idx3) inclRng1 = np.degrees([min(theta[idx1]), max(theta[idx1])]) inclRng2 = np.degrees([min(theta[idx2]), max(theta[idx2])]) inclRng3 = np.degrees([min(theta[idx3]), max(theta[idx3])]) omegRng1 = np.degrees([min(phi[idx1]), max(phi[idx1])]) omegRng2 = np.degrees([min(phi[idx2]), max(phi[idx2])]) omegRng3 = np.degrees([min(phi[idx3]), max(phi[idx3])]) fmt = '%d sigma ranges: i = [%5.1f - %5.1f] o = [%5.1f - %5.1f] (N=%d)' print fmt % (1, inclRng1[0], inclRng1[1], omegRng1[0], omegRng1[1], cnt1) print fmt % (2, inclRng2[0], inclRng2[1], omegRng2[0], omegRng2[1], cnt2) print fmt % (3, inclRng3[0], inclRng3[1], omegRng3[0], omegRng3[1], cnt3) # Now display gaussian fits along inclination and Omega to get # estimate of the disk thickness iidx = np.where((np.degrees(theta) > (peakIncl - 45.0)) & (np.degrees(theta) < (peakIncl + 45.0)) & (np.degrees(phi) > (peakOmeg - 1.0)) & (np.degrees(phi) < (peakOmeg + 1.0)))[0] oidx = np.where((np.degrees(phi) > (peakOmeg - 45.0)) & (np.degrees(phi) < (peakOmeg + 45.0)) & (np.degrees(theta) > (peakIncl - 1.0)) & (np.degrees(theta) < (peakIncl + 1.0)))[0] #py.clf() #py.plot(np.degrees(theta[iidx]),healpix[iidx],'r.') #py.plot(np.degrees(phi[oidx]),healpix[oidx],'b.') #py.show() # Plot the previously proposed disks if olddisks == True: i = [129.0, 30.0] # clockwise (Bartko+09); CCW (Paumard+06) i_err = [3.0, 4.0] i_thick = [9.0, 9.5] Om = [98.0, 167.0] Om_err = [3.0, 9.0] Om_thick = [9.0, 9.5] disks = {'s1': ellipseOutline(i[0], Om[0], i_err[0], Om_err[0]), 's2': ellipseOutline(i[1], Om[1], i_err[1], Om_err[1]), 's3': ellipseOutline(i[0], Om[0], i_thick[0], Om_thick[0], line='--'), 's4': ellipseOutline(i[1], Om[1], i_thick[1], Om_thick[1], line='--')} s1 = ellipseOutline(i[0], Om[0], i_err[0], Om_err[0]) s2 = ellipseOutline(i[1], Om[1], i_err[1], Om_err[1]) s3 = ellipseOutline(i[0], Om[0], i_thick[0], Om_thick[0]) s4 = ellipseOutline(i[1], Om[1], i_thick[1], Om_thick[1]) # Plot up the orientation of the orbital plane for this star py.clf() healpy.mollview(healpix, 1, coord=['C','C'], flip='geo', rot=[0,180], #cmap=py.cm.gist_stern_r,title='i=180', cmap=py.cm.Blues,title='i=180', fontsize=12,notext=True) healpy.graticule(dpar=30,dmer=45) # old disk plotting not functional yet: #py.plot(s1['dec'], s1['ra'], 'k-') #py.plot(s2['dec'], s2['ra'], 'k-') #py.plot(s3['dec'], s3['ra'], 'k--') #py.plot(s4['dec'], s4['ra'], 'k--') fs = 12 py.text(0.02, -0.98, '0', fontsize=fs) py.text(0.02, -0.73, '30', fontsize=fs) py.text(0.02, -0.38, '60', fontsize=fs) py.text(0.02, 0.02, '90', fontsize=fs) py.text(0.00, 0.43, '120', fontsize=fs) py.text(0.00, 0.80, '150', fontsize=fs) py.text(-1.07, 0.02, 'N', fontsize=fs) py.text(-0.07, 0.02, 'W', fontsize=fs) py.text(0.93, 0.02, 'S', fontsize=fs) py.text(1.93, 0.02, 'E', fontsize=fs) py.savefig(mcFile + '.png') py.close()
def plotSkyMap(self, metricValueIn, xlabel=None, title='', logScale=False, cbarFormat='%.2f', cmap=cm.jet, percentileClip=None, colorMin=None, colorMax=None, zp=None, normVal=None, cbar_edge=True, label=None, nTicks=None, rot1=0, rot2=0, rot3=0, **kwargs): """ Plot the sky map of metricValue using healpy Mollweide plot. metricValue = metric values units = units for metric color-bar label title = title for plot cbarFormat = format for color bar numerals (i.e. '%.2g', etc) (default to matplotlib default) rot1,2,3 = rotations passed to mollview. """ # Generate a Mollweide full-sky plot. norm = None if logScale: norm = 'log' if cmap is None: cmap = cm.jet if type(cmap) == str: cmap = getattr(cm,cmap) # Make colormap compatible with healpy cmap = colors.LinearSegmentedColormap('cmap', cmap._segmentdata, cmap.N) cmap.set_over(cmap(1.0)) cmap.set_under('w') cmap.set_bad('gray') if zp: metricValue = metricValueIn - zp elif normVal: metricValue = metricValueIn/normVal else: metricValue = metricValueIn if percentileClip: pcMin, pcMax = percentileClipping(metricValue.compressed(), percentile=percentileClip) if colorMin is None and percentileClip: colorMin = pcMin if colorMax is None and percentileClip: colorMax = pcMax if (colorMin is not None) or (colorMax is not None): clims = [colorMin, colorMax] else: clims = None # Make sure there is some range on the colorbar if clims is None: if metricValue.compressed().size > 0: clims=[metricValue.compressed().min(), metricValue.compressed().max()] else: clims = [-1,1] if clims[0] == clims[1]: clims[0] = clims[0]-1 clims[1] = clims[1]+1 rot = (rot1,rot2,rot3) hp.mollview(metricValue.filled(self.badval), title=title, cbar=False, min=clims[0], max=clims[1], rot=rot, flip='astro', cmap=cmap, norm=norm) # This graticule call can fail with old versions of healpy and matplotlib 1.4.0. # Make sure the latest version of healpy in the stack is setup hp.graticule(dpar=20, dmer=20, verbose=False) # Add colorbar (not using healpy default colorbar because want more tickmarks). ax = plt.gca() im = ax.get_images()[0] # Add label. if label is not None: plt.figtext(0.8, 0.8, '%s' %label) # supress silly colorbar warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") cb = plt.colorbar(im, shrink=0.75, aspect=25, orientation='horizontal', extend='both', extendrect=True, format=cbarFormat) cb.set_label(xlabel) if nTicks is not None: tick_locator = ticker.MaxNLocator(nbins=nTicks) cb.locator = tick_locator cb.update_ticks() # If outputing to PDF, this fixes the colorbar white stripes if cbar_edge: cb.solids.set_edgecolor("face") fig = plt.gcf() return fig.number
def plot(data, showdisks=False, unit='stars/deg^2'): _fontsize = rcParams['font.size'] _fontweight = rcParams['font.weight'] rcParams['font.size'] = 14 rcParams['font.weight'] = 'normal' # Draw the map healpy.mollview(map=data, rot=[0, 180], cmap=cm.gist_stern_r, title='', unit=unit) healpy.graticule(dpar=30.0, dmer=45.0, local=True) # Handle colorbar labels try: fig = py.gcf() cbar = fig.axes[-1] cbarLabels = cbar.xaxis.get_ticklabels() for cc in range(len(cbarLabels)): cbarLabels[cc] = '%.5f' % float(cbarLabels[cc].get_text()) cbar.xaxis.set_ticklabels(cbarLabels, fontweight='bold', fontsize=14) except UnicodeEncodeError: pass # Draw contours for the old disk positions if showdisks: incl = [124.0, 30.0] incl_err = [2.0, 4.0] incl_thick = [7.0, 9.5] Om = [100.0, 167.0] Om_err = [3.0, 9.0] Om_thick = [7.0, 9.5] for jj in range(len(incl)): x1, y1 = ellipseOutline(incl[jj], Om[jj], incl_err[jj], Om_err[jj]) x2, y2 = ellipseOutline(incl[jj], Om[jj], incl_thick[jj], Om_thick[jj]) healpy.projplot(x1, y1, lonlat=True, color='k', linestyle='-', linewidth=2) healpy.projplot(x2, y2, lonlat=True, color='k', linestyle='--', linewidth=2) # Flip so that the axes go in the right direction foo = py.axis() py.xlim(2.01, -2.01) # Make axis labels. healpy.projtext(178, 90, '0', lonlat=True) healpy.projtext(178, 60, '30', lonlat=True) healpy.projtext(178, 30, '60', lonlat=True) healpy.projtext(178, 0, '90', lonlat=True) healpy.projtext(178, -30, '120', lonlat=True) healpy.projtext(178, -60, '150', lonlat=True) healpy.projtext(178, -90, 'i = 180', lonlat=True, horizontalalignment='center') healpy.projtext(92, 1, 'S', lonlat=True, horizontalalignment='right', verticalalignment='top') healpy.projtext(182, 1, 'W', lonlat=True, horizontalalignment='right', verticalalignment='top') healpy.projtext(272, 1, 'N', lonlat=True, horizontalalignment='right', verticalalignment='top') healpy.projtext(362, 1, 'E', lonlat=True, horizontalalignment='right', verticalalignment='top') rcParams['font.size'] = _fontsize rcParams['font.weight'] = _fontweight
def main(): """Simple test unit """ from scipy.interpolate import interp1d cat_file = os.path.join(GRATOOLS_CONFIG,'catalogs/gll_psc_v16.fit') src_cat = pf.open(cat_file) CAT = src_cat['LAT_Point_Source_Catalog'] SOURCES = CAT.data src_cat.close() flux = np.sort(SOURCES.field('Flux1000')) flux_min, flux_max = min(flux), max(flux) """ rad_min, rad_max = 0.5, 5. RADdeg = rad_min + flux*((rad_max - rad_min)/(flux_max - flux_min)) -\ flux_min*((rad_max - rad_min)/(flux_max - flux_min)) plt.figure(facecolor='white') plt.title('Disk Radius as a function of $\Phi_{src}$') plt.plot(flux, RADdeg, '*-', color='cornflowerblue', linewidth=1, ms=5, alpha=0.2) plt.xlabel('Flux [photon/cm$^{2}$/s]') plt.ylabel('mask disk Radius [$^{\circ}$]') plt.yscale('log') plt.xscale('log') plt.ylim(1.5, 6) plt.grid(which='both', linestyle='--', linewidth=1) """ """ from GRATools.utils.gWindowFunc import get_psf_ref psf_ref_file = os.path.join(GRATOOLS_CONFIG, 'ascii/PSF_UCV_custom.txt') psf_ref = get_psf_ref(psf_ref_file) energy = np.logspace(1, 6, 10) energy = [301.99,524.81,1000.00,2754.23, 8317.64,22908.68,331131.12] lab = ['PSF3','PSF3','PSF1+2+3', 'PSF1+2+3', 'PSF1+2+3','PSF1+2+3', 'PSF1+2+3'] plt.figure(facecolor='white') for i, en in enumerate(energy): r_min = 2*psf_ref(en) r_max = 5*psf_ref(en) print 'R min', r_min, 'R max', r_max print 'F min', flux_min, 'F max', flux_max RADdeg = r_min + np.log10(flux)*((r_max - r_min)/(np.log10(flux_max) - np.log10(flux_min))) -\ np.log10(flux_min)*((r_max - r_min)/(np.log10(flux_max) - np.log10(flux_min))) #plt.figure(facecolor='white') plt.title('Disk Radius as a function of $\Phi_{src}$') plt.plot(np.log10(flux), RADdeg, 'o-', linewidth=1, ms=3, alpha=0.4, label="%.1f GeV (%s)"%(en/1000., lab[i])) plt.xlabel('Flux [photon/cm$^{2}$/s]') plt.ylabel('Mask disk Radius [$^{\circ}$]') #plt.yscale('log') #plt.xscale('log') #plt.ylim(1.5, 6) plt.grid(which='both', linestyle='--', linewidth=1) plt.legend(fontsize=11, loc=2) """ nside = 512 SRC_CATALOG_FILE = os.path.join(GRATOOLS_CONFIG,'catalogs/gll_psc_v16.fit') bad_pix = mask_src_weighted(SRC_CATALOG_FILE, SRC_CATALOG_FILE,8317, nside) bad_pix += mask_bat_gp(2.5e-7, nside) npix = hp.nside2npix(nside) mask = np.ones(npix) for bpix in np.unique(bad_pix): mask[bpix] = 0 fsky = 1-(len(np.unique(bad_pix))/float(npix)) #title = 'Energy = 100 GeV, F$_{sky}$ = %.3f'%(fsky) title = 'F$_{sky}$ = %.3f'%(fsky) hp.mollview(mask, title=title, coord='G', cmap='bone') hp.graticule(color='silver') plt.show()
def main(): """ This is the main routine. """ ''' # Parse the command line. parser = OptionParser(usage=usage) parser.disable_interspersed_args() parser.add_option('-q','--quiet',dest='quiet',action='store_true', default=False,help='quiet output') parser.add_option('-v','--verbose',dest='verbose',action='store_true', default=False,help='verbose output') (options,args) = parser.parse_args() nargs = len(args) ''' # Read Galaxy Catalog Parameters filenameCat1 = '/Users/Elisa/c/EAntolini/Healpix/Catalogs/Complete/Tully_Magnitude_Completed_shape.txt' outfilename = '/Users/Elisa/c/EAntolini/Healpix/IpacTableFromSource.fits' #Name,Morphology,GAL_RA,GAL_DEC,r_k20fe,j_m_k20fe,k_m_k20fe,k_ba,k_pa,distance = np.loadtxt(filenameCat1,dtype=[('f0',str),('f1',str),('f2',float),('f3',float),('f4',float),('f5',float),('f6',float),('f7',float),('f8',float),('f9',float)], unpack = True) # 2MASS MAP #GAL_RA,GAL_DEC,r_k20fe,j_m_k20fe,k_m_k20fe,k_ba,k_pa, vel, distance = np.loadtxt(filenameCat1,dtype=[('f0',float),('f1',float),('f2',float),('f3',float),('f4',float),('f5',float),('f6',float),('f7',float),('f8',float)], unpack = True) #TULLY MAP 1794 RA,DEC,radius,frac_diameter,distance,mag,incl= np.loadtxt(filenameCat1,dtype=[('f0',float),('f1',float),('f2',float),('f3',float),('f4',float),('f5',float),('f6',float)], unpack = True) GAL_RA = RA GAL_DEC =DEC r_k20fe = radius k_ba = frac_diameter k_pa = np.cos(np.absolute(incl-3)) #degree k_m_k20fe = mag # Generate my own Map ''' subplot(221, projection="aitoff") title("Aitoff") grid(True) show() ''' # Open LIGO map # By default, input maps are converted to RING ordering, if they are in NESTED ordering. map_dir = '/Users/Elisa/Documents/Robotic_Telescope/LIGO/Healpix/' map_name = 'bayestar.fits' #wmap_map_Nested = hp.read_map(map_dir+map_name, nest=True) #Remains NESTED wmap_map_Ring = hp.read_map(map_dir+map_name,0) #Change to RING (Default), read the 0 columns of the file hp.mollview(np.log10(wmap_map_Ring),coord='C',rot = [0,0.3], title='Histogram equalized Ecliptic', unit='prob', min=-8,max=-6, xsize=4096) hp.graticule() plt.show() #Get RA and DEC values from LIGO map mypixels = np.asarray(np.log10(wmap_map_Ring)) galpixels=0*mypixels print(len(mypixels)) #2) #LIGO_RA=[] #LIGO_DEC=[] # Convert Pixels to RA and DEC in LIGO map ''' for i in range(len(mypixels)): dec, ra = IndexToDeclRa(512,i) LIGO_RA.append(ra) LIGO_DEC.append(dec) with open('/Users/Elisa/c/EAntolini/Healpix/LigoRADEC.txt', 'w') as fLigofile: for i in range(len(LIGO_RA)): fLigofile.write(str(LIGO_RA[i])+" "+str(LIGO_DEC[i])+"\n") ''' #Load File with M31 and Andromeda (LIGO data set) LIGO_RA,LIGO_DEC = np.loadtxt('/Users/Elisa/c/EAntolini/Healpix/LigoRADEC.txt',dtype=[('f0',float),('f1',float)], unpack = True) pos = (mt.pi/180.0) arcsec_to_radians = 4.84813681e-06 cosdec_c= np.cos((LIGO_DEC)*pos) #cos(dec_c) radians sindec_c= np.sin((LIGO_DEC)*pos) #sin(dec_c) radians #2) Take RA and DEC from GALAXY Catalog and convert to Index #for r, d, radius in zip(GAL_RA[Name=='M31'],GAL_DEC[Name=='M31'],r_k20fe[Name=='M31']): #for r, d,radius, semi_mayor,polar_angle in zip(GAL_RA,GAL_DEC,r_k20fe,k_ba,k_pa): #2MASS #for r, d,semi_mayor,K_mag,ba,polar_angle,dist in zip(GAL_RA,GAL_DEC,r_k20fe,k_m_k20fe,k_ba,k_pa,distance): #Tully for r, d,semi_mayor,K_mag,ba,polar_angle,dist in zip(GAL_RA,GAL_DEC,r_k20fe,k_m_k20fe,k_ba,k_pa,distance): #polar_angle = 0 # Distance of the galaxy from the center [radians] dumy=np.arccos(np.cos(d*pos)*cosdec_c*np.cos((r-LIGO_RA)*pos)+np.sin(d*pos)*sindec_c) # Polar Angle (between North-South directions) [radians] dumx=np.arctan2(np.sin(d*pos)-np.cos(dumy)*sindec_c,np.cos(d*pos)*np.sin((r-LIGO_RA)*pos)*cosdec_c); dumx +=(polar_angle+90)*pos ''' dumx -=(polar_angle+90)*pos dumx +=(90-polar_angle)*pos dumx -=(90-polar_angle)*pos ''' semi_minor=ba*semi_mayor #Compute the semi-minor axes of the Glaxy from Catalog f_dumx = (semi_mayor * semi_minor)/np.sqrt(np.square(semi_minor*np.cos(dumx))+np.square(semi_mayor*np.sin(dumx))) LumK = np.power(10,(-0.4*(K_mag-5*np.log10(dist*1e5)-6.35))) # lUMINOSTY OF THE GALAXY IN SOLAR LUMINOSITY radius = f_dumx*pos/3600 #Utilizzare dumy se non ho tutte le distanze delle galassie # Quando ho tutte le galassie posso usare Lumk #galpixels += np.exp(-dumy/radius) galpixels += (LumK/(semi_mayor * semi_minor))*np.exp(-dumy/radius) #galpixels += (1/(semi_mayor * semi_minor))*np.exp(-dumy/radius) hp.mollview(np.log10(galpixels),coord='C',rot = [0,0.3], title='Histogram equalized Ecliptic', unit='prob', xsize=4096) #hp.mollview(galpixels,coord='C',rot = [0,0.3], title='Histogram equalized Ecliptic', unit='prob', xsize=4096) hp.graticule() plt.show()
def main(argv): _path = os.path.expanduser('~/Develop/SMAPs/') file_area = [ 'dcorr_smpas_obstime_2_area12.fits' ,'dcorr_smpas_obstime_2_area18.fits' ,'dcorr_smpas_obstime_2_area6.fits'] nna_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/norpointT80.dat') nsa_file = os.path.expanduser('~/Develop/SMAPs/coordinatesystemandtiling/surpointT80.dat') smaps_sul = os.path.expanduser('~/Develop/SMAPs/smaps_pointsulT80.dat') smaps_nor = os.path.expanduser('~/Develop/SMAPs/smaps_pointT80norte.dat') # # Reading data # map_area = np.array([H.read_map(os.path.join(_path,file_area[0])),]) for i in range(1,len(file_area)): map_area = np.append(map_area,np.array([H.read_map(os.path.join(_path,file_area[i])),]),axis=0) # # Plotting graph # ## ## This is best area cut observability ## plmap = np.zeros(map_area.shape[1]) #for i in range(3): # plmap += map_area[i] # #H.mollview(plmap,fig=1,title='secz < 1.5',coord=['G','E'],sub=(1,2,4),cbar=False,notext=True,max=3.5) # #plmap = np.zeros(map_area.shape[1]) for i in range(len(map_area)): plmap += map_area[i] # make a color map of fixed colors cmap = colors.ListedColormap(['grey', 'blue', 'green', 'red']) H.mollview(plmap,coord=['G','E'],cmap=cmap,cbar=False,notext=True,title='S-MAPS Survey Area Selection')#,rot=(0,-90,90))#, norm=norm) #H.cartview(plmap,coord='G',cmap=cmap,cbar=False,notext=True,title='S-MAPS Survey Area Selection')#, norm=norm) H.graticule() nna_pt = np.loadtxt(nna_file,unpack=True,usecols=(4,5)) nsa_pt = np.loadtxt(nsa_file,unpack=True,usecols=(4,5)) pt_smaps_sul = np.loadtxt(smaps_sul,unpack=True,usecols=(4,5)) pt_smaps_nor = np.loadtxt(smaps_nor,unpack=True,usecols=(4,5)) #myPatches=[] #for i in range(len(nna_pt[0])): # r2 = patches.RegularPolygon(((90-nna_pt[1][i])*np.pi/180.,nna_pt[0][i]*np.pi/180.),4,0.573*np.pi,orientation=45*np.pi/180.) # myPatches.append(r2) #collection = PatchCollection(myPatches,alpha=0.5) #H.add_collection(collection) H.projplot((90-nna_pt[1])*np.pi/180.,nna_pt[0]*np.pi/180.,'.',color='w',alpha=0.5)#,coord=['E','G']) H.projplot((90-nsa_pt[1])*np.pi/180.,nsa_pt[0]*np.pi/180.,'.',color='w',alpha=0.5)#,coord=['E','G']) H.projplot((90-pt_smaps_sul[1])*np.pi/180.,pt_smaps_sul[0]*np.pi/180.,'.',color='k',alpha=0.5)#,coord=['E','G']) H.projplot((90-pt_smaps_nor[1])*np.pi/180.,pt_smaps_nor[0]*np.pi/180.,'.',color='k',alpha=0.5)#,coord=['E','G']) # # Area 1 - SGH # #sgh_x = [ [135,180] , [135, 120] , [ 120 , 105] , [ 105 , 80] , [80 , 105] , [105] , [105 , 180] ] #sgh_y = [ [100] , [100 , 40] , [ 40 ] , [ 40 , -55] , [-55, -60] , [-60 , -85] , [-85 ] sgh_x = [ [135,180] , [135, 120] , [ 120 , 113.] , [ 113. , 100] , [100 , 112] , [112] , [112 , 180] ] sgh_y = [ [85] , [85 , 25] , [ 25 ] , [ 25 , -40] , [ -40] , [-40 , -65] , [-65 ] ] #plotArea(sgh_x,sgh_y) #ngh_x1 = [ [135, 125] , [125,100] , [55,100]] #ngh_y1 = [ [180,130] , [130, 110] , [179,110]] ngh_x1 = [ [115] , [115,80] , [80]] ngh_y1 = [ [180,160] , [160] , [179.9,160]] #plotArea(ngh_x1,ngh_y1) #ngh_x2 = [ [135, 115] , [115,55] , [55]] #ngh_y2 = [ [-180,-130] , [-130, -115] , [-115,-180]] ngh_x2 = [ [115] , [90,115] , [90] , [90,65] , [65]] ngh_y2 = [ [-165,-180] , [-165] , [-165,-150] , [-150] , [-150,-180]] #plotArea(ngh_x2,ngh_y2) x1 = np.zeros(100)+np.pi/2. #np.linspace(0,np.pi/2.,100) y1 = np.linspace(-np.pi,np.pi,100) H.projplot(x1,y1,'w',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E']) #H.projplot([0],[np.pi/2.],'ko',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E']) H.projplot([192.859508],[27.128336],'ko',lw=2.,coord=['E'],lonlat=True)#,rot=(0,-90,90),coord=['G','E']) H.projplot([192.859508-180],[-27.128336],'wo',lw=2.,coord=['E'],lonlat=True)#,rot=(0,-90,90),coord=['G','E']) #H.projplot([-np.pi],[np.pi/2.],'wo',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E']) #H.projplot([-np.pi],[0],'wo',lw=2.,coord=['G','E'])#,rot=(0,-90,90),coord=['G','E']) # ngh_x2 = [ [135, 115] , [90, 115], [90,55] , [55]] # ngh_y2 = [ [-180,-120] , [-140, -120 ], [-140, -115] , [-115,-180]] # plotArea(ngh_x2,ngh_y2) py.savefig(os.path.join(_path,'Figures/areaSelection.pdf')) py.show()