コード例 #1
0
ファイル: interp.py プロジェクト: plaplant/radionopy
def healpixellize(f_in, theta_in, phi_in, nside=16, verbose=False):
    '''
    A dumb method for converting data f sampled at points theta and phi
    (not on a healpix grid)
    into a healpix at resolution nside

    Parameters
    ----------
    f_in | array: square map
    theta_in | array: latitude to grid to
    phi_in | array in: longitude to grid to
    nside | Optional[int]: healpix value (IONEX maps give nside=16 natively)
    verbose | Optional[bool]: whether to print values and info or not

    Returns
    -------
    array: healpixellized version of square map input
    '''
    # Input arrays are likely to be rectangular, but this is inconvenient
    f = f_in.flatten()
    theta = theta_in.flatten()
    phi = phi_in.flatten()

    pix = hp.ang2pix(nside, theta, phi)

    hp_map = np.zeros(hp.nside2npix(nside))
    hits = np.zeros(hp.nside2npix(nside))

    for i, v in enumerate(f):
        # Find the nearest pixels to the pixel in question
        neighbours, weights = hp.get_interp_weights(nside, theta[i], phi[i])
        # Add weighted values to hp_map
        hp_map[neighbours] += v * weights
        # Keep track of weights
        hits[neighbours] += weights

    hp_map = hp_map / hits
    wh_no_hits = np.where(hits == 0)
    if verbose:
        print('pixels with no hits', wh_no_hits[0].shape)
    hp_map[wh_no_hits[0]] = hp.UNSEEN

    wh = np.where(hp_map == np.nan)[0]
    for i, w in enumerate(wh):
        neighbors = hp.get_interp_weights(nside, theta[i], phi[i])
        hp_map[w] = np.median(neighbors)

    return hp_map
コード例 #2
0
ファイル: interp.py プロジェクト: jaguirre/radionopy
def healpixellize(f_in, theta_in, phi_in, nside=16, verbose=False):
    '''
    A dumb method for converting data f sampled at points theta and phi
    (not on a healpix grid)
    into a healpix at resolution nside

    Parameters
    ----------
    f_in | array: square map
    theta_in | array: latitude to grid to
    phi_in | array in: longitude to grid to
    nside | Optional[int]: healpix value (IONEX maps give nside=16 natively)
    verbose | Optional[bool]: whether to print values and info or not

    Returns
    -------
    array: healpixellized version of square map input
    '''
    # Input arrays are likely to be rectangular, but this is inconvenient
    f = f_in.flatten()
    theta = theta_in.flatten()
    phi = phi_in.flatten()

    pix = hp.ang2pix(nside, theta, phi)

    hp_map = np.zeros(hp.nside2npix(nside))
    hits = np.zeros(hp.nside2npix(nside))

    for i, v in enumerate(f):
        # Find the nearest pixels to the pixel in question
        neighbours, weights = hp.get_interp_weights(nside, theta[i], phi[i])
        # Add weighted values to hp_map
        hp_map[neighbours] += v * weights
        # Keep track of weights
        hits[neighbours] += weights

    hp_map = hp_map / hits
    wh_no_hits = np.where(hits == 0)
    if verbose:
        print('pixels with no hits', wh_no_hits[0].shape)
    hp_map[wh_no_hits[0]] = hp.UNSEEN

    wh = np.where(hp_map == np.nan)[0]
    for i, w in enumerate(wh):
        neighbors = hp.get_interp_weights(nside, theta[i], phi[i])
        hp_map[w] = np.median(neighbors)

    return hp_map
コード例 #3
0
ファイル: mapsampler.py プロジェクト: ziotom78/toast
    def at(self, theta, phi, interp_pix=None, interp_weights=None):
        """
        Use healpy bilinear interpolation to interpolate the
        map.  User must make sure that coordinate system used
        for theta and phi matches the map coordinate system.
        """
        if self._map is None:
            raise RuntimeError("No temperature map to sample")

        n = len(theta)
        stepsize = self.buflen
        signal = np.zeros(n, dtype=np.float32)

        # DEBUG begin
        if np.any(theta < 0) or np.any(theta > np.pi):
            raise RuntimeError("bad theta")
        if np.any(phi < 0) or np.any(phi > 2 * np.pi):
            raise RuntimeError("bad phi")
        # DEBUG end

        for istart in range(0, n, stepsize):
            istop = min(istart + stepsize, n)
            ind = slice(istart, istop)
            if interp_pix is None or interp_weights is None:
                p, w = hp.get_interp_weights(self.nside,
                                             theta[ind],
                                             phi[ind],
                                             nest=self.nest)
            else:
                p = np.ascontiguousarray(interp_pix[:, ind])
                w = np.ascontiguousarray(interp_weights[:, ind])
            buf = np.zeros(istop - istart, dtype=np.float64)
            fast_scanning_float32(buf, p, w, self._map[:])
            signal[ind] = buf
        return signal
