Esempio n. 1
0
def get_pix_ranges(shape, wcs, horbox, daz, nt=4, azdown=1, ndet=1.0):
	(t1,t2),(az1,az2),el = horbox[:,0], horbox[:,1], np.mean(horbox[:,2])
	nphi = np.abs(utils.nint(360/wcs.wcs.cdelt[0]))
	# Find the pixel coordinates of first az sweep
	naz  = utils.nint(np.abs(az2-az1)/daz)/azdown
	ahor = np.zeros([3,naz])
	ahor[0] = utils.ctime2mjd(t1)
	ahor[1] = np.linspace(az1,az2,naz)
	ahor[2] = el
	acel    = coordinates.transform("hor","cel",ahor[1:],time=ahor[0],site=site)
	y, x1   = upscale(fixx(utils.nint(enmap.sky2pix(shape, wcs, acel[::-1])),nphi),azdown)
	# Reduce to unique y values
	_, uinds, hits = np.unique(y, return_index=True, return_counts=True)
	y, x1 = y[uinds], x1[uinds]
	# Find the pixel coordinates of time drift
	thor = np.zeros([3,nt])
	thor[0] = utils.ctime2mjd(np.linspace(t1,t2,nt))
	thor[1] = az1
	thor[2] = el
	tcel    = coordinates.transform("hor","cel",thor[1:],time=thor[0],site=site)
	_, tx   = utils.nint(fixx(enmap.sky2pix(shape, wcs, tcel[::-1]),nphi))
	x2 = x1 + tx[-1]-tx[0]
	x1, x2  = np.minimum(x1,x2), np.maximum(x1,x2)
	pix_ranges = np.concatenate([y[:,None],x1[:,None],x2[:,None]],1)
	# Weight per pixel in pix ranges. If ndet=1 this corresponds to
	# telescope time per output pixel
	weights = (t2-t1)/(naz*azdown)/(x2-x1)*ndet * hits
	return pix_ranges, weights
Esempio n. 2
0
    def __init__(self,
                 shape,
                 wcs,
                 pattern,
                 offset,
                 site,
                 pad=2.0 * utils.degree):
        """This unskew operation assumes that equal spacing in
		dec corresponds to equal spacing in time, and that shifts in
		RA can be done in units of whole pixels. This is an approximation
		relative to UnskewCurved, but it is several times faster, uses
		less memory, and causes less smoothing."""
        ndec, nra = shape[-2:]
        info = calc_az_sweep(pattern, offset, site, pad=pad)
        sweep_ra, sweep_dec = info.sweep_cel
        # For each pixel in dec (that we hit for this scanning pattern), we
        # want to know how far we have been displaced in ra.
        # First get the dec of each pixel center.
        ysweep, xsweep = enmap.sky2pix(shape, wcs, [sweep_dec, sweep_ra])
        y1 = max(int(np.min(ysweep)), 0)
        y2 = min(int(np.max(ysweep)) + 1, shape[-2])
        # Make fft-friendly
        ny = y2 - y1
        ny2 = fft.fft_len(ny, "above", [2, 3, 5, 7])
        y1 = max(y1 - (ny2 - ny) / 2, 0)
        y2 = min(y1 + ny2, shape[-2])
        y = np.arange(y1, y2)
        dec, _ = enmap.pix2sky(shape, wcs, [y, y * 0])
        # Then interpolate the ra values corresponding to those decs.
        # InterpolatedUnivariateSpline broken. Returns nan even when
        # interpolating. So we will use UnivariateSpline
        spline = scipy.interpolate.UnivariateSpline(sweep_dec, sweep_ra)
        ra = spline(dec)
        dra = ra - ra[len(ra) / 2]
        y, x = np.round(enmap.sky2pix(shape, wcs, [dec, ra]))
        dx = x - x[len(x) / 2]
        # It's also useful to be able to go from normal map index to
        # position in y and dx
        inv_y = np.zeros(shape[-2], dtype=int) - 1
        inv_y[y.astype(int)] = np.arange(len(y))
        # Compute the azimuth step size based on the total azimuth sweep.
        daz = (pattern[2] - pattern[1] + 2 * pad) / len(y)
        # Build the geometry of the unskewed system
        ushape, uwcs = enmap.geometry(pos=[0, 0],
                                      shape=[len(y), shape[-1]],
                                      res=[daz,
                                           enmap.pixshape(shape, wcs)[1]],
                                      proj="car")
        # And store the result
        self.y = y.astype(int)
        self.dx = np.round(dx).astype(int)
        self.dx_raw = dx
        self.inv_y = inv_y
        self.ushape = ushape
        self.uwcs = uwcs
