def get_map_range(hpxmap, pixel=None, nside=None, wrap_angle=180): """ Calculate the longitude and latitude range for a map. """ check_hpxmap(hpxmap,pixel,nside) if isinstance(hpxmap,np.ma.MaskedArray): hpxmap = hpxmap.data if pixel is None: nside = hp.get_nside(hpxmap) pixel = np.arange(len(hpxmap),dtype=int) ipring,=np.where(np.isfinite(hpxmap) & (hpxmap!=hp.UNSEEN)) theta,phi = hp.pix2ang(nside, pixel[ipring]) lon = np.mod(np.degrees(phi),360) lat = 90.0-np.degrees(theta) # Small offset to add to make sure we get the whole pixel eps = np.degrees(hp.max_pixrad(nside)) # CHECK ME hi,=np.where(lon > wrap_angle) lon[hi] -= 360.0 lon_min = max(np.nanmin(lon)-eps,wrap_angle-360) lon_max = min(np.nanmax(lon)+eps,wrap_angle) lat_min = max(np.nanmin(lat)-eps,-90) lat_max = min(np.nanmax(lat)+eps,90) return (lon_min,lon_max), (lat_min,lat_max)
def while_loop(self, id, rms): count = 0 #initialize a counter at 0 to keep track of number of iterations. while not self.conditions(rms, id): id = int(abs(np.random.normal( id, self.step_size, 1))) #calculate another ID with a gaussian stepsize lon, lat = healpy.pix2ang( self.nside, id, lonlat=True ) * u.deg #do the same conversion to RA/DEC in ICRS as before id_coords = SkyCoord( lon, lat, representation='unitspherical').transform_to('icrs') rms = self.pull_values( id_coords ) #calculate the map model then both rms and sfbrtness if self.conditions(rms, id): #check the conditions and append is True self.m_centers[self.sim, :] = np.array([ float(id_coords.ra.to_string(decimal=True)), float(id_coords.dec.to_string(decimal=True)) ]) self.id_list.append(id) self.sim += 1 count += 1 #increment iteration count if self.sim == self.nsims: break if count > 100000: #raise an error if we have gone too far down the rabbit hole print(self.sim) raise TimeoutError( 'Program has reached maximum number of iterations, %s, looking for similar fields, try weakening search parameters.' % count) break
def field_search(self): #healpix class representing a reduced resolution of the Planck Maps hp_class = HEALPix(nside=self.nside, order='RING', frame='Galactic') #calculate a starting pixel healpix ID id = int(abs(np.random.normal(hp_class.npix / 2., self.step_size, 1))) #convert this ID to a longitude / latitude and then to a RA/DEC in ICRS lon, lat = healpy.pix2ang(self.nside, id, lonlat=True) * u.deg id_coords = SkyCoord( lon, lat, representation='unitspherical').transform_to('icrs') #initialize an empty container for accepted field maps self.m_centers = np.zeros((self.nsims, 2), dtype=float) self.id_list = [] self.sim = 0 #check to see if initial map fits the given conditions rms = self.pull_values(id_coords) if self.conditions(rms, id): self.id_list.append(id) self.m_centers[0, :] = np.array([ float(id_coords.ra.to_string(decimal=True)), float(id_coords.dec.to_string(decimal=True)) ]) self.sim += 1 #iterate to find 100 similar maps # for i in range(10 - len(cirrus_sim_maps)): # -len(id_list) for the case that the first realization matched the conditions. self.while_loop(id, rms) print(len(self.m_centers)) np.save(config.PLANCKDATA + 'Planck_Models/center_values.npy', self.m_centers, allow_pickle=True)
def pix2ang(nside, pix): """ Return (lon, lat) in degrees instead of (theta, phi) in radians """ theta, phi = hp.pix2ang(nside, pix) lon = phi2lon(phi) lat = theta2lat(theta) return lon, lat
def healpix_mesh(nSide): #import healpy as hp from astropy_healpix import healpy as hp othetas, ophis = hp.pix2ang(nSide, np.arange(12 * nSide**2)) othetas = np.pi / 2 - othetas ophis[ophis > np.pi] -= np.pi * 2 # ophis -> longitude, othetas -> latitude return np.degrees(ophis), np.degrees(othetas)
def healpix_mesh(nSide): """ create a set of healpix points, returned as numpy arrays of the longitudes and latitudes """ #import healpy as hp from astropy_healpix import healpy as hp othetas,ophis = hp.pix2ang(nSide,np.arange(12*nSide**2)) othetas = np.pi/2-othetas ophis[ophis>np.pi] -= np.pi*2 # ophis -> longitude, othetas -> latitude return np.degrees(ophis), np.degrees(othetas)
def test_offzenith_vis(): # Construct a shell with a single point source a known position off from zenith. # Similar to test_vis_calc, but set the pointing center 5deg off from the zenith and adjust analytic calculation freqs = [1.0e8] Nfreqs = 1 fov = 60 ant1_enu = np.array([10.0, 0, 0]) ant2_enu = np.array([0.0, 140.6, 0]) bl = observatory.Baseline(ant1_enu, ant2_enu) # Set pointing center to ra/dec = 0/0 center = [0, 0] # Make a shell and place a 1 Jy/pix point source at ra/dec of 5/0 Nside = 128 Npix = Nside**2 * 12 shell = np.zeros((Npix, Nfreqs)) pix_area = 4 * np.pi / float(Npix) ind = hp.ang2pix(Nside, 5, 0.0, lonlat=True) shell[ind] = 1 # Jy/pix shell[ind] *= utils.jy2Tsr(freqs[0], bm=pix_area) # K obs = observatory.Observatory(0, 0, array=[bl], freqs=freqs) obs.pointing_centers = [center] obs.times_jd = np.array([1]) obs.set_fov(fov) obs.set_beam("uniform") sky = sky_model.SkyModel(Nside=Nside, freqs=np.array(freqs), data=shell) vis_calc, times, bls = obs.make_visibilities(sky) ra_deg, dec_deg = hp.pix2ang(Nside, ind, lonlat=True) src_az = np.radians(90.0) src_za = np.radians(ra_deg) src_l = np.sin(src_az) * np.sin(src_za) src_m = np.cos(src_az) * np.sin(src_za) src_n = np.cos(src_za) u, v, w = bl.get_uvw(freqs[0]) vis_analytic = (1) * np.exp(2j * np.pi * (u * src_l + v * src_m + w * src_n)) print(vis_analytic) print(vis_calc) print(vis_calc[0, 0, 0] - vis_analytic) vis_calc = vis_calc[0, 0, 0] assert np.isclose(vis_calc.real, vis_analytic.real) assert np.isclose(vis_calc.imag, vis_analytic.imag)
def sphericalThetaGen(nVal): # Returns only the theta information of the event nside = 2**nVal numPix = 12 * (nside**2) spherPoint = [] # Use HEALPix to generate points for j in range(numPix): theta, phi = hp.pix2ang(nside, j) if phi > np.pi: point = np.array([np.sin(theta), 0, np.cos(theta)]) spherPoint.append(point) else: point = np.array([-np.sin(theta), 0, np.cos(theta)]) spherPoint.append(point) return np.array(spherPoint)
def test_az_za(): """ Check the calculated azimuth and zenith angle of a point exactly 5 deg east on the sphere (az = 90d, za = 5d) """ Nside = 128 obs = observatory.Observatory(latitude, longitude, fov=20, nside=Nside) center = [0, 0] lon, lat = [5, 0] ind0 = hp.ang2pix(Nside, lon, lat, lonlat=True) lon, lat = hp.pix2ang(Nside, ind0, lonlat=True) za, az, pix = obs.calc_azza(center, return_inds=True) ind = np.where(pix == ind0) # lon = longitude of the source, which is set to 5deg off zenith (hence, zenith angle) assert np.isclose(np.degrees(za[ind]), lon) assert np.isclose(np.degrees(az[ind]), 90.0)
def test_az_za_astropy(): """ Check the calculated azimuth and zenith angle for a selection of HEALPix pixels against the corresponding astropy calculation. """ Nside = 128 altitude = 0.0 loc = EarthLocation.from_geodetic(longitude, latitude, altitude) obs = observatory.Observatory(latitude, longitude, nside=Nside) t0 = Time(2458684.453187554, format="jd") obs.set_fov(180) zen = AltAz(alt=Angle("90d"), az=Angle("0d"), obstime=t0, location=loc) zen_radec = zen.transform_to(ICRS()) center = [zen_radec.ra.deg, zen_radec.dec.deg] northloc = EarthLocation.from_geodetic(lat="90.d", lon="0d", height=0.0) north_radec = AltAz(alt="90.0d", az="0.0d", obstime=t0, location=northloc).transform_to(ICRS()) yvec = np.array([north_radec.ra.deg, north_radec.dec.deg]) za, az, inds = obs.calc_azza(center, yvec, return_inds=True) ra, dec = hp.pix2ang(Nside, inds, lonlat=True) altaz_astropy = ICRS(ra=Angle(ra, unit="deg"), dec=Angle(dec, unit="deg")).transform_to( AltAz(obstime=t0, location=loc)) za0 = altaz_astropy.zen.rad az0 = altaz_astropy.az.rad if environ.get("VIS", False): hmap = np.zeros(12 * Nside**2) + hp.UNSEEN hmap[inds] = np.unwrap(az0 - az) import IPython IPython.embed() print(np.degrees(za0 - za)) assert np.allclose(za0, za, atol=1e-4) assert np.allclose( np.unwrap(az0 - az), 0.0, atol=3e-4 ) # About 1 arcmin precision. Worst is at the southern horizon.
def test_vis_calc(): """Construct a shell with a single point source at the zenith. Confirm against analytic calculation. """ ant1_enu = np.array([0, 0, 0]) ant2_enu = np.array([0.0, 14.6, 0]) bl = observatory.Baseline(ant1_enu, ant2_enu) freqs = np.array([1e8]) nfreqs = 1 fov = 20 # Deg # Longitude/Latitude in degrees. nside = 32 ind = 10 center = list(hp.pix2ang(nside, ind, lonlat=True)) centers = [center] npix = nside**2 * 12 shell = np.zeros((npix, nfreqs)) pix_area = 4 * np.pi / float(npix) shell[ind] = 1 # Jy/pix shell[ind] *= utils.jy2Tsr(freqs[0], bm=pix_area) # K obs = observatory.Observatory(latitude, longitude, array=[bl], freqs=freqs) obs.pointing_centers = centers obs.times_jd = np.array([1]) obs.set_fov(fov) obs.set_beam("uniform") sky = sky_model.SkyModel(Nside=nside, freqs=freqs, data=shell[np.newaxis, :, :]) visibs, times, bls = obs.make_visibilities(sky) assert np.isclose(np.real(visibs), 1.0).all() # Unit point source at zenith
cp /data40s/erosim/eRASS/simulated_photons.fits wwwDir/erosita_stuff/ cd data/eRoMok wget http://www.mpe.mpg.de/~comparat/erosita_stuff/simulated_photons.fits erosim Simput=/data17s/darksim/MD/MD_1.0Gpc/cat_AGN_SIMPUT/SIMPUT_000000_1024.fit Prefix=/data40s/erosim/eRASS/eRASS8_agn/000/erass_ Attitude=/data40s/erosim/eRASS/eRASS_4yr_epc85_att.fits RA=224.99999999999997 Dec=84.14973293629666 GTIFile=/data40s/erosim/eRASS/eRASS8_agn/000/erass.gti TSTART=0.0 Exposure=126144000.0 MJDREF=51543.875 dt=1.0 Seed=42 clobber=yes chatter=3 Background=yes """ import subprocess import os import errno import sys from astropy_healpix import healpy import numpy as n pix_ids = n.arange(healpy.nside2npix(8)) ra_cen_s, dec_cen_s = healpy.pix2ang(8, pix_ids, nest=False, lonlat=True) class Simulator: """ SIXTE simulator for eROSITA observations. 1. Compute GTI file for given simput 2. Simulate eROSITA observations of simput, using GTI to speed things up. """ def __init__(self, with_bkg_par, t_start, exposure, seed, simput, data_dir, ra_cen, dec_cen): # def __init__(self, with_bkg_par, t_start, exposure, seed, simput, # simput2, simput3): """ :param with_bkg_par: Simulate with particle background. :param t_start: Start time of simulation. Input units of [s]
p.grid() #p.yscale('log') #p.legend(frameon=False, loc=0) p.savefig(fig_out) p.clf() NN = out[0].astype('int') print('sum(NN)', np.sum(NN)) print('histogram', NN) print('histogram fraction', np.round(100 * NN * 1. / N_pixels_with_observed_targets, 1)) not_observed = np.in1d(uniq_all[0], uniq_observed[0], invert=True) ra_all, dec_all = healpy.pix2ang(nside, uniq_all[0][not_observed], nest=True, lonlat=True) ra, dec = healpy.pix2ang(nside, uniq_observed[0], nest=True, lonlat=True) fig_out = os.path.join(figure_dir, 'completeness_ra_dec_' + nside_str + '.png') p.figure(1, (6.5, 5.5)) p.axes([0.17, 0.17, 0.78, 0.75]) p.tight_layout() #p.hist(completeness, bins = np.arange(0.,1.1, 0.05, ), histtype='step', rasterized=True, lw=2) p.plot(ra_all, dec_all, 'k,', label='not observed') p.scatter(ra, dec, c=completeness, s=16 - 2 * nside_int, rasterized=True) p.colorbar(shrink=0.9) p.xlabel('R.A. [degree]') p.ylabel('Dec. [degree]') p.grid()
def make_plot(args): """ Take the steps to make the plot. Parameters ---------- args: dict Command line arguments Returns ------- Nothing """ infile = './data/' + args['inputFile'] basename = 'PMmap-' + args['inputFile'].split('.')[0] default_proj = ccrs.PlateCarree() sky_proj = ccrs.Mollweide() backgr = plt.imread( '../star-trail-animation/sky-images/GaiaSky-colour-2k.png') nside = hp.order2nside(args['hplevel']) hpcol = 'healpix_{0}'.format(args['hplevel']) edr3data = Table.read(infile) alpha, delta = hp.pix2ang(nside, edr3data[hpcol], lonlat=True, nest=True) pmra = edr3data['avg_pmra'] pmdec = edr3data['avg_pmdec'] icrs = ICRS(ra=alpha * u.degree, dec=delta * u.degree, pm_ra_cosdec=pmra * u.mas / u.yr, pm_dec=pmdec * u.mas / u.yr) galactic = icrs.transform_to(Galactic) pmtot = np.sqrt(galactic.pm_l_cosb.value**2 + galactic.pm_b.value**2) fig = plt.figure(figsize=(16, 9), dpi=120, frameon=False, tight_layout={'pad': 0.01}) gs = GridSpec(1, 1, figure=fig) ax = fig.add_subplot(gs[0, 0], projection=sky_proj) ax.imshow(np.fliplr(backgr), transform=default_proj, zorder=-1, origin='upper') pmcmap = cm.viridis veccolor = plt.cm.get_cmap('tab10').colors[9] linecolor = plt.cm.get_cmap('tab10').colors[9] if args['quiver']: vscale = np.median(pmtot) / 10 ax.quiver(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, angles='xy', scale=vscale, scale_units='dots', color=veccolor, headwidth=1, headlength=3, headaxislength=2.5) else: if args['colourstreams']: ax.streamplot(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, linewidth=2.0, density=2, color=pmtot, cmap=pmcmap, maxlength=0.5, arrowsize=1, arrowstyle=ArrowStyle.Fancy(head_length=1.0, head_width=.4, tail_width=.4)) elif args['lwcode'] > 0: ax.streamplot(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, linewidth=args['lwcode'] * pmtot / np.median(pmtot), density=2, color=linecolor, maxlength=0.5, arrowsize=1, arrowstyle=ArrowStyle.Fancy(head_length=1.0, head_width=.4, tail_width=.4)) else: ax.streamplot(galactic.l.value, galactic.b.value, galactic.pm_l_cosb.value, galactic.pm_b.value, transform=default_proj, linewidth=1.5, density=2, color=linecolor, maxlength=0.5, arrowsize=1, arrowstyle=ArrowStyle.Fancy(head_length=1.0, head_width=.4, tail_width=.4)) ax.invert_xaxis() if args['pdfOutput']: plt.savefig(basename + '.pdf') elif args['pngOutput']: plt.savefig(basename + '.png') else: plt.show()