コード例 #4
0
ファイル: hpxnd.py プロジェクト: registerrier/gammapy
    def _get_interp_weights(self, coords, idxs):

        import healpy as hp

        c = MapCoords.create(coords)
        coords_ctr = list(coords[:2])
        coords_ctr += [ax.pix_to_coord(t)
                       for ax, t in zip(self.geom.axes, idxs)]
        pix_ctr = pix_tuple_to_idx(self.geom.coord_to_pix(coords_ctr))
        pix_ctr = self.geom.global_to_local(pix_ctr)

        if np.any(pix_ctr[0] == -1):
            raise ValueError('HPX pixel index out of map bounds.')

        theta = np.array(np.pi / 2. - np.radians(c.lat), ndmin=1)
        phi = np.array(np.radians(c.lon), ndmin=1)

        if self.geom.nside.size > 1:
            nside = self.geom.nside[idxs]
        else:
            nside = self.geom.nside

        pix, wts = hp.get_interp_weights(nside, theta,
                                         phi, nest=self.geom.nest)

        if self.geom.nside.size > 1:
            pix_local = [self.geom.global_to_local([pix] + list(idxs))[0]]
        else:
            pix_local = [self.geom[pix]]

        m = pix_local[0] == -1
        pix_local[0][m] = (pix_ctr[0] * np.ones(pix.shape, dtype=int))[m]

        return pix_local + list(idxs), wts
コード例 #5
0
    def probability(self, ra, dec, dist):
        """
        returns probability density at given ra, dec, dist
        p(ra,dec) * p(dist | ra,dec )
        RA, dec : radians
        dist : Mpc
        """
        theta = np.pi / 2.0 - dec
        # Step 1: find 4 nearest pixels
        (pixnums, weights) = \
            hp.get_interp_weights(self.nside, theta, ra,
                                  nest=self.nested, lonlat=False)

        dist_pdfs = [
            scipy.stats.norm(loc=self.mean[i], scale=self.sigma[i])
            for i in pixnums
        ]
        # Step 2: compute p(ra,dec)
        # p(ra, dec) = sum_i weight_i p(pixel_i)
        probvals = np.array([
            self.distnorm[i] * dist_pdfs[i].pdf(dist)
            for i, pixel in enumerate(pixnums)
        ])
        skyprob = self.prob[pixnums]
        p_ra_dec = np.sum(weights * probvals * skyprob)

        return (p_ra_dec)
コード例 #6
0
ファイル: zm_tools.py プロジェクト: jaguirre/polskysim
def healpixellize(f_in,theta_in,phi_in,nside,fancy=True):
    """ A dumb method for converting data f sampled at points theta and phi (not on a healpix grid) into a healpix at resolution nside """

    # Input arrays are likely to be rectangular, but this is inconvenient
    f = f_in.flatten()
    theta = theta_in.flatten()
    phi = phi_in.flatten()
    
    pix = hp.ang2pix(nside,theta,phi)

    map = np.zeros(hp.nside2npix(nside))
    hits = np.zeros(hp.nside2npix(nside))
    
    # Simplest gridding is map[pix] = val. This tries to do some
    #averaging Better would be to do some weighting by distance from
    #pixel center or something ...
    if (fancy):
        for i,v in enumerate(f):
            # Find the nearest pixels to the pixel in question
            neighbours,weights = hp.get_interp_weights(nside,theta[i],phi[i])
            # Add weighted values to map
            map[neighbours] += v*weights
            # Keep track of weights
            hits[neighbours] += weights
        map = map/hits
        wh_no_hits = np.where(hits == 0)
        print 'pixels with no hits',wh_no_hits[0].shape
        map[wh_no_hits[0]] = hp.UNSEEN
    else:    
        for i,v in enumerate(f):
            map[pix[i]] += v
            hits[pix[i]] +=1
        map = map/hits

    return map