Esempio n. 3
0
def calc_pbox(shape, wcs, box, n=10):
    nphi = utils.nint(np.abs(360 / wcs.wcs.cdelt[0]))
    dec = np.linspace(box[0, 0], box[1, 0], n)
    ra = np.linspace(box[0, 1], box[1, 1], n)
    y = enmap.sky2pix(shape, wcs, [dec, dec * 0 + box[0, 1]])[0]
    x = enmap.sky2pix(shape, wcs, [ra * 0 + box[0, 0], ra])[1]
    x = utils.unwind(x, nphi)
    pbox = np.array([[np.min(y), np.min(x)], [np.max(y), np.max(x)]])
    xm1 = np.mean(pbox[:, 1])
    xm2 = utils.rewind(xm1, shape[-1] / 2, nphi)
    pbox[:, 1] += xm2 - xm1
    pbox = utils.nint(pbox)
    return pbox
Esempio n. 4
0
	def __init__(self, shape, wcs, pattern, offset, site, pad=2.0*utils.degree, order=0, subsample=2.0):
		"""Build an unskew operator that uses spline interpolation along an azimuth sweep
		to straighten out the scanning motion for one scanning pattern. Relatively slow, and
		leads to some smoothing due to the interpolation, but does not assume that dec changes
		with a constant speed during a sweep."""
		# Find the unskew transformation for this pattern.
		# We basically want dec->az and ra->ra0, with az spacing
		# similar to el spacing.
		ndec, nra = shape[-2:]
		info = calc_az_sweep(pattern, offset, site, pad=pad, subsample=subsample)
		sweep_ra, sweep_dec = info.sweep_cel
		#(sweep_ra, sweep_dec), naz, daz = calc_az_sweep(pattern, offset, site, pad=pad, subsample=subsample)
		# We want to be able to go from (y,x) to (ra,dec), with
		# dec = dec[y]
		# ra  = ra[y]-ra[0]+x
		# Precompute the pixel mapping. This will have the full witdh in ra,
		# but will be smaller in dec due to the limited az range.
		raw_dec, raw_ra = enmap.posmap(shape, wcs)
		skew_pos = np.zeros((2, info.naz, nra))
		skew_pos[0] = sweep_dec[:,None]
		skew_pos[1] = (sweep_ra-sweep_ra[0])[:,None] + raw_ra[None,ndec/2,:]
		skew_pix = enmap.sky2pix(shape, wcs, skew_pos).astype(dtype)
		# Build geometry for the unskewed system
		ushape, uwcs = enmap.geometry(pos=[0,0], shape=[info.naz, nra], res=[np.abs(info.daz), enmap.pixshape(shape,wcs)[1]], proj="car")
		# Save
		self.order    = order
		self.shape    = shape
		self.wcs      = wcs
		self.pattern  = pattern
		self.site     = site
		self.skew_pix = skew_pix
		# External interface
		self.ushape   = ushape
		self.uwcs     = uwcs
Esempio n. 5
0
    def __init__(self,
                 ras_deg,
                 decs_deg,
                 shape=None,
                 wcs=None,
                 nside=None,
                 verbose=True):

        self.verbose = verbose
        if nside is not None:
            if verbose: print("Calculating pixels...")
            self.pixs = hp.ang2pix(nside, ras_deg, decs_deg, lonlat=True)
            if verbose: print("Done with pixels...")
            self.nside = nside
            self.shape = hp.nside2npix(nside)
            self.curved = True
        else:
            coords = np.vstack((decs_deg, ras_deg)) * np.pi / 180.
            self.shape = shape
            self.wcs = wcs
            if verbose: print("Calculating pixels...")
            self.pixs = enmap.sky2pix(shape, wcs, coords,
                                      corner=True)  # should corner=True?!
            if verbose: print("Done with pixels...")
            self.curved = False
        self.counts = self.get_map()
        if not self.curved:
            self.counts = enmap.enmap(self.counts, self.wcs)
Esempio n. 6
0
	def __init__(self, shape, wcs, pattern, offset, site, pad=2.0*utils.degree, order=0, subsample=2.0):
		"""Build an unskew operator that uses spline interpolation along an azimuth sweep
		to straighten out the scanning motion for one scanning pattern. Relatively slow, and
		leads to some smoothing due to the interpolation, but does not assume that dec changes
		with a constant speed during a sweep."""
		# Find the unskew transformation for this pattern.
		# We basically want dec->az and ra->ra0, with az spacing
		# similar to el spacing.
		ndec, nra = shape[-2:]
		info = calc_az_sweep(pattern, offset, site, pad=pad, subsample=subsample)
		sweep_ra, sweep_dec = info.sweep_cel
		#(sweep_ra, sweep_dec), naz, daz = calc_az_sweep(pattern, offset, site, pad=pad, subsample=subsample)
		# We want to be able to go from (y,x) to (ra,dec), with
		# dec = dec[y]
		# ra  = ra[y]-ra[0]+x
		# Precompute the pixel mapping. This will have the full witdh in ra,
		# but will be smaller in dec due to the limited az range.
		raw_dec, raw_ra = enmap.posmap(shape, wcs)
		skew_pos = np.zeros((2, info.naz, nra))
		skew_pos[0] = sweep_dec[:,None]
		skew_pos[1] = (sweep_ra-sweep_ra[0])[:,None] + raw_ra[None,ndec/2,:]
		skew_pix = enmap.sky2pix(shape, wcs, skew_pos).astype(dtype)
		# Build geometry for the unskewed system
		ushape, uwcs = enmap.geometry(pos=[0,0], shape=[info.naz, nra], res=[np.abs(info.daz), enmap.pixshape(shape,wcs)[1]], proj="car")
		# Save
		self.order    = order
		self.shape    = shape
		self.wcs      = wcs
		self.pattern  = pattern
		self.site     = site
		self.skew_pix = skew_pix
		# External interface
		self.ushape   = ushape
		self.uwcs     = uwcs
