def from_point_sources(self,d,t): # if p.circular_pol == True: # I,Q,U,V = sky_list # else: # I,Q,U = sky_list print "t is " + str(t) total_angle = float(self.nhours * 15) # degrees offset_angle = float(self.hour_offset * 15) # degrees zl_ra = ((float(t) / float(self.ntime)) * np.radians(total_angle) + np.radians(offset_angle)) % (2.*np.pi)# radians RotAxis = np.array([0.,0.,1.]) RotAngle = -zl_ra # basicly Hour Angle with t=0 # R_t = irf.rotation_matrix(RotAxis, RotAngle) # s0 = hp.ang2vec(src_cza,src_ra) # sf = np.einsum('...ab,...b->...b', R_t, s0) self.src_ra_f = self.src_ra + RotAngle sf = hp.ang2vec(self.src_cza, self.src_ra_f) # s0 = hp.ang2vec(src_cza,src_ra) # hpR_t = hp.Rotator(rot=[RotAngle]) # sf = np.array(hpR_t(s0[:,0],s0[:,1],s0[:,2])).T if len(sf.shape) > 1: inds_f = hp.vec2pix(self.nside, sf[:,0],sf[:,1],sf[:,2]) else: inds_f = hp.vec2pix(self.nside, sf[0],sf[1],sf[2]) It = self.I #XXX ?? ijones_t = self.ijones[:,inds_f,:,:] ijonesH_t = self.ijonesH[:,inds_f,:,:] Kt = self.K[:,inds_f] if self.unpolarized == True: Ut = np.zeros((self.nfreq,It.shape[-1])) sky_t = np.array([ [It, Ut], [Ut, It]]).transpose(2,3,0,1) # sky_t.shape = (p.nfreq, p.npix, 2, 2) else: Ut = self.U Qt = self.Q sky_t = np.array([ [It + Qt, Ut], [Ut, It - Qt]]).transpose(2,3,0,1) # sky_t.shape = (p.nfreq, p.npix, 2, 2) irnf.instrRIME_integral(ijones_t, sky_t, ijonesH_t, Kt, self.Vis[d,t,:,:,:].squeeze())
def generateLensPart(fname, nside=64): """ Generate a lens part from the given CRPropa 3 simulation. """ f = np.genfromtxt(fname, names=True) row = healpy.vec2pix(nside, f['P0x'], f['P0y'], f['P0z']) # earth col = healpy.vec2pix(nside, f['Px'], f['Py'], f['Pz']) # galaxy npix = healpy.nside2npix(nside) data = np.ones(len(row)) M = sparse.coo_matrix((data, (row, col)), shape=(npix, npix)) M = M.tocsc() normalizeRowSum(M) return M
def generateLensPart(fname, nside=64): """ Generate a lens part from the given CRPropa 3 simulation. """ f = np.genfromtxt(fname, names=True) row = healpy.vec2pix(nside, f['P0x'], f['P0y'], f['P0z']) # earth col = healpy.vec2pix(nside, f['Px'], f['Py'], f['Pz'] ) # galaxy npix = healpy.nside2npix(nside) data = np.ones(len(row)) M = sparse.coo_matrix((data, (row, col)), shape=(npix, npix)) M = M.tocsc() normalizeRowSum(M) return M
def match_hpx_pixel(nside, nest, nside_pix, ipix_ring): """ """ ipix_in = np.arange(12 * nside * nside) vecs = hp.pix2vec(nside, ipix_in, nest) pix_match = hp.vec2pix(nside_pix, vecs[0], vecs[1], vecs[2]) == ipix_ring return ipix_in[pix_match]
def create_ps_map(self, temp, psf_r=None): """ Add PS photon counts to map following a given PSF description and template. Based on NPTFit-Sim (https://github.com/nickrodd/NPTFit-Sim). :param temp: Template for spatial distribution of PSs :param psf_r: Radial PSF """ # Sample the radial PSF to later determine placement of photons. f = np.linspace(0.0, np.pi, 1000000) pdf_psf = f * psf_r(f) pdf = PDFSampler(f, pdf_psf) nside = hp.npix2nside(len(temp)) # Draw coordinates according to template self.th_ary, self.ph_ary = self.get_coords(temp, self.n_draw) the_map = np.zeros(hp.nside2npix(nside)) for ips in tqdm(range(self.n_draw)): th = self.th_ary[ips] ph = self.ph_ary[ips] num_phot = self.counts_sample[ips] dist = pdf(num_phot) phm = ph + np.pi / 2.0 rotx = np.matrix([[1, 0, 0], [0, np.cos(th), -np.sin(th)], [0, np.sin(th), np.cos(th)]]) rotz = np.matrix([[np.cos(phm), -np.sin(phm), 0], [np.sin(phm), np.cos(phm), 0], [0, 0, 1]]) dist = pdf(num_phot) randPhi = 2 * np.pi * np.random.random(num_phot) X = hp.ang2vec(dist, randPhi).T Xp = rotz * (rotx * X) posit = np.array(hp.vec2pix(nside, *Xp)) np.add.at(the_map, posit, 1) return the_map
def gen_dipole(nside, unit): # from WMAP 1st yaer Bennett et al l = 263.85 # +/-0.1 degs b = 48.25 # +/-0.04 degs amp_mK = 3.346 # +/-0.017 mK if unit == 'uK': amp_unit = amp_mK * 1.e3 print unit if unit == 'mK': amp_unit = amp_mK print unit if unit == 'K': amp_unit = amp_mK * 1.e-3 print unit npix = h.nside2npix(nside) ipix = range(npix) theta, phi = h.pix2ang(nside, ipix) dipole = np.cos(theta) xyz = h.ang2vec(theta, phi) theta0 = pi / 2. - b / radeg phi0 = l / radeg x = np.cos(phi0) * np.cos(theta0) * xyz[:, 0] + np.sin(phi0) * np.cos( theta0) * xyz[:, 1] - np.sin(theta0) * xyz[:, 2] y = -np.sin(phi0) * xyz[:, 0] + np.cos(phi0) * xyz[:, 1] z = np.sin(theta0) * np.cos(phi0) * xyz[:, 0] + np.sin(phi0) * np.sin( theta0) * xyz[:, 1] + np.cos(theta0) * xyz[:, 2] ipix = h.vec2pix(nside, x, y, z) dipole_out = amp_unit * dipole[ipix] return dipole_out
def pixelsForAng(lon, lat, nside, nest=True, convention='celestial', unit='degrees'): """ Return the array of healpixels in which the set of points represented by the arrays lon, and lat fall """ vecs = angToVec(lon, lat, convention, unit) return hp.vec2pix(nside, vecs[:, 0], vecs[:, 1], vecs[:, 2], nest=nest)
def latlon2healpix( lat , lon , res ): lat = lat * math.pi / 180.0 lon = lon * math.pi / 180.0 xs = ( math.cos(lat) * math.cos(lon) ) ys = ( math.cos(lat) * math.sin(lon) ) zs = ( math.sin(lat) ) return H.vec2pix( int(res) , xs , ys , zs )
def mask_unseen(hpmap, az, el, doconvert = False, nest = False): ''' Mask unseen directions in the scan. Use as input the house keeping coordinates. Parameters: hpmap. Healpix map (npix) az and el. Azimuth and Elevation coordinates read from azimuth.fits and elevation.fits doconvert. Consider the data as real azimuth and elevation (not implemented in that way in demodulation yet). Return: hpmap[masked] ''' if doconvert: hkcoords = np.meshgrid(az, el) radec = qubic.hor2equ(hkcoords[0].ravel(), hkcoords[1].ravel(), 0) phi = radec[0] theta = radec[1] #Rotation from Az,El housekiping to Az, El = 0,0 newcoords = np.dot(sbfit.rotmatY(qubic.hor2equ(0,+50,0)[1]), hp.ang2vec(np.pi/2-np.deg2rad(theta), np.deg2rad(phi)).T).T else: hkcoords = np.meshgrid(az, el-50) phi = hkcoords[0].ravel() theta = hkcoords[1].ravel() newcoords = hp.ang2vec(np.pi/2-np.deg2rad(theta), np.deg2rad(phi)) nside = hp.get_nside(hpmap) coordspix = hp.vec2pix(nside, newcoords[...,0], newcoords[...,1], newcoords[...,2], nest = nest) mask = np.zeros((12 * nside **2 ), dtype = bool) mask[coordspix] = 1 hpmap[~mask] = hp.UNSEEN #hp.mollview(hpmap, nest = True) show() return hpmap
def catalogue_to_map(self, halodata, nside=512, weight=1): """project halos into healpix map of size nside Parameters ---------- halodata : array halo catalogue of size (Nhalo, 10) nside: int healpix nside of map created weight: str weighting to give halos when adding to map possibilities: 1=number density, or array of size Nhalo for custom (e.g. mass) Returns ------- map : np.array( (12 * nside**2)) healpy map of halos, with "flux" proportional to weight """ # create empty healpy map map = np.zeros(hp.nside2npix(nside)) # get pixel id from halo x,y,z vector pix = hp.vec2pix(nside, halodata[:, 0], halodata[:, 1], halodata[:, 2]) # add flux to map np.add.at(map, pix, weight) return map
def healpixelize(self, n_side): """ For each galaxy, finds the corresponding pixel number in healpix pixelization of n_side. """ self.healpix_n_side = n_side self.healpix_pixels = hp.vec2pix(self.healpix_n_side,self.nhat0, self.nhat1, self.nhat2)
def min_all_cos_dtheta_fast(pix, nside, nest=False, safe=False): """ computes the maximum angular separation between any two pixels within pix=[ipix,ipix,...] does this with a boarder-to-boarder search after checking some other things this could be in error up to the pixel size (hopefully small) This algorithm is due in part to Antonios Kontos, who helped Reed Essick think through the details """ Npix = len(pix) ### check to see if more than half the sky is filled if Npix * hp.nside2pixarea(nside) > 2 * np.pi: return -1 ### check to see if the antipode of any point is in the set npix = hp.nside2npix(nside) selected = np.zeros(npix, dtype=bool) selected[pix] = True antipodes = np.zeros_like(selected) vec = -np.array(hp.pix2vec(nside, pix, nest=nest)) ### reflect vectors antipodes[hp.vec2pix(nside, vec[0], vec[1], vec[2], nest=nest)] = True ### reflection -> antipode ### reflection accomplished in cartesian coords if np.sum(selected * antipodes): ### point and it's antipode are in the set return -1 ### could be in error by the pixel size... ### boarder-to-boarder search boarder_pix = [] for bpix in __into_boarders(nside, pix, nest=nest): boarder_pix += bpix return min_all_cos_dtheta(boarder_pix, nside, nest=nest, safe=False)
def Response(self, l, m, fq, pol): z = np.sqrt(1.-l**2-m**2) px = hp.vec2pix(self.nside, l, m, z) f = interp1d(self.afreqs, [self.bm_maps[pol][i][px] for i in range(self.ndeg)], kind='cubic') return f(fq)
def find_biggest_pixel(ra, dec, radius, root_nside=1, max_nside=32): from astropy.coordinates import SkyCoord from astropy import units as u import healpy as hp import numpy as np nside = root_nside radius = np.radians(radius) sc = SkyCoord(ra=ra * u.degree, dec=dec * u.degree, frame='icrs') theta = sc.galactic.l.degree phi = sc.galactic.b.degree vec = hp.ang2vec(theta=theta, phi=phi, lonlat=True) pixels = hp.query_disc(vec=vec, nside=nside, radius=radius, inclusive=False, nest=True) while len(pixels) <= 1: if nside == max_nside: break nside *= 2 pixels = hp.query_disc(vec=vec, nside=nside, radius=radius, inclusive=False, nest=True) if nside > 1: nside //= 2 return nside, hp.vec2pix(nside, *vec, nest=True)
def exec(self, data): """ Create the gradient timestreams. This pixelizes each detector's pointing and then assigns a timestream value based on the cartesian Z coordinate of the pixel center. Args: data (toast.Data): The distributed data. """ autotimer = timing.auto_timer(type(self).__name__) comm = data.comm zaxis = np.array([0, 0, 1], dtype=np.float64) nullquat = np.array([0, 0, 0, 1], dtype=np.float64) range = self._max - self._min for obs in data.obs: tod = obs['tod'] offset, nsamp = tod.local_samples common = tod.local_common_flags() & self._common_flag_mask for det in tod.local_dets: flags = tod.local_flags(det) & self._flag_mask totflags = (flags | common) del flags pdata = tod.local_pointing(det).copy() pdata[totflags != 0, :] = nullquat dir = qa.rotate(pdata, zaxis) pixels = hp.vec2pix(self._nside, dir[:, 0], dir[:, 1], dir[:, 2], nest=self._nest) x, y, z = hp.pix2vec(self._nside, pixels, nest=self._nest) z += 1.0 z *= 0.5 z *= range z += self._min z[totflags != 0] = 0.0 cachename = "{}_{}".format(self._out, det) if not tod.cache.exists(cachename): tod.cache.create(cachename, np.float64, (nsamp, )) ref = tod.cache.reference(cachename) ref[:] += z del ref if not self._keep_quats: cachename = 'quat_{}'.format(det) tod.cache.destroy(cachename) del common return
def run_mpi(): print "Rank :", rank, "started" npix = hp.nside2npix(config.nside_out) dim, ind_elements = cov_ut.get_dim(config.pol_type) bolo_list = [None, None, None] inv_cov_matrix_local = np.zeros((npix, ind_elements), dtype=np.float) b_matrix_local = np.zeros((npix, dim), dtype=np.float) hitmap_local = np.zeros(npix, dtype=np.float) bolo_segment_dict = get_local_bolo_segment_list(rank, size, config.bolo_list, config.segment_list) time.sleep(0.1*rank) print "Rank :", rank, ", Bolos and Segments :", bolo_segment_dict comm.Barrier() recon_dir = get_recon_dir() if rank == 0: make_data_dirs() for bolo_name in bolo_segment_dict.keys(): print "Rank :", rank, "Bolos class being generated" bolo_list = initialise_bolo(bolo_name, bolo_list) for segment in bolo_segment_dict[bolo_name]: prompter.prompt("Rank : %d doing Bolo : %s and segment : %d" % (rank, bolo_name, segment)) if config.take_diff_signal: signal, v, pol_ang = acquire_difference_signal(bolo_a, bolo_b, segment) else: signal, v, pol_ang = acquire_signal(bolo, segment) if config.subtract_template: signal_TEMPLATE = bolo_TEMPLATE.read_timestream(segment, read_list=["signal"])["signal"] signal -= estimated_y*signal_TEMPLATE print "Rank :", rank, "Bolos signal read" hitpix = hp.vec2pix(config.nside_out, v[...,0], v[...,1], v[...,2]) del v cov_ut.get_inv_cov_matrix(hitpix, pol_ang, signal, inv_cov_matrix_local, b_matrix_local, hitmap_local, npix, config.pol_type) print "Rank :", rank, "Inverse covariance matrix generated" if config.subtract_template: del signal_TEMPLATE del signal del pol_ang del hitpix inv_cov_matrix_local_segment = distribute_matrix(inv_cov_matrix_local, "cov_matrix") del inv_cov_matrix_local b_matrix_local_segment = distribute_matrix(b_matrix_local, "b_matrix") del b_matrix_local hitmap_local_segment = distribute_matrix(hitmap_local, "hitmap") del hitmap_local cov_matrix_local_segment = cov_ut.get_covariance_matrix(inv_cov_matrix_local_segment, hitmap_local_segment, config.pol_type) sky_map_local_segment = cov_ut.get_sky_map(cov_matrix_local_segment, b_matrix_local_segment, hitmap_local_segment, config.pol_type) write_segments(hitmap_local_segment, "hitmap", recon_dir) write_segments(inv_cov_matrix_local_segment, "inverse_covariance_matrix", recon_dir) write_segments(cov_matrix_local_segment, "covariance_matrix", recon_dir) write_segments(sky_map_local_segment, "sky_map", recon_dir)
def healpixelize(self, n_side): """ For each galaxy, finds the corresponding pixel number in healpix pixelization of n_side. """ self.healpix_n_side = n_side self.healpix_pixels = hp.vec2pix(self.healpix_n_side, self.nhat0, self.nhat1, self.nhat2)
def match_hpx_pix(nside, nest, nside_pix, ipix_ring): """TODO: document.""" import healpy as hp ipix_in = np.arange(12 * nside * nside) vecs = hp.pix2vec(nside, ipix_in, nest) pix_match = hp.vec2pix(nside_pix, vecs[0], vecs[1], vecs[2]) == ipix_ring return ipix_in[pix_match]
def latlon2healpix(lat, lon, res): lat = float(lat) lon = float(lon) lat = lat * math.pi / 180.0 lon = lon * math.pi / 180.0 xs = (math.cos(lat) * math.cos(lon)) ys = (math.cos(lat) * math.sin(lon)) zs = (math.sin(lat)) return healpy.vec2pix(int(res), xs, ys, zs)
def exec(self, data): """ Create the gradient timestreams. This pixelizes each detector's pointing and then assigns a timestream value based on the cartesian Z coordinate of the pixel center. Args: data (toast.Data): The distributed data. """ autotimer = timing.auto_timer(type(self).__name__) comm = data.comm zaxis = np.array([0, 0, 1], dtype=np.float64) nullquat = np.array([0, 0, 0, 1], dtype=np.float64) range = self._max - self._min for obs in data.obs: tod = obs['tod'] offset, nsamp = tod.local_samples common = tod.local_common_flags() & self._common_flag_mask for det in tod.local_dets: flags = tod.local_flags(det) & self._flag_mask totflags = (flags | common) del flags pdata = tod.local_pointing(det).copy() pdata[totflags != 0, :] = nullquat dir = qa.rotate(pdata, zaxis) pixels = hp.vec2pix(self._nside, dir[:, 0], dir[:, 1], dir[:, 2], nest=self._nest) x, y, z = hp.pix2vec(self._nside, pixels, nest=self._nest) z += 1.0 z *= 0.5 z *= range z += self._min z[totflags != 0] = 0.0 cachename = "{}_{}".format(self._out, det) if not tod.cache.exists(cachename): tod.cache.create(cachename, np.float64, (nsamp,)) ref = tod.cache.reference(cachename) ref[:] += z del ref if not self._keep_quats: cachename = 'quat_{}'.format(det) tod.cache.destroy(cachename) del common return
def get_pix_iqu(self, rad, nside=1024, nest=True): from healpy import vec2pix, vec2ang vec = self.get(rad) theta, phi = vec2ang(vec) psi = self.compute_psi(theta, phi, rad) # return vec2pix(nside, vec[:,0], vec[:,1], vec[:,2], nest), np.cos(2*psi), np.sin(2*psi) cos2psi, sin2psi = compute_pol_weigths(psi) return vec2pix(nside, vec[:, 0], vec[:, 1], vec[:, 2], nest), cos2psi, sin2psi
def get_healpix(self, array_of_synthetic_observation_times_TT, array_of_observatory_positions_wrt_center_ECLIPTIC): UV = self.get_unit_vector( array_of_synthetic_observation_times_TT, array_of_observatory_positions_wrt_center_ECLIPTIC) return np.array([ hp.vec2pix(params.hp_nside, *uv, nest=params.hp_nested) for uv in UV ])
def healpix_budavari_dict(zone_dict, nside=8): tmp_dict = { k: hp.vec2pix(nside, *v) for k, v in budavari_magnier_centers(zone_dict).items() } hb_dict = defaultdict(list) for k, v in tmp_dict.items(): hb_dict[v].append(k) return hb_dict
def vec2pix_ring(testcase): cs = [] for norder in range(16): nside = 1 << norder for i in range(1000): v = random_vec() cs.append( dict(args=(nside, v), expected=healpy.vec2pix(nside, *v).tolist())) testcase['vec2pix_ring'] = cs
def get_pix_iqu(self, rad, nside=1024, nest=True): from healpy import vec2pix, vec2ang vec = self.get(rad) theta, phi = vec2ang(vec) psi = self.compute_psi(theta, phi, rad) #return vec2pix(nside, vec[:,0], vec[:,1], vec[:,2], nest), np.cos(2*psi), np.sin(2*psi) spsi = np.sin(psi) cpsi = np.cos(psi) cf = 1./(cpsi**2 + spsi**2) return vec2pix(nside, vec[:,0], vec[:,1], vec[:,2], nest), (cpsi**2 - spsi**2)*cf, 2*cpsi*spsi*cf
def create_healpix_map(input_file, nside=2048, read_inputs=True, object1=None): ''' creating healpix map - assuming particle masses are the same. We can remove this assumption easily if we want to check halo maps''' map_dens = np.zeros(hp.nside2npix(nside)) if read_inputs: object1 = read_in_lightcone(input_file, vars=['x', 'y', 'z']) print('read in lightcone values') pix_list = hp.vec2pix(nside, object1['x'], object1['y'], object1['z']) unique, unique_counts = np.unique(pix_list, return_counts=True) map_dens[unique] += unique_counts print('created ngp density map') return map_dens
def transformVec(self, x, y, z, E, Z=1): """ Attempt to transform a galactic direction, given an energy E [EeV] and charge number Z. Returns a triple (x,y,z) if successful or None if not. """ j = healpy.vec2pix(self.nside, x, y, z) i = self.transformPix(j, E, Z) if i == None: return None v = healpytools.randVecInPix(self.nside, i) return v
def EQU2GAL_E(m_equ): npix = len(m_equ) nside = hp.npix2nside(npix) m_gal = np.full(npix, hp.UNSEEN) r = hp.Rotator(coord=['C', 'G']) n_equ = np.arange(npix) v_equ = hp.pix2vec(nside, n_equ) v_gal = r(v_equ) n_gal = hp.vec2pix(nside, v_gal[0], v_gal[1], v_gal[2]) m_gal[n_gal] = m_equ[n_equ] return m_gal
def HP_of_center(self): ''' Get the healpix of the center ''' if np.any(self.UV == None): self.calc_UV() self.HPcenter = hp.vec2pix(params.hp_nside, self.UV[0], self.UV[1], self.UV[2], nest=params.hp_nested) return self.HPcenter
def create_pixel_list(nside, area_center_nside=None, area_center_pixel=None, area_num_pixels=None): if (area_center_nside is not None or area_center_pixel is not None or area_num_pixels is not None) and \ (area_center_nside is None or area_center_pixel is None or area_num_pixels is None): raise RuntimeError( "You have to either set none of the three options area_center_nside,area_center_pixel,area_num_pixels or all of them" ) npixel_max = healpy.nside2npix(nside) # just return all pixels if no specific area is requested or the area covers the entire map if (area_center_nside is None) or (area_num_pixels >= npixel_max): return range(npixel_max) # otherwise, build the area iteratively pixel_area_sqdeg = healpy.nside2pixarea(nside, degrees=True) area_for_requested_pixels_sqdeg = pixel_area_sqdeg * float(area_num_pixels) approx_radius = numpy.sqrt(area_for_requested_pixels_sqdeg) / numpy.pi print( "Building healpix pixel list for nside {} with an area of {} (out of {}) pixels (=={:.2f}sqdeg; radius={:.2f}deg)" .format(nside, area_num_pixels, npixel_max, area_for_requested_pixels_sqdeg, approx_radius)) # get the center coordinate c_x, c_y, c_z = healpy.pix2vec(area_center_nside, area_center_pixel) start_pixel = healpy.vec2pix(nside, c_x, c_y, c_z) c_x, c_y, c_z = healpy.pix2vec(nside, start_pixel) pixel_set = set([start_pixel]) print("start pixel:", start_pixel) # Create a full list of pixels ordered so that the center pixel is first and the distance to the center is growing. # Then crop the list to return the number of requested pixels. This makes sure that we can extend the list later. pixels = numpy.array(range(npixel_max)) p_x, p_y, p_z = healpy.pix2vec(nside, pixels) pixel_space_angles = numpy.arccos( numpy.clip(c_x * p_x + c_y * p_y + c_z * p_z, -1., 1.)) pixel_num = numpy.array(range(len(pixel_space_angles)), dtype=numpy.float) # pixels, sorted by distance from the requested pixel; secondary sort key is just the healpix pixel index pixel_list_sorted = pixels[numpy.lexsort( (pixel_num, pixel_space_angles))].tolist() return_list = pixel_list_sorted[:area_num_pixels] print("Pixel set created. It has {} entries (requested entries were {})". format(len(return_list), area_num_pixels)) return return_list
def read_files_lightcone(files, z_min, z_max, cosmology, nside_jack, pix_jack, nd=1e-2, rsd=True): pdtype = np.dtype([('px', np.float), ('py', np.float), ('pz', np.float), ('vx', np.float), ('vy', np.float), ('vz', np.float), ('z_cos', np.float)]) for i, f in enumerate(files): if i == 0: if rsd: pos, vel = read_file_downsample(f, nd=nd, read_vel=True) else: pos = read_file_downsample(f, nd=nd) else: if rsd: p, v = read_file_downsample(f, nd=nd, read_vel=True) vel = np.vstack([vel, v]) else: p = read_file_downsample(f, nd=nd) pos = np.vstack([pos, p]) parts = np.zeros(len(pos), dtype=pdtype) # cut to min/max redshifts # temporarily store radii in z column parts['z_cos'] = np.sqrt(pos[:, 0]**2 + pos[:, 1]**2 + pos[:, 2]**2) parts['z_cos'] = cosmo.zofR(parts['z_cos']) pix = hp.vec2pix(nside_jack, pos[:, 0], pos[:, 1], pos[:, 2], nest=True) idx = ((z_min < parts['z_cos']) & (parts['z_cos'] <= z_max) & (pix == pix_jack)) pos = pos[idx] vel = vel[idx] parts = parts[idx] parts['px'] = pos[:, 0] parts['py'] = pos[:, 1] parts['pz'] = pos[:, 2] parts['vx'] = vel[:, 0] parts['vy'] = vel[:, 1] parts['vz'] = vel[:, 2] del vel, pos return parts
def get_centralsignal(skymap, mask, pos_src_all, out_edge, in_edge, fwhm, tol=1): ''' Return central signal of a collection of sources which is calculated by taking the signal of the pixel which countains the source then multiply by beam normalization factor. Input: skymap: healpix skymap; mask: mask healpix map; pos_src_all: position of sources (with shape (Nsource, 3)); out_edge: outer disk of the ring to calculate background(in arcmin); in_edge: inner disk of the ring to calculate background(in arcmin); fwhm: FWHM of the gaussian beam of the skymap tol: tolerance between 0 and 1 indicating a threshold of fraction of unmasked pixels in a disk Output: central signal corresponding to each source ''' sigma = fwhm / 2.35482004503 Nsource = pos_src_all.shape[0] skymap_masked = skymap * mask Ns = hp.npix2nside(mask.size) tot_signal = np.zeros(Nsource) fraction = 0 print('Total source number: ' + str(Nsource)) print('Calculating...') for i in range(Nsource): fraction_next = np.int(i * 10 / np.float(Nsource)) if fraction_next > fraction: print(int(i * 100 / np.float(Nsource))), '%' fraction = fraction_next list_out_unmasked, list_in_unmasked = get_disk(mask, pos_src_all[i], out_edge, in_edge, tol) if np.asarray(list_out_unmasked) is np.array([0]): tot_signal[i] = 0 continue bkg = get_bkg(skymap, mask, list_out_unmasked, list_in_unmasked) pos_src_ind = hp.vec2pix(Ns, pos_src_all[i][0], pos_src_all[i][1], pos_src_all[i][2]) tot_signal[i] = ((skymap_masked)[pos_src_ind] - bkg) tot_signal *= (sigma * np.sqrt(2 * np.pi)) N_inmask = np.nonzero(tot_signal)[0].size print("Number of Objects (in mask): ", N_inmask) print("Used " + str(N_inmask / float(Nsource) * 100) + '%') return tot_signal
def RADECToPatch(nside, RA, DEC=None, nest=False, lonlat=True, invRotMat=np.diag(np.ones(3))): if DEC is None: DEC = RA[1] RA = RA[0] uXYZ = hp.dir2vec(RA, DEC, lonlat=lonlat) uXYZ = invRotMat.dot(uXYZ) patch = hp.vec2pix(nside, uXYZ[0], uXYZ[1], uXYZ[2], nest=nest) return patch
def project_map_beam( pixels, nside, width_deg, theta_beam, phi_beam, pixels_per_side=150 ): gamma_map = np.zeros(len(pixels)) vecrot = healpy.pix2vec(nside, np.arange(len(pixels))) pixrotate = healpy.vec2pix(nside, vecrot[0], vecrot[1], vecrot[2]) Ry = [ [np.cos(-theta_beam), 0, np.sin(-theta_beam)], [0, 1, 0], [-np.sin(-theta_beam), 0, np.cos(-theta_beam)], ] Rz = [ [np.cos(-phi_beam), -np.sin(-phi_beam), 0], [np.sin(-phi_beam), np.cos(-phi_beam), 0], [0, 0, 1], ] RotMat = np.dot(Ry, Rz) vec = np.dot(np.linalg.inv(RotMat), vecrot) pix = healpy.vec2pix(nside, vec[0], vec[1], vec[2]) index = 0 for i in pix: gamma_map[index] = pixels[i] index += 1 theta_max = np.deg2rad(width_deg) extr_inf = -np.sin(theta_max) extr_sup = np.sin(theta_max) u = np.linspace(extr_inf, extr_sup, pixels_per_side) v = np.linspace(extr_inf, extr_sup, pixels_per_side) u_grid, v_grid = np.meshgrid(u, v) theta_grid = np.arcsin(np.sqrt(u_grid ** 2 + v_grid ** 2)) phi_grid = np.arctan2(v_grid, u_grid) return ( u_grid, v_grid, healpy.get_interp_val( gamma_map, theta_grid.flatten(), phi_grid.flatten() ).reshape(pixels_per_side, -1), )
def galmap2eqmap(map): """ function to rotate galactic coord map (healpix) to equatorial """ nside=np.int(np.sqrt(len(map)/12)) grot=hp.Rotator(coord='GC') pixlist=range(len(map)) veclist=hp.pix2vec(nside,pixlist) rveclist=grot(veclist) rpixlist=hp.vec2pix(nside,rveclist[0,:],rveclist[1,:],rveclist[2,:]) outmap=np.zeros(len(map)) outmap[rpixlist]=map[pixlist] return outmap
def crd2px(self, c1, c2, c3=None, interpolate=False): """Convert 1 dimensional arrays of input coordinates to pixel indices. If only c1,c2 provided, then read them as th,phi. If c1,c2,c3 provided, read them as x,y,z. If interpolate is False, return a single pixel coordinate. If interpolate is True, return px,wgts where each entry in px contains the 4 pixels adjacent to the specified location, and wgt contains the 4 corresponding weights of those pixels.""" is_nest = (self._scheme == 'NEST') if not interpolate: if c3 is None: # th/phi angle mode px = healpy.ang2pix(self._nside, c1, c2, nest=is_nest) else: # x,y,z mode px = healpy.vec2pix(self._nside, c1, c2, c3, nest=is_nest) return px else: if c3 is not None: # need to translate xyz to th/phi c1,c2 = healpy.vec2ang(np.array([c1,c2,c3]).T) px,wgts = healpy.get_interp_weights(self._nside, c1, c2, nest=is_nest) return px.T, wgts.T
def downsample(cosmo, lightcone_base, mask_pix, rot, rank, outbase, zrange=[0.0, 1.5], comoving_nd=1e-2, nside_jack=4): # rotate mask centers to simulation coordinates vec = np.array(hp.pix2vec(4096, mask_pix, nest=True)).T vec = np.dot(vec, rot) pix = hp.vec2pix(int(nside_jack), vec[:, 0], vec[:, 1], vec[:, 2], nest=True) upix = np.unique(pix) if rank == 0: print('Total number of pix: {}'.format(len(upix))) for i, p in enumerate(upix[rank::size]): print('{}: Working on pixel {}'.format(rank, p)) sys.stdout.flush() rrange = cosmo.rofZ(np.array(zrange)) r_min_idx = rrange[0] // 25 r_max_idx = rrange[1] // 25 ridx = np.arange(r_min_idx, r_max_idx + 1) print('Radial cells to read: {}'.format(ridx)) # read in particles in this pixel/redshift range files_lightcone = get_lightcone_files(nside_jack, p, ridx, lightcone_base) part = read_files_lightcone(files_lightcone, zrange[0], zrange[1], cosmo, nside_jack, p, nd=comoving_nd) part = mask_parts(part, mask, rot) save_downsampled_particles(outbase + '/downsampled_particles.{}.fits', part, rank)
def read_map(num): a = hp.read_map( "/astro/u/anze/work/BMX/CRIME/output/colore__imap_s1_nu%03d.fits" % num) # a = hp.read_map("output2/cosmo_%03d.fits" % num) proj = hp.projector.GnomonicProj(rot=(-170, 40.8, 0), coord=["G", "C"], xsize=180, ysize=4, reso=60) vec2pix = lambda x, y, z: hp.vec2pix(Nside, x, y, z) Nside = 512 pmap = proj.projmap(a, vec2pix) return np.mean(pmap, axis=0)
def sim2(fp, freq, borequats, hwpang, hits, alps, inpp=None, hwprate=88.0, outdir = ''): nsim = borequats.shape[0] nhpix = hits.shape[0] nside = int(np.sqrt(nhpix / 12)) if nhpix != 12*nside*nside: raise RuntimeError('invalid healpix nside value') if hwpang.shape[0] != borequats.shape[0]: raise RuntimeError('HWP angle vector must be same length as boresight quaternions') if inpp is not None: if inpp.shape[0] != nhpix: raise RuntimeError('N_pp^-1 number of pixels must match N_hits') if inpp.shape[1] != 6: raise RuntimeError('N_pp^-1 must have 6 elements per pixel') xaxis = np.array([1,0,0], dtype=np.float64) yaxis = np.array([0,1,0], dtype=np.float64) zaxis = np.array([0,0,1], dtype=np.float64) # generate hitcount map and alpha for i, det in enumerate(fp.detectors(freq=freq)): detrot = qa.mult(borequats, fp.quat(det)) detdir = qa.rotate(detrot, np.tile(zaxis, nsim).reshape(-1,3)) dettheta, detphi = hp.vec2ang(detdir) detpix = hp.vec2pix(nside, detdir[:,0], detdir[:,1], detdir[:,2]) detbinned = np.bincount(detpix) hits[0:detbinned.shape[0]] += detbinned[:] outfile = os.path.join(outdir, 'theta.bin') with open(outfile, 'wb') as f: dettheta.tofile(f) outfile = os.path.join(outdir, 'phi.bin') with open(outfile, 'wb') as f: detphi.tofile(f) outfile = os.path.join(outdir, 'pix.bin') with open(outfile, 'wb') as f: detpix.tofile(f) if np.mod(i,2)!=1: alpdir = qa.rotate(detrot, np.tile(xaxis, nsim).reshape(-1,3)) x = alpdir[:,0]*detdir[:,1] - alpdir[:,1]*detdir[:,0] y = alpdir[:,0]*(-detdir[:,2]*detdir[:,0]) + alpdir[:,1]*(-detdir[:,2]*detdir[:,1]) + alpdir[:,2]*(detdir[:,0]*detdir[:,0]+detdir[:,1]*detdir[:,1]) angle = np.arctan2(y,x) outfile = os.path.join(outdir, 'angle.bin') with open(outfile, 'wb') as f: angle.tofile(f)
def reproject_map(nside, phi, healpix_array=None): """Reproject beam map to be centered around healpix pixel instead of zenith. :param nside: Healpix nside :param phi: Angle to rotate beam by, from E --> N (anticlockwise) :param healpix_array: Input healpix array to be rotated :returns: - Reprojected healpix map """ vec = hp.pix2vec(nside, np.arange(hp.nside2npix(nside))) eu_mat = euler(-phi, 0, 0, deg=True) rot_map = hp.rotator.rotateVector(eu_mat, vec) new_hp_inds = hp.vec2pix(nside, rot_map[0], rot_map[1], rot_map[2]) return healpix_array[new_hp_inds]
def vec2pix(nside, v, y=None, z=None, nest=False): """ Convert HEALpixel ipix to spherical angles (astrotools definition) Substitutes hp.vec2pix :param nside: nside of the healpy pixelization :param v: either (x, y, z) vector of the pixel center(s) or only x-coordinate :param y: y-coordinate(s) of the center :param z: z-coordinate(s) of the center :param nest: set True in case you work with healpy's nested scheme :return: vector of the pixel center(s) """ if y is None and z is None: v, y, z = v ipix = hp.vec2pix(nside, v, y, z, nest=nest) return ipix
def cartesian_proj(hp_map, projector): """Create an array containing the Cartesian projection of the map. Parameters ---------- map : array-like An array containing a healpix map, can be complex. projector : cartesian projector The Cartesian projector. """ nside = healpy.npix2nside(healpy.get_map_size(hp_map.real)) vec2pix_func = lambda x, y, z: healpy.vec2pix(nside, x, y, z) cart_map = projector.projmap(hp_map.real, vec2pix_func) if np.iscomplexobj(hp_map): cart_map = cart_map + 1.0J * projector.projmap(hp_map.imag, vec2pix_func) return cart_map
def load_beam(self): self.afreqs = [] self.bm_maps = {'xx': [], 'yy': []} for ff in sorted(__import__('glob').glob('%s/*.fits'%self.fitsdir)): self.afreqs.append(get_freq_from_filename(ff)) _bm = hp.read_map(ff) _bm = hp.ud_grade(_bm, self.nside) try: _bm /= _bm[self.zen] except(AttributeError): self.zen = hp.vec2pix(self.nside, 0, 0, 1) _bm /= _bm[self.zen] self.bm_maps['xx'].append(_bm) if not hasattr(self, 'npx'): self.npx = len(_bm) self.bm_maps['yy'].append(self.rotate_xy(_bm)) self.ndeg = len(self.bm_maps['xx'])
def correlations(i_ang): ang_low = (pi / 180) * (ang[i_ang] - (ang_res / 2)) ang_high = (pi / 180) * (ang[i_ang] + (ang_res / 2)) n = np.zeros(N_jkmpix) c = np.zeros((n_corr, N_jkmpix)) c_out = np.zeros((n_corr, N_jkmpix)) #c_gal = 0 #n_gal = 0 for i in range(N_mpix): i_vec = hp.pix2vec(nside, mpix2hpix[i]) disc_low = hp.query_disc(nside, i_vec, ang_low, inclusive = False) disc_high = hp.query_disc(nside, i_vec, ang_high, inclusive = False) disc = hpix2mpix[np.setdiff1d(disc_high, disc_low)] disc = disc[disc >= 0] k = hp.vec2pix(nside_jk, i_vec[0], i_vec[1], i_vec[2]) k = jkhpix2jkmpix[k] for l in range(n_corr): dmap1 = dmap[l][0] dmap2 = dmap[l][1] c[l][k] += dmap1[i] * dmap2[disc].sum() n[k] += len(disc) #c_gal += dmap[0][0][i] * dmap[0][1][disc].sum() #n_gal += len(disc) for l in range(n_corr): for k in range(N_jkmpix): c_out[l][k] = (c[l].sum() - c[l][k]) / (n.sum() - n[k]) print "theta = %.2f Done!" % ang[i_ang] return c_out
def eq2gal(m): Rgal2eq = hp.Rotator(coord='GC') npix = len(m[0]) nside = hp.npix2nside(npix) newpix = hp.vec2pix(nside, *Rgal2eq(hp.pix2vec(nside, np.arange(npix)))) return [mm[newpix] for mm in m]
def jones2celestial_basis(jones, z0_cza=None): if z0_cza is None: z0_cza = np.radians(120.7215) npix = jones.shape[0] nside = hp.npix2nside(npix) hpxidx = np.arange(npix) cza, ra = hp.pix2ang(nside, hpxidx) z0 = irf.r_hat_cart(z0_cza, 0.) RotAxis = np.cross(z0, np.array([0,0,1.])) RotAxis /= np.sqrt(np.dot(RotAxis,RotAxis)) RotAngle = np.arccos(np.dot(z0, [0,0,1.])) R_z0 = irf.rotation_matrix(RotAxis, RotAngle) R_jones = irf.rotate_jones(jones, R_z0, multiway=True) # beams are now pointed at -31 deg latitude jones_out = np.zeros((npix, 2,2), dtype=np.complex128) ######## ## This next bit is a routine to patch the topological hole by grabbing pixel ## data from a neighborhood of the corrupted pixels. ## It uses the crucial assumption that in the ra/cza basis the dipoles ## are orthogonal at zenith. This means that for the diagonal components, ## the zenith pixels should be a local maximum, while for the off-diagonal ## components the zenith pixels should be a local minimum (in absolute value). ## Using this assumption, we can cover the corrupted pixel(s) in the ## zenith neighborhood by the maximum pixel of the neighborhood ## for the diagonal, and the minimum of the neighborhood for the off-diagonal. ## As long as the function is relatively flat in this neighborhood, this should ## be a good fix jones_b = transform_basis(nside, R_jones, z0_cza, R_z0) cf = [np.real,np.imag] u = [1.,1.j] z0pix = hp.vec2pix(nside, z0[0],z0[1],z0[2]) if nside < 128: z0_nhbrs = hp.get_all_neighbours(nside, z0_cza, phi=0.) else: z0_nhbrs = neighbors_of_neighbors(nside, z0_cza, phi=0.) jones_c = np.zeros((npix,2,2,2), dtype=np.float64) for k in range(2): jones_c[:,:,:,k] = cf[k](jones_b) for i in range(2): for j in range(2): for k in range(2): z0_nbhd = jones_c[z0_nhbrs,i,j,k] if i == j: fill_val_pix = np.argmax(abs(z0_nbhd)) fill_val = z0_nbhd[fill_val_pix] else: fill_val_pix = np.argmin(abs(z0_nbhd)) fill_val = z0_nbhd[fill_val_pix] jones_c[z0_nhbrs,i,j,k] = fill_val jones_c[z0pix,i,j,k] = fill_val jones_out = jones_c[:,:,:,0] + 1j*jones_c[:,:,:,1] return jones_out
def gal2eq(m): Rgal2eq = hp.Rotator(coord='CG') npix = len(m) nside = hp.npix2nside(npix) newpix = hp.vec2pix(nside, *Rgal2eq(hp.pix2vec(nside, np.arange(npix)))) return m[newpix]
def vec2pix_ring(self, x, y, z): return hp.vec2pix(self.nside,x,y,z)
def rotate_xy(self, m): xyz = hp.pix2vec(self.nside, range(self.npx)) X2Y = a.coord.rot_m(-np.pi/2., np.array([0,0,1])) ycrd = np.dot(X2Y, xyz) ypx = hp.vec2pix(self.nside, ycrd[0], ycrd[1], ycrd[2]) return m[ypx]
def get_pix(self, rad, nside=1024, nest=True): from healpy import vec2pix vec = self.get(rad) return vec2pix(nside, vec[:, 0], vec[:, 1], vec[:, 2], nest)
# Rotation is a rotation with respect to the `z` axis # In[ ]: rotation_speed = np.radians(-1 * 360/60) az = rotation_speed * (target_ut_h * 3600.) % (2*np.pi) q_rotation = qa.rotation(z, az) # We compose the rotations direction = qa.rotate( qa.mult(qfull, qa.mult(q_rotation, q_elev)), z) lon, lat= hp.vec2dir(direction[:,0], direction[:,1], direction[:,2], lonlat=True) # ### Hitmap pix = hp.vec2pix(NSIDE,direction[:,0], direction[:,1], direction[:,2] ) hit += hp.ma(pix2map(pix, NSIDE)) hit.mask = hit == 0 hp.write_map('hitmap_%s_%d_opening.fits' % (LOCATION, OPENING_ANGLE),hit)
def simulate_timestream(self, segment, return_field=["signal", "v", "pol_ang"]): if segment == 0: #self.display_params() #self.beam.display_beam_settings() if self.config.write_beam: self.beam.write_beam(self.bolo_dir) rot_qt = self.generate_quaternion(segment) t_stream = {"signal" : None, "v" : None, "pol_ang" : None, "noise" : None} prompter.prompt("0.0") #Simulating the scan along the centre of the FOV v_init = self.get_initial_vec(0.0) v_central = self.get_v_obv(v_init, rot_qt) t_stream['v'] = v_central pol_ang = self.get_pol_ang(rot_qt, v_central) t_stream['pol_ang'] = pol_ang if self.config.sim_pol_type == "T": cos2=None sin2=None else: cos2 = np.cos(2*pol_ang) sin2 = np.sin(2*pol_ang) if "timestream_data" in self.config.timestream_data_products: self.make_write_dir(segment) self.write_timestream_data(v_central, "pointing_vec", segment) self.write_timestream_data(pol_ang, "pol_ang", segment) if not self.config.pipe_with_map_maker: del pol_ang beam_kernel_row = self.beam.get_beam_row(0.0) #The input argument is the beam offset from the centre hit_pix = hp.vec2pix(self.config.nside_in, v_central[...,0], v_central[...,1], v_central[...,2]) signal = self.generate_signal(hit_pix, beam_kernel_row, cos2, sin2) for del_beta in self.beam.del_beta: if del_beta == 0.0: continue prompter.prompt(str(del_beta)) beam_kernel_row = self.beam.get_beam_row(del_beta) v_init = self.get_initial_vec(del_beta) v = quaternion.transform(rot_qt, v_init) hit_pix = hp.vec2pix(self.config.nside_in, v[...,0], v[...,1], v[...,2]) signal += self.generate_signal(hit_pix, beam_kernel_row, cos2, sin2) beam_sum = np.sum(self.beam.beam_kernel[0]) signal /= beam_sum if self.config.add_noise: noise = self.noise_class.simulate_timestream_noise_from_parameters() if "timestream_data" in self.config.timestream_data_products: self.write_timestream_data(noise, "noise", segment) signal[::self.config.oversampling_rate] += noise if "timestream_data" in self.config.timestream_data_products: self.write_timestream_data(signal, "signal", segment) if self.config.pipe_with_map_maker: if self.config.do_pencil_beam: t_stream["signal"] = signal t_stream["v"] = v_central t_stream["pol_ang"] = pol_ang return t_stream else: t_stream["signal"] = signal[::self.config.oversampling_rate] t_stream["v"] = v_central[self.pad:-self.pad][::self.config.oversampling_rate] t_stream["pol_ang"] = pol_ang[self.pad:-self.pad][::self.config.oversampling_rate] return t_stream if "hitmap" in self.config.timestream_data_products: del signal hit_pix = hp.vec2pix(self.config.nside_in, v_central[...,0], v_central[...,1], v_central[...,2]) hitmap = self.get_hitmap(hit_pix) return hitmap
def healmap(map, proj='mollweide', nest=False, rot=None, coord=None, flipconv=None): proj = projs[proj](flipconv=flipconv) f = lambda x,y,z: vec2pix(npix2nside(len(map)), x,y,z,nest) image = proj.projmap(map, f, rot=rot, coord=coord) return image, [v * 0.5 * pi for v in proj.get_extent()]