コード例 #7
0
ファイル: geom.py プロジェクト: registerrier/gammapy
    def interp_weights(self, coords, idxs=None):
        """Get interpolation weights for given coords

        Parameters
        ----------
        coords : `MapCoord` or dict
            Input coordinates
        idxs : `~numpy.ndarray`
            Indices for non-spatial axes.

        Returns
        -------
        weights : `~numpy.ndarray`
            Interpolation weights
        """
        import healpy as hp

        coords = MapCoord.create(coords, frame=self.frame).broadcasted

        if idxs is None:
            idxs = self.coord_to_idx(coords, clip=True)[1:]

        theta, phi = coords.theta, coords.phi

        m = ~np.isfinite(theta)
        theta[m] = 0
        phi[m] = 0

        if not self.is_regular:
            nside = self.nside[tuple(idxs)]
        else:
            nside = self.nside

        pix, wts = hp.get_interp_weights(nside, theta, phi, nest=self.nest)
        wts[:, m] = 0
        pix[:, m] = INVALID_INDEX.int

        if not self.is_regular:
            pix_local = [self.global_to_local([pix] + list(idxs))[0]]
        else:
            pix_local = [self.global_to_local(pix, ravel=True)]

        # If a pixel lies outside of the geometry set its index to the center pixel
        m = pix_local[0] == INVALID_INDEX.int
        if m.any():
            coords_ctr = [coords.lon, coords.lat]
            coords_ctr += [
                ax.pix_to_coord(t) for ax, t in zip(self.axes, idxs)
            ]
            idx_ctr = self.coord_to_idx(coords_ctr)
            idx_ctr = self.global_to_local(idx_ctr)
            pix_local[0][m] = (idx_ctr[0] * np.ones(pix.shape, dtype=int))[m]

        pix_local += [np.broadcast_to(t, pix_local[0].shape) for t in idxs]
        return pix_local, wts
コード例 #8
0
ファイル: healpix.py プロジェクト: AaronParsons/aipy
 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
コード例 #9
0
ファイル: healpix.py プロジェクト: tamiratgebeyehu/aipy
 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
コード例 #10
0
ファイル: hpxnd.py プロジェクト: thomasarmstrong/gammapy
    def _get_interp_weights(self, coords, idxs):

        import healpy as hp

        c = MapCoord.create(coords)
        coords_ctr = list(coords[:2])
        coords_ctr += [
            ax.pix_to_coord(t) for ax, t in zip(self.geom.axes, idxs)
        ]
        idx_ctr = pix_tuple_to_idx(self.geom.coord_to_pix(coords_ctr))
        idx_ctr = self.geom.global_to_local(idx_ctr)

        theta = np.array(np.pi / 2. - np.radians(c.lat), ndmin=1)
        phi = np.array(np.radians(c.lon), ndmin=1)

        m = ~np.isfinite(theta)
        theta[m] = 0.0
        phi[m] = 0.0

        if self.geom.nside.size > 1:
            nside = self.geom.nside[idxs]
        else:
            nside = self.geom.nside

        pix, wts = hp.get_interp_weights(nside,
                                         theta,
                                         phi,
                                         nest=self.geom.nest)
        wts[:, m] = 0.0
        pix[:, m] = -1

        if not self.geom.is_regular:
            pix_local = [self.geom.global_to_local([pix] + list(idxs))[0]]
        else:
            pix_local = [self.geom[pix]]

        # If a pixel lies outside of the geometry set its index to the
        # center pixel
        m = pix_local[0] == -1
        pix_local[0][m] = (idx_ctr[0] * np.ones(pix.shape, dtype=int))[m]
        pix_local += [np.broadcast_to(t, pix_local[0].shape) for t in idxs]
        return pix_local, wts