Esempio n. 7
0
def box2pix(shape, wcs, box):
    """Convert one or several bounding boxes of shape [2,2] or [n,2,2]
	into pixel counding boxes in standard python half-open format.
	The box must be [{from,to},...].
	"""
    nphi = int(np.round(np.abs(360. / wcs.wcs.cdelt[0])))
    box = np.asarray(box)
    fbox = box.reshape(-1, 2, 2)
    if wcs.wcs.cdelt[0] < 0: fbox[..., 1] = fbox[..., ::-1, 1]
    # Must rollaxis because sky2pix expects [{dec,ra},...]
    ibox = enmap.sky2pix(shape, wcs, utils.moveaxis(fbox, 2, 0), corner=True)
    # FIXME: This is one of many places in the code that will break if a bounding
    # box goes more than half the way around the sky. Properly fixing
    # this will require a big overhaul, especially if we want to handle
    # bounding boxes that are bigger than the full sky.
    ibox[1] = utils.unwrap_range(ibox[1].T, nphi).T
    #ibox[1] = utils.unwind(ibox[1], nphi)
    # We now have [{y,x},:,{from,to}
    # Truncate to integer, and add one to endpoint to make halfopen interval
    ibox = np.floor(np.sort(ibox, 2)).astype(int)
    # Add 1 to endpoint to make halfopen interval
    ibox[:, :, 1] += 1
    #ibox = np.array([np.floor(ibox[0]),np.ceil(ibox[1])]).astype(int)
    # Shuffle to [:,{from,to},{y,x}]
    ibox = utils.moveaxis(ibox, 0, 2)
    return ibox.reshape(box.shape)
Esempio n. 8
0
	def __init__(self, shape, wcs, pattern, offset, site, pad=2.0*utils.degree):
		"""This unskew operation assumes that equal spacing in
		dec corresponds to equal spacing in time, and that shifts in
		RA can be done in units of whole pixels. This is an approximation
		relative to UnskewCurved, but it is several times faster, uses
		less memory, and causes less smoothing."""
		ndec, nra = shape[-2:]
		info = calc_az_sweep(pattern, offset, site, pad=pad)
		sweep_ra, sweep_dec = info.sweep_cel
		# For each pixel in dec (that we hit for this scanning pattern), we
		# want to know how far we have been displaced in ra.
		# First get the dec of each pixel center.
		ysweep, xsweep = enmap.sky2pix(shape, wcs, [sweep_dec,sweep_ra])
		y1  = max(int(np.min(ysweep)),0)
		y2  = min(int(np.max(ysweep))+1,shape[-2])
		# Make fft-friendly
		ny  = y2-y1
		ny2 = fft.fft_len(ny, "above", [2,3,5,7])
		y1  = max(y1-(ny2-ny)/2,0)
		y2  = min(y1+ny2,shape[-2])
		y   = np.arange(y1,y2)
		dec, _ = enmap.pix2sky(shape, wcs, [y,y*0])
		# Then interpolate the ra values corresponding to those decs.
		# InterpolatedUnivariateSpline broken. Returns nan even when
		# interpolating. So we will use UnivariateSpline
		spline  = scipy.interpolate.UnivariateSpline(sweep_dec, sweep_ra)
		ra      = spline(dec)
		dra     = ra - ra[len(ra)/2]
		y, x    = np.round(enmap.sky2pix(shape, wcs, [dec,ra]))
		dx      = x-x[len(x)/2]
		# It's also useful to be able to go from normal map index to
		# position in y and dx
		inv_y   = np.zeros(shape[-2],dtype=int)-1
		inv_y[y.astype(int)]= np.arange(len(y))
		# Compute the azimuth step size based on the total azimuth sweep.
		daz = (pattern[2]-pattern[1]+2*pad)/len(y)
		# Build the geometry of the unskewed system
		ushape, uwcs = enmap.geometry(pos=[0,0], shape=[len(y),shape[-1]], res=[daz,enmap.pixshape(shape,wcs)[1]], proj="car")
		# And store the result
		self.y  = y.astype(int)
		self.dx = np.round(dx).astype(int)
		self.dx_raw = dx
		self.inv_y  = inv_y
		self.ushape = ushape
		self.uwcs   = uwcs
