def healpy_rejection_sampler_OLD(m, n): """ Special version of the generic rejection sampler. Here we sample map indices uniformly across the map (range [0, pi]x[0, 2*pi]) and check if the rejection criterium is fullfilled at that point. We can sample indices uniformly because healpixel areas are are equal across the sphere. Rejection algorithm: For each point draw a uniform rand number and reject the point if the value of the pdf is smaller. Else accept it and repeat until the n points are sampled. Returns n map indices drawn from the map transformed to a pdf. The resolution is the same as the input map which is sampled from. """ if hp.maptype(m) != 0: raise ValueError( "Given map is no healpy map (-1) or a series of maps (>0) : " + "{}.".format(hp.maptype(m))) # Get map parameter NPIX = hp.get_map_size(m) # Make sure the map is in pdf form, which is all positive and area = 1 m = norm_healpy_map(m) # Get the pdf maximium to set the sampling bounding box fmax = np.amax(m) def pdf(ind): """Simple wrapper to consistently use the name pdf. Returns the mapvals at given indices""" return m[ind] # Create list to store the sampled events sample = [] # Rejection sampling loop nstart = n efficiency = 0 while n > 0: # Count trials for efficinecy, has nothing to do with the sampling efficiency += n # Only choose integer map indices randomly as we operate on discrete # maps r1 = np.random.randint(0, NPIX, size=n) # Create n uniform distributed rand numbers between 0 and the maximum # of the function r2 = fmax * np.random.uniform(0, 1, n) # Calculate the pdf value pdf(r1) and compare to r2 # --> If r2 is below or equal func(r1) accept the event, else reject it accepted = (r2 <= pdf(r1)) # --> Where func(r2) is near the box boundary of fmax the efficiency is # good, else it gets worse. Append only accepted random numbers sample += r1[accepted].tolist() # Redo with n = events that are missing until n = 0 and all n requested # events are generated n = np.sum(~accepted) # eff first counts how many events where drawn from the pdf and is then the # fraction of the actual desired events n by the generetaded events. efficiency = nstart / float(efficiency) return np.array(sample), efficiency
def healpy_rejection_sampler(m, nsamples, jitter=False, ret_idx=False): """ Sampler to sample positions from given skymaps that are treated as PDFs. Pixel indices are drawn according to the pixel weight defined by the map. If 'jitter' is True, positions are sampled with a gaussian with width of the pixel resolution, to escape from the healpix grid. Paramters --------- m : array-like Valid healpy map. nsamples : int How many sampled to draw from the map. jitter : bool, optional If True, sample "ungridded" positions as explained above. (default: False) ret_idx bool, optional If True, return the sampled map indices, too. (default: False) Returns ------- theta, phi : array-like, shape (nsamples) Sampled positions in healpy coordinates. idx : array-like, shape (nsamples), optional Sampled map indices. If jitter is True, indices may not be the same as obtained by ``hp.ang2pix`` using the sampled positions. Only returned if `ret_idx` is True. """ if hp.maptype(m) != 0: raise ValueError( "Given map is no healpy map (-1) or a series of maps (>0) : " + "{}.".format(hp.maptype(m))) # Make sure the map is in pdf form, which is all positive and area = 1 m = norm_healpy_map(m) # Get weights per pixel from normal space map and normalize weights = m / np.sum(m) # Draw N pixels from the weighted indices NSIDE = hp.get_nside(m) NPIX = hp.nside2npix(NSIDE) idx = np.random.choice(np.arange(NPIX), size=nsamples, p=weights) # Get angles from pix indices theta, phi = hp.pix2ang(NSIDE, idx) # Sample new angles from a gaussian with width of half the pixel resolution. # Otherwise we get angles on a grid, exactly one position from one pixel. if jitter: res = hp.nside2resol(NSIDE) / 2. theta = np.random.normal(theta, res) phi = np.random.normal(phi, res) theta, phi = wrap_theta_phi_range(theta, phi) if ret_idx: return theta, phi, idx else: return theta, phi
def norm_healpy_map(m, ret_area=False): """ Norm an arbitrary healpy map to integral over unit sphere to one. The discrete integral is then np.sum(pixarea * pixvalue) = 1. Returns the normed map and if `ret_area`= True the pixel area for the parameters of the given map. """ if hp.maptype(m) != 0: raise ValueError( "Given map is no healpy map (-1) or a series of maps (>0) : " + "{}.".format(hp.maptype(m))) # Get needed map parameters NSIDE = hp.get_nside(m) # First normalize to positive values m >= 0 for being a pdf if np.any(m < 0): m = m - np.amin(m) # All pixels are equal area by definition (healpix) so norm to sum # of entries and pixel area dA = hp.nside2pixarea(NSIDE) norm = dA * np.sum(m) if norm != 0: m = m / norm else: print("norm is zero. Returning unnormed map.") if ret_area: return m, dA else: return m
def display_mask_statistics(mask): mask_dtype = mask.dtype mask_dim = hp.maptype(mask) nside = hp.get_nside(mask) sky_frac = get_sky_fraction(mask) print("#*#*#*") print("d-type\tdim\tnside\tsky-fraction") print("{}\t{}\t{}\t{}".format(mask_dtype, mask_dim, nside, sky_frac)) print("#*#*#*\n")
def testBinDeg(self): """ Test that healbin returns correct values and valid healpy maps. """ ra = np.zeros(3) dec = np.zeros(3) values = ra * 0. + 1. nside = 128 hpid = utils.raDec2Hpid(nside, ra[0], dec[0]) map1 = utils.healbin(ra, dec, values, nside=nside) self.assertEqual(map1[hpid], 1.) self.assertEqual(hp.maptype(map1), 0) map2 = utils.healbin(ra, dec, values, nside=nside, reduceFunc=np.sum) self.assertEqual(map2[hpid], 3.) self.assertEqual(hp.maptype(map2), 0) map3 = utils.healbin(ra, dec, values, nside=nside, reduceFunc=np.std) self.assertEqual(map3[hpid], 0.) self.assertEqual(hp.maptype(map3), 0)
def get_sky_fraction(binary_mask): """ Returns the fraction of the sky that is valid. The function determines the dimension of the binary mask. It returns a scalar for a single mask. It returns an array of the same number of masks otherwise. """ dim_mask = hp.maptype(binary_mask) n_pix = 12 * hp.get_nside(binary_mask)**2 if dim_mask == 0: sky_fraction = np.sum(binary_mask.astype(np.float)) / n_pix else: sky_fraction = np.sum(binary_mask.astype(np.float), axis=1) / n_pix return sky_fraction
def get_healpy_map_value(th, phi, m): """ Returns the value at angle (th, phi) from an arbitrary healpy map m. Angle th (theta) is something like zenith [0, pi]. Angle phi is something like azimuth [0, 2pi]. """ if hp.maptype(m) != 0: raise ValueError( "Given map is no healpy map (-1) or a series of maps (>0) : " + "{}.".format(hp.maptype(m))) # Check if th, phi ranges are valid if np.any(th) < 0 or np.any(th) > np.pi: raise ValueError("th not in range [0, pi].") if np.any(phi) < 0 or np.any(phi) > 2 * np.pi: raise ValueError("phi not in range [0, 2*pi].") # Get needed map parameters NSIDE = hp.get_nside(m) # Convert all angles to pix indices and get the values at their positions pixind = hp.ang2pix(NSIDE, th, phi) pdf_vals = m[pixind] return pdf_vals
def src_map(self, src_map): if hp.maptype(src_map) != 0: raise ValueError( "Given src_map is not a single, valid healpy map.") self._src_map = src_map return
def src_map(self, src_map): if hp.maptype(src_map) != 0: raise ValueError( "Given src_map is not a single, valid healpy map.") self._src_map = src_map return
# NSIDE = 32 fact = 1.42144524614e-05 filename = 'data/HFI_CompMap_ThermalDustModel_2048_R1.20.fits' filename = 'data/HFI_SkyMap_353_2048_R2.02_full.fits' test_map = hp.read_map(filename) #hp.mollview(test_map, title=filename, coord='G', unit='K', norm='hist', min=1e-7,max=1e-3, xsize=800) hp.mollview(test_map, title=filename, coord='G', unit='K', norm='hist', xsize=800) #hp.mollview(test_map) #hp.cartview(test_map, title=filename, coord='G', rot=[0,0], unit='K', norm='hist', min=-1375,max=2687, xsize=800, lonra=[-1,1], latra=[-1,1]) #hp.orthview(test_map) #hp.gnomview(test_map) print hp.get_nside(test_map) print hp.maptype(test_map) print hp.get_map_size(test_map) print len(test_map) print test_map[0:10]*np.float(fact) equateur_lon = [10.,0.] equateur_lat = [10.,0.] hp.projplot(equateur_lon, equateur_lat, lonlat=True, coord='G') # plt.loglog(hp.anafast(test_map)) # plt.grid() # plt.xlabel("$\ell$") # plt.ylabel("$C_\ell$") plt.grid() plt.show()
def extract_region(hmap,lst_id=None,region=None,keep_reso=True,minpix=128, iter=0,ortho=False,fwhm_deg=None,reorder_ns=None): #Extract a map for the current region try: dict_match= get_region(lst_id=lst_id,name=region) nside=hp.get_nside(hmap) nmaps=hp.maptype(hmap) print(nmaps) #case single map, write it as a list if nmaps==0: pmap=[hmap] nmaps=1 else: pmap=hmap if fwhm_deg is not None: if hasattr(fwhm_deg, "__len__"): assert(len(fwhm_deg) == nmaps),"Not enough fwhm: {0} vs {1}"\ "map(s).".format(len(fwhm_deg),nmaps) fwhm_use= fwhm_deg else: fwhm_use=np.zeros([nmaps])+fwhm_deg lmax=np.zeros((nmaps)) for kmap in range(nmaps): fl=hp.sphtfunc.gauss_beam(fwhm_use[kmap]*DtoR,lmax=2048, pol=False) llist=(np.where(fl < 1e-6))[0] if len(llist)==0: lmax[kmap]=3*nside-1 else: lmax[kmap]=llist[0] if (reorder_ns is not None) and (hp.isnsideok(reorder_ns)): nside=reorder_ns sm_map=[smooth_map_reorder_alm(pmap[kmap], fwhm_deg=fwhm_use[kmap], lmax=lmax[kmap],nside_out=nside,iter=iter)\ for kmap in range(nmaps)] else: sm_map=pmap patch=[] for kreg in range(len(dict_match)): rotation=(dict_match[kreg]["lc"],dict_match[kreg]["bc"],0.) if keep_reso is True: reso_arcmin=hp.nside2resol(nside,arcmin=True) nxpix=np.int(max([np.ceil(dict_match[kreg]["dl"]*60./ reso_arcmin),minpix])) nypix=np.int(max([np.ceil(dict_match[kreg]["db"]*60./ reso_arcmin),minpix])) print("STAT=",reso_arcmin,nxpix,nypix,rotation) else: reso=np.min([dict_match[kreg]["dl"]/minpix, dict_match[kreg]["db"]/minpix]) reso_arcmin=reso*60. nxpix=np.int(dict_match[kreg]["dl"]/reso) nypix=np.int(dict_match[kreg]["db"]/reso) a=plt.figure() nsub=np.int(np.max((np.ceil(np.sqrt(nmaps)),1))) patchreg = [np.array(hp.visufunc.gnomview(map=sm_map[kmap], rot=rotation,fig=a,coord='G', xsize=nxpix,ysize=nypix, reso=reso_arcmin,gal_cut=0,title=dict_match[kreg]["Name"]+ " map "+str(kmap),flip='astro',format='%.3g',cbar=True, hold=False,margins=None,notext=False,sub=(nsub,nsub,kmap+1), return_projected_map=True)) for kmap in range(nmaps)] patch.append(patchreg) except Exception as inst: print("FAILURE: ",inst) return patch
def test_input_cmb_map_type(self): filename = modelconf['cmbFile'] Nside = 64 cmb_map_to_test = gm.make_cmb_map(filename, nside_out=Nside) # Should be 3 maps -- T,Q,U self.assertEqual(hp.maptype(cmb_map_to_test), 3)