コード例 #11
0
    def _get_interp_weights(self, coords, idxs=None):
        import healpy as hp

        if idxs is None:
            idxs = self.geom.coord_to_idx(coords, clip=True)[1:]

        theta, phi = coords.theta, coords.phi

        m = ~np.isfinite(theta)
        theta[m] = 0
        phi[m] = 0

        if not self.geom.is_regular:
            nside = self.geom.nside[tuple(idxs)]
        else:
            nside = self.geom.nside

        pix, wts = hp.get_interp_weights(nside,
                                         theta,
                                         phi,
                                         nest=self.geom.nest)
        wts[:, m] = 0
        pix[:, m] = INVALID_INDEX.int

        if not self.geom.is_regular:
            pix_local = [self.geom.global_to_local([pix] + list(idxs))[0]]
        else:
            pix_local = [self.geom[pix]]

        # If a pixel lies outside of the geometry set its index to the center pixel
        m = pix_local[0] == INVALID_INDEX.int
        if m.any():
            coords_ctr = [coords.lon, coords.lat]
            coords_ctr += [
                ax.pix_to_coord(t) for ax, t in zip(self.geom.axes, idxs)
            ]
            idx_ctr = self.geom.coord_to_idx(coords_ctr)
            idx_ctr = self.geom.global_to_local(idx_ctr)
            pix_local[0][m] = (idx_ctr[0] * np.ones(pix.shape, dtype=int))[m]

        pix_local += [np.broadcast_to(t, pix_local[0].shape) for t in idxs]
        return pix_local, wts
コード例 #12
0
ファイル: hpxnd.py プロジェクト: cdeil/gammapy
    def _get_interp_weights(self, coords, idxs):

        import healpy as hp

        c = MapCoord.create(coords)
        coords_ctr = list(coords[:2])
        coords_ctr += [ax.pix_to_coord(t)
                       for ax, t in zip(self.geom.axes, idxs)]
        idx_ctr = pix_tuple_to_idx(self.geom.coord_to_pix(coords_ctr))
        idx_ctr = self.geom.global_to_local(idx_ctr)

        theta = np.array(np.pi / 2. - np.radians(c.lat), ndmin=1)
        phi = np.array(np.radians(c.lon), ndmin=1)

        m = ~np.isfinite(theta)
        theta[m] = 0.0
        phi[m] = 0.0

        if self.geom.nside.size > 1:
            nside = self.geom.nside[idxs]
        else:
            nside = self.geom.nside

        pix, wts = hp.get_interp_weights(nside, theta,
                                         phi, nest=self.geom.nest)
        wts[:, m] = 0.0
        pix[:, m] = -1

        if not self.geom.is_regular:
            pix_local = [self.geom.global_to_local([pix] + list(idxs))[0]]
        else:
            pix_local = [self.geom[pix]]

        # If a pixel lies outside of the geometry set its index to the
        # center pixel
        m = pix_local[0] == -1
        pix_local[0][m] = (idx_ctr[0] * np.ones(pix.shape, dtype=int))[m]
        pix_local += [np.broadcast_to(t, pix_local[0].shape) for t in idxs]
        return pix_local, wts
コード例 #13
0
ファイル: hpxnd.py プロジェクト: gallanty/gammapy
    def _get_interp_weights(self, coords, idxs):

        import healpy as hp

        c = MapCoords.create(coords)
        coords_ctr = list(coords[:2])
        coords_ctr += [
            ax.pix_to_coord(t) for ax, t in zip(self.geom.axes, idxs)
        ]
        pix_ctr = pix_tuple_to_idx(self.geom.coord_to_pix(coords_ctr))
        pix_ctr = self.geom.global_to_local(pix_ctr)

        if np.any(pix_ctr[0] == -1):
            raise ValueError('HPX pixel index out of map bounds.')

        theta = np.array(np.pi / 2. - np.radians(c.lat), ndmin=1)
        phi = np.array(np.radians(c.lon), ndmin=1)

        if self.geom.nside.size > 1:
            nside = self.geom.nside[idxs]
        else:
            nside = self.geom.nside

        pix, wts = hp.get_interp_weights(nside,
                                         theta,
                                         phi,
                                         nest=self.geom.nest)

        if self.geom.nside.size > 1:
            pix_local = [self.geom.global_to_local([pix] + list(idxs))[0]]
        else:
            pix_local = [self.geom[pix]]

        m = pix_local[0] == -1
        pix_local[0][m] = (pix_ctr[0] * np.ones(pix.shape, dtype=int))[m]

        return pix_local + list(idxs), wts