Esempio n. 9
0
 def draw(self, shape, wcs, window=False, nsigma=10, pad=False):
     m = enmap.zeros((3, ) + shape[-2:], wcs)
     w = np.max(self.widths) * nsigma
     # Find all sources that enter even partially into our area
     ipos = np.array([
         enmap.sky2pix(shape, wcs, self.pos - w, corner=True, safe=True),
         enmap.sky2pix(shape, wcs, self.pos + w, corner=True, safe=True)
     ]).astype(int)
     ipos = np.sort(ipos, 0)
     ashape = np.array(shape[-2:])
     mask = np.all(ipos[1] >= 0, 0) & np.all(
         ipos[0] < ashape[:, None], 0) & np.all(
             ipos[1] - ipos[0] < ashape[:, None], 0)
     nmask = np.sum(mask)
     if nmask == 0: return m
     if pad:
         # We will include enough pixels on each side that we avoid
         # truncating any part of the source
         ipos2 = np.array([
             enmap.sky2pix(shape,
                           wcs,
                           self.pos[:, mask] - w * 2,
                           corner=True,
                           safe=True),
             enmap.sky2pix(shape,
                           wcs,
                           self.pos[:, mask] + w * 2,
                           corner=True,
                           safe=True)
         ]).astype(int)
         npad = np.maximum(
             0, [-np.min(ipos2, (0, 2)),
                 np.max(ipos2, (0, 2)) - ashape])
         m, mslice = enmap.pad(m, npad, return_slice=True)
     for i, (pos, amp, width, ibeam) in enumerate(
             zip(self.pos.T[mask], self.amps.T[mask], self.widths.T[mask],
                 self.ibeam.T[mask])):
         # Find necessary bounding box
         sub = m.submap([pos - w, pos + w])
         if sub.size == 0: continue
         add_gauss(sub, pos, amp, ibeam)
     # Optinally apply window function
     if window: m = enmap.apply_window(m)
     if pad: m = m[mslice]
     return m
Esempio n. 10
0
 def __init__(self, shape, wcs, ras_deg, decs_deg):
     coords = np.vstack((decs_deg, ras_deg)) * np.pi / 180.
     self.shape = shape
     self.wcs = wcs
     print("Calculating pixels...")
     self.pixs = enmap.sky2pix(shape, wcs, coords,
                               corner=True)  # should corner=True?!
     print("Done with pixels...")
     self.counts = self.get_map()
Esempio n. 11
0
 def update_kappa(self, kappa):
     # Converts kappa map to pixel displacements
     import alhazen.lensTools as lt
     fphi = lt.kappa_to_fphi(kappa, self.modlmap)
     grad_phi = enmap.gradf(enmap.ndmap(fphi, self.wcs))
     pos = self.posmap + grad_phi
     self._displace_pix = enmap.sky2pix(self.shape,
                                        self.wcs,
                                        pos,
                                        safe=False)
Esempio n. 12
0
def get_rotated_pixels(shape_source,
                       wcs_source,
                       shape_target,
                       wcs_target,
                       inverse=False):
    """ Given a source geometry (shape_source,wcs_source)
    return the pixel positions in the target geometry (shape_target,wcs_target)
    if the source geometry were rotated such that its center lies on the center
    of the target geometry.

    WARNING: Only currently tested for a rotation along declination from one CAR
    geometry to another CAR geometry.
    """

    from enlib import coordinates

    # what are the center coordinates of each geometris
    center_source = enmap.pix2sky(shape_source, wcs_source,
                                  (shape_source[0] / 2., shape_source[1] / 2.))
    center_target = enmap.pix2sky(shape_target, wcs_target,
                                  (shape_target[0] / 2., shape_target[1] / 2.))
    decs, ras = center_source
    dect, rat = center_target

    # what are the angle coordinates of each pixel in the target geometry
    pos_target = enmap.posmap(shape_target, wcs_target)
    lra = pos_target[1, :, :].ravel()
    ldec = pos_target[0, :, :].ravel()
    del pos_target

    # recenter the angle coordinates of the target from the target center to the source center
    if inverse:
        newcoord = coordinates.decenter((lra, ldec), (rat, dect, ras, decs))
    else:
        newcoord = coordinates.recenter((lra, ldec), (rat, dect, ras, decs))
    del lra
    del ldec

    # reshape these new coordinates into enmap-friendly form
    new_pos = np.empty((2, shape_target[0], shape_target[1]))
    new_pos[0, :, :] = newcoord[1, :].reshape(shape_target)
    new_pos[1, :, :] = newcoord[0, :].reshape(shape_target)
    del newcoord

    # translate these new coordinates to pixel positions in the target geometry based on the source's wcs
    pix_new = enmap.sky2pix(shape_source, wcs_source, new_pos)

    return pix_new
