def pixelstrips(params): dec1,dec0 = range_dec(params) nside = params['NSIDE'] theta_min = np.array(dec2col(dec1)) theta_max = np.array(dec2col(dec0)) pix = [] if theta_min.size==1: pix = np.append(pix,hp.query_strip(nside,theta_max,theta_min, inclusive=True)) else: for i in range(theta_min.size): pix = np.append(pix,hp.query_strip(nside,theta_max[i],theta_min[i], inclusive=True)) return pix.astype(int)
def mask_band(self, band_size): # masks a band of size band_size around # the Equator if isinstance(band_size, u.quantity.Quantity): t1 = band_size else: # assume the value is in degrees t1 = band_size * u.deg tuno = np.pi / 2 - t1.to(u.rad).value tdos = np.pi / 2 + t1.to(u.rad).value isnest = False if self.ordering.upper() == 'NEST': isnest = True ipix = hp.query_strip(self.nside, tuno, tdos, nest=isnest) n = self.nmaps if n == 1: self.mask[ipix] = True if self.ismask: self.data[ipix] = True else: for i in range(n): self.mask[i, ipix] = True if self.ismask: self.data[i, ipix] = True
def get_def_hp(nside,dlm,th1,th2): # FIXME band only calc. with vtm ? pix = hp.query_strip(nside, max(th1, 0.), min(np.pi, th2), inclusive=True) Red, Imd = hp.alm2map_spin([dlm, np.zeros_like(dlm)], nside, 1, hp.Alm.getlmax(dlm.size)) Red = Red[pix] Imd = Imd[pix] return _buildangles(hp.pix2ang(nside, pix),Red[pix],Imd[pix])
def hp_in_dec_range(nside, decmin, decmax, inclusive=True): """HEALPixels in a specified range of Declination. Parameters ---------- nside : :class:`int` (NESTED) HEALPixel nside. decmin, decmax : :class:`float` Declination range (degrees). inclusive : :class:`bool`, optional, defaults to ``True`` see documentation for `healpy.query_strip()`. Returns ------- :class:`list` (Nested) HEALPixels at `nside` in the specified Dec range. Notes ----- - Just syntactic sugar around `healpy.query_strip()`. - `healpy.query_strip()` isn't implemented for the NESTED scheme in early healpy versions, so this queries in the RING scheme and then converts to the NESTED scheme. """ # ADM convert Dec to co-latitude in radians. # ADM remember that, min/max swap because of the -ve sign. thetamin = np.radians(90.-decmax) thetamax = np.radians(90.-decmin) # ADM determine the pixels that touch the box. pixring = hp.query_strip(nside, thetamin, thetamax, inclusive=inclusive, nest=False) pixnest = hp.ring2nest(nside, pixring) return pixnest
def get_pixels_in_region_new(nside, lst_id=None,region=None): #Get a list of pixels belonging to a given region try: dict_match= get_region(lst_id=lst_id,name=region) lst_coll=[] for kreg in range(len(dict_match)): print(kreg) lc_min=(dict_match[kreg]["lc"]-dict_match[kreg]["dl"]/2) lc_max=(dict_match[kreg]["lc"]+dict_match[kreg]["dl"]/2) bc_max=(90-(dict_match[kreg]["bc"]-dict_match[kreg]["db"]/2))*math.pi/180 bc_min=(90-(dict_match[kreg]["bc"]+dict_match[kreg]["db"]/2))*math.pi/180 lst_ext=hp.query_strip(nside, bc_min, bc_max, inclusive=True) lstang=np.asarray(hp.pix2ang(nside, lst_ext,lonlat=True)) if(lc_min<0): lst_rest=np.argwhere( ((lstang[0]>=0)&(lstang[0]<=lc_max))| (lstang[0]>lc_min+360)&(lstang[0]<=360) ).flatten() if(lc_max>360): lst_rest=np.argwhere( ((lstang[0]>=360)&(lstang[0]+360<=lc_max))| (lstang[0]>lc_min)&(lstang[0]<=360) ).flatten() else: lst_rest=np.argwhere((lstang[0]>=lc_min)&(lstang[0]<=lc_max)).flatten() lstang=lstang[:,lst_rest] lst_coll.append(lst_ext[lst_rest]) except Exception as inst: print("FAILURE: ",inst) return lst_coll
def crop_mse(y_true, y_pred): nside = hp.npix2nside(y_true.shape[1]) ipix = hp.query_strip(nside, theta1, theta2, inclusive=True, nest=False, buff=None) y_true_crop = tf.gather(y_true, ipix, axis=1) y_pred_crop = tf.gather(y_pred, ipix, axis=1) # print (y_true_crop.shape) # print (y_pred_crop.shape) return tf.keras.backend.mean(tf.keras.backend.square(y_pred_crop - y_true_crop))
def lens_glm_sym(spin,dlm,glm,nside,nband = 32,facres = 0,clm = None,rotpol = True): """ Same as lens_alm but lens simultnously a North and South colatitude band, to make profit of the symmetries of the spherical harmonics. Note that tlm = -glm in the spin 0 case. """ target_nt = 3 ** 1 * 2 ** (11 + facres) th1s = np.arange(nband) * (np.pi * 0.5 / nband) th2s = np.concatenate((th1s[1:],[np.pi * 0.5])) Nt_perband = target_nt / nband Redtot, Imdtot = hp.alm2map_spin([dlm, np.zeros_like(dlm)], nside, 1, hp.Alm.getlmax(dlm.size)) ret = np.zeros(hp.nside2npix(nside),dtype = float if spin == 0 else complex) for th1,th2 in zip(th1s,th2s): pixN = hp.query_strip(nside, th1, th2, inclusive=True) pixS = hp.query_strip(nside, np.pi- th2,np.pi - th1, inclusive=True) tnewN,phinewN = _buildangles(hp.pix2ang(nside, pixN),Redtot[pixN],Imdtot[pixN]) tnewS,phinewS = _buildangles(hp.pix2ang(nside, pixS), Redtot[pixS], Imdtot[pixS]) matnewN = np.max(tnewN) mitnewN = np.min(tnewN) matnewS = np.max(tnewS) mitnewS = np.min(tnewS) buffN = 10 * (matnewN - mitnewN) / (Nt_perband - 1) / (1. - 2. * 10. / (Nt_perband - 1)) buffS = 10 * (matnewS - mitnewS) / (Nt_perband - 1) / (1. - 2. * 10. / (Nt_perband - 1)) thup = min(np.pi - (matnewS + buffS),mitnewN - buffN) thdown = max(np.pi - (mitnewS - buffS),matnewN + buffN) if spin == 0: lenN,lenS = lens_band_sym(glm,thup,thdown,Nt_perband,(tnewN,phinewN),(tnewS,phinewS), Nphi=get_Nphi(thup, thdown, facres=facres)) ret[pixN] = lenN ret[pixS] = lenS else : lenNR,lenNI,lenSR,lenSI = lens_gcband_sym(spin,glm,thup,thdown, Nt_perband,(tnewN,phinewN),(tnewS,phinewS), Nphi=get_Nphi(thup, thdown, facres=facres),clm = clm) ret[pixN] = lenNR + 1j * lenNI ret[pixS] = lenSR + 1j * lenSI if rotpol : ret[pixN] *= polrot(spin,ret[pixN], hp.pix2ang(nside, pixN)[0],Redtot[pixN],Imdtot[pixN]) ret[pixS] *= polrot(spin,ret[pixS], hp.pix2ang(nside, pixS)[0],Redtot[pixS],Imdtot[pixS]) return ret
def strip_auto(data, ang_rad, nside): ipix_strip1 = hp.query_strip(NSIDE, ang_rad - (np.pi / 360), ang_rad + (np.pi / 360)) ipix_strip2 = hp.query_strip(NSIDE, ang_rad - (np.pi / 360), ang_rad + (np.pi / 360)) strip1_data = np.zeros((len(ipix_strip1), 3)) strip2_data = np.zeros((len(ipix_strip2), 3)) lon1, lat1 = hp.pixelfunc.pix2ang(2048, ipix_strip1, lonlat=True) lon2, lat2 = hp.pixelfunc.pix2ang(2048, ipix_strip2, lonlat=True) strip1_data[:, 0] = data[ipix_strip1] strip1_data[:, 1] = lon1 strip1_data[:, 2] = lat1 strip2_data[:, 0] = data[ipix_strip2] strip2_data[:, 1] = lon2 strip2_data[:, 2] = lat2 fname1 = 'strip_a' fname2 = 'strip_b' col11 = fits.Column(name='index', array=ipix_strip1, format='D') col12 = fits.Column(name='T', array=strip1_data[:, 0], format='D') col13 = fits.Column(name='long', array=lon1, format='D') col14 = fits.Column(name='lat', array=lat1, format='D') u = fits.BinTableHDU.from_columns([col11, col12, col13, col14]) u.writeto('/opt/local/l4astro/rbbg94/cmb_maps/' + fname1, overwrite=True) col21 = fits.Column(name='index', array=ipix_strip2, format='D') col22 = fits.Column(name='T', array=strip2_data[:, 0], format='D') col23 = fits.Column(name='long', array=lon2, format='D') col24 = fits.Column(name='lat', array=lat2, format='D') v = fits.BinTableHDU.from_columns([col21, col22, col23, col24]) v.writeto('/opt/local/l4astro/rbbg94/cmb_maps/' + fname2, overwrite=True)
def test_rotate_dipole_and_back(): """Rotate a smooth signal (dipole) from Galactic to Ecliptic and back""" nside = 64 npix = hp.nside2npix(nside) pix = np.arange(npix) vec = np.array(hp.pix2vec(nside, pix)) # dipole max is at North Pole dip_dir = np.array([0, 0, 1]) m_gal = np.dot(vec.T, dip_dir) gal2ecl = Rotator(coord=["C", "E"]) ecl2gal = Rotator(coord=["E", "C"]) m_ecl = gal2ecl.rotate_map_pixel(m_gal) # Remove 10 deg along equator because dipole signal is so low that relative error is # too large cut_equator_deg = 5 no_equator = hp.query_strip(nside, np.radians(90 + cut_equator_deg), np.radians(90 - cut_equator_deg)) np.testing.assert_allclose(m_gal[no_equator], ecl2gal.rotate_map_pixel(m_ecl)[no_equator], rtol=1e-3)
def test_rotate_dipole_and_back(): """Rotate a smooth signal (dipole) from Galactic to Ecliptic and back""" nside = 64 npix = hp.nside2npix(nside) pix = np.arange(npix) vec = np.array(hp.pix2vec(nside, pix)) # dipole max is at North Pole dip_dir = np.array([0, 0, 1]) m_gal = np.dot(vec.T, dip_dir) gal2ecl = Rotator(coord=["C", "E"]) ecl2gal = Rotator(coord=["E", "C"]) m_ecl = gal2ecl.rotate_map_pixel(m_gal) # Remove 10 deg along equator because dipole signal is so low that relative error is # too large cut_equator_deg = 5 no_equator = hp.query_strip( nside, np.radians(90 + cut_equator_deg), np.radians(90 - cut_equator_deg) ) np.testing.assert_allclose( m_gal[no_equator], ecl2gal.rotate_map_pixel(m_ecl)[no_equator], rtol=1e-3 )
def gen_map_strip(mindec, maxdec, nside): '''Generates a Healpix map with the only non-zero values in the pixels inside a strip between the input declinations/latitudes Parameters ---------- mindec : float Minimum declination/latitude in degrees maxdec : float Maximum declinaton/latitude in degrees nside : int The nside of the output Healpix map Returns ------- hpx_map: array-like A healpix map with the non-zero values inside the strip ''' theta1 = np.radians(90.0 - maxdec) theta2 = np.radians(90.0 - mindec) if theta2 < theta1: theta1, theta2 = theta2, theta2 npix = H.nside2npix(nside) hpx_map = np.zeros(npix) ipix = H.query_strip(nside, theta1, theta2) hpx_map[ipix] = 1.0 return hpx_map
def gen_map_strip(mindec, maxdec, nside): '''Generates a Healpix map with the only non-zero values in the pixels inside a strip between the input declinations/latitudes Parameters ---------- mindec : float Minimum declination/latitude in degrees maxdec : float Maximum declinaton/latitude in degrees nside : int The nside of the output Healpix map Returns ------- hpx_map: array-like A healpix map with the non-zero values inside the strip ''' theta1 = np.radians(90.0 - maxdec) theta2 = np.radians(90.0 - mindec) if theta2 < theta1: theta1, theta2 = theta2, theta2 npix = H.nside2npix(nside) hpx_map =np.zeros(npix) ipix = H.query_strip(nside, theta1, theta2) hpx_map[ipix] = 1.0 return hpx_map
from __future__ import division import numpy as np import healpy as hp import matplotlib.pyplot as plt SMICA_MAP = hp.read_map("/opt/local/l4astro/rbbg94/cmb_maps/planck_data.fits") NSIDE=2048 strip_1 = hp.query_strip(NSIDE, np.radians(40), np.radians(41)) strip_2 = hp.query_strip(NSIDE, np.radians(130), np.radians(131)) SMICA_MAP[strip_1] = SMICA_MAP.max() SMICA_MAP[strip_2] = SMICA_MAP.max() hp.mollview(SMICA_MAP, title = '', cbar = False) plt.savefig("/opt/local/l4astro/rbbg94/figures/cmb_map.png") plt.show()
def _lens_gclm_sym_timed(spin, dlm, glm, nside, nband=8, facres=0, clm=None, dclm=None, verbose=True): """Performs the deflection by splitting the full latitude range into distinct bands which are done one at a time. See *_lens_gcband_sym* for the single band (north and south hemispheres) lensing. """ assert spin >= 0,spin times = utils.timer(verbose, suffix=' ' + __name__) target_nt = 3 ** 1 * 2 ** (11 + facres) # on one hemisphere #co-latitudes th1s = np.arange(nband) * (np.pi * 0.5 / nband) th2s = np.concatenate((th1s[1:],[np.pi * 0.5])) nt_perband = int(target_nt / nband) if np.iscomplexobj(dlm): # inputs are the spin 1 d map lmax = hp.Alm.getlmax(dlm.size) redtot, imdtot = hp.alm2map_spin([dlm, np.zeros_like(dlm) if dclm is None else dclm], nside, 1, lmax) else: assert dclm is not None and dclm.size == dlm.size and dlm.size == hp.nside2npix(nside) redtot = dlm imdtot = dclm times.add('defl. spin 1 transform') interp_pix = 0 ret = np.empty(hp.nside2npix(nside),dtype = float if spin == 0 else complex) for ib, th1, th2 in zip(range(nband), th1s, th2s): if verbose: print("BAND %s in %s :"%(ib, nband)) pixn = hp.query_strip(nside, th1, th2, inclusive=True) pixs = hp.query_strip(nside, np.pi- th2,np.pi - th1, inclusive=True) thtp, phipn = angles.get_angles(nside, pixn, redtot[pixn], imdtot[pixn], 'north', verbose=verbose) thtps, phips = angles.get_angles(nside, pixs, redtot[pixs], imdtot[pixs], 'south', verbose=verbose) # Adding a 10 pixels buffer for new angles to be safely inside interval. # th1,th2 is mapped onto pi - th2,pi -th1 so we need to make sure to cover both buffers mathtp = np.max(thtp); mithtp = np.min(thtp) mathtps = np.max(thtps); mithtps = np.min(thtps) buffN = 10 * (mathtp - mithtp) / (nt_perband - 1) / (1. - 2. * 10. / (nt_perband - 1)) buffS = 10 * (mathtps - mithtps) / (nt_perband - 1) / (1. - 2. * 10. / (nt_perband - 1)) th1 = min(np.pi - (mathtps + buffS),mithtp - buffN) th2 = max(np.pi - (mithtps - buffS),mathtp + buffN) #==== these are the theta and limits. It is ok to go negative or > 180 if verbose: print('input t1,t2 %.3f %.3f in degrees'%(th1 /np.pi * 180,th2/np.pi * 180.)) if verbose: print('North %.3f and South %.3f buffers in amin'%(buffN /np.pi * 180 * 60,buffS/np.pi * 180. * 60.)) nphi = utils.get_nphi(th1, th2, facres=facres) dphi_patch = (2. * np.pi) / nphi * max(np.sin(th1),np.sin(th2)) dth_patch = (th2 - th1) / (nt_perband -1) if verbose: print("cell (theta,phi) in amin (%.3f,%.3f)" % (dth_patch / np.pi * 60. * 180, dphi_patch / np.pi * 60. * 180)) times.add('defl. angles calc.') len_nr, len_ni, len_sr, len_si = _lens_gcband_sym(spin, glm, th1, th2, nt_perband, nphi, thtp, phipn, thtps, phips, clm=clm, times=times) if spin == 0: ret[pixn] = len_nr ret[pixs] = len_sr else : ret[pixn] = (len_nr + 1j * len_ni) * angles.rotation(nside, spin, pixn, redtot[pixn], imdtot[pixn]) ret[pixs] = (len_sr + 1j * len_si) * angles.rotation(nside, spin, pixs, redtot[pixs], imdtot[pixs]) times.add(r'pol. //-transport rot.') interp_pix += nphi * nt_perband * 2 if verbose: print(times) if verbose: print(r"Number of interpolating pixels: %s ~ %s^2 "%(interp_pix, int(np.sqrt(interp_pix)))) return ret
def simulate_high_galactic_latitude_CO(self): """ Coadd High Galactic Latitude CO emission, simulated with MCMole3D. """ if self.run_mcmole3d: import mcmole3d as cl # params to MCMole N = 40000 L_0 = 20.4 # pc L_min = .3 L_max = 60. R_ring = 5.8 sigma_ring = 2.7 # kpc R_bulge = 3. R_z = 10 # kpc z_0 = 0.1 Em_0 = 240. R_em = 6.6 model = "LogSpiral" nside = self.nside Itot_o, _ = cl.integrate_intensity_map( self.planck_templatemap, hp.get_nside(self.planck_templatemap), planck_map=True, ) Pop = cl.Cloud_Population(N, model, randseed=self.random_seed) Pop.set_parameters( radial_distr=[R_ring, sigma_ring, R_bulge], typical_size=L_0, size_range=[L_min, L_max], thickness_distr=[z_0, R_z], emissivity=[Em_0, R_em], ) Pop() if self.verbose: Pop.print_parameters() # project into Healpix maps mapclouds = cl.do_healpy_map( Pop, nside, highgalcut=np.deg2rad(90. - self.theta_high_galactic_latitude_deg), apodization="gaussian", verbose=self.verbose, ) Itot_m, _ = cl.integrate_intensity_map(mapclouds, nside) # convert simulated map into the units of the Planck one rescaling_factor = Itot_m / Itot_o mapclouds /= rescaling_factor hglmask = np.zeros_like(mapclouds) # Apply mask to low galactic latitudes listhgl = hp.query_strip( nside, np.deg2rad(90. + self.theta_high_galactic_latitude_deg), np.deg2rad(90 - self.theta_high_galactic_latitude_deg), ) hglmask[listhgl] = 1. rmsplanck = self.planck_templatemap[listhgl].std() rmssim = mapclouds[listhgl].std() if rmssim == 0.: belowplanck = 1. else: belowplanck = rmssim / rmsplanck return mapclouds * hglmask / belowplanck else: mapclouds = self.read_map( "co/mcmoleCO_HGL_{}.fits".format(self.template_nside), field=self.line_index, ) return mapclouds
def prob_observable(m, header, time, plot=False): """ Determine the integrated probability contained in a gravitational-wave sky map that is observable with HET at a particular time. Needs hetpix.dat, pixels and lonlat of HET pupil, in the directory. """ # Determine resolution of sky map mplot = np.copy(m) npix = len(m) nside = hp.npix2nside(npix) # Get time now and Local Sidereal Time # time = astropy.time.Time.now() # Or at the time of the gravitational-wave event... # time = astropy.time.Time(header['MJD-OBS'], format='mjd') # Or at a particular time... # time = astropy.time.Time(time) # Geodetic coordinates of MacDonald Obs HET_loc = (-104.01472, 30.6814, 2025) hetpupil = np.loadtxt('hetpix.dat') hetfullpix = hp.query_strip(nside, minhetdec_rad, \ maxhetdec_rad) observatory = astropy.coordinates.EarthLocation(lat=HET_loc[1] * u.deg, lon=HET_loc[0] * u.deg, height=HET_loc[2] * u.m) # Find pixels of HET pupil in this time t = astropy.time.Time(time, scale='utc', location=HET_loc) LST = t.sidereal_time('mean').deg HETphi = ((hetpupil[:, 1] + LST) % 360) * np.pi / 180 HETtheta = (90 - hetpupil[:, 2]) * np.pi / 180 newpix = hp.ang2pix(nside, HETtheta, HETphi) newpixp = newpix # Alt/az reference frame at the observatory, in this time frame = astropy.coordinates.AltAz(obstime=t, location=observatory) # Look up (celestial) spherical polar coordinates of HEALPix grid. theta, phi = hp.pix2ang(nside, np.arange(npix)) # Convert to RA, Dec. radecs = astropy.coordinates.SkyCoord(ra=phi * u.rad, dec=(0.5 * np.pi - theta) * u.rad) # Transform grid to alt/az coordinates at observatory, in this time altaz = radecs.transform_to(frame) #Get RA,DEC of the sun in this time sun = astropy.coordinates.get_sun(time) # Where is the sun in the Texas sky, in this time? sun_altaz = sun.transform_to(frame) delta_time = np.linspace(0, 24, 1000) * u.hour times24 = t + delta_time frames24 = astropy.coordinates.AltAz(obstime=times24, location=observatory) sunaltazs24 = astropy.coordinates.get_sun(times24).transform_to(frames24) timetilldark = 0 * u.hour timetillbright = 0 * u.hour nightstart = times24[sunaltazs24.alt < -18 * u.deg][0] nighttimemask = np.array((sunaltazs24.alt < -18 * u.deg)) * 1 if (sun_altaz.alt > -18 * u.deg): nightend = times24[(np.roll(nighttimemask, 1) - nighttimemask) != 0][1] else: nightend = times24[(np.roll(nighttimemask, 1) - nighttimemask) != 0][0] nightime = nightend - nightstart nightime.format = 'sec' #Moving to start of the night if in daytime if (sun_altaz.alt > -18 * u.deg): timetilldark = (nightstart - t) timetilldark.format = 'sec' LST = nightstart.sidereal_time('mean').deg HETphi = ((hetpupil[:, 1] + LST) % 360) * np.pi / 180 newpix = hp.ang2pix(nside, HETtheta, HETphi) else: timetillbright = (nightend - t) timetillbright.format = 'sec' # How likely is it that the (true, unknown) location of the source # is within the area that is visible, in this time and within 24 hours? # Demand that it falls in the HETDEX pupil, that the sun is at least 18 # degrees below the horizon and that the airmass (secant of zenith angle # approximation) is at most 2.5. msortedpix = np.flipud(np.argsort(m)) cumsum = np.cumsum(m[msortedpix]) cls = np.empty_like(m) cls[msortedpix] = cumsum * 100 p90i = np.where(cls <= 90) if plot: #SUN CIRCLE OF 18 DEGREES radius = 18 phis = Angle(sun.ra).radian thetas = 0.5 * np.pi - Angle(sun.dec).radian radius = np.deg2rad(radius) xyz = hp.ang2vec(thetas, phis) ipix_sun = hp.query_disc(nside, xyz, radius) #Coloring the plot, order important here! mplot[:] = 1 mplot[altaz.secz > 2.5] = 0.1 mplot[altaz.alt < 0] = 0.99 mplot[newpixp] = 0.2 mplot[p90i] = 0.4 mplot[ipix_sun] = 0.6 hp.mollview(mplot, coord='C', cmap='nipy_spectral', cbar=False, max=1, title='HET NOW') hp.graticule(local=True) ax1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24] for ii in ax1: hp.projtext(ii / 24. * 360 - 1, -5, str(ii) + 'h', lonlat=True) ax2 = [60, 30, 0, -30, -60] for ii in ax2: hp.projtext(360. / 2, ii, ' ' + str(ii) + '°', lonlat=True) plt.savefig('MOLL_GWHET_%s.png' % header['GraceID']) #plt.show() #from astropy.wcs import WCS #ax = plt.subplot(1,1,1, projection=WCS(target_header)) #ax.imshow(array, vmin=0, vmax=1.e-8) #ax.coords.grid(color='white') #ax.coords.frame.set_color('none') #plt.show() theta90, phi90 = hp.pix2ang(nside, p90i) #mask skymap pixels by hetdex accesible region theta90HETi = (theta90 > minhetdec_rad) * (theta90 < maxhetdec_rad) print(theta90HETi.sum(), theta90.min(), theta90.max()) theta90HET = theta90[theta90HETi] phi90HET = phi90[theta90HETi] timetill90 = 0 #if the region doesn't intersect HET now if len(np.intersect1d(p90i, newpix)) == 0: #if the region doesn't intersect HET at all if len(np.intersect1d(p90i, hetfullpix)) == 0: return 0, 0, -99, 0 hetedge = np.loadtxt('hetedge.dat') hetedgef = lambda x: np.interp(x, hetedge[:, 0], hetedge[:, 1]) y = theta90HET * 180 / np.pi #DEC SKYMAP x = (phi90HET * 180 / np.pi - LST) % 360 #RA SKYMAP ZEROING HET PUPIL wsecs = np.min(x - hetedgef(y)) * 3600 * 12 / 180 if wsecs < 0: #it's inside the pupil... hetedgef2 = lambda x: np.interp(x, hetedge[:, 0], hetedge[:, 2]) y = (hetedgef2(y) + 180) % 360 - 180 x = (x + 180) % 360 - 180 wsecs = np.min(x - y) * 3600 * 12 / 180 if timetilldark == 0: if wsecs > timetillbright.value: return 0, 0, -99, 0 else: if wsecs > nightime.value: return 0, 0, -99, 0 timetill90 = (wsecs + timetilldark.value) / 3600 elif timetilldark.value > 0: timetill90 = timetilldark.value / 3600 mask_arraynow = np.zeros(len(m), dtype=int) mask_arraynow[newpixp] = 1 mask_arraynow *= (altaz.secz <= 2.5) & (sun_altaz.alt <= -18 * u.deg) prob = m[mask_arraynow > 0].sum() probfull = m[np.intersect1d(p90i, hetfullpix)].sum() m[np.setdiff1d(np.arange(len(m)), np.intersect1d(p90i, hetfullpix), assume_unique=True)] = m.min() #hp.orthview(m) #plt.show() #plt.savefig('MOLL_GWHET_%s.pdf'%header['GraceID']) # Done! return prob, probfull, timetill90, m
def main(survey, plot=True, write=True): print("Creating mask with NSIDE={} and NEST={}...".format(NSIDE, NEST)) # Initiate_mask if args.load is not None: healpix_mask = ugali.utils.healpix.read_map(args.load, nest=NEST) else: healpix_mask = np.tile(0, hp.nside2npix(NSIDE)) infile_dust = 'ebv_sfd98_fullres_nside_4096_nest_equatorial.fits.gz' ebv_map = ugali.utils.healpix.read_map(infile_dust, nest=True) cut_ebv = (ebv_map > 0.2) healpix_mask[cut_ebv] |= 0b00001 """ McConnachie15: Half-light radius along major axis. Could incorporate ellipticity info Harris96: Half-light radius Corwen04: No radius data Nilson73: Major axis (no ellipticity info) Webbink85: 10**log(radius) Kharchenko13: Radius of the central part Bica08: Major axis. Could incorporate ellipticity info WEBDA: Diameter/2 ExtraDwarfs: Half-light radius ExtraClusters: Half-light radius Vizier data on: Nilson73, Webbink85 (should check log or ln), Kharchenko13 (3 radii, used middle), Bica08 ugali data on: McConnachi15, Harris96, WEBDA14 """ external_cat_list = [ 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'Bica08', 'WEBDA14', 'ExtraClusters', 'ExtraStructures' ] for external_cat in external_cat_list: if args.mode == 1: catalog = ugali.candidate.associate.catalogFactory(external_cat) external_cut = cut_circles(catalog['ra'], catalog['dec'], default_radius=0.1) elif args.mode == 2: catalog = associate.catalogFactory(external_cat) external_cut = cut_circles(catalog['ra'], catalog['dec'], catalog['radius'], default_radius=0.1) healpix_mask[external_cut] |= 0b00010 known_dwarfs = ['McConnachie15', 'ExtraDwarfs'] for external_cat in known_dwarfs: if args.mode == 1: catalog = ugali.candidate.associate.catalogFactory(external_cat) external_cut = cut_circles(catalog['ra'], catalog['dec'], default_radius=0.1) elif args.mode == 2: catalog = associate.catalogFactory(external_cat) external_cut = cut_circles(catalog['ra'], catalog['dec'], catalog['radius'], default_radius=0.1) healpix_mask[external_cut] |= 0b00100 reader_bsc = pyfits.open('bsc5.fits') d_bsc = reader_bsc[1].data bsc_cut = cut_circles(d_bsc['RA'], d_bsc['DEC'], default_radius=0.1) healpix_mask[bsc_cut] |= 0b01000 if 'des' == survey: des_footprint = ugali.utils.healpix.read_map( 'y3a2_footprint_griz_1exp_v2.0.fits.gz', nest=True) #print('Masking footprint...') #npix = hp.nside2npix(NSIDE) #nbad = 3 #des_cut = np.fromiter( (des_footprint[i] < 1 or sum(des_footprint[hp.get_all_neighbours(NSIDE, i)] < 1) >= nbad for i in range(npix)), dtype=bool, count=npix ) # Mask if at least nbad neighbors outside the footprint des_cut = des_footprint < 1 healpix_mask[des_cut] |= 0b10000 if 'ps1' == survey: ps1_cut = hp.query_strip( NSIDE, np.radians(90.0 - -25.0), np.radians(90.0 - -90.0), nest=False ) # This function apparently isn't implemented for nest=True ps1_cut = hp.ring2nest(NSIDE, ps1_cut) healpix_mask[ps1_cut] |= 0b10000 #failures = pyfits.open('ugali_failures.fits')[1].data # NSIDE = 256 #fail_pix_256 = [ugali.utils.healpix.angToPix(256, fail['ra'], fail['dec'], nest=NEST) for fail in failures] #fail_pix = ugali.utils.healpix.ud_grade_ipix(fail_pix_256, 256, NSIDE, nest=NEST) #healpix_mask[fail_pix] |= 0b100000 # Artifact masks artifact_coords = np.array([ (278.70, 38.67), # J1834.8+3840, obvious masking issue (35.01, -3.04), # J0220.1-0302, psf failures (201.59, -11.47), # J1326.4-1128, obvious masking issue (214.52, 19.20), # J1418.1+1912, obvious masking issue #(131.50, 28.57), # J0846.0+2834, ??? (262.66, 52.11), # J1730.7+5206, likely artifact #(169.99, -14.96), # J1120.0-1457, ??? (186.55, 46.17), # J1226.2+4609, likely artifact (145.22, -13.74), # J0940.9-1344, likely artifact (28.11, 19.39), # J0152.5+1923, no uglai source? #(247.73, -0.97), # J1630.9+0058, real star cluster (19.40, -17.44) ]) # J0117.6-1726, Cetus II #(39.88, 0.18)]) # J0239.5+0010, artifact_ras, artifact_decs = artifact_coords.T artifact_cut = cut_circles(artifact_ras, artifact_decs, default_radius=0.1) healpix_mask[artifact_cut] |= 0b1000000 if plot: print("Simplifying mask for plotting...") simplified_mask = np.copy(healpix_mask) cut_catalog = np.where((simplified_mask & 0b00010) | (simplified_mask & 0b00100) | (simplified_mask & 0b01000)) cut_ebv = np.where(simplified_mask & 0b00001) cut_footprint = np.where((simplified_mask & 0b10000) | (simplified_mask & 0b100000) | (simplified_mask & 0b1000000)) simplified_mask[cut_catalog] = 1 simplified_mask[cut_ebv] = 2 simplified_mask[cut_footprint] = 3 print("Plotting...") title = '' if survey == 'des': title = 'DES ' + title elif survey == 'ps1': title = 'Pan-STARRS ' + title """ # Using mollview hp.mollview(simplified_mask, nest=True, coord='C', cmap=new_cmap, title=title, xsize=1600) ax = plt.gca() cbar = ax.images[-1].colorbar cbar.set_ticks( (np.arange(n) + 0.5)*(n-1)/n ) cbar.set_ticklabels(['Unmasked', 'Association', r'$E(B-V)$', 'Footprint']) hp.graticule() plt.savefig('healpix_mask_{}_v{}.png'.format(survey, version), bbox_inches='tight') """ # Using skymap simplified_mask_ring = hp.reorder(simplified_mask, n2r=True) fig, ax = plt.subplots(figsize=(12, 8)) smap = Skymap(projection='mbtfpq', lon_0=0) im, lon, lat, values = smap.draw_hpxmap(simplified_mask_ring, xsize=1600, cmap=new_cmap) cbar = plt.colorbar(ticks=(np.arange(n) + 0.5) * (n - 1) / n, fraction=0.02) cbar.set_ticklabels( ['Unmasked', 'Association', r'$E(B-V) > 0.2$', 'Footprint']) plt.title(title) plt.savefig('healpix_mask_{}_v{}.png'.format(survey, version), bbox_inches='tight') if write: print('Writing mask to healpix_mask_{}_v{}.fits.gz ...'.format( survey, version)) hp.write_map('healpix_mask_{}_v{}.fits.gz'.format(survey, version), healpix_mask, dtype=np.int32, nest=NEST, coord='C', overwrite=True) return healpix_mask, simplified_mask_ring
def make_normmaps(maps, supmap, etacut=0.9): r"""Divide an ensemble of maps by a single map, preferably the sum of said ensemble. Parameters ---------- maps : float, array_like A single map or an ensemble of maps. They should be limited in pseudorapidity by the value in `etacut`. supmap : float, ndarray A 1-D array usually representing the sum of all elements in `maps`. etacut : float, scalar, optional The value of the pseudorapidity limit, :math:`|\eta|` < `etacut`. If there is no limit, set it to *None*. Default: 0.9. Returns ------- norm_maps : float, array_like The result of dividing `maps` by `supmap`. Its shape will be the same as `maps`. Notes ----- In the power spectral analysis at hand [1]_ [2]_, `supmap` is the sum of all event maps and it is represented by :math:`F^{all}(\mathbf{n_p})`, where :math:`\mathbf{n_p}` is a pixel number. A normalized map is thus defined by the following expression: .. math:: \bar{f}(\mathbf{n_p}) = \frac{f(\mathbf{n_p})}{F^{all}(\mathbf{n_p})}, where :math:`f(\mathbf{n_p})` is a map from the original event ensemble, the latter denoted by the `maps` parameter. References ---------- .. [1] M. Machado, P.H. Damgaard, J.J. Gaardhoeje, and C. Bourjau, "Angular power spectrum of heavy ion collisions", Phys. Rev. C **99**, 054910 (2019). .. [2] M. Machado, "Heavy ion anisotropies: a closer look at the angular power spectrum", arXiv:1907.00413 [hep-ph] (2019). """ if maps[0].ndim == 0: maps = np.reshape(maps, (1, len(maps))) npix = hp.get_map_size(maps[0]) nside = hp.npix2nside(npix) if etacut: qi, qf = 2. * np.arctan(np.exp(-np.array([etacut, -etacut]))) mask = np.ones(npix) mask[hp.query_strip(nside, qi, qf)] = 0. else: qi, qf = 0., 2 * np.pi mask = 0. finmap = supmap / npix * (1. - mask) + mask pixs = np.where(finmap == 0.) finmap[pixs] = 1. norm_maps = maps / (npix * finmap) norm_maps *= npix / np.sum(norm_maps, axis=1)[:, None] return norm_maps
def lens_glm_sym_timed(spin, dlm, glm, nside, nband=32, facres=0, clm=None, rotpol=True): """ Same as lens_alm but lens simultnously a North and South colatitude band, to make profit of the symmetries of the spherical harmonics. """ assert spin >= 0, spin t = timer(True, suffix=' ' + __name__) target_nt = 3**1 * 2**(11 + facres) # on one hemisphere times = {} #co-latitudes th1s = np.arange(nband) * (np.pi * 0.5 / nband) th2s = np.concatenate((th1s[1:], [np.pi * 0.5])) ret = np.zeros(hp.nside2npix(nside), dtype=float if spin == 0 else complex) Nt_perband = target_nt / nband t0 = time.time() Redtot, Imdtot = hp.alm2map_spin([dlm, np.zeros_like(dlm)], nside, 1, hp.Alm.getlmax(dlm.size)) times['dx,dy (full sky)'] = time.time() - t0 times['dx,dy band split'] = 0. times['pol. rot.'] = 0. t.checkpoint('healpy Spin 1 transform for displacement (full %s map)' % nside) _Npix = 0 # Total number of pixels used for interpolation def coadd_times(tim): for _k, _t in tim.iteritems(): if _k not in times: times[_k] = _t else: times[_k] += _t for ib, th1, th2 in zip(range(nband), th1s, th2s): print "BAND %s in %s :" % (ib, nband) t0 = time.time() pixN = hp.query_strip(nside, th1, th2, inclusive=True) pixS = hp.query_strip(nside, np.pi - th2, np.pi - th1, inclusive=True) tnewN, phinewN = _buildangles(hp.pix2ang(nside, pixN), Redtot[pixN], Imdtot[pixN]) tnewS, phinewS = _buildangles(hp.pix2ang(nside, pixS), Redtot[pixS], Imdtot[pixS]) # Adding a 10 pixels buffer for new angles to be safely inside interval. # th1,th2 is mapped onto pi - th2,pi -th1 so we need to make sure to cover both buffers matnewN = np.max(tnewN) mitnewN = np.min(tnewN) matnewS = np.max(tnewS) mitnewS = np.min(tnewS) buffN = 10 * (matnewN - mitnewN) / (Nt_perband - 1) / (1. - 2. * 10. / (Nt_perband - 1)) buffS = 10 * (matnewS - mitnewS) / (Nt_perband - 1) / (1. - 2. * 10. / (Nt_perband - 1)) _thup = min(np.pi - (matnewS + buffS), mitnewN - buffN) _thdown = max(np.pi - (mitnewS - buffS), matnewN + buffN) #print "min max tnew (degrees) in the band %.3f %.3f "%(_th1 /np.pi * 180.,_th2 /np.pi * 180.) #==== these are the theta and limits. It is ok to go negative or > 180 print 'input t1,t2 %.3f %.3f in degrees' % (_thup / np.pi * 180, _thdown / np.pi * 180.) print 'North %.3f and South %.3f buffers in amin' % ( buffN / np.pi * 180 * 60, buffS / np.pi * 180. * 60.) Nphi = get_Nphi(_thup, _thdown, facres=facres) dphi_patch = (2. * np.pi) / Nphi * max(np.sin(_thup), np.sin(_thdown)) dth_patch = (_thdown - _thup) / (Nt_perband - 1) print "cell (theta,phi) in amin (%.3f,%.3f)" % ( dth_patch / np.pi * 60. * 180, dphi_patch / np.pi * 60. * 180) times['dx,dy band split'] += time.time() - t0 if spin == 0: lenN, lenS, tim = lens_band_sym_timed(glm, _thup, _thdown, Nt_perband, (tnewN, phinewN), (tnewS, phinewS), Nphi=Nphi) ret[pixN] = lenN ret[pixS] = lenS else: lenNR, lenNI, lenSR, lenSI, tim = gclm2lensmap_symband_timed( spin, glm, _thup, _thdown, Nt_perband, (tnewN, phinewN), (tnewS, phinewS), Nphi=Nphi, clm=clm) ret[pixN] = lenNR + 1j * lenNI ret[pixS] = lenSR + 1j * lenSI t0 = time.time() if rotpol and spin > 0: ret[pixN] *= polrot(spin, ret[pixN], hp.pix2ang(nside, pixN)[0], Redtot[pixN], Imdtot[pixN]) ret[pixS] *= polrot(spin, ret[pixS], hp.pix2ang(nside, pixS)[0], Redtot[pixS], Imdtot[pixS]) times['pol. rot.'] += time.time() - t0 coadd_times(tim) #coadd_times(tim) _Npix += 2 * Nt_perband * Nphi t.checkpoint('Total exec. time') print "STATS for lmax tlm %s lmax dlm %s" % (hp.Alm.getlmax( glm.size), hp.Alm.getlmax(dlm.size)) tot = 0. for _k, _t in times.iteritems(): print '%20s: %.2f' % (_k, _t) tot += _t print "%20s: %2.f sec." % ('tot', tot) print "%20s: %2.f sec." % ('excl. defl. angle calc.', tot - times['dx,dy (full sky)'] - times['dx,dy band split']) print '%20s: %s = %.1f^2' % ('Tot. int. pix.', int(_Npix), np.sqrt(_Npix * 1.)) return ret
NSIDE_dg = 32 NPIX_dg = hp.nside2npix(NSIDE_dg) m = np.arange(NPIX_dg) coords = hp.pix2ang(NSIDE_dg, m, lonlat=True) l = coords[0] b = coords[1] nu = 1420e6 T_eg = 0.08866 # K T_CMB = 2.725 # K # make sure maps are in Kelvin map_1420 = (hp.read_map('STOCKERT+VILLA-ELISA_1420MHz_1_256.fits')) / 1000 map_1420_dg = hp.pixelfunc.ud_grade(map_1420, NSIDE_dg) idx_exb = hp.query_strip(NSIDE_dg, np.deg2rad(90 - 10), np.deg2rad(90 + 10)) ### set up priors for each MCMC run ### # You change: value of priors # def lnprior(param): R_disk = param[0] h_disk = param[1] j_disk = param[2] R_halo = param[3] j_halo = param[4] T_bkg = param[5] if d < R_disk < 100 * d and 0 < h_disk < 5 * d and 1e-42 < j_disk < 1e-39 and R_halo > 0 and 1e-43 < j_halo < 1e-38 and T_bkg > 0: return 0.0
mse_test_ = [] r_test_ = [] psnr_test_ = [] ssim_test_ = [] for i in range(0, test1.shape[0]): in_map = test2[i, :, 0] rec_map = test_predict[i, :, 0] # crop before measure computation nside = hp.npix2nside(in_map.shape[0]) theta1 = 0.0 theta2 = np.radians(120.0) ipix = hp.query_strip(nside, theta1, theta2, inclusive=True, nest=False, buff=None) in_map = in_map[ipix] rec_map = rec_map[ipix] # compute mse # l = np.mean((in_map - rec_map)**2) l = mean_squared_error(in_map, rec_map) mse_test_.append(l) # compute pearson r r_, p = pearsonr(in_map.flatten(), rec_map.flatten()) r_test_.append(r_) # compute psnr