コード例 #14
0
def healpixellize(f_in, theta_in, phi_in, nside, fancy=True, verbose=False):
    """ A dumb method for converting data f sampled at points theta and phi (not on a healpix grid) into a healpix at resolution nside """

    # Input arrays are likely to be rectangular, but this is inconvenient
    f = f_in.flatten()
    theta = theta_in.flatten()
    phi = phi_in.flatten()

    pix = hp.ang2pix(nside, theta, phi)

    map = np.zeros(hp.nside2npix(nside))
    hits = np.zeros(hp.nside2npix(nside))

    # Simplest gridding is map[pix] = val. This tries to do some
    #averaging Better would be to do some weighting by distance from
    #pixel center or something ...
    if (fancy):
        for i, v in enumerate(f):
            # Find the nearest pixels to the pixel in question
            neighbours, weights = hp.get_interp_weights(
                nside, theta[i], phi[i])
            # Add weighted values to map
            map[neighbours] += v * weights
            # Keep track of weights
            hits[neighbours] += weights
        map = map / hits
        wh_no_hits = np.where(hits == 0)
        #print 'pixels with no hits',wh_no_hits[0].shape
        map[wh_no_hits[0]] = hp.UNSEEN
    else:
        for i, v in enumerate(f):
            map[pix[i]] += v
            hits[pix[i]] += 1
        map = map / hits
    if verbose:
        print 'Healpixellization successful.'
    return map
コード例 #15
0
ファイル: hpxnd.py プロジェクト: adonath/gammapy
    def _get_interp_weights(self, coords, idxs=None):
        import healpy as hp

        if idxs is None:
            idxs = self.geom.coord_to_idx(coords, clip=True)[1:]

        theta, phi = coords.theta, coords.phi

        m = ~np.isfinite(theta)
        theta[m] = 0
        phi[m] = 0

        if not self.geom.is_regular:
            nside = self.geom.nside[tuple(idxs)]
        else:
            nside = self.geom.nside

        pix, wts = hp.get_interp_weights(nside, theta, phi, nest=self.geom.nest)
        wts[:, m] = 0
        pix[:, m] = INVALID_INDEX.int

        if not self.geom.is_regular:
            pix_local = [self.geom.global_to_local([pix] + list(idxs))[0]]
        else:
            pix_local = [self.geom[pix]]

        # If a pixel lies outside of the geometry set its index to the center pixel
        m = pix_local[0] == INVALID_INDEX.int
        if m.any():
            coords_ctr = [coords.lon, coords.lat]
            coords_ctr += [ax.pix_to_coord(t) for ax, t in zip(self.geom.axes, idxs)]
            idx_ctr = self.geom.coord_to_idx(coords_ctr)
            idx_ctr = self.geom.global_to_local(idx_ctr)
            pix_local[0][m] = (idx_ctr[0] * np.ones(pix.shape, dtype=int))[m]

        pix_local += [np.broadcast_to(t, pix_local[0].shape) for t in idxs]
        return pix_local, wts
コード例 #16
0
ファイル: mapsampler.py プロジェクト: hpc4cmb/toast
    def at(self, theta, phi, interp_pix=None, interp_weights=None):
        """
        Use healpy bilinear interpolation to interpolate the
        map.  User must make sure that coordinate system used
        for theta and phi matches the map coordinate system.
        """
        autotimer = timing.auto_timer(type(self).__name__)

        if self._map is None:
            raise RuntimeError('No temperature map to sample')

        n = len(theta)
        stepsize = self.buflen
        signal = np.zeros(n, dtype=np.float32)

        # DEBUG begin
        if np.any(theta < 0) or np.any(theta > np.pi):
            raise RuntimeError('bad theta')
        if np.any(phi < 0) or np.any(phi > 2 * np.pi):
            raise RuntimeError('bad phi')
        # DEBUG end

        for istart in range(0, n, stepsize):
            istop = min(istart + stepsize, n)
            ind = slice(istart, istop)
            if interp_pix is None or interp_weights is None:
                p, w = hp.get_interp_weights(self.nside, theta[ind], phi[ind],
                                             nest=self.nest)
            else:
                p = np.ascontiguousarray(interp_pix[:, ind])
                w = np.ascontiguousarray(interp_weights[:, ind])
            buf = np.zeros(istop - istart, dtype=np.float64)
            fast_scanning32(buf, p, w, self._map[:])
            signal[ind] = buf
        del autotimer
        return signal