Esempio n. 13
0
    def __init__(self,ras_deg,decs_deg,shape=None,wcs=None,nside=None,verbose=True,hp_coords="equatorial"):

        self.verbose = verbose
        if nside is not None:

            eq_coords = ['fk5','j2000','equatorial']
            gal_coords = ['galactic']

            if verbose: print( "Calculating pixels...")
            if hp_coords in gal_coords:
                if verbose: print( "Transforming coords...")
                from astropy.coordinates import SkyCoord
                import astropy.units as u
                gc = SkyCoord(ra=ras_deg*u.degree, dec=decs_deg*u.degree, frame='fk5')
                gc = gc.transform_to('galactic')
                phOut = gc.l.deg * np.pi/180.
                thOut = gc.b.deg * np.pi/180.
                thOut = np.pi/2. - thOut #polar angle is 0 at north pole

                self.pixs = hp.ang2pix( nside, thOut, phOut )
            elif hp_coords in eq_coords:
                ras_out = ras_deg
                decs_out = decs_deg
                lonlat = True
                self.pixs = hp.ang2pix(nside,ras_out,decs_out,lonlat=lonlat)
                
            else:
                raise ValueError
                
            if verbose: print( "Done with pixels...")
            self.nside = nside
            self.shape = hp.nside2npix(nside)
            self.curved = True
        else:
            coords = np.vstack((decs_deg,ras_deg))*np.pi/180.
            self.shape = shape
            self.wcs = wcs
            if verbose: print( "Calculating pixels...")
            self.pixs = enmap.sky2pix(shape,wcs,coords,corner=True) # should corner=True?!
            if verbose: print( "Done with pixels...")
            self.curved = False
        self.counts = self.get_map()
        if not self.curved:
            self.counts = enmap.enmap(self.counts,self.wcs)

        self.mask = np.ones(shape)
        self._counts()
Esempio n. 14
0

# Simulate
lmax = int(modlmap.max()+1)
ells = np.arange(0,lmax,1)
ps = theory.uCl('TT',ells).reshape((1,1,lmax))
~ps_noise = np.array([(noise_uK_rad)**2.]*ells.size).reshape((1,1,ells.size))
mg = maps.MapGen(shape,wcs,ps)
ng = maps.MapGen(shape,wcs,ps_noise)
kamp_true = args.Amp
kappa = lensing.nfw_kappa(kamp_true*1e15,modrmap,cc,overdensity=200.,critical=True,atClusterZ=True)
phi,_ = lensing.kappa_to_phi(kappa,modlmap,return_fphi=True)
grad_phi = enmap.grad(phi)
posmap = enmap.posmap(shape,wcs)
pos = posmap + grad_phi
alpha_pix = enmap.sky2pix(shape,wcs,pos, safe=False)
lens_order = 5


if rank==0: print("Starting sims...")
# Stats
Nsims = args.Nclusters
Njobs = Nsims
num_each,each_tasks = mpi.mpi_distribute(Njobs,numcores)
if rank==0: print ("At most ", max(num_each) , " tasks...")
my_tasks = each_tasks[rank]
mstats = stats.Stats(comm)
np.random.seed(rank)


# QE
Esempio n. 15
0
# We assume that site and pointing offsets are the same for all tods,
# so get them based on the first one
entry = filedb.data[ids[0]]
site  = actdata.read(entry, ["site"]).site

# Determine the bounding box of our selected data
bounds    = db.data["bounds"].reshape(2,-1).copy()
bounds[0] = utils.rewind(bounds[0], bounds[0,0], 360)
box = utils.widen_box(utils.bounding_box(bounds.T), 4*args.rad, relative=False)
waz, wel = box[1]-box[0]
# Use fullsky horizontally if we wrap too far
if waz <= 180:
	shape, wcs = enmap.geometry(pos=box[:,::-1]*utils.degree, res=args.res*utils.degree, proj="car", ref=(0,0))
else:
	shape, wcs = enmap.fullsky_geometry(res=args.res*utils.degree)
	y1, y2 = np.sort(enmap.sky2pix(shape, wcs, [box[:,1]*utils.degree,[0,0]])[0].astype(int))
	shape, wcs = enmap.slice_geometry(shape, wcs, (slice(y1,y2),slice(None)))

sys.stderr.write("using %s workspace with resolution %.2f deg" % (str(shape), args.res) + "\n")

