def look_up_D(detnorm, source, array=False): """The look up table for detector D. Parameters ---------- detnorm : array The vector normal to detector D. source : array The vector pointing to where in the sky the GRB came from. Returns ------- x : float The exponent of dependence for the detector's response. """ if array: ang = findAngles(detnorm, source) if not array: ang = angle(detnorm, source) sourceang = hp.vec2ang(source) sourcetheta = sourceang[0] sourcephi = sourceang[1] #convert to degrees for now, not a big dealio or anything yet. sourcetheta = np.around( np.rad2deg(sourcetheta) ) #This needs to be able to take in an array and produce corresponding R's. sourcephi = np.around(np.rad2deg(sourcephi)) X = np.arange(0, 180, 1) #full sky now. Y = np.arange(0, 360, 1) X, Y = np.meshgrid(X, Y) R = 0.76 * np.ones(shape=np.shape(X)) if not array: if ang > np.pi / 2: x = 0 else: mask1 = X == sourcetheta mask2 = Y == sourcephi x = R[mask1 & mask2] else: x = [] for i in range(len(source)): sourceang = hp.vec2ang(source[i]) mask1 = X == np.around(np.rad2deg(sourceang[0])) #theta mask mask2 = Y == np.around(np.rad2deg(sourceang[1])) #phi mask x.append(R[mask1 & mask2]) return x
def antipode(x, y, coord="C", degrees=False): """ if coord=C : x->ra, y->dec if coord=E : x->phi, y->theta returns the anitpode position """ if coord == "C": Y, X = hp.vec2ang(-hp.ang2vec(0.5 * np.pi - y, x)) Y = 0.5 * np.pi - Y elif coord == "E": Y, X = hp.vec2ang(-hp.ang2vec(y, x)) return X, Y
def get_fp_rotations(phi, theta, psi, x_fp, n_horns, time, n=None, cartesian=False): """ It returns the temporal sequence of pointings for each horn. Parameters ---------- phi : numpy array of shape (obs_time * sampling_rate), radians The Azimith angle. theta : numpy array of shape (obs_time * sampling_rate), radians The Zenith distance. psi : numpy array of shape (obs_time * sampling_rate), radians The polarization angle. x_fp : numpy array of shape (n_horns, 3) They are the positions (versors) of the horns in the frame of reference of the focal plane (the one in which the central horn points towards the local Zenith with versor (0, 0, 1)). n_honrs : integer It is the total number of horns. time : numpy array of shape (obs_time * sampling rate), sec It is the time sample expressed in seconds. n : integer in the range (0, n_horns - 1), default = None It is the horn for which the pointings are computed. If None, will be returned the pointings for all the horns. cartesian : boolean, dafault = False If True will be returned the pointings in cartesian coordinates. Otherwise, the spherical coordinates of the pointings will be returned. Returns ------- out : numpy array of shape (n_horns, obs_time * sampling_rate, 2), numpy array of shape (n_horns, obs_time * sampling_rate, 3) if cartesian, numpy array of shape (obs_time * sampling_rate, 2) if n, numpy array of shape (obs_time * sampling_rate, 3) if n and cartesian """ tc, tw = (timing.clock(), timing.time()) fp_rotations = euler_rotation_matrix(phi, theta, psi) if n is None: fp_pointings = np.sum(fp_rotations[None, ...] * x_fp[:, None, None, :], axis=-1) fp_pointings_spherical = np.column_stack(hp.vec2ang(fp_pointings)).reshape( n_horns, len(time), 2) else: fp_pointings = np.sum(fp_rotations * x_fp[n, None, :], axis=-1) fp_pointings_spherical = np.column_stack(hp.vec2ang(fp_pointings)) clock_time, wall_time = (timing.clock() - tc, timing.time() - tw) print ('fp conversion clock time [sec]:', clock_time, '\n', 'fp conversion wall time [sec]:', wall_time) if cartesian: return fp_pointings return fp_pointings_spherical
def get_vertices(m): m = np.copy(m) top_npix = len(m) top_nside = hp.npix2nside(top_npix) top_order = int(np.log2(top_nside)) for order in range(top_order + 1): nside = 1 << order npix = hp.nside2npix(nside) stride = 1 << (2 * (top_order - order)) keep = (hp.pix2vec(nside, np.arange(npix), nest=True) * np.expand_dims(xyz0, 1)).sum(0) >= np.cos(np.deg2rad(30)) if order < top_order: mm = m.reshape((-1, stride)) keep &= (mm[:, :-1] == mm[:, 1:]).all(axis=1) m += hp.ud_grade(np.where(keep, np.nan, 0), nside_out=top_nside, order_in='NEST', order_out='NEST') else: keep &= ~np.isnan(m) for ipix in np.flatnonzero(keep): boundaries = hp.boundaries(nside, ipix, nest=True, step=1).T theta, phi = hp.vec2ang(boundaries) ra = np.rad2deg(phi) dec = np.rad2deg(0.5 * np.pi - theta) vertices = np.column_stack((ra, dec)) yield vertices
def visualizeHealPixMap(theMap, nest=True, title="map", norm=None, vmin=None, vmax=None, cmap=plt.cm.hot_r): from matplotlib.collections import PolyCollection from matplotlib.colors import Normalize nside = hp.npix2nside(theMap.size) mapValue = theMap[theMap != hp.UNSEEN] indices = np.arange(theMap.size) seenInds = indices[theMap != hp.UNSEEN] print "Building polygons from HEALPixel map." vertices = np.zeros( (seenInds.size, 4, 2) ) print "Building polygons for "+str(seenInds.size)+" HEALPixels." for HPixel,i in zip(seenInds,xrange(seenInds.size)): corners = hp.vec2ang( np.transpose(hp.boundaries(nside,HPixel,nest=nest) ) ) # HEALPix insists on using theta/phi; we in astronomy like to use ra/dec. vertices[i,:,0] = corners[1] *180./np.pi vertices[i,:,1] = 90.0 - corners[0] * 180/np.pi fig, ax = plt.subplots(figsize=(12,12)) #coll = PolyCollection(vertices, array = mapValue, cmap = plt.cm.seismic, edgecolors='none') coll = PolyCollection(vertices, array=mapValue, cmap=cmap, edgecolors='none') coll.set_clim(vmin=vmin, vmax=vmax) ax.add_collection(coll) ax.set_title(title) ax.autoscale_view() fig.colorbar(coll,ax=ax) #ax.set_ylim([-60.2, -43]) print "Writing to file: "+title+".png" fig.savefig(title+".png",format="png")
def read_buzzard_catalog(pixel, mag_lensed=False, coord_lensed=True): path = os.path.join('/', 'project', 'projectdirs', 'desi', 'mocks', 'buzzard', 'buzzard_v2.0', 'buzzard-4', 'i25_lensing_cat', '8') path = os.path.join(path, '{}'.format(pixel // 100), '{}'.format(pixel)) fname = 'Buzzard_v2.0_lensed-8-{}.fits'.format(pixel) table = Table.read(os.path.join(path, fname)) table.rename_column('GAMMA1', 'gamma_1') table.rename_column('GAMMA2', 'gamma_2') table.rename_column('Z', 'z_true') table.rename_column('MU', 'mu') if mag_lensed: table['mag'] = np.hstack((table['LMAG'], table['LMAG_WISE'])) else: table['mag'] = np.hstack((table['TMAG'], table['TMAG_WISE'])) if coord_lensed: table.rename_column('RA', 'ra') table.rename_column('DEC', 'dec') else: table['ra'], table['dec'] = hp.vec2ang(np.array( [table['PX'], table['PY'], table['PZ']]).T, lonlat=True) table.keep_columns( ['z_true', 'ra', 'dec', 'mag', 'gamma_1', 'gamma_2', 'mu']) table.meta = {} return table
def simulate_points(m_in, n, info, scaling=SCALING): m = (1 + scaling * m_in).clip(0, np.inf) m[m_in == 0] = 0 npix = m.size pix_prob = m / m.sum() # Choose random pixels pix = np.random.choice(npix, size=n, replace=True, p=pix_prob) counts = np.zeros(npix, dtype=int) for p in pix: counts[p] += 1 Ra = [] Dec = [] for i in range(npix): if counts[i] == 0: continue P = sample_quadrilateral(counts[i], info[i]) ra, dec = hp.vec2ang(P, lonlat=True) Ra.append(ra) Dec.append(dec) Ra = np.concatenate(Ra) Dec = np.concatenate(Dec) return Ra, Dec
def getDipole(p): py = p['Y(1,-1)'] pz = p['Y(1,0)'] px = p['Y(1,1)'] dpy = p['dY(1,-1)'] dpz = p['dY(1,0)'] dpx = p['dY(1,1)'] # Calculate dipole strength #p0 = np.sqrt(3.*(px**2 + py**2 + pz**2)/(4.*np.pi)) p0 = np.sqrt(px**2 + py**2 + pz**2) dp0 = np.sqrt(((px*dpx)**2 + (py*dpy)**2 + (px*dpz)**2) / p0**2) # Calculate dipole phase theta, phi = hp.vec2ang(np.array([px, py, pz])) # phi = arctan(y/x) dphidy = px / (px**2 + py**2) dphidx = -py / (px**2 + py**2) dPhi = np.sqrt((dphidx * dpx)**2 + (dphidy * dpy)**2) # theta = arccos(z / np.sqrt(x**2 + y**2 + z**2)) dthetadx = px * pz / (np.sqrt((px**2 + py**2)/(px**2+py**2+pz**2)) * \ np.sqrt((px**2 + py**2 + pz**2)**(3))) dthetady = py * pz / (np.sqrt((px**2 + py**2)/(px**2+py**2+pz**2)) * \ np.sqrt((px**2 + py**2 + pz**2)**(3))) dthetadz = -np.sqrt((px**2 + py**2)/(px**2+py**2+pz**2)) / \ np.sqrt(px**2 + py**2 + pz**2) dTheta = np.sqrt((dthetadx*dpx)**2 + (dthetady*dpy)**2 + (dthetadz*dpz)**2) return p0, dp0, theta, dTheta, phi, dPhi
def overhead( ifo, coord="E", tgeocent=None, degrees=False ): """ get the overhead direction of an ifo. overhead is defined as (nx x ny) = nz """ if ifo not in detectors.keys(): raise ValueError("ifo=%s not understood"%ifo ) nz = __overhead_Evec( ifo ) t, p = hp.vec2ang( nz ) if isinstance(t, np.ndarray): t = t[0] p = p[0] if coord == "E": if degrees: t *= deg2rad p *= deg2rad return t, p elif coord == "C": if tgeocent==None: raise ValueError("please supply tgeocent when coord=C") dc, ra = __earth2celest( t, p, tgeocent ) if degrees: dc *= rad2deg ra *= rad2deg return dc, ra
def make_rect_poly(width, height, theta, phi, subdivisions=10): """Create a Polygon patch representing a rectangle with half-angles width and height rotated from the north pole to (theta, phi).""" # Convert width and height to radians, then to Cartesian coordinates. w = np.sin(np.deg2rad(width)) h = np.sin(np.deg2rad(height)) # Generate vertices of rectangle. v = np.asarray([[-w, -h], [w, -h], [w, h], [-w, h]]) # Subdivide. v = subdivide_vertices(v, subdivisions) # Project onto sphere by calculating z-coord from normalization condition. v = np.hstack((v, np.sqrt(1. - np.expand_dims(np.square(v).sum(1), 1)))) # Transform vertices. v = np.dot(v, hp.rotator.euler_matrix_new(phi, theta, 0, Y=True)) # Convert to spherical polar coordinates. thetas, phis = hp.vec2ang(v) # FIXME: Remove this after all Matplotlib monkeypatches are obsolete. if mpl_version < '1.2.0': # Return list of vertices as longitude, latitude pairs. return np.column_stack((reference_angle(phis), 0.5 * np.pi - thetas)) else: # Return list of vertices as longitude, latitude pairs. return np.column_stack((wrapped_angle(phis), 0.5 * np.pi - thetas))
def make_rect_poly(width, height, theta, phi, subdivisions=10): """Create a Polygon patch representing a rectangle with half-angles width and height rotated from the north pole to (theta, phi).""" # Convert width and height to radians, then to Cartesian coordinates. w = np.sin(np.deg2rad(width)) h = np.sin(np.deg2rad(height)) # Generate vertices of rectangle. v = np.array([[-w, -h], [w, -h], [w, h], [-w, h]]) # Subdivide. v = subdivide_vertices(v, subdivisions) # Project onto sphere by calculating z-coord from normalization condition. v = np.hstack((v, np.sqrt(1. - np.expand_dims((v * v).sum(1), 1)))) # Transform vertices. v = np.dot(v, hp.rotator.euler_matrix_new(phi, theta, 0, Y=True)) # Convert to spherical polar coordinates. thetas, phis = hp.vec2ang(v) # FIXME: Remove this after all Matplotlib monkeypatches are obsolete. if mpl_version < '1.2.0': # Return list of vertices as longitude, latitude pairs. return np.vstack((reference_angle(phis), 0.5 * np.pi - thetas)).T else: # Return list of vertices as longitude, latitude pairs. return np.vstack((wrapped_angle(phis), 0.5 * np.pi - thetas)).T
def GetHealPixRectangles(nside, dbrange, nest): hpindex = np.arange(hp.nside2npix(nside)) vec_corners = hp.boundaries(nside, hpindex, nest=nest) vec_corners = np.transpose(vec_corners, (0,2,1)) vec_corners = np.reshape(vec_corners, (vec_corners.shape[0]*vec_corners.shape[1], vec_corners.shape[2])) theta_corners, phi_corners = hp.vec2ang(vec_corners) theta_corners = np.reshape(theta_corners, (theta_corners.shape[0]/4, 4)) phi_corners = np.reshape(phi_corners, (phi_corners.shape[0]/4, 4)) ra_corners = np.degrees(phi_corners) dec_corners = 90.0 - np.degrees(theta_corners) rainside = ( (ra_corners > dbrange[0]) & (ra_corners < dbrange[1]) ) rakeep = np.sum(rainside, axis=-1) decinside = ( (dec_corners > dbrange[2]) & (dec_corners < dbrange[3]) ) deckeep = np.sum(decinside, axis=-1) keep = ( (rakeep > 0) & (deckeep > 0) ) ra_corners, dec_corners, hpindex = Cut(ra_corners, dec_corners, hpindex, cut=keep) ramin = np.amin(ra_corners, axis=-1) ramax = np.amax(ra_corners, axis=-1) decmin = np.amin(dec_corners, axis=-1) decmax = np.amax(dec_corners, axis=-1) return ramin, ramax, decmin, decmax, hpindex
def write_rdzw(self, fn): '''Write the galaxy catalog in RA, DEC, Z (real & RSD) and weight.''' print('>> writing to file: {0:s}'.format(fn)) t0 = time.time() chi_real = np.sqrt(np.sum(np.power(self.gcat['xyz'], 2), axis=1)) vlos = np.sum(self.gcat['xyz'] * self.gcat['vxyz'], axis=1) / chi_real z_real = self.chi2z(chi_real) # real space redshift theta, phi = hp.vec2ang(self.gcat['xyz']) ra, dec = utils.get_ra_dec(theta, phi) Hz = self.cosmo.efunc(z_real) * 100. # km/s/(Mpc/h) chi_rsd = chi_real + (1. + z_real) * vlos / Hz z_rsd = self.chi2z(chi_rsd) weight = np.ones(z_rsd.shape[0]) header = self.header + 'RA DEC Z (RSD) weight' fmt = '%15.7e %15.7e %15.7e %3g' np.savetxt(fn, np.column_stack((ra, dec, z_rsd, weight)), fmt=fmt, header=header) print('<< time elapsed: {0:.2f} s'.format(time.time() - t0))
def gc2radec(self, gc_phi, gc_theta, min_lon=None): """ convert coordinates in galactic coordinate system to equatorial ra, dec. Parameters ---------- gc_phi : `np.ndarray`, float angular coordinate in Galactic coordinate system, where the MW disk is at theta=0. gc_theta : `np.ndarray`, float azimuthal coordinate in Galactic coordinate system. min_lon : degrees, defaults to None min longitude beyond which the galaxy is cut off. If None, `self.min_lon` is used. max_lon : None, Not implemented yet """ vec = hp.ang2vec(gc_theta, gc_phi) vec_radec = np.asarray(list(np.dot(self.rmat_inv, v) for v in vec)) theta, phi = hp.vec2ang(vec_radec) ra, dec = convertToCelestialCoordinates(theta, phi) if min_lon is None: min_lon = self.min_lon mask = dec > min_lon return ra[mask], dec[mask]
def vec2sky(cls, vec, degrees=False): """ Convert [x,y,z] vectors into sky coordinates ra,dec Parameters ---------- vec : numpy.array Unit vectors as an array of (x,y,z) degrees Returns ------- sky : numpy.array Sky coordinates as an array of (ra,dec) See Also -------- :func:`AegeanTools.regions.Region.sky2vec` """ theta, phi = hp.vec2ang(vec) ra = phi dec = np.pi / 2 - theta if degrees: ra = np.degrees(ra) dec = np.degrees(dec) return cls.radec2sky(ra, dec)
def get_vecpsi(self, rad): from healpy import vec2ang vec = self.get(rad) theta, phi = vec2ang(vec) psi = self.compute_psi(theta, phi, rad) return vec, psi
def get_vert(pixel, nside, nest): """Get the coordinates for the vertices for a single Healpix index for a given resolution (nside) and schema (nest) Args: * All arguments are required pixel(int): Healpix index nside(int) : Healpix resolution given by nside parameters for the input pixel nest(bool): Pixelization schema, True: Nested Schema, False: Ring Schema Returns: Two lists with the RA and DEC positions for the vertices for the given pixel. """ # Get vertices in radian coordinates for a given pixel vertices = np.array( hp.vec2ang(np.transpose(hp.boundaries(nside, pixel, nest=nest)))) # To degrees vertices = vertices * 180. / np.pi diff = vertices[1] - vertices[1][0] # RA = 0 diff[diff > 180] -= 360 diff[diff < -180] += 360 ra_vert = vertices[1][0] + diff ra_vert = np.append(ra_vert, ra_vert[0]) dec_vert = 90.0 - vertices[0] dec_vert = np.append(dec_vert, dec_vert[0]) return ra_vert, dec_vert
def get_detector_pair_axis(ifo1, ifo2, gmst): """Find the sky position where the line between two detectors pierces the celestial sphere. Parameters ---------- ifo1 : str or `~lal.Detector` or `~np.ndarray` The first detector; either the name of the detector (e.g. `'H1'`), or a `lal.Detector` object (e.g., as returned by `lalsimulation.DetectorPrefixToLALDetector('H1')` or the geocentric Cartesian position of the detection in meters. ifo2 : str or `~lal.Detector` or `~np.ndarray` The second detector; same as described above. gmst : float The Greenwich mean sidereal time in radians, as returned by `lal.GreenwichMeanSiderealTime`. Returns ------- pole_ra : float The right ascension in radians at which a ray from `ifo1` to `ifo2` would pierce the celestial sphere. pole_dec : float The declination in radians at which a ray from `ifo1` to `ifo2` would pierce the celestial sphere. light_travel_time : float The light travel time from `ifo1` to `ifo2` in seconds. """ # Get location of detectors if ifo1, ifo2 are LAL detector structs try: ifo1 = lalsimulation.DetectorPrefixToLALDetector(ifo1) except TypeError: pass try: ifo1 = ifo1.location except AttributeError: pass try: ifo2 = lalsimulation.DetectorPrefixToLALDetector(ifo2) except TypeError: pass try: ifo2 = ifo2.location except AttributeError: pass n = ifo2 - ifo1 light_travel_time = np.sqrt(np.sum(np.square(n))) / lal.C_SI (theta, ), (phi, ) = hp.vec2ang(n) pole_ra = (gmst + phi) % (2 * np.pi) pole_dec = 0.5 * np.pi - theta return pole_ra, pole_dec, light_travel_time
def get_detector_pair_axis(ifo1, ifo2, gmst): """Find the sky position where the line between two detectors pierces the celestial sphere. Parameters ---------- ifo1 : str or `~lal.Detector` or `~np.ndarray` The first detector; either the name of the detector (e.g. `'H1'`), or a `lal.Detector` object (e.g., as returned by `lalsimulation.DetectorPrefixToLALDetector('H1')` or the geocentric Cartesian position of the detection in meters. ifo2 : str or `~lal.Detector` or `~np.ndarray` The second detector; same as described above. gmst : float The Greenwich mean sidereal time in radians, as returned by `lal.GreenwichMeanSiderealTime`. Returns ------- pole_ra : float The right ascension in radians at which a ray from `ifo1` to `ifo2` would pierce the celestial sphere. pole_dec : float The declination in radians at which a ray from `ifo1` to `ifo2` would pierce the celestial sphere. light_travel_time : float The light travel time from `ifo1` to `ifo2` in seconds. """ # Get location of detectors if ifo1, ifo2 are LAL detector structs try: ifo1 = lalsimulation.DetectorPrefixToLALDetector(ifo1) except TypeError: pass try: ifo1 = ifo1.location except AttributeError: pass try: ifo2 = lalsimulation.DetectorPrefixToLALDetector(ifo2) except TypeError: pass try: ifo2 = ifo2.location except AttributeError: pass n = ifo2 - ifo1 light_travel_time = np.sqrt(np.sum(np.square(n))) / lal.C_SI (theta,), (phi,) = hp.vec2ang(n) pole_ra = (gmst + phi) % (2 * np.pi) pole_dec = 0.5 * np.pi - theta return pole_ra, pole_dec, light_travel_time
def zenith(self): nx = self.nx ny = self.ny nz = np.array([ nx[1] * ny[2] - nx[2] * ny[1], -nx[0] * ny[2] + nx[2] * ny[0], nx[0] * ny[1] - nx[1] * ny[0] ]) ### take cross product by hand... return hp.vec2ang(nz) ### theta, phi
def __init__(self, nSide, ident, nest, tractBuilder, ctrCoord, tractOverlap, wcs): """Set vertices from nside, ident, nest""" theta, phi = healpy.vec2ang( numpy.transpose(healpy.boundaries(nSide, ident, nest=nest))) vertexList = [angToCoord(thetaphi) for thetaphi in zip(theta, phi)] super(HealpixTractInfo, self).__init__(ident, tractBuilder, ctrCoord, vertexList, tractOverlap, wcs)
def get_ang(self, rad, degrees=False): from healpy import vec2ang vec = self.get(rad) ang = vec2ang(vec) if degrees: return map(np.rad2deg, ang) else: return ang
def get_dipole_dir(sky): ''' Return the direction of the reconstructed dipole in (RA, dec) coordinated ''' mono, dipole = hp.fit_dipole(sky) d = hp.vec2ang(dipole, lonlat=True) return (d[0][0], d[1][0])
def mollweid_vec(l, lmin, lmax, dir_vec, size_var, symbol, fill_style): lon, lat = hp.vec2ang(dir_vec, lonlat=True) hp.visufunc.projplot(lon, lat, symbol, lonlat=True, color=cmap_func((l - lmin) / (lmax - lmin)), markersize=size_var, fillstyle=fill_style)
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_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 get_detector_pair_axis(ifo1, ifo2, gmst): ifo1 = _get_detector_location(ifo1) ifo2 = _get_detector_location(ifo2) n = ifo2 - ifo1 light_travel_time = np.sqrt(np.sum(np.square(n))) / constants.c.value (theta,), (phi,) = hp.vec2ang(n) pole_ra = (gmst + phi) % (2 * np.pi) pole_dec = 0.5 * np.pi - theta return pole_ra, pole_dec, light_travel_time
def getFgcmReferenceStarsHealpix(self, nside, pixel, filterList, nest=False): """ Get a reference catalog that overlaps a healpix pixel, using multiple filters. In addition, apply colorterms if available. Return format is a numpy recarray for use with fgcm, with the format: dtype = ([('ra', `np.float64`), ('dec', `np.float64`), ('refMag', `np.float32`, len(filterList)), ('refMagErr', `np.float32`, len(filterList)]) Reference magnitudes (AB) will be 99 for non-detections. Parameters ---------- nside: `int` Healpix nside of pixel to load pixel: `int` Healpix pixel of pixel to load filterList: `list` list of `str` of camera filter names. nest: `bool`, optional Is the pixel in nest format? Default is False. Returns ------- fgcmRefCat: `np.recarray` """ # Determine the size of the sky circle to load theta, phi = hp.pix2ang(nside, pixel, nest=nest) center = lsst.geom.SpherePoint(phi * lsst.geom.radians, (np.pi/2. - theta) * lsst.geom.radians) corners = hp.boundaries(nside, pixel, step=1, nest=nest) theta_phi = hp.vec2ang(np.transpose(corners)) radius = 0.0 * lsst.geom.radians for ctheta, cphi in zip(*theta_phi): rad = center.separation(lsst.geom.SpherePoint(cphi * lsst.geom.radians, (np.pi/2. - ctheta) * lsst.geom.radians)) if (rad > radius): radius = rad # Load the fgcm-format reference catalog fgcmRefCat = self.getFgcmReferenceStarsSkyCircle(center.getRa().asDegrees(), center.getDec().asDegrees(), radius.asDegrees(), filterList) catPix = hp.ang2pix(nside, np.radians(90.0 - fgcmRefCat['dec']), np.radians(fgcmRefCat['ra']), nest=nest) inPix, = np.where(catPix == pixel) return fgcmRefCat[inPix]
def parallactic_angle(ze, deg=True): """ Calculates angle between theta axes given a direction in Equatorial and Galactic coordinates. *numpy.einsum()* functions in some products are replaced with numpy.tensordot() for speed. Parameters ---------- ze : float or float array Direction vector in equatorial coordinate. deg : bool If it is set 'True', the output angle is in degree. Otherwise, the output angle is in radian (default: True). Returns -------- psi_par : float parallactic angle for the given direction """ ze = np.array(ze) if (hasattr(ze[0], '__iter__')): zg = np.tensordot(R_E2G.mat, ze, axes=(1,1)).T xp = xp_coord(hp.vec2ang(ze)).T xe = np.tensordot(R_E2G.mat, xp, axes=(1,1)).T xg = xp_coord(hp.vec2ang(zg)).T xcx = np.cross(xe, xg) xdx = np.einsum('ij,ij->i', xe, xg) idx1 = np.where(xdx > 1) xdx[idx1] = 0 sign = np.sign(np.einsum('ij,ij->i',zg, xcx)) else: zg = R_E2G(ze) xp = xp_coord(hp.vec2ang(ze)).flatten() xe = R_E2G(xp) xg = xp_coord(hp.vec2ang(zg)).flatten() xcx = np.cross(xe, xg) xdx = np.dot(xe, xg) if xdx > 1: xdx = 1 sign = np.sign(np.dot(zg, xcx)) psi_par = np.arccos(xdx) * sign return psi_par
def load_catalog(catalog_path): """ Load catalog of galaxies as comma seperated x, y, z and convert to angular coordinates. """ x, y, z, _, _, _ = np.loadtxt(catalog_path, delimiter=',', unpack=True) x = x - 62.5/2 y = y - 62.5/2 z = z - 62.5/2 v = np.array([x, y, z]).T t, p = hp.vec2ang(v) return t, p
def healpix_boundaries(ipix, nside=256, step=2, nest=True, convention='spherical', units='degrees'): """ return an array of points on the boundaries of the healpixels with ids given by ipix in the form of (colongitudes, colatitudes) Parameters ---------- ipix : `np.ndarray`, dtype int healpixel ids of pixels whose boundaries are required nside : int, defaults to 256 Healpix NSIDE step : int factor by which the number of points in the corners (4) are stepped up. ie. a step of 2 returns 8 points along the boundaries of the Healpixel inlcuding the corners nest : Bool, defaults to True using the `nested` rather than `ring` scheme. convention : {'spherical', 'celestial'}, defaults to 'spherical' (theta, phi) of the usual spherical coordinate system or (ra, dec) units : {'degrees', 'radians'} , defaults to 'degrees' units in which the points are returned Returns -------- tuple (colongitude, colatitude) .. note: This also produces the 'inner' boundaries for connected pixels. """ corner_vecs = hp.boundaries(nside, ipix, step=step, nest=nest) if len(np.shape(corner_vecs)) > 2: corner_vecs = np.concatenate(corner_vecs, axis=1) phi_theta = hp.vec2ang(np.transpose(corner_vecs)) # These are in radians and spherical coordinates by construction theta, phi = phi_theta if convention == 'celestial': return convertToCelestialCoordinates(theta, phi, output_unit=units) # else return in spherical coordinates, but convert to degrees if requested if units == 'degrees': lon = np.degrees(phi) lat = np.degrees(theta) else: lon = phi lat = theta return lon, lat
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 polygon(self): if not self.__polygon: pixel_xyz_vertices = hp.boundaries(self.nside, pix=self.index) theta, phi = hp.vec2ang(np.transpose(pixel_xyz_vertices)) ra_rad = phi dec_rad = (np.pi / 2. - theta) pixel_radian_vertices = [[ra, dec] for ra, dec in zip(ra_rad, dec_rad)] self.__polygon = geometry.Polygon(pixel_radian_vertices) return [self.__polygon]
def getCountAtLocations(ra, dec, nside=512, return_vertices=False): """Get number density of objects from RA/Dec in HealPix cells. Requires: healpy Args: ra: list of rectascensions dec: list of declinations nside: HealPix nside return_vertices: whether to also return the boundaries of HealPix cells Returns: bc, ra_, dec_, [vertices] bc: count of objects [per arcmin^2] in a HealPix cell if count > 0 ra_: rectascension of the cell center (same format as ra/dec) dec_: declinations of the cell center (same format as ra/dec) vertices: (N,4,2), RA/Dec coordinates of 4 boundary points of cell """ import healpy as hp # get healpix pixels ipix = hp.ang2pix(nside, (90 - dec) / 180 * np.pi, ra / 180 * np.pi, nest=False) # count how often each pixel is hit bc = np.bincount(ipix) pixels = np.nonzero(bc)[0] bc = bc[bc > 0] / hp.nside2resol(nside, arcmin=True)**2 # in arcmin^-2 # get position of each pixel in RA/Dec theta, phi = hp.pix2ang(nside, pixels, nest=False) ra_ = phi * 180 / np.pi dec_ = 90 - theta * 180 / np.pi # get the vertices that confine each pixel # convert to RA/Dec (thanks to Eric Huff) if return_vertices: vertices = np.zeros((pixels.size, 4, 2)) for i in xrange(pixels.size): corners = hp.vec2ang(np.transpose(hp.boundaries(nside, pixels[i]))) corners = np.array(corners) * 180. / np.pi diff = corners[1] - corners[1][0] diff[diff > 180] -= 360 diff[diff < -180] += 360 corners[1] = corners[1][0] + diff vertices[i, :, 0] = corners[1] vertices[i, :, 1] = 90.0 - corners[0] return bc, ra_, dec_, vertices else: return bc, ra_, dec_
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 vec2sky(cls,vec,degrees=False): """ Convert [x,y,z] vectors into sky coordinates ra,dec :param vec: An array-like list of ([x,y,z],...) :param degrees: Return ra/dec in degrees? Default = false :return: [(ra,...),(dec,...)] """ theta,phi = hp.vec2ang(vec) ra=phi dec=np.pi/2-theta if degrees: ra=np.degrees(ra) dec=np.degrees(dec) return cls.radec2sky(ra,dec)
def vec2sky(cls, vec, degrees=False): """ Convert [x,y,z] vectors into sky coordinates ra,dec :param vec: An array-like list of ([x,y,z],...) :param degrees: Return ra/dec in degrees? Default = false :return: [(ra,...),(dec,...)] """ theta, phi = hp.vec2ang(vec) ra = phi dec = np.pi / 2 - theta if degrees: ra = np.degrees(ra) dec = np.degrees(dec) return cls.radec2sky(ra, dec)
def generate_uniform_random_ra_dec_healpixel(n, pix, nside, nest=False): """ Parameters ---------- n : int number of random points needed pix : int healpixel ID nside : int number of healpixel nside, must be 2**k nest : bool, optional using healpixel nest or ring ordering Returns ------- ra : ndarray 1d array of length n that contains RA in degrees dec : ndarray 1d array of length n that contains Dec in degrees """ ra, dec = hp.vec2ang(hp.boundaries(nside, pix, 1, nest=nest).T, lonlat=True) ra_dec_min_max = ra.min(), ra.max(), dec.min(), dec.max() ra = np.empty(n) dec = np.empty_like(ra) n_needed = n while n_needed > 0: ra_this, dec_this = generate_uniform_random_ra_dec_min_max( n_needed * 2, *ra_dec_min_max) mask = np.where( hp.ang2pix(nside, ra_this, dec_this, nest=nest, lonlat=True) == pix)[0] count_this = mask.size if n_needed - count_this < 0: count_this = n_needed mask = mask[:n_needed] s = slice( -n_needed, -n_needed + count_this if -n_needed + count_this < 0 else None) ra[s] = ra_this[mask] dec[s] = dec_this[mask] n_needed -= count_this return ra, dec
def observe_sky(self, pnt_obj, sky_map_obj, tod, segment_length, sat_vel, noise_type, tod_write_field): sky_map = sky_map_obj.sky_map self.axis_sight = pnt_obj.get_detector_axis(self.params['pos']) v_pointing = pnt_obj.get_pointing(self.axis_sight) psi = pnt_obj.get_polariser_phase(v_pointing, self.params['pol_phase_ini']) if np.sum(sat_vel**2) != 0.0: orb_dip = pnt_obj.get_orbital_dipole( v_pointing, sat_vel, self.params['central_frequency']) theta, phi = hp.vec2ang(v_pointing) del v_pointing if self.params['pol_modulation'] == 'passive': pol_phase = 2 * psi else: pol_phase = 2 * psi + 4 * tod['psi_hwp'] hit_pix = hp.ang2pix(sky_map_obj.nside, theta, phi) signal = sky_map[0][hit_pix] + sky_map[1][hit_pix] * np.cos( pol_phase) + sky_map[2][hit_pix] * np.sin(pol_phase) if np.sum(sat_vel**2) != 0.0: signal += orb_dip if noise_type != 'no_noise': noise_params = copy.deepcopy(self.params['noise']) noise_params.update({ 'sampling_rate': self.params['sampling_rate'], 'noise_type': noise_type }) noise_obj = Noise(noise_params) noise = noise_obj.simulate_noise(segment_length) signal += noise if "noise" in tod_write_field: tod['noise'] = noise tod['theta'] = theta tod['phi'] = phi tod['psi'] = psi tod['signal'] = signal if "orb_dip" in tod_write_field: tod['orb_dip'] = orb_dip
def getCountAtLocations(ra, dec, nside=512, return_vertices=False): """Get number density of objects from RA/Dec in HealPix cells. Requires: healpy Args: ra: list of rectascensions dec: list of declinations nside: HealPix nside return_vertices: whether to also return the boundaries of HealPix cells Returns: bc, ra_, dec_, [vertices] bc: count of objects [per arcmin^2] in a HealPix cell if count > 0 ra_: rectascension of the cell center (same format as ra/dec) dec_: declinations of the cell center (same format as ra/dec) vertices: (N,4,2), RA/Dec coordinates of 4 boundary points of cell """ import healpy as hp # get healpix pixels ipix = hp.ang2pix(nside, (90-dec)/180*np.pi, ra/180*np.pi, nest=False) # count how often each pixel is hit bc = np.bincount(ipix) pixels = np.nonzero(bc)[0] bc = bc[bc>0] / hp.nside2resol(nside, arcmin=True)**2 # in arcmin^-2 # get position of each pixel in RA/Dec theta, phi = hp.pix2ang(nside, pixels, nest=False) ra_ = phi*180/np.pi dec_ = 90 - theta*180/np.pi # get the vertices that confine each pixel # convert to RA/Dec (thanks to Eric Huff) if return_vertices: vertices = np.zeros((pixels.size, 4, 2)) for i in xrange(pixels.size): corners = hp.vec2ang(np.transpose(hp.boundaries(nside,pixels[i]))) corners = np.array(corners) * 180. / np.pi diff = corners[1] - corners[1][0] diff[diff > 180] -= 360 diff[diff < -180] += 360 corners[1] = corners[1][0] + diff vertices[i,:,0] = corners[1] vertices[i,:,1] = 90.0 - corners[0] return bc, ra_, dec_, vertices else: return bc, ra_, dec_
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 wmap5_parameters(): """WMAP5 solar system dipole parameters, from: http://arxiv.org/abs/0803.0732""" # 369.0 +- .9 Km/s SOLSYSSPEED = 369e3 #l.critical('USING 371') #SOLSYSSPEED = 371e3 ## direction in galactic coordinates ##(d, l, b) = (3.355 +- 0.008 mK,263.99 +- 0.14,48.26deg +- 0.03) SOLSYSDIR_GAL_THETA = np.deg2rad( 90 - 48.26 ) SOLSYSDIR_GAL_PHI = np.deg2rad( 263.99 ) SOLSYSSPEED_GAL_U = healpy.ang2vec(SOLSYSDIR_GAL_THETA,SOLSYSDIR_GAL_PHI) #SOLSYSSPEED_GAL_V = SOLSYSSPEED * SOLSYSSPEED_GAL_U SOLSYSSPEED_ECL_U = gal2ecl(SOLSYSSPEED_GAL_U) SOLSYSDIR_ECL_THETA, SOLSYSDIR_ECL_PHI = healpy.vec2ang(SOLSYSSPEED_ECL_U) ########## /WMAP5 return SOLSYSSPEED, SOLSYSDIR_ECL_THETA, SOLSYSDIR_ECL_PHI
def mask_parts(part, mask_pix, rot): vec = np.zeros((len(part), 3)) vec[:, 0] = part['px'] vec[:, 1] = part['py'] vec[:, 2] = part['pz'] rvec = np.dot(vec, np.linalg.inv(rot)) dec, ra = hp.vec2ang(rvec) pix = hp.ang2pix(4096, dec, ra, nest=True) dec = -dec * 180. / np.pi + 90 ra = ra * 180. / np.pi pidx = np.in1d(pix, mask_pix) part = part[pidx] return part
def project_healpix(M,rotate_angle=0): #flat plotting try: M.mask except(AttributeError): M = np.ma.array(M) xmax = 1#np.sin(theta.max()) X,Y = np.meshgrid(np.linspace(-xmax,xmax,num=100), np.linspace(-xmax,xmax,num=100)) R = X**2 + Y**2 Z = np.sqrt(1-X**2 - Y**2) Z[np.isnan(Z)] = 0 THETA,PHI = hp.vec2ang(np.array([X,Y,Z]).T) THETA.shape = PHI.shape = X.shape PHI += rotate_angle*np.pi/180 IM = get_interp_val(M,THETA,PHI).T IM = np.ma.masked_where(R>1,IM) return THETA,PHI,IM
def ring_outer_product(theta, phi): outAng = [0, 0] nsamps = min(100, len(theta)) pair1 = random.sample(range(len(theta)), nsamps) pair2 = random.sample(range(len(theta)), nsamps) vecs = hp.pixelfunc.ang2vec(theta, phi) for a1, a2 in zip(pair1, pair2): crossP = np.cross(vecs[a1], vecs[a2]) if (crossP[0] < 0): crossP *= -1 theta1, phi1 = hp.vec2ang(crossP) if (not math.isnan(theta1) and not math.isnan(phi1)): outAng[0] += theta1 / nsamps outAng[1] += phi1 / nsamps else: outAng[0] += outAng[0] / nsamps outAng[1] += outAng[1] / nsamps return outAng
def boundary(self, k, steps=None, max_stepsize=None, edge=1e-6): """ Return boundary of a bin; used for drawing polygons. If steps is None, max_stepsize is used to automatically determine the appropriate step size. """ if max_stepsize is None: max_stepsize = self.max_stepsize if steps is None: steps = self._determine_steps(max_stepsize=max_stepsize) bd = hp.boundaries(self.nside, k, step=steps, nest=self.nest) dec_raw, ra_raw = hp.vec2ang(np.transpose(bd)) ra = (ra_raw / _d2r) % 360 dec = 90 - dec_raw / _d2r return self.split_bin(ra, dec, max_stepsize, edge)
def get_pol_ang(self, rot_qt, v_dir): alpha = np.deg2rad(self.config.alpha) #radians beta = np.deg2rad(self.config.beta) #radians total_opening = alpha + beta pol_ini = np.deg2rad(self.config.pol_phase_ini) pol_vec_ini = np.array([0.0, 1.0, 0.0]) pol_vec = quaternion.transform(rot_qt, np.tile(pol_vec_ini, self.nsamples).reshape(-1,3)) if self.config.gal_coords: pol_vec = self.transform_to_gal_coords(pol_vec) theta, phi = hp.vec2ang(v_dir) x_local = np.array(zip(np.cos(theta)*np.cos(phi), np.cos(theta)*np.sin(phi), -np.sin(theta))) y_local = np.array(zip(-np.sin(phi), np.cos(phi), np.zeros(phi.size))) proj_x = np.sum(pol_vec*x_local, axis=-1) proj_y = np.sum(pol_vec*y_local, axis=-1) pol_ang = np.pi - (np.arctan2(proj_y, proj_x) + pol_ini) % np.pi return pol_ang
def getHealpixVertices(pixels, nside, nest=False): """Get polygon vertices for list of HealPix pixels. Requires: healpy Args: pixels: list of HealPix pixels nside: HealPix nside nest: HealPix nesting scheme Returns: vertices: (N,4,2), RA/Dec coordinates of 4 boundary points of cell """ vertices = np.zeros((pixels.size, 4, 2)) for i in xrange(pixels.size): corners = hp.vec2ang(np.transpose(hp.boundaries(nside,pixels[i], nest=nest))) corners = np.array(corners) * 180. / np.pi diff = corners[1] - corners[1][0] diff[diff > 180] -= 360 diff[diff < -180] += 360 corners[1] = corners[1][0] + diff vertices[i,:,0] = corners[1] vertices[i,:,1] = 90.0 - corners[0] return vertices
def jsa_tile_wcs(header): """ Determine WCS information for a JSA tile. """ # Find tile number and Nside. tile_number = header['TILENUM'] match = tilenum_comment.search(header.comments['TILENUM']) if not match: raise CAOMError('Cannot find Nside in TILENUM comment') nside = int(match.group(1)) # Get corner coordinates. (colatitude, longitude) = healpy.vec2ang(np.transpose( healpy.boundaries(nside, tile_number, nest=True))) assert len(colatitude) == 4 assert len(longitude) == 4 # Convert to a CAOM-2 polygon. Note the ordering appears to be # the other way round from what CAOM-2 requires, hence iteration # over the corners backwards. tile = CoordPolygon2D() for i in range(3, -1, -1): tile.vertices.append(ValueCoord2D( 180 * longitude[i] / math.pi, 90 - (180 * colatitude[i] / math.pi))) spatial_axes = CoordAxis2D(Axis('RA', 'deg'), Axis('DEC', 'deg')) spatial_axes.bounds = tile return SpatialWCS(spatial_axes, coordsys='ICRS', equinox=2000.0)
def _vec2radec(vertices, degrees=False): theta, phi = hp.vec2ang(np.asarray(vertices)) ret = np.column_stack((phi % (2 * np.pi), 0.5 * np.pi - theta)) if degrees: ret = np.rad2deg(ret) return ret
opts.nside = hp.npix2nside(len(beammap)) npix = hp.nside2npix(opts.nside) pix = np.arange(npix) theta,phi = hp.pix2ang(opts.nside,pix) #only keep points above the horizon phi = phi[theta<np.pi/2] theta = theta[theta<np.pi/2] intpix = hp.ang2pix(opts.nside,theta,phi) x,y,z = hp.pix2vec(opts.nside,intpix) print z.max(),z.min() pixarea = hp.nside2pixarea(opts.nside) #pixel area in radians print "pixel area in steradians",pixarea #V is defined as the voltage beam, there are two terms of it in the visibility equation if len(args)==1: theta,phi = hp.vec2ang(np.vstack((x,y,z))) V = beammap[intpix]/np.max(beammap) else: aa = a.cal.get_aa(opts.cal, freqs) V = aa[0].bm_response((x,y,z),pol=opts.pol) V /= V.max() #nomenclature after Parsons 2016 (1503.05564v2) print V.max(),V.min() Omega_V = np.sum(V) * pixarea print "Omega voltage = ",np.round(Omega_V,2) A = V**2 #A is defined as the power beam, there is one term of it in the visibility equation Omega_p = np.sum(A)*pixarea print "Omega_p = ",Omega_p
def dipole_parameters_galactic_to_ecl_amp_ang(dipole_vector_galactic): dipole_vector_ecliptic = gal2ecl(dipole_vector_galactic) SOLSYSSPEED = np.linalg.norm(dipole_vector_ecliptic) SOLSYSDIR_ECL_THETA, SOLSYSDIR_ECL_PHI = healpy.vec2ang(dipole_vector_ecliptic/SOLSYSSPEED) return SOLSYSSPEED, SOLSYSDIR_ECL_THETA, SOLSYSDIR_ECL_PHI
def _plot_poly(self, proj='AIT', step=1, ax=None): """Plot the map using a collection of polygons. Parameters ---------- proj : string, optional Any valid WCS projection type. step : int Set the number vertices that will be computed for each pixel in multiples of 4. """ # FIXME: At the moment this only works for all-sky maps if the # projection is centered at (0,0) # FIXME: Figure out how to force a square aspect-ratio like imshow import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection import healpy as hp wcs = self.geom.make_wcs(proj=proj, oversample=1) if ax is None: fig = plt.gcf() ax = fig.add_subplot(111, projection=wcs.wcs, aspect='equal') wcs_lonlat = wcs.center_coord[:2] idx = self.geom.get_idx() vtx = hp.boundaries(self.geom.nside, idx[0], nest=self.geom.nest, step=step) theta, phi = hp.vec2ang(np.rollaxis(vtx, 2)) theta = theta.reshape((4 * step, -1)).T phi = phi.reshape((4 * step, -1)).T patches = [] data = [] def get_angle(x, t): return 180. - (180. - x + t) % 360. for i, (x, y) in enumerate(zip(phi, theta)): lon, lat = np.degrees(x), np.degrees(np.pi / 2. - y) # Add a small ofset to avoid vertices wrapping to the # other size of the projection if get_angle(np.median(lon), wcs_lonlat[0]) > 0.0: idx = wcs.coord_to_pix((lon - 1E-4, lat)) else: idx = wcs.coord_to_pix((lon + 1E-4, lat)) dist = np.max(np.abs(idx[0][0] - idx[0])) # Split pixels that wrap around the edges of the projection if (dist > wcs.npix[0] / 1.5): lon, lat = np.degrees(x), np.degrees(np.pi / 2. - y) lon0 = lon - 1E-4 lon1 = lon + 1E-4 pix0 = wcs.coord_to_pix((lon0, lat)) pix1 = wcs.coord_to_pix((lon1, lat)) idx0 = np.argsort(pix0[0]) idx1 = np.argsort(pix1[0]) pix0 = (pix0[0][idx0][:3], pix0[1][idx0][:3]) pix1 = (pix1[0][idx1][1:], pix1[1][idx1][1:]) patches.append(Polygon(np.vstack((pix0[0], pix0[1])).T, True)) patches.append(Polygon(np.vstack((pix1[0], pix1[1])).T, True)) data.append(self.data[i]) data.append(self.data[i]) else: polygon = Polygon(np.vstack((idx[0], idx[1])).T, True) patches.append(polygon) data.append(self.data[i]) p = PatchCollection(patches, linewidths=0, edgecolors='None') p.set_array(np.array(data)) ax.add_collection(p) ax.autoscale_view() ax.coords.grid(color='w', linestyle=':', linewidth=0.5) return fig, ax, p
def mpchdec2rad(mapunit, mapkey): theta, phi = hp.vec2ang(mapunit[mapkey]) return theta
def mpchdec2dec(mapunit, mapkey): theta, phi = hp.vec2ang(mapunit[mapkey]) return -theta * 180. / np.pi + 90.
def mpchra2ra(mapunit, mapkey): theta, phi = hp.vec2ang(mapunit[mapkey]) return phi * 180. / np.pi
for f in np.arange(32): if len(TI.faces[f]) == 5: print f c = fig.transFigure.inverted().transform(ax.transData.transform(centers[f])) #c = ax.transAxes.inverted().transform(ax.transData.transform(centers[f])) center_offset = penta_dimfac*edge/2 local_ax = plt.axes([c[0]-center_offset, c[1]-center_offset, penta_dimfac*edge, penta_dimfac*edge], frameon=False) imglim = np.radians(imgresolution * imgsize /60)/2. local_ax.axis("off") #local_ax.set_xlim((-imglim, imglim)) #local_ax.set_ylim((-imglim, imglim)) theta,phi = hp.vec2ang(TI.centroids[f]) face_theta = theta[0] face_phi = phi[0] rotang = [phi[0]*180.0/np.pi,90.0-theta[0]*180.0/np.pi,0.0] print "Face", f, "Face centroid: " , np.degrees([face_theta, face_phi]) planck_freqmap_cmap.set_bad("none") gnomD = hp.gnomview(D,cmap=planck_freqmap_cmap,rot=rotang,min=-3,max=7,title='%s GHz face %d'%(freq,f),reso=imgresolution,xsize=imgsize,ysize=imgsize,coord='G',notext=True,cbar=False, return_projected_map=True) hp.graticule(dpar=grat_spacing,dmer=grat_spacing,local=False,force=True) gnomD.mask = np.zeros(gnomD.shape, dtype=np.bool) #gnomD.mask[300:400] = 1 cut_y = 110 gnomD.mask[:cut_y, :] = 1 gnomD.mask[-cut_y:, :] = 1 cut_x = 67
def remove_dipole( inmap, return_fit=False, mask=None, rms=1., cut=0., debug=False, show=False, return_A=False, verbose=True, onlymonopole=False, onlydipole=False ): import numpy as np import healpy as hp if debug: print type( inmap ) if isinstance( inmap, str ): if verbose: info_message('reading map from "'+inmap+'"') inmap = hp.read_map( infile ) elif not isinstance( inmap, np.ndarray ): info_message( ' - ERROR: input failure. Abort.') sys.exit() npix = len( inmap ) nside = int( np.sqrt( float(npix) / 12 ) ) # --- setting up mask if mask != None: if isinstance(mask,str): if verbose: info_message( '- Using mask:'+mask ) mask = hp.read_map( mask ) elif not isinstance( mask, np.ndarray): info_message( 'mask type not understood. Abort.' ) sys.exit() if len(mask) != npix: hp.pixel_func.ud_grade( mask, nside ) else: mask = np.ones( npix, dtype=float ) if show and verbose: hp.mollview( mask, norm='hist' ) pl.show() if cut != 0: c = make_sky_cut(nside, cut) mask *= c bp = np.array( mask == 0.) gp = np.array( mask == 1.) ngp = np.sum( gp ) nbp = np.sum( bp ) if not isinstance(rms, np.ndarray): if isinstance(rms, str): rms = hp.read_map( rms ) else: rms = np.ones(npix, dtype=np.float64) if show and verbose: hp.mollview( rms, norm='hist' ) pl.show() if show and verbose: cc = inmap cc[bp] = hp.UNSEEN hp.mollview( cc, min=-300, max=300, title='!6Input map') pl.show() if onlymonopole: nfg = 1 elif onlydipole: nfg = 3 else: nfg = 4 if nfg == 1: fit = np.mean( inmap[gp] ) info_message( 'monopole = '+str('%f' %fit) ) if True: info_message( 'nfg = ' + str(nfg) ) A_err = np.zeros( nfg, dtype=np.float64 ) oneOsigma = np.zeros( (nfg, nfg), dtype=np.float64 ) temp = np.zeros( (npix,nfg), dtype=np.float64 ) if onlymonopole: template_files = ['monopole'] temp[:,0] = np.ones( npix ) elif onlydipole: template_files = ['dipole_x','dipole_y','dipole_z'] temp[:,0] = make_dipole( nside, [1.,0.,0.] ) temp[:,1] = make_dipole( nside, [0.,1.,0.] ) temp[:,2] = make_dipole( nside, [0.,0.,1.] ) else: template_files = ['monopole','dipole_x','dipole_y','dipole_z'] temp[:,0] = 1. temp[:,1] = make_dipole( nside, [1.,0.,0.] ) temp[:,2] = make_dipole( nside, [0.,1.,0.] ) temp[:,3] = make_dipole( nside, [0.,0.,1.] ) if (show or debug) and verbose: for ifg in range(nfg): hp.mollview( temp[:,ifg], norm='asinh' ) pl.show() T = np.zeros( (nfg, nfg), dtype=np.float64 ) B = np.zeros( nfg, dtype=np.float64 ) warn = True for ifg in range(nfg): # --- Changed if warn: info_message( ' - Code changed: correlate is not used anymore!' ) warn = False B[ifg] = np.sum( inmap[gp]/rms[gp] * temp[gp,ifg]/rms[gp] ) for jfg in range(ifg,nfg): T[ifg,jfg] = np.sum( temp[gp,ifg] * temp[gp,jfg] / rms[gp]**2 ) T[jfg,ifg] = T[ifg,jfg] oneOsigma[ifg,jfg] = 2. * T[ifg,jfg] oneOsigma[jfg,ifg] = oneOsigma[ifg,jfg] if debug: print T, B Tm1 = np.linalg.inv( T ) A = np.dot( Tm1, B ) sigma = np.linalg.inv( oneOsigma ) for kfg in range( nfg ): if (sigma[kfg,kfg] > 0.): A_err[kfg] = np.sqrt( sigma[kfg,kfg] ) else: info_message( 'Sigma Error' ) if verbose: info_message( ' ============================================================' ) info_message( 'Coefficients:' ) for ifg in range( nfg ): print template_files[ifg], A[ifg],' +/-',A_err[ifg] if onlydipole: vec = np.array( A ) elif not onlymonopole: vec = np.array( A[1:4] ) theta, phi = hp.vec2ang( vec ) theta_deg = 90.-theta*180./np.pi phi_deg = phi*180./np.pi dip_ampl = np.sqrt( np.dot(vec,vec) ) info_message( '(theta,phi) = ('+str('%f' %theta_deg)+','+str('%f' %phi_deg)+')' ) info_message( 'A_dip = '+str('%f' %dip_ampl) ) info_message( ' ============================================================' ) fit = np.zeros( npix, dtype=np.float64 ) for ifg in range( nfg ): fit += temp[:,ifg] * A[ifg] if (show or debug) and verbose: cc = fit cc[bp] = hp.UNSEEN thrs = np.min(abs(np.array([np.min(fit),np.max(fit)]))) hp.mollview( cc, title='Template Linear Combination', min=-thrs, max=thrs ) pl.show() res = np.array(inmap - fit) if (show or debug) and verbose: cc = res cc[bp] = -1.6375e30 thrs = np.min(abs(np.array([np.min(fit),np.max(fit)]))) hp.mollview( cc, title='Residual Foregrounds', min=-thrs, max=thrs ) # info_message( ' - total chi2 = ' + str( np.sum( (res/rms)**2 ) / npix ) + ', ' + str( 1./np.sqrt(npix) ) ) # chi2 = np.sum( (res[gp]/rms[gp])**2 ) / ngp # if verbose: # info_message( ' - total chi2 = ' + str( chi2 ) + ', ' + str( 1./np.sqrt(ngp) ) ) # info_message( ' - total chi2 = ' + str( np.sum( (res[bp]/rms[bp])**2 ) / nbp ) + ', ' + str( 1./np.sqrt(nbp) ) ) if verbose: info_message( ' --- End of Procedure ---' ) outcome = [ res ] if return_fit: outcome.append( fit ) if return_A: outcome.append( (A, A_err) ) return tuple(outcome)