コード例 #17
0
ファイル: readmap.py プロジェクト: UPennEoR/polskysim
hp.orthview(UT22,
            rot=[0, 90],
            max=2,
            unit=r'rad m$^{-1}$',
            title='SAST 00:00 2012-02-13',
            half_sky=True)
#pylab.show()
print UT22
print 'Interpolating NaNs'
UT22_interp = np.zeros_like(UT22)
c = 0
for i, val in enumerate(UT22):
    if np.isnan(val):
        c += 1
        theta, phi = hp.pix2ang(nside, i)
        neybs = hp.get_interp_weights(nside, theta, phi=phi)

        v = np.nanmean(UT22[neybs[0]])
        UT22_interp[i] = v

    else:
        UT22_interp[i] = val
print c, 'NaN vals'
hp.orthview(UT22_interp,
            rot=[0, 90],
            min=0,
            max=2,
            unit=r'rad m$^{-1}$',
            title='SAST 00:00 2012-02-13',
            half_sky=True)
#pylab.show()
コード例 #18
0
ファイル: mapsampler.py プロジェクト: ziotom78/toast
    def atpol(
        self,
        theta,
        phi,
        IQUweight,
        onlypol=False,
        interp_pix=None,
        interp_weights=None,
        pol=True,
        pol_deriv=False,
    ):
        """
        Use healpy bilinear interpolation to interpolate the
        map.  User must make sure that coordinate system used
        for theta and phi matches the map coordinate system.
        IQUweight is an array of shape (nsamp,3) returned by the
        pointing library that gives the weights of the I,Q, and U maps.

        Args:
            pol_deriv(bool):  Return the polarization angle derivative
                of the signal instead of the actual signal.

        """
        if onlypol and not self.pol:
            return None

        if not self.pol or not pol:
            return self.at(theta,
                           phi,
                           interp_pix=interp_pix,
                           interp_weights=interp_weights)

        if np.shape(IQUweight)[1] != 3:
            raise RuntimeError("Cannot sample polarized map with only "
                               "intensity weights")

        n = len(theta)
        stepsize = self.buflen
        signal = np.zeros(n, dtype=np.float32)

        for istart in range(0, n, stepsize):
            istop = min(istart + stepsize, n)
            ind = slice(istart, istop)

            if interp_pix is None or interp_weights is None:
                p, w = hp.get_interp_weights(self.nside,
                                             theta[ind],
                                             phi[ind],
                                             nest=self.nest)
            else:
                p = np.ascontiguousarray(interp_pix[:, ind])
                w = np.ascontiguousarray(interp_weights[:, ind])

            weights = np.ascontiguousarray(IQUweight[ind].T)

            buf = np.zeros(istop - istart, dtype=np.float64)
            fast_scanning_float32(buf, p, w, self._map_Q[:])
            if pol_deriv:
                signal[ind] = -2 * weights[2] * buf
            else:
                signal[ind] = weights[1] * buf

            buf[:] = 0
            fast_scanning_float32(buf, p, w, self._map_U[:])
            if pol_deriv:
                signal[ind] += 2 * weights[1] * buf
            else:
                signal[ind] += weights[2] * buf

            if not onlypol:
                if self._map is None:
                    raise RuntimeError("No temperature map to sample")
                buf[:] = 0
                fast_scanning_float32(buf, p, w, self._map[:])
                signal[ind] += weights[0] * buf

        return signal