# Get the hitmap for each block
hits = enmap.zeros((nblock,narray)+shape, wcs)
ndig = calc_ndig(nblock)
sys.stderr.write("estimating hitmap for block %*d/%d" % (ndig,0,nblock))
for bi in range(nblock):
	for ai in range(narray):
		block_db = db.select(block_inds[bi,ai])
		hits[bi,ai] = fastweight.fastweight(shape, wcs, block_db, array_rad=args.rad*utils.degree, site=site, weight=args.weight)
	sys.stderr.write("%s%*d/%d" % ("\b"*(1+2*ndig),ndig,bi+1,nblock))
sys.stderr.write("\n")
Esempio n. 16
0
def get_pix_ranges(shape, wcs, horbox, daz, nt=4, ndet=1.0, site=None):
    """An appropriate daz for this function is about 1 degree"""
    # For each row in the map we want to know the hit density for that row,
    # as well as its start and end. In the original function we got one
    # sample per row by oversampling and then using unique. This is unreliable,
    # and also results in quantized steps in the depth. We can instead
    # do a coarse equispaced az -> ra,dec -> y,x. We can then interpolate
    # this to get exactly one sample per y. To get the density properly,
    # we just need dy/dt = dy/daz * daz/dt, where we assume daz/dt is constant.
    # We get dy/daz from the coarse stuff, and interpolate that too, which gives
    # the density per row.
    (t1, t2), (az1, az2), el = horbox[:, 0], horbox[:, 1], np.mean(horbox[:,
                                                                          2])
    nphi = np.abs(utils.nint(360 / wcs.wcs.cdelt[0]))
    # First produce the coarse single scan
    naz = utils.nint(np.abs(az2 - az1) / daz)
    if naz <= 1: return None, None
    ahor = np.zeros([3, naz])
    ahor[0] = utils.ctime2mjd(t1)
    ahor[1] = np.linspace(az1, az2, naz)
    ahor[2] = el
    acel = coordinates.transform("hor",
                                 "cel",
                                 ahor[1:],
                                 time=ahor[0],
                                 site=site)
    ylow, x1low = fixx(enmap.sky2pix(shape, wcs, acel[::-1]), nphi)
    if ylow[1] < ylow[0]:
        ylow, x1low = ylow[::-1], x1low[::-1]
    # Find dy/daz for these points
    glow = np.gradient(ylow) * (naz - 1) / (az2 - az1)
    # Now interpolate to full resolution
    y = np.arange(utils.nint(ylow[0]), utils.nint(ylow[-1]) + 1)
    if len(y) == 0:
        print "Why is y empty?", naz, ylow[0], ylow[1]
        return None, None
    x1 = np.interp(y, ylow, x1low)
    grad = np.interp(y, ylow, glow)
    # Now we just need the width of the rows, x2, which comes
    # from the time drift
    thor = np.zeros([3, nt])
    thor[0] = utils.ctime2mjd(np.linspace(t1, t2, nt))
    thor[1] = az1
    thor[2] = el
    tcel = coordinates.transform("hor",
                                 "cel",
                                 thor[1:],
                                 time=thor[0],
                                 site=site)
    _, tx = utils.nint(fixx(enmap.sky2pix(shape, wcs, tcel[::-1]), nphi))
    x2 = x1 + tx[-1] - tx[0]
    x1, x2 = np.minimum(x1, x2), np.maximum(x1, x2)
    pix_ranges = utils.nint(
        np.concatenate([y[:, None], x1[:, None], x2[:, None]], 1))
    # Weight per pixel. We want this to be in units of seconds of
    # observing time per pixel if ndet=1. We know the total number of pixels
    # hit (ny*nx) and the total time (t2-t1), and we know the relative
    # weight per row (1/grad), so we can just normalize things
    ny, nx = len(y), x2[0] - x1[0]
    npix = ny * nx
    if npix == 0 or np.any(grad <= 0):
        return pix_ranges, grad * 0
    else:
        weights = 1 / grad
        weights *= (t2 - t1) / (np.sum(weights) *
                                nx) * ndet  # *nx because weight is per row
        return pix_ranges, weights
Esempio n. 17
0
 def __call__(self, hor):
     """Transform from [{tsec,az,el},nsamp] to [{y,x,c,s},nsamp]"""
     res = hor2cel(hor, self.toff)
     res[:2] = enmap.sky2pix(self.shape, self.wcs, res[1::-1])
     return res
Esempio n. 18
0
bazs = []
for iaz in range(naz):
    # Get our boresight az
    bazs.append(imaps.pix2sky([0, iaz])[1])
    vals = []
    for i in range(nfile):
        # Go from detectors to y-pixel in input maps
        ypix = utils.transpose_inds(dets[i], nrow, ncol)
        vals.append(imaps[i, ypix, iaz])
    vals = np.concatenate(vals)
    pos = np.concatenate(offs)
    # Write to appropriate position in array
    pix = np.maximum(
        0,
        np.minimum((np.array(shape[-2:]) - 1)[:, None],
                   enmap.sky2pix(shape, wcs, pos.T).astype(np.int32)))
    m = enmap.zeros(shape[-2:], wcs)
    m[tuple(pix)] = vals
    # Grow by smoothing
    m = enmap.smooth_gauss(m, rad) / norm
    omap[iaz] = m

# Truncate very low values
refval = np.mean(np.abs(omap)) * 0.01
mask = np.any(np.abs(omap) > refval, 0)
omap[:, ~mask] = 0

if not args.individual:
    # output a single file
    enmap.write_map(args.ofile, omap)
else:
Esempio n. 19
0
shape,wcs = maps.rect_geometry(width_deg=20.,px_res_arcmin=0.5)
bigmap = enmap.zeros(shape,wcs)

Nobj = 1000
ras,decs = catalogs.random_catalog(shape,wcs,Nobj,edge_avoid_deg=1.)

arcmin_width = 30.
res = np.min(bigmap.extent()/bigmap.shape[-2:])*180./np.pi*60.
Npix = int(arcmin_width/res)*1.
if Npix%2==0: Npix += 1
cshape,cwcs = enmap.geometry(pos=(0.,0.),res=res/(180./np.pi*60.),shape=(Npix,Npix))
cmodrmap = enmap.modrmap(cshape,cwcs)

sigmas = []
for ra,dec in zip(ras,decs):
    iy,ix = enmap.sky2pix(shape,wcs,(dec*np.pi/180.,ra*np.pi/180.))

    sigma = np.random.normal(3.0,1.0)*np.pi/180./60.
    paste_in = np.exp(-cmodrmap**2./2./sigma**2.)
    bigmap[int(iy-Npix/2):int(iy+Npix/2),int(ix-Npix/2):int(ix+Npix/2)] += paste_in
    sigmas.append(sigma)
    
    
io.plot_img(bigmap,"cat.png",high_res=True)

print("done")

st = maps.Stacker(bigmap,arcmin_width=30.)
stack = 0.
for ra,dec in zip(ras,decs):
    stack += st.cutout(ra*np.pi/180.,dec*np.pi/180.)
#print 'len PS15', len(PS15mJy)
#print 'Pass:'******'Fail:', len([x for x in PS15mJy_cut if x==0])
#print 'len PS100', len(PS100mJy)
#print 'Pass:'******'Fail:', len([x for x in PS100mJy_cut if x==0])

######## Mask Component Separated Map Areas (D56 and BN)
#
d56mask = enmap.read_fits(pathd56mask, hdu=None, sel=None, sel_threshold=10e6)
bnmask = enmap.read_fits(pathbnmask, hdu=None, sel=None, sel_threshold=10e6)

subs = 18  #in number of pixels

pixarrayd56 = enmap.sky2pix(d56mask.shape,
                            d56mask.wcs,
                            np.vstack((dec, ra)) * np.pi / 180.,
                            safe=True)
radpixelsd56 = pixarrayd56[1, :]
decdpixelsd56 = pixarrayd56[0, :]

pixarraybn = enmap.sky2pix(bnmask.shape,
                           bnmask.wcs,
                           np.vstack((dec, ra)) * np.pi / 180.,
                           safe=True)
radpixelsbn = pixarraybn[1, :]
decdpixelsbn = pixarraybn[0, :]

d56mask_rep = np.zeros((len(ra), subs, subs))
bnmask_rep = np.zeros((len(ra), subs, subs))

print 'Creating submaps...'
Esempio n. 21
0
fshape, fwcs = maps.rect_geometry(width_arcmin=20., px_res_arcmin=0.1)
cshape, cwcs = maps.rect_geometry(width_arcmin=20., px_res_arcmin=0.5)
rmodrmap = enmap.modrmap(rshape, rwcs)
fmodrmap = enmap.modrmap(fshape, fwcs)
cmodrmap = enmap.modrmap(cshape, cwcs)
rmodlmap = enmap.modlmap(rshape, rwcs)
fmodlmap = enmap.modlmap(fshape, fwcs)
cmodlmap = enmap.modlmap(cshape, cwcs)
print(fshape, cshape)

mass = 2.e14
fkappa = lens_func(fmodrmap)
phi, _ = lensing.kappa_to_phi(fkappa, fmodlmap, return_fphi=True)
grad_phi = enmap.grad(phi)
pos = enmap.posmap(fshape, fwcs) + grad_phi
alpha_pix = enmap.sky2pix(fshape, fwcs, pos, safe=False)

lmax = cmodlmap.max()
ells = np.arange(0, lmax, 1)
cls = theory.uCl('TT', ells)
ps = cls.reshape((1, 1, ells.size))
mg = maps.MapGen(cshape, cwcs, ps)
unlensed = mg.get_map()