コード例 #19
0
ファイル: mapsampler.py プロジェクト: hpc4cmb/toast
    def atpol(self, theta, phi, IQUweight, onlypol=False,
              interp_pix=None, interp_weights=None, pol=True,
              pol_deriv=False):
        """
        Use healpy bilinear interpolation to interpolate the
        map.  User must make sure that coordinate system used
        for theta and phi matches the map coordinate system.
        IQUweight is an array of shape (nsamp,3) returned by the
        pointing library that gives the weights of the I,Q, and U maps.

        Args:
            pol_deriv(bool):  Return the polarization angle derivative
                of the signal instead of the actual signal.

        """
        autotimer = timing.auto_timer(type(self).__name__)

        if onlypol and not self.pol:
            return None

        if not self.pol or not pol:
            return self.at(theta, phi, interp_pix=interp_pix,
                           interp_weights=interp_weights)

        if np.shape(IQUweight)[1] != 3:
            raise RuntimeError('Cannot sample polarized map with only '
                               'intensity weights')

        n = len(theta)
        stepsize = self.buflen
        signal = np.zeros(n, dtype=np.float32)

        for istart in range(0, n, stepsize):
            istop = min(istart + stepsize, n)
            ind = slice(istart, istop)

            if interp_pix is None or interp_weights is None:
                p, w = hp.get_interp_weights(self.nside, theta[ind], phi[ind],
                                             nest=self.nest)
            else:
                p = np.ascontiguousarray(interp_pix[:, ind])
                w = np.ascontiguousarray(interp_weights[:, ind])

            weights = np.ascontiguousarray(IQUweight[ind].T)

            buf = np.zeros(istop - istart, dtype=np.float64)
            fast_scanning32(buf, p, w, self._map_Q[:])
            if pol_deriv:
                signal[ind] = -2 * weights[2] * buf
            else:
                signal[ind] = weights[1] * buf

            buf[:] = 0
            fast_scanning32(buf, p, w, self._map_U[:])
            if pol_deriv:
                signal[ind] += 2 * weights[1] * buf
            else:
                signal[ind] += weights[2] * buf

            if not onlypol:
                if self._map is None:
                    raise RuntimeError('No temperature map to sample')
                buf[:] = 0
                fast_scanning32(buf, p, w, self._map[:])
                signal[ind] += weights[0] * buf

        del autotimer
        return signal
コード例 #20
0
def convert_to_healpix(theta, phi, gains, nside=32, interp_method='spline', gainunit_in='dB', gainunit_out=None, angunits='radians'):
    try:
        theta, phi, gains
    except NameError:
        raise NameError('Inputs theta, phi and gains must be specified')
    if not HP.isnsideok(nside):
        raise ValueError('Specified nside invalid')
    if not isinstance(interp_method, str):
        raise TypeError('Input interp_method must be a string')
    if interp_method not in ['spline', 'nearest', 'healpix']:
        raise valueError('Input interp_method value specified is invalid')
    if gains.shape == (theta.size, phi.size):
        gridded = True
    elif (gains.size == theta.size) and (gains.size == phi.size):
        gridded = False
    else:
        raise ValueError('Inputs theta, phi and gains have incompatible dimensions')
    
    if angunits.lower() == 'degrees':
        theta = NP.radians(theta)
        phi = NP.radians(phi)

    phi = NP.angle(NP.exp(1j*phi)) # Bring all phi in [-pi,pi] range
    phi[phi<0.0] += 2*NP.pi # Bring all phi in [0, 2 pi] range

    hmap = NP.empty(HP.nside2npix(nside))
    wtsmap = NP.empty(HP.nside2npix(nside))
    hmap.fill(NP.nan)
    wtsmap.fill(NP.nan)
    
    if interp_method == 'spline':
        if gainunit_in.lower() != 'db':
            gains = 10.0 * NP.log10(gains)
        hpxtheta, hpxphi = HP.pix2ang(nside, NP.arange(HP.nside2npix(nside)))

        # Find the in-bound and out-of-bound indices to handle the boundaries
        inb = NP.logical_and(NP.logical_and(hpxtheta>=theta.min(), hpxtheta<=theta.max()), NP.logical_and(hpxphi>=phi.min(), hpxphi<=phi.max()))
        pub = hpxphi < phi.min()
        pob = hpxphi > phi.max()
        oob = NP.logical_not(inb)
        inb_ind = NP.where(inb)[0]
        oob_ind = NP.where(oob)[0]
        pub_ind = NP.where(pub)[0]
        pob_ind = NP.where(pob)[0]

        # Perform regular interpolation in in-bound indices
        if NP.any(inb):
            if gridded:
                interp_func = interpolate.RectBivariateSpline(theta, phi, gains)
                hmap[inb_ind] = interp_func.ev(hpxtheta[inb_ind], hpxphi[inb_ind])
            else:
                # interp_func = interpolate.interp2d(theta, phi, gains, kind='cubic')
                # hmap = interp_func(hpxtheta, hpxphi)
                hmap[inb_ind] = interpolate.griddata(NP.hstack((theta.reshape(-1,1),phi.reshape(-1,1))), gains, NP.hstack((hpxtheta[inb_ind].reshape(-1,1),hpxphi[inb_ind].reshape(-1,1))), method='cubic')
        if NP.any(pub): # Under bound at phi=0
            phi[phi>NP.pi] -= 2*NP.pi # Bring oob phi in [-pi, pi] range
            if gridded:
                interp_func = interpolate.RectBivariateSpline(theta, phi, gains)
                hmap[pub_ind] = interp_func.ev(hpxtheta[pub_ind], hpxphi[pub_ind])
            else:
                # interp_func = interpolate.interp2d(theta, phi, gains, kind='cubic')
                # hmap = interp_func(hpxtheta, hpxphi)
                hmap[pub_ind] = interpolate.griddata(NP.hstack((theta.reshape(-1,1),phi.reshape(-1,1))), gains, NP.hstack((hpxtheta[pub_ind].reshape(-1,1),hpxphi[pub_ind].reshape(-1,1))), method='cubic')
        if NP.any(pob): # Over bound at phi=2 pi
            phi[phi<0.0] += 2*NP.pi # Bring oob phi in [0, 2 pi] range
            phi[phi<NP.pi] += 2*NP.pi # Bring oob phi in [pi, 3 pi] range
            if gridded:
                interp_func = interpolate.RectBivariateSpline(theta, phi, gains)
                hmap[pob_ind] = interp_func.ev(hpxtheta[pob_ind], hpxphi[pob_ind])
            else:
                # interp_func = interpolate.interp2d(theta, phi, gains, kind='cubic')
                # hmap = interp_func(hpxtheta, hpxphi)
                hmap[pob_ind] = interpolate.griddata(NP.hstack((theta.reshape(-1,1),phi.reshape(-1,1))), gains, NP.hstack((hpxtheta[pob_ind].reshape(-1,1),hpxphi[pob_ind].reshape(-1,1))), method='cubic')

        hmap -= NP.nanmax(hmap)
        if gainunit_out.lower() != 'db':
            hmap = 10**(hmap/10)
    else:
        if gainunit_in.lower() == 'db':
            gains = 10**(gains/10.0)
        if gridded:
            phi_flattened, theta_flattened = NP.meshgrid(phi, theta)
            theta_flattened = theta_flattened.flatten()
            phi_flattened = phi_flattened.flatten()
            gains = gains.flatten()
        else:
            theta_flattened = theta
            phi_flattened = phi
        if interp_method == 'healpix':
            ngbrs, wts = HP.get_interp_weights(nside, theta_flattened, phi=phi_flattened)
            gains4 = gains.reshape(1,-1) * NP.ones(ngbrs.shape[0]).reshape(-1,1)
            wtsmap, be, bn, ri = OPS.binned_statistic(ngbrs.ravel(), values=wts.ravel(), statistic='sum', bins=NP.arange(HP.nside2npix(nside)+1))
            hmap, be, bn, ri = OPS.binned_statistic(ngbrs.ravel(), values=(wts*gains4).ravel(), statistic='sum', bins=NP.arange(HP.nside2npix(nside)+1))
        else: # nearest neighbour
            ngbrs = HP.ang2pix(nside, theta_flattened, phi_flattened)
            wtsmap, be, bn, ri = OPS.binned_statistic(ngbrs.ravel(), statistic='count', bins=NP.arange(HP.nside2npix(nside)+1))
            hmap, be, bn, ri = OPS.binned_statistic(ngbrs.ravel(), values=gains.ravel(), statistic='sum', bins=NP.arange(HP.nside2npix(nside)+1))

        ind_nan = NP.isnan(wtsmap)
        other_nanind = wtsmap < 1e-12
        ind_nan = ind_nan | other_nanind
        wtsmap[ind_nan] = NP.nan
        hmap /= wtsmap
        hmap /= NP.nanmax(hmap)
        if gainunit_out.lower() == 'db':
            hmap = 10.0 * NP.log10(hmap)
    ind_nan = NP.isnan(hmap)
    hmap[ind_nan] = HP.UNSEEN

    return hmap