hunlensed = enmap.enmap(resample.resample_fft(unlensed.copy(), fshape), fwcs)
hlensed = enlensing.displace_map(hunlensed,
                                 alpha_pix,
                                 order=lens_order,
                                 mode=mode)
lensed = enmap.enmap(resample.resample_fft(hlensed, cshape), cwcs)
Esempio n. 22
0
kamps = np.linspace(amin, amax, num_amps)

cinvs = []
logdets = []
for k, kamp in enumerate(kamps):

    kappa_template = lensing.nfw_kappa(kamp * 1e15,
                                       bmodrmap,
                                       cc,
                                       overdensity=200.,
                                       critical=True,
                                       atClusterZ=True)
    phi, _ = lensing.kappa_to_phi(kappa_template, bmodlmap, return_fphi=True)
    grad_phi = enmap.grad(phi)
    pos = posmap + grad_phi
    alpha_pix = enmap.sky2pix(bshape, bwcs, pos, safe=False)

    #if k==0: io.plot_img(kappa_template)

    with bench.show("lensing cov"):
        Scov = lensing.lens_cov(Ucov,
                                alpha_pix,
                                lens_order=lens_order,
                                kbeam=kbeam,
                                bshape=shape)

    Tcov = Scov + Ncov + 5000  # !!!
    with bench.show("covwork"):
        s, logdet = np.linalg.slogdet(Tcov)
        assert s > 0
        cinv = pinv2(Tcov).astype(np.float64)
Esempio n. 23
0
# We assume that site and pointing offsets are the same for all tods,
# so get them based on the first one
entry = filedb.data[ids[0]]
site  = actdata.read(entry, ["site"]).site

# Determine the bounding box of our selected data
bounds    = db.data["bounds"].reshape(2,-1).copy()
bounds[0] = utils.rewind(bounds[0], bounds[0,0], 360)
box = utils.widen_box(utils.bounding_box(bounds.T), 4*args.rad, relative=False)
waz, wel = box[1]-box[0]
# Use fullsky horizontally if we wrap too far
if waz <= 180:
	shape, wcs = enmap.geometry(pos=box[:,::-1]*utils.degree, res=args.res*utils.degree, proj="car", ref=(0,0))
else:
	shape, wcs = enmap.fullsky_geometry(res=args.res*utils.degree)
	y1, y2 = np.sort(enmap.sky2pix(shape, wcs, [box[:,1]*utils.degree,[0,0]])[0].astype(int))
	shape, wcs = enmap.slice_geometry(shape, wcs, (slice(y1,y2),slice(None)))

sys.stderr.write("using %s workspace with resolution %.2f deg" % (str(shape), args.res) + "\n")

# Get the hitmap for each block
hits = enmap.zeros((nblock,narray)+shape, wcs)
ndig = calc_ndig(nblock)
sys.stderr.write("estimating hitmap for block %*d/%d" % (ndig,0,nblock))
for bi in range(nblock):
	for ai in range(narray):
		block_db = db.select(block_inds[bi,ai])
		hits[bi,ai] = fastweight.fastweight(shape, wcs, block_db, array_rad=args.rad*utils.degree, site=site, weight=args.weight)
	sys.stderr.write("%s%*d/%d" % ("\b"*(1+2*ndig),ndig,bi+1,nblock))
sys.stderr.write("\n")
Esempio n. 24
0
	def __call__(self, hor):
		"""Transform from [{tsec,az,el},nsamp] to [{y,x,c,s},nsamp]"""
		res = hor2cel(hor, self.toff)
		res[:2] = enmap.sky2pix(self.shape, self.wcs, res[1::-1])
		return res
Esempio n. 25
0
norm = enmap.smooth_gauss(norm, rad)[0,0]

# Loop through slices and populate
bazs = []
for iaz in range(naz):
	# Get our boresight az
	bazs.append(imaps.pix2sky([0,iaz])[1])
	vals = []
	for i in range(nfile):
		# Go from detectors to y-pixel in input maps
		ypix = utils.transpose_inds(dets[i], nrow, ncol)
		vals.append(imaps[i,ypix,iaz])
	vals = np.concatenate(vals)
	pos  = np.concatenate(offs)
	# Write to appropriate position in array
	pix  = np.maximum(0,np.minimum((np.array(shape[-2:])-1)[:,None],enmap.sky2pix(shape, wcs, pos.T).astype(np.int32)))
	m    = enmap.zeros(shape[-2:],wcs)
	m[tuple(pix)] = vals
	# Grow by smoothing
	m = enmap.smooth_gauss(m, rad)/norm
	omap[iaz] = m

# Truncate very low values
refval = np.mean(np.abs(omap))*0.01
mask = np.any(np.abs(omap)>refval,0)
omap[:,~mask] = 0

if not args.individual:
	# output a single file
	enmap.write_map(args.ofile, omap)
else: