Esempio n. 1
0
def get_los_tec(tec_hp, rms_hp, coord_lat, coord_lon, zen_punct):
    '''
    finds the LoS TEC on a given healpix map

    Parameters
    ----------
    tec_hp | array: tec healpix map
    rms_hp | array: rms tec healpix map
    coord_lat | array[float]: array of latitudes
    coord_lon | array[float]: array of longitudes
    zen_punct | array: array of zenith puncture points

    Returns
    -------
    tuple:
        array: space interpolated TEC map
        array: space interpolated RMS TEC map
    '''
    lat_rad = np.radians(90. - coord_lat)
    lon_rad = np.radians(coord_lon % 360)
    VTEC = hp.get_interp_val(tec_hp, lat_rad, lon_rad)
    VRMS_TEC = hp.get_interp_val(rms_hp, lat_rad, lon_rad)

    TEC_path = np.array(VTEC) * TEC2m2 / np.cos(
        zen_punct)  # from vertical TEC to line of sight TEC
    RMS_TEC_path = np.array(VRMS_TEC) * TEC2m2 / np.cos(
        zen_punct)  # from vertical RMS_TEC to line of sight RMS_TEC

    return TEC_path, RMS_TEC_path
Esempio n. 2
0
def get_los_tec(tec_hp, rms_hp, coord_lat, coord_lon, zen_punct):
    '''
    finds the LoS TEC on a given healpix map

    Parameters
    ----------
    tec_hp | array: tec healpix map
    rms_hp | array: rms tec healpix map
    coord_lat | array[float]: array of latitudes
    coord_lon | array[float]: array of longitudes
    zen_punct | array: array of zenith puncture points

    Returns
    -------
    tuple:
        array: space interpolated TEC map
        array: space interpolated RMS TEC map
    '''
    lat_rad = np.radians(90. - coord_lat)
    lon_rad = np.radians(coord_lon % 360)
    VTEC = hp.get_interp_val(tec_hp, lat_rad, lon_rad)
    VRMS_TEC = hp.get_interp_val(rms_hp, lat_rad, lon_rad)

    TEC_path = np.array(VTEC) * TEC2m2 / np.cos(zen_punct) # from vertical TEC to line of sight TEC
    RMS_TEC_path = np.array(VRMS_TEC) * TEC2m2 / np.cos(zen_punct) # from vertical RMS_TEC to line of sight RMS_TEC

    return TEC_path, RMS_TEC_path
Esempio n. 3
0
    def gpower_integrand(self, theta, phi):

        wavelength = 299.9 / self.frequency
        if (phi == 0): phi = 0.00001
        if (phi == np.pi): phi = np.pi - 0.00001

        self.aa.alt = np.pi / 2.0 - theta
        self.aa.az = np.pi / 2.0 - phi

        coords = self.aa.raDec(self.__lst_current, self.location)
        if self.haslam:
            coords = self.Rotator(np.pi / 2 - coords.dec,
                                  coords.ra)  #if Haslam

        if self.haslam:
            Tsky = hp.get_interp_val(self.hpmap, coords[0], coords[1]) * (
                self.frequency / 408.0)**(-2.55)  #if Haslam
        else:
            Tsky = hp.get_interp_val(self.hpmap, coords.ra, coords.dec)

        ans = self.lofasm.beam_pattern(theta, phi, [0, 0, 1])
        ans += self.lofasm.beam_pattern(theta, phi, [0, 1, 0])
        ans *= (Tsky * (1.380e-23) / wavelength**2) / (1e-26) / 2.0

        return ans
Esempio n. 4
0
def rotate_map_spin_eul(hmap, eulAngle):
    """Take hmap (a healpix map array) and return another healpix map array
    which is ordered such that it has been rotated in (theta, phi) by the
    amounts given.

    Parameters:
    -----------
    hmap - healPy map list
        hmap[0] - healPy map corresponding to theta
        hmap[1] - healPy map corresponding to phi
    eulAngle - euler Angle

    Returns:
    --------
    (rot_map0, rot_map1)
    rot_map0 - healPy map
        rotated map corresponding to theta
    rot_map1 - healPy map
        rotated map corresponding to phi
    """
    npix = len(hmap[0])
    nside = hp.npix2nside(npix)

    # Get theta, phi for non-rotated map
    theta, phi = hp.pix2ang(nside, np.arange(npix))
    costh, cosph = np.cos(theta), np.cos(phi)
    sinth, sinph = np.sin(theta), np.sin(phi)
    vth = np.array([costh * cosph, costh * sinph, -sinth])
    vph = np.array([-sinph, cosph, 0.0 * cosph])

    r = hp.rotator.Rotator(eulAngle, deg=False, eulertype='zxz')

    # Get theta, phi under rotated co-ordinates
    theta_rot, phi_rot = r(theta, phi)
    costh_rot, cosph_rot = np.cos(theta_rot), np.cos(phi_rot)
    sinth_rot, sinph_rot = np.sin(theta_rot), np.sin(phi_rot)
    vth_rot = np.array(
        [costh_rot * cosph_rot, costh_rot * sinph_rot, -sinth_rot])
    vph_rot = np.array([-sinph_rot, cosph_rot, 0.0 * cosph_rot])

    rot_mat = R.from_euler('zxz', eulAngle).as_dcm()
    vth_rot = vth_rot.transpose().dot(rot_mat).transpose()
    vph_rot = vph_rot.transpose().dot(rot_mat).transpose()

    # Interpolate map onto these co-ordinates
    rot_map0temp = hp.get_interp_val(hmap[0], theta_rot, phi_rot)
    rot_map1temp = hp.get_interp_val(hmap[1], theta_rot, phi_rot)

    # Obtaining the rotated maps
    rot_map0 = ((vth * vph_rot).sum(axis=0) * rot_map0temp +
                (vph * vph_rot).sum(axis=0) * rot_map1temp)

    rot_map1 = ((vth * vth_rot).sum(axis=0) * rot_map0temp +
                (vph * vth_rot).sum(axis=0) * rot_map1temp)

    return rot_map0, rot_map1
Esempio n. 5
0
 def displace_objects(self, theta, phi):
     dtheta = hp.get_interp_val(self.dpsi_dtheta, theta, phi)
     dphi = hp.get_interp_val(self.dpsi_dphi, theta, phi)
     dd = np.sqrt(dtheta**2 + dphi**2)
     alpha = np.arctan2(dphi, dtheta)
     ## Equation A15 from 0502469
     thetap = np.arccos(
         np.cos(dd) * np.cos(theta) -
         np.sin(dd) * np.sin(theta) * np.cos(alpha))
     phip = phi + np.arcsin(np.sin(alpha) * np.sin(dd) / np.sin(thetap))
     return thetap, phip
Esempio n. 6
0
 def test_beam_relative_amplitudes(self):
     Nside = 64
     # Keep beams at 0,0 otherwise have to worry about x,y <-> theta, phi conversion
     params_1 = [1, 0, 0, 0.1, 0.1, 1]
     params_2 = [2, 0, 0, 0.1, 0.1, 1]
     beammap_1 = gm.make_beam_map(params=params_1, nside=Nside)
     beammap_2 = gm.make_beam_map(params=params_2, nside=Nside)
     # Compare peaks near center
     peak_1 = hp.get_interp_val(beammap_1, 0, 0)
     peak_2 = hp.get_interp_val(beammap_2, 0, 0)
     self.assertTrue(peak_2 > peak_1)
Esempio n. 7
0
def TestErrorVsPSFext():
    PSFErrors = []
    PSFextFactors = np.arange(1, 10, .5)
    for extFactor in PSFextFactors:
        resultsDirectory = Mapmaker(mainDirectory,
                                    PSFextensionBeyondFacetFactor=extFactor,
                                    simulateVisibilitiesWithGSM=True,
                                    simulateVisibilitiesWithPointSources=True)
        s, times, ps, Dmatrix, PSF, coaddedMap, pointSourcePSF = MapMats.loadAllResults(
            resultsDirectory)
        convolvedPointSources = np.dot(pointSourcePSF, ps.scaledFluxes)
        if s.GSMNSIDE < s.mapNSIDE:
            s.GSMNSIDE = s.mapNSIDE
        coordsGSM = Geometry.Coordinates(s, useAnotherResolution=s.GSMNSIDE)
        coords = Geometry.Coordinates(s)
        GSM = GlobalSkyModel(s.freq, s.GSMlocation, s.GSMNSIDE)
        interpoltedGSMRotated = hp.get_interp_val(
            GSM.hpMap, -coordsGSM.galCoords.b.radian + np.pi / 2,
            np.asarray(coordsGSM.galCoords.l.radian))
        convolvedGSM = np.dot(PSF, interpoltedGSMRotated[coords.PSFIndices])
        PSFErrors.append(
            np.linalg.norm(coaddedMap - convolvedPointSources - convolvedGSM) /
            np.linalg.norm(convolvedPointSources + convolvedGSM))
    plt.figure()
    plt.semilogy(PSFextFactors, PSFErrors)
    plt.xlabel('PSF Size Relative to Facet Size')
    plt.ylabel('PSF Convolution vs. Mapmaking Error')
Esempio n. 8
0
def get_skytemp(gal_long, gal_lat, freq=HASLAM_FREQ, index=SYNCHROTRON_INDEX):
    """Given galactic longitude, latitude and observing
        frequency return the sky temperature in Kelvin
        using the Haslam et al. map.

        Notes: * galactic longitude and latitude should be 
                  provided in degrees.
               * frequency should be provided in MHz.
        
        Optional argument:
        index: synchrotron spectrum index
    """

    global HASLAM_MAP
    if HASLAM_MAP is None:
        read_map()

    # Theta and Phi angles defined as expected by healpy
    # Theta and Phi are given expected by healpy in radians
    # In (theta, phi) the centre of Galaxy is (pi/2, 0)
    theta = (90.0 - gal_lat) * DEGTORAD
    phi = (gal_long) * DEGTORAD

    # get value from map
    temp_408 = healpy.get_interp_val(HASLAM_MAP, theta, phi)

    # Adjust temperatures for given observing frequency
    temp_obs = change_obsfreq(temp=temp_408, oldfreq=HASLAM_FREQ, \
                                newfreq=freq, index=index)

    return temp_obs
Esempio n. 9
0
    def get_zeropoint_offset(self, band, ra, dec, interpolate=True):
        '''
        Inputs: band {g,r,i,z,Y}, arrays for ra (deg), dec (deg)
        Return: array of zeropoint offsets to be added
        Note: returns 99 for bad fits outside region
        '''

        # get band index
        bind,=np.where(band.upper() == self.bands)
        if (bind.size == 0):
            self._Print("Error: could not find band %s in list of bands %s" % (band.upper(), str(self.bands)), level='warning')
            return np.zeros(ra.size,dtype=np.float32) + 99.0
        bind=bind[0]
        
        # get theta/phi
        theta = np.radians(90.0-dec)
        phi = np.radians(ra)

        # interpolate zeropoints (if necessary)
        if (interpolate):
            # use masked array here...
            m=np.ma.array(self.shiftmap[bind,:],mask=(self.shiftmap[bind,:] == hp.UNSEEN))
            zp_shift = np.ma.filled(hp.get_interp_val(m,theta,phi),hp.UNSEEN)
        else :
            pix = hp.ang2pix(self.nside, theta, phi)
            zp_shift = self.shiftmap[bind,pix]

        bd,=np.where(np.abs(zp_shift) > 10.0)
        if (bd.size > 0):
            zp_shift[bd] = 99.0

        return zp_shift
Esempio n. 10
0
    def run_background_trials(self, month=None, ntrials=1000):
        if month is None:
            # month = datetime.datetime.utcnow().month
            month = Time(self.centertime, format='mjd').datetime.month

        bg_trial_dir = '/data/ana/analyses/NuSources/' \
            + '2021_v2_alert_stacking_FRA/fast_response/gw_precomputed_trials/'
        pre_ts_array = np.load(f'{bg_trial_dir}ts_map_{month:02d}.npy',
                               allow_pickle=True,
                               encoding='latin1')

        # Create spatial prior weighting
        max_ts = []
        ts_norm = np.log(np.amax(self.skymap))
        for i in range(pre_ts_array.size):
            # If a particular scramble in the pre-computed ts_array is empty,
            #that means that sky scan had no events in the sky, so max_ts=0
            if pre_ts_array[i]['ts'].size == 0:
                max_ts.append(-1 * np.inf)
            else:
                theta, ra = hp.pix2ang(512, pre_ts_array[i]['pixel'])
                interp = hp.get_interp_val(self.skymap, theta, ra)
                interp[interp < 0] = 0.
                ts_prior = pre_ts_array[i]['ts'] + 2 * (np.log(interp) -
                                                        ts_norm)
                max_ts.append(ts_prior.max())

        max_ts = np.array(max_ts)
        self.tsd = max_ts
        return max_ts
Esempio n. 11
0
def rotate_jones(j, rotmat, multiway=True):
    """
    Rotates the scalar components of a complex-valued 2x2 matrix field, relative
    to the Healpix coordinate frame.
    """
    if multiway == True:
        j = flatten_jones(j)

    npix = len(j[:,0])
    nside = hp.npix2nside(npix)
    hpxidx = np.arange(npix)
    c, a = hp.pix2ang(nside, hpxidx)

    t, p = rotate_sphr_coords(rotmat, c, a)

    intp = lambda m: hp.get_interp_val(m, t, p)

    # This is the fastest by ~2%. 99.1ms vs 101ms for the loop. (at nside=2**6)
    # ...totally worth it!
    jones = (np.asarray(map(intp,j.T))).T

    # 101ms
    # jR = np.empty_like(j)
    # for i in range(8):
    #     jR[:,i] = intp(j[:,i])

    # 102ms SO SLOW WTF NUMPY?
    #jR = np.apply_along_axis(intp, 0, j)
    # ahem. apparently this is just synactic sugar

    if multiway == True:
        jones = inverse_flatten_jones(jones)

    return jones
Esempio n. 12
0
def _interpolate_level(m):
    """Recursive multi-resolution interpolation. Modifies `m` in place."""
    # Determine resolution.
    npix = len(m)

    if npix > 12:
        # Determine which pixels comprise multi-pixel tiles.
        ipix = np.flatnonzero(
            (m[0::4] == m[1::4]) &
            (m[0::4] == m[2::4]) &
            (m[0::4] == m[3::4]))

        if len(ipix):
            ipix = (4 * ipix +
                np.expand_dims(np.arange(4, dtype=np.intp), 1)).T.ravel()

            nside = hp.npix2nside(npix)

            # Downsample.
            m_lores = hp.ud_grade(
                m, nside // 2, order_in='NESTED', order_out='NESTED')

            # Interpolate recursively.
            _interpolate_level(m_lores)

            # Record interpolated multi-pixel tiles.
            m[ipix] = hp.get_interp_val(
                m_lores, *hp.pix2ang(nside, ipix, nest=True), nest=True)
Esempio n. 13
0
 def query_local_map(self, dustmap='sfd'):
     """Query one of the local map."""
     nest = True if dustmap in ['green'] else False
     if dustmap not in self.loaded_maps:
         self._load_maps(dustmap)
     return healpy.get_interp_val(self.loaded_maps[dustmap]['map'],
                                  self.theta, self.phi, nest=nest)
Esempio n. 14
0
    def addZeropoint(self, filter, ra, dec, mag, interpolate=True, plot=False):
        '''
        Inputs: filter name {g, r, i, z}, arrays for ra (deg), dec (deg), and magnitude
        Return: array of corrected magnitudes, array quality flag
        Note: uses median fitted zeropoint shift for objects having (rad, dec) outside fitted or periphery pixels
        '''
        pix = healpy.ang2pix(self.nside, numpy.radians(90. - dec),
                             numpy.radians(ra))

        # Interpolate zeropoints
        if interpolate:
            zeropoint_shift = healpy.get_interp_val(
                self.zeropoint_shiftmap.data.field(filter),
                numpy.radians(90. - dec), numpy.radians(ra))
        else:
            zeropoint_shift = self.zeropoint_shiftmap.data.field(filter)[pix]

        # Quality flag
        quality_flag = self.zeropoint_shiftmap.data.field('n_des')[pix]
        quality_flag[quality_flag > 0] = 0
        quality_flag[quality_flag < 0] = 2
        if self.fill_periphery:
            quality_flag[numpy.logical_and(
                quality_flag == 2,
                numpy.fabs(zeropoint_shift) <= 10.)] = 1

        # Use median zeropoint shift for objects outside interpolated region
        median_fitted_zeropoint_shift = numpy.median(
            zeropoint_shift[numpy.fabs(zeropoint_shift) <= 10.])
        zeropoint_shift[
            numpy.fabs(zeropoint_shift) > 10.] = median_fitted_zeropoint_shift

        return mag + zeropoint_shift, quality_flag
Esempio n. 15
0
    def transformed_to(self, coordsystem):
        """
        Transforms the skymap to another coordinate system

        If initial and target coordinate systems have the same type, the reference
        time of the coordinate system is the only parameter that is changed.
        """

        if self.coordsystem.has_same_type_as(coordsystem):
            return Skymap.like(self, coordsystem=coordsystem)
        
        # Get co-latitude and longitude coordinates of the skygrid in the target coord system 
        colat, lon = healpy.pix2ang(self.nside, \
                                    numpy.arange(healpy.nside2npix(self.nside)), \
                                    nest=self.is_nested())
        
        # Map target to original coordinates
        points = [Skypoint(l, math.pi/2-c, coordsystem).transformed_to(self.coordsystem) \
                                  for l, c in zip(lon, colat)]
        
        # Transform the list of coordinate tuples [(lon, lat), ...] into two lists [lons, lats]
        coords_rot = [p.coords() for p in points]
        (colat_rot, lon_rot) = tuple(map(list,zip(*coords_rot)))
 
        # Compute skymap in target coord system: interpolate the skymap at points that map to target coords
        data_rotated = healpy.get_interp_val(self.data, numpy.array(colat_rot), numpy.array(lon_rot), \
                                             nest=self.is_nested())
        
        # Create target skymap and update its data 
        return Skymap.like(self, coordsystem=coordsystem, data=data_rotated)
Esempio n. 16
0
def coord_x2y(map, x, y):
    """Rotate a map from galactic co-ordinates into celestial co-ordinates.

    This will operate on a series of maps (provided the Healpix index is last).

    Parameters
    ----------
    map : np.ndarray[..., npix]
        Healpix map.
    x, y : {'C', 'G', 'E'}
        Coordinate system to transform to/from. Celestial, 'C'; Galactic 'G'; or
        Ecliptic 'E'.

    Returns
    -------
    rotmap : np.ndarray
        The rotated map.
    """

    if x not in ['C', 'G', 'E'] or y not in ['C', 'G', 'E']:
        raise Exception("Co-ordinate system invalid.")

    npix = map.shape[-1]

    angpos = ang_positions(healpy.npix2nside(npix))
    theta, phi = healpy.Rotator(coord=[y, x])(angpos[:, 0], angpos[:, 1])

    map_flat = map.reshape((-1, npix))

    for i in range(map_flat.shape[0]):
        map_flat[i] = healpy.get_interp_val(map_flat[i], theta, phi)

    return map_flat.reshape(map.shape)
def _interpolate_level(m):
    """Recursive multi-resolution interpolation. Modifies `m` in place."""
    # Determine resolution.
    npix = len(m)

    if npix > 12:
        # Determine which pixels comprise multi-pixel tiles.
        ipix = np.flatnonzero(
            (m[0::4] == m[1::4]) &
            (m[0::4] == m[2::4]) &
            (m[0::4] == m[3::4]))

        if len(ipix):
            ipix = 4 * ipix + np.expand_dims(np.arange(4, dtype=np.intp), 1)
            ipix = ipix.T.ravel()

            nside = hp.npix2nside(npix)

            # Downsample.
            m_lores = hp.ud_grade(
                m, nside // 2, order_in='NESTED', order_out='NESTED')

            # Interpolate recursively.
            _interpolate_level(m_lores)

            # Record interpolated multi-pixel tiles.
            m[ipix] = hp.get_interp_val(
                m_lores, *hp.pix2ang(nside, ipix, nest=True), nest=True)
Esempio n. 18
0
def get_skytemp(gal_long, gal_lat, freq=HASLAM_FREQ, index=SYNCHROTRON_INDEX):
    """Given galactic longitude, latitude and observing
        frequency return the sky temperature in Kelvin
        using the Haslam et al. map.

        Notes: * galactic longitude and latitude should be 
                  provided in degrees.
               * frequency should be provided in MHz.
        
        Optional argument:
        index: synchrotron spectrum index
    """
    
    global HASLAM_MAP
    if HASLAM_MAP is None:
        read_map()
    
    # Theta and Phi angles defined as expected by healpy
    # Theta and Phi are given expected by healpy in radians
    # In (theta, phi) the centre of Galaxy is (pi/2, 0)
    theta = (90.0 - gal_lat)*DEGTORAD
    phi = (gal_long)*DEGTORAD

    # get value from map
    temp_408 = healpy.get_interp_val(HASLAM_MAP, theta, phi)

    # Adjust temperatures for given observing frequency
    temp_obs = change_obsfreq(temp=temp_408, oldfreq=HASLAM_FREQ, \
                                newfreq=freq, index=index)

    return temp_obs
Esempio n. 19
0
def rotate_jones(j, rotmat, multiway=True):
    """
    Rotates the scalar components of a complex-valued 2x2 matrix field, relative
    to the Healpix coordinate frame.
    """
    if multiway == True:
        j = flatten_jones(j)

    npix = len(j[:,0])
    nside = hp.npix2nside(npix)
    hpxidx = np.arange(npix)
    c, a = hp.pix2ang(nside, hpxidx)

    t, p = rotate_sphr_coords(rotmat, c, a)

    intp = lambda m: hp.get_interp_val(m, t, p)

    # This is the fastest by ~2%. 99.1ms vs 101ms for the loop. (at nside=2**6)
    # ...totally worth it!
    jones = (np.asarray(map(intp,j.T))).T

    # 101ms
    # jR = np.empty_like(j)
    # for i in range(8):
    #     jR[:,i] = intp(j[:,i])

    # 102ms SO SLOW WTF NUMPY?
    #jR = np.apply_along_axis(intp, 0, j)
    # ahem. apparently this is just synactic sugar

    if multiway == True:
        jones = inverse_flatten_jones(jones)

    return jones
Esempio n. 20
0
    def get_implementation(self, theta, phi, z):

        # here theta, phi, z are all arrays.
        # angular interpolation could be done at each z bin, to make one vector of values in z for each galaxy, to be interpolated at each individual z. Since the z are different for each galaxy, scipy.interpolate does not vectorize here (neither does numpy.interp)
        # interpolating in z first would mean making a map for each galaxy, which is even worse.
        # therefore, we do not support interpolation in angle here!

        from scipy import interpolate

        f = interpolate.interp1d(self.zcenters,
                                 self._map,
                                 kind='linear',
                                 bounds_error=False,
                                 fill_value=(1, 0))

        # different z will be different columns
        # each column is the interpolated map
        buf = f(z)

        if self._interpolateOmega:
            ret = np.zeros((len(theta), len(z)))
            # interpolate map by map
            for i in np.arange(len(z)):
                ret[:, i] = hp.get_interp_val(buf[:, i], theta, phi)
            return ret
        else:
            return buf[hp.ang2pix(self._nside, theta, phi), :]
Esempio n. 21
0
def coord_x2y(map, x, y):
    """Rotate a map from galactic co-ordinates into celestial co-ordinates.

    This will operate on a series of maps (provided the Healpix index is last).

    Parameters
    ----------
    map : np.ndarray[..., npix]
        Healpix map.
    x, y : {'C', 'G', 'E'}
        Coordinate system to transform to/from. Celestial, 'C'; Galactic 'G'; or
        Ecliptic 'E'.

    Returns
    -------
    rotmap : np.ndarray
        The rotated map.
    """

    if x not in ['C', 'G', 'E'] or y not in ['C', 'G', 'E']:
        raise Exception("Co-ordinate system invalid.")

    npix = map.shape[-1]

    angpos = ang_positions(healpy.npix2nside(npix))
    theta, phi = healpy.Rotator(coord=[y, x])(angpos[:, 0], angpos[:, 1])

    map_flat = map.reshape((-1, npix))

    for i in range(map_flat.shape[0]):
        map_flat[i] = healpy.get_interp_val(map_flat[i], theta, phi)

    return map_flat.reshape(map.shape)
Esempio n. 22
0
def rotate_map(hmap, rot_theta, rot_phi):
    nside = hp.npix2nside(len(hmap))
    t, p = hp.pix2ang(nside, np.arange(hp.nside2npix(nside)))
    r = hp.Rotator(deg=False, rot=[rot_phi, rot_theta])
    trot, prot = r(t, p)
    rmap = hp.get_interp_val(hmap, trot, prot)
    return rmap
Esempio n. 23
0
    def addZeropoint(self, filter, ra, dec, mag, interpolate=True, plot=False):
        """
        Inputs: filter name {g, r, i, z}, arrays for ra (deg), dec (deg), and magnitude
        Return: array of corrected magnitudes, array quality flag
        Note: uses median fitted zeropoint shift for objects having (rad, dec) outside fitted or periphery pixels
        """
        pix = healpy.ang2pix(self.nside, numpy.radians(90.0 - dec), numpy.radians(ra))

        # Interpolate zeropoints
        if interpolate:
            zeropoint_shift = healpy.get_interp_val(
                self.zeropoint_shiftmap.data.field(filter), numpy.radians(90.0 - dec), numpy.radians(ra)
            )
        else:
            zeropoint_shift = self.zeropoint_shiftmap.data.field(filter)[pix]

        # Quality flag
        quality_flag = self.zeropoint_shiftmap.data.field("n_des")[pix]
        quality_flag[quality_flag > 0] = 0
        quality_flag[quality_flag < 0] = 2
        if self.fill_periphery:
            quality_flag[numpy.logical_and(quality_flag == 2, numpy.fabs(zeropoint_shift) <= 10.0)] = 1

        # Use median zeropoint shift for objects outside interpolated region
        median_fitted_zeropoint_shift = numpy.median(zeropoint_shift[numpy.fabs(zeropoint_shift) <= 10.0])
        zeropoint_shift[numpy.fabs(zeropoint_shift) > 10.0] = median_fitted_zeropoint_shift

        return mag + zeropoint_shift, quality_flag
Esempio n. 24
0
def rotate_map(healpy_map, rotation_axis, rotation_angle):
    """
    Perform rotation of healpy map for given rotation axis and angle(s).

    :param healpy_map: healpix map to be rotated
    :param rotation_axis: rotation axis, either np.array([x, y, z]) or ndarray with shape (3, n)
    :param rotation_angle: rotation angle in radians, either float or array size n
    :return: rotated healpy map, same shape as input healpy map or shape (n, npix)
    """
    rotation_axis = coord.atleast_kd(rotation_axis, 2)
    nside, npix = hp.get_nside(healpy_map), len(healpy_map)
    n_ang, n_ax = np.size(rotation_angle), np.shape(rotation_axis)[-1]
    assert (n_ang == n_ax) or (np.min([
        n_ang, n_ax
    ]) == 1), "Rotation axes and angles dimensions not compatible."
    n = np.max([n_ang, n_ax])
    rotation_vectors = pix2vec(nside, np.arange(npix))
    if n > 1:
        rotation_vectors = np.tile(rotation_vectors, n)
        rotation_axis = np.repeat(rotation_axis,
                                  npix * ((n_ax == 1) * n + (n_ax > 1)),
                                  axis=1)
        rotation_angle = np.repeat(rotation_angle,
                                   npix * ((n_ang == 1) * n + (n_ang > 1)))
    _vecs = coord.rotate(rotation_vectors, rotation_axis, -rotation_angle)
    _phi, _theta = vec2ang(np.squeeze(_vecs.reshape(3, -1, npix)))
    return hp.get_interp_val(healpy_map, np.pi / 2. - _theta, _phi)
Esempio n. 25
0
def rotateHealpix(hpmap, transf=['C', 'G'], phideg=0., thetadeg=0.):
    """Rotates healpix map from one system to the other. Returns reordered healpy map.
    Healpy coord transformations are used, or you can specify your own angles in degrees.
    To specify your own angles, ensure that transf has length != 2.
    Original code by Xiaolong Li
    """

    # For reasons I don't understand, entering in ['C', 'G'] seems to do the
    # transformation FROM galactic TO equatorial. Possibly something buried in
    # the conventions used by healpy.

    # Heavily influenced by stack overflow solution here:
    # https://stackoverflow.com/questions/24636372/apply-rotation-to-healpix-map-in-healpy

    nside = hp.npix2nside(len(hpmap))

    # Get theta, phi for non-rotated map
    t, p = hp.pix2ang(nside, np.arange(hp.nside2npix(nside)))

    # Define a rotator
    if len(transf) == 2:
        r = hp.Rotator(coord=transf)
    else:
        r = hp.Rotator(deg=True, rot=[phideg, thetadeg])

    # Get theta, phi under rotated co-ordinates
    trot, prot = r(t, p)

    # Interpolate map onto these co-ordinates
    rot_map = hp.get_interp_val(hpmap, trot, prot)

    return rot_map
Esempio n. 26
0
 def beam_interp_func(theta, phi):
     # convert to radians
     theta = copy.copy(theta) * np.pi / 180.0
     phi = copy.copy(phi) * np.pi / 180.0
     shape = theta.shape
     beam_interp = map(lambda m: healpy.get_interp_val(m, theta.ravel(), phi.ravel(), lonlat=False).reshape(shape), beam_maps)
     return np.array(beam_interp)
Esempio n. 27
0
    def rotate(self,
               theta: float,
               phi: float,
               which: str,
               rtn: bool = False) -> np.ndarray:
        """
        Rotate the full-sky.

        Args:
            theta and phi:
                Rotational angles [deg]
            which:
                Identify which map in self.data should be rotated.
        """
        if (theta is None) or (phi is None):
            theta = np.random.random() * 180
            phi = np.random.random() * 180

        # Get theta, phi for non-rotated map
        _pixel_index = np.arange(self._npix)
        t, p = hp.pix2ang(self._nside, _pixel_index)
        # Define a rotator
        r = hp.Rotator(deg=True, rot=[theta, phi])
        # Get theta, phi under rotated co-ordinates
        trot, prot = r(t, p)
        # Interpolate map onto these co-ordinates
        _skymap = copy.deepcopy(self.data[which])
        _skymap = hp.get_interp_val(_skymap, trot, prot)
        if rtn is True:
            return _skymap
        else:
            self.data[which] = _skymap
Esempio n. 28
0
 def Diffuse(self,ra, dec):
     rot = hp.rotator.Rotator(coord=['C','G'])
     gb, gl = rot((90-dec)*np.pi/180., ra*np.pi/180.)
     #gb, gl = (np.pi/2. - gb)*180./np.pi, gl*180./np.pi
    # pix = hp.ang2pix(2048,gb,gl)
     
     return hp.get_interp_val(self.skymap, gb,gl) #self.skymap[pix]
Esempio n. 29
0
 def rotate(self, *a, **kw):
     kw['inv'] = kw.get('inv', True)
     rot = healpy.Rotator(*a, **kw)
     thetas0, phis0 = self._thetas_phis
     thetas, phis = rot(thetas0, phis0)
     rmap = healpy.get_interp_val(self.map, thetas, phis)
     return HealHist(rmap)
Esempio n. 30
0
def healpix_to_other(healpix_data, other_image):
    """Convert image in HPX format to some other format (e.g. CAR or AIT).
    @param healpix_data: numpy.ndarray containing the HEALPIX data
    @param other_image: kapteyn.maputils.FITSimage containing the other image"""
    from healpy import get_interp_val
    glon, glat = coordinates(other_image, glon_sym=False, radians=True)
    data = get_interp_val(healpix_data, glon, glat)
    other_image.dat = data
Esempio n. 31
0
def lensing(cmb, lp1, lp2, deflt_1, deflt_2, nsources, nside):
    """
    lp1 lp2: from ray-ramses theta_co phi_co
    """
    # Mapping light rays from image plane to source plan
    [sp1, sp2] = [lp1 - deflt_1, lp2 - deflt_2]  # [arcsec]
    cmb_lensed = hp.get_interp_val(cmb, sp1, sp2)
    return cmb_lensed
Esempio n. 32
0
def rotateBeam(inputMap,rot=[90,0,0]):
    rotator=hp.Rotator(rot=rot)
    npix=len(inputMap)
    nside=hp.npix2nside(npix)
    theta,phi=hp.pix2ang(nside,range(npix))
    newtheta,newphi=rotator(theta,phi)
    output=hp.get_interp_val(inputMap,newtheta,newphi)
    return output
Esempio n. 33
0
 def test_ground_temperature(self):
     Nside = 64
     ground_T_test = 150
     groundmap_test = gm.make_ground_template(T=ground_T_test, nside=Nside)
     # Check temp at some point on ground (lat > 0, any long)
     output_ground_T_ground = hp.get_interp_val(groundmap_test,
                                                3,
                                                32,
                                                lonlat=True)
     # Check temp at some point on sky (lat < 0, any long)
     output_ground_T_sky = hp.get_interp_val(groundmap_test,
                                             14,
                                             -32,
                                             lonlat=True)
     self.assertEqual(round(output_ground_T_ground, 5),
                      round(ground_T_test, 5))
     self.assertEqual(round(output_ground_T_sky, 5), round(0, 5))
Esempio n. 34
0
def getval(l, b, map='dust', field='ebv', nest=True):
    planck_dir = os.environ['PLANCK_DIR']
    if map in maps:
        map = maps[map]
    map = fits.getdata(os.path.join(planck_dir, map))
    map = map[field]
    t, p = ((90. - b) * numpy.pi / 180., l * numpy.pi / 180.)
    return healpy.get_interp_val(map, t, p, nest=nest)
Esempio n. 35
0
def angular_slice(skymaps, theta, phi):
    nfreq = skymaps.shape[0]
    za = np.zeros((nfreq, phi.size), dtype=np.complex128)

    for i in range(nfreq):
        za[i] = healpy.get_interp_val(skymaps[i], theta, phi)

    return za
Esempio n. 36
0
def angular_slice(skymaps, theta, phi):
    nfreq = skymaps.shape[0]
    za = np.zeros((nfreq, phi.size), dtype=np.complex128)

    for i in range(nfreq):
        za[i] = healpy.get_interp_val(skymaps[i], theta, phi)
        
    return za
Esempio n. 37
0
 def displace_objects(self, theta, phi, old=False):
     if old:
         ipix = hp.ang2pix(self.nside, theta, phi)
         dtheta = self.dtheta_map.A[ipix]
         dphi = self.dphi_map.A[ipix] / np.sin(theta)
     else:
         dtheta = hp.get_interp_val(self.dtheta_map.A, theta, phi)
         dphi = hp.get_interp_val(self.dphi_map.A, theta,
                                  phi) / np.sin(theta)
     dd = np.sqrt(dtheta**2 + dphi**2)
     alpha = np.arctan2(dphi, dtheta)
     ## Equation A15 from 0502469
     thetap = np.arccos(
         np.cos(dd) * np.cos(theta) -
         np.sin(dd) * np.sin(theta) * np.cos(alpha))
     phip = phi + np.arcsin(np.sin(alpha) * np.sin(dd) / np.sin(thetap))
     return thetap, phip
Esempio n. 38
0
 def export_fits_prisim(self,fitsfile,pol_list,freq_list,scheme='RING',nside_out=None):
     '''
     export fits-file at channel chan and polarization pol
     Args:
     fitsfile, str, name of file to save .fits to
     pol_list, list of labels of polarizations to write
     chan_list, list of frequencies to write
     '''
     if nside_out is None:
         nside_out=self.nside
     pol_list=n.array(pol_list)
     freq_list=n.array(freq_list)
     pol_inds=[]
     freq_inds=[]
     for pol in pol_list:
         assert pol in self.pols
         pol_inds.append(n.where(n.array(self.pols)==pol)[0][0])
     for freq in freq_list:
         assert freq in self.fAxis
         freq_inds.append(n.where(n.array(self.fAxis)==freq)[0][0])
     data=self.data[:,freq_inds,:].reshape(-1,1)
     theta_out,phi_out=hp.pix2ang(nside_out,n.arange(hp.nside2npix(nside_out)))
     #freq_col=[fits.Column(name='Frequency [MHz]',format='D',array=n.array(freq_list))]
     #freq_columns=fits.ColDefs(freq_col,ascii=False)
     #freq_tbhdu = fits.BinTableHDU.from_columns(freq_col)
     #freq_tbhdu = fits.BinTableHDU.from_columns(n.array(freq_list))
     
     hduprimary=fits.PrimaryHDU()
     hduprimary.header.set('EXTNAME','PRIMARY')
     hduprimary.header.set('NEXTEN',2)
     hduprimary.header.set('FITSTYPE','IMAGE')
     hduprimary.header['NSIDE']=(nside_out,'NSIDE')
     hduprimary.header['PIXAREA']=(hp.nside2pixarea(nside_out),'pixel solid angle (steradians)')
     hduprimary.header['NEXTEN']=(2,'Number of extensions')
     hduprimary.header['NPOL'] = (len(pol_inds), 'Number of polarizations')
     hduprimary.header['SOURCE'] = ('HERA-CST', 'Source of data')
     hdulist=[hduprimary]
     fits.HDUList(hdulist).writeto(fitsfile,clobber=True)
     for pol in pol_list:
         #freq_tbhdu.header.set('EXTNAME','FREQS_{0}'.format(pol))
         freq_tbhdu=fits.ImageHDU(freq_list,name='FREQS_{0}'.format(pol))
         fits.append(fitsfile,freq_tbhdu.data,freq_tbhdu.header,verify=False)
     data_interp=n.zeros((hp.nside2npix(nside_out),len(freq_inds)))
     for polind,pol in zip(pol_inds,pol_list):
         for fi,freqind in enumerate(freq_inds):
             data=self.data[polind,freqind,:].flatten()
             data_interp[:,fi]=hp.get_interp_val(data,theta_out,phi_out)
             #if DEBUG:
             #    hp.mollview(data_interp[:,fi])
             #    plt.show()
         imghdu = fits.ImageHDU(data_interp, name='BEAM_{0}'.format(pol))
         imghdu.header['PIXTYPE'] = ('HEALPIX', 'Type of pixelization')
         imghdu.header['ORDERING'] = (scheme, 'Pixel ordering scheme, either RING or NESTED')
         imghdu.header['NSIDE'] = (nside_out, 'NSIDE parameter of HEALPIX')
         imghdu.header['NPIX'] = (hp.nside2npix(nside_out), 'Number of HEALPIX pixels')
         imghdu.header['FIRSTPIX'] = (0, 'First pixel # (0 based)')
         imghdu.header['LASTPIX'] = (len(data_interp)-1, 'Last pixel # (0 based)')
         fits.append(fitsfile,imghdu.data,imghdu.header,verify=False)
Esempio n. 39
0
def VisibilitySimulator(s, PBs, ps, times, coords):
    print "Now simulating visibilities (assuming XX beams only)..."
    if s.GSMNSIDE < s.mapNSIDE:
        s.GSMNSIDE = s.mapNSIDE
    coordsGSM = Geometry.Coordinates(s, useAnotherResolution=s.GSMNSIDE)
    visibilities = np.zeros([len(times.LSTs), len(s.baselines)], dtype=complex)

    #TODO: this ignores polarization and differing primary beams
    if s.simulateVisibilitiesWithGSM:
        GSM = GlobalSkyModel(s.freq, s.GSMlocation, s.GSMNSIDE)
        interpoltedGSMRotated = hp.get_interp_val(
            GSM.hpMap, -coordsGSM.galCoords.b.radian + np.pi / 2,
            np.asarray(coordsGSM.galCoords.l.radian))

        #loop over times and baselines to calculate visibilities
        for t in range(len(times.LSTs)):
            pixelAlts, pixelAzs = Geometry.convertEquatorialToHorizontal(
                s, coordsGSM.pixelRAs, coordsGSM.pixelDecs, times.LSTs[t])
            rHatVectors = Geometry.convertAltAzToCartesian(pixelAlts, pixelAzs)
            primaryBeam = hp.get_interp_val(
                PBs.beamSquared("X", "x", s.pointings[t]),
                np.pi / 2 - pixelAlts, pixelAzs)
            for b in range(len(s.baselines)):
                exponent = np.exp(-1j * s.k *
                                  np.dot(rHatVectors, s.baselines[b]))
                visibilities[t,
                             b] += np.sum(interpoltedGSMRotated * primaryBeam *
                                          exponent) * 4 * np.pi / len(
                                              GSM.hpMap) / s.convertJyToKFactor

    if s.simulateVisibilitiesWithPointSources and ps.nSources > 0:
        for t in range(len(times.LSTs)):
            psAlts, psAzs = Geometry.convertEquatorialToHorizontal(
                s, ps.RAs, ps.decs, times.LSTs[t])
            rHatVectors = Geometry.convertAltAzToCartesian(psAlts, psAzs)
            primaryBeam = hp.get_interp_val(
                PBs.beamSquared("X", "x", s.pointings[t]), np.pi / 2 - psAlts,
                psAzs)
            for b in range(len(s.baselines)):
                exponent = np.exp(-1j * s.k *
                                  np.dot(rHatVectors, s.baselines[b]))
                visibilities[t, b] += np.sum(ps.scaledFluxes * primaryBeam *
                                             exponent)

    return visibilities
Esempio n. 40
0
 def interp_mwa(self, delays, RA, Dec, frequency=150e6):
     """
     beam=MWA_GW.interp_mwa(delays, RA, Dec, frequency=150e6)
     """
     beam = self.get_mwabeam(delays, frequency=frequency)
     return healpy.get_interp_val(beam,
                                  np.radians(90 - Dec),
                                  np.radians(RA),
                                  nest=True)
Esempio n. 41
0
def rotate_healpix_map(m, R):
    """
    Performs a scalar rotation of the map relative to the Healpix coordinate
    frame by interpolating the map at the coordinates of new coordinate frame.
    """
    npix = len(m)
    nside = hp.npix2nside(npix)
    hpxidx = np.arange(npix)
    c, a = hp.pix2ang(nside, hpxidx)
    t, p = rotate_sphr_coords(R, c, a)
    return hp.get_interp_val(m, t, p)
def generateDataFromShell(shellIndex, nbSamples):

    '''
    This function generates nbSamples Poisson samples from the intensity
    defined on the shellIndex-th shell.

    Default is the 1REI biomolecule. Intensities were calculated numerically
    on a HEALPix grid of parameter nside = 128.
    Parameters:
    - shellIndex: int, shell index of the considered shell
    - nbSamples: int, number of desired samples
    Return: Ndec \times nbSamples real matrix.
    '''

    # load intensity function
    IShell = np.load('path_to_shells_intensities/'+str(shellIndex)+'.npy')
    nside = 128

    # define detector characteristics and experimental conditions
    wavelength = 2  # in Angstroms
    zD = 1e-2  # detector distance, in meters
    pw = 3.38e-5  # pixel size, in meters

    qmax = 4*pi/wavelength
    gridsize = 512  # number of pixels in one direction (total size of the detector 1024*1024)
    qmax_grid = qmax*np.sin(0.5*np.arctan(pw*gridsize/zD)) #largest value of q on the detector 
    Deltaq = qmax*np.sin(0.5*np.arctan(pw*1/zD))  # pixel spacing at the origin

    q_shell = qmax*np.sin(0.5*np.arctan(pw*shellIndex/zD)) # q value at the shellIndex given
    Npix_dec = int(np.ceil(2*pi*q_shell/Deltaq))  # Corresponding number of pixels

    # coords detector in reciprocal space
    qdec = np.ones(Npix_dec)*q_shell
    thetadec = pi/2-np.arcsin(qdec/qmax)
    phidec = np.linspace(0, 2*pi, Npix_dec+1)[:Npix_dec]
    xdec, ydec, zdec = sph2cart(qdec, thetadec, phidec)

    # create output array
    Myk = np.zeros((Npix_dec, nbSamples))

    # generate nbSamples uniform rotations in SO(3)
    quatList = randS3(nbSamples)
    # Get the samples
    for k in range(nbSamples):
        xr, yr, zr = rotate(xdec, ydec, zdec, quatList[:, k])

        q, theta, phi = cart2sph(xr, yr, zr)

        sampledI = hp.get_interp_val(IShell, theta, phi)
        Myk[:, k] = np.random.poisson(sampledI)

    return Myk
Esempio n. 43
0
def hpCut(phi,nPix,data):
    '''
    '''
    nSide=hp.npix2nside(len(data))
    output=n.zeros(nPix)
    thetaVals=n.arange(nPix/2)/(nPix/2.)*pi/2.
    thetaVals=n.hstack([n.flipud(thetaVals),thetaVals,]).T
    phiVals=n.ones(len(thetaVals))
    phi1=phi+pi
    phiVals[:nPix/2]=phi1
    phiVals[nPix/2:]=phi
    output=hp.get_interp_val(data,thetaVals,phiVals)
    return output
Esempio n. 44
0
    def vec2pix(l, b):
        if galactic:
            f = FK5(l, b, unit=(u.rad, u.rad))
            g = f.transform_to(Galactic)
            l, b = g.l.rad, g.b.rad

        theta = np.pi / 2 - b
        phi = l

        if interp:
            return get_interp_val(data, theta, phi, nest=nest)

        return data[ang2pix(nside, theta, phi, nest=nest)]
def hpx2sine(i):
    sparse_m = np.load(
        '/data6/piyanat/projects/hera1p/lightcone_healpix_northpole_fov35d/'
        'lightcone_healpix_northpole_fov35d_{:.3f}MHz.npy'.format(F[i]))
    m = np.ones(hp.nside2npix(nside)) * hp.UNSEEN
    m[valid_hpx_pix] = sparse_m
    proj_lightcone = hp.get_interp_val(m, pixlon[:, :],
                                       pixlat[:, :], lonlat=True)
    hdu = fits.PrimaryHDU(data=proj_lightcone, header=hdr)
    hdu.writeto(
        '/data6/piyanat/projects/hera1p/lightcone_sine_northpole_fov30d/'
        'lightcone_sine_northpole_fov30d_{:.3f}MHz.fits'.format(F[i]),
        overwrite=True
    )
Esempio n. 46
0
def rotate_healpix_mapHPX(m, rot):
    """
    This one uses the Healpix Rotator object, thus the rotation must be
    specified by an Euler angle sequence.

    Otherwise, same thing as rotate_healpix_map.
    """
    npix = len(m)
    nside = hp.npix2nside(npix)
    hpxidx = np.arange(npix)
    c, a = hp.pix2ang(nside, hpxidx)
    R = hp.Rotator(rot=rot)
    t, p = R(c,a)
    return hp.get_interp_val(m, t, p)
Esempio n. 47
0
def rotate_map(hpmap,coord=['C','G'],cov=True):
    '''
    Rotates the coordinates of a map
    By default, rotates from C to G
    '''
    (theta,phi) = _hp.pix2ang(_hp.get_nside(hpmap),
      _np.arange(0, len(hpmap)))
    r = _hp.Rotator(coord=coord, inv = True)
    #rotate new coordinate system to original coordinates
    theta_map, phi_map = r(theta, phi)
    rotated = _hp.get_interp_val(hpmap, theta_map, phi_map)
    if cov:
        ind1 = (rotated > 0.5); rotated[ind1] = 1.0; rotated[~ind1] = 0.0

    return rotated
Esempio n. 48
0
def rotate_map(hmap, rot_theta, rot_phi, nest=True):
    nside = hp.npix2nside(len(hmap))

    # Get theta, phi for non-rotated map
    t, p = hp.pix2ang(nside, np.arange(hp.nside2npix(nside)), nest= nest)  # theta, phi

    # Define a rotator
    r = hp.Rotator(deg=False, rot=[rot_phi, rot_theta])

    # Get theta, phi under rotated co-ordinates
    trot, prot = r(t, p)

    # Inerpolate map onto these co-ordinates
    rot_map = hp.get_interp_val(hmap, trot, prot, nest= nest)

    return rot_map
Esempio n. 49
0
def heal2cart(heal, interp=True, return_pts=False):
    import healpy
    nside = healpy.get_nside(heal)#*(2 if interp else 1)
    owidth = 8*nside
    oheight = 4*nside-1
    dm,rm = numpy.mgrid[0:oheight,0:owidth]
    rm = 360.-(rm+0.5) / float(owidth) * 360.
    dm = -90. + (dm+0.5) / float(oheight) * 180.
    t, p = lb2tp(rm.ravel(), dm.ravel())
    if interp:
        map = healpy.get_interp_val(heal, t, p)
    else:
        pix = healpy.ang2pix(nside, t, p)
        map = heal[pix]
    map = map.reshape((oheight, owidth))
    if return_pts:
        map = (map, numpy.sort(numpy.unique(rm)), numpy.sort(numpy.unique(dm)))
    return map
Esempio n. 50
0
def _hpm2sin_base(args):
    """
    Base calculation for hpm2sin. Implemented to be called with
    multiprocessing.Pool.map

    """
    fitsfile, ra, dec, dim, res, multiplier, hdr = args
    print 'extracting' + fitsfile

    # Create a new WCS object. The number of axes must be set from the start
    w = wcs.WCS(naxis=2)

    # Set up a SIN projection
    w.wcs.crpix = [dim / 2, dim / 2]
    w.wcs.cdelt = [-res, res]
    w.wcs.crval = [ra, dec]
    w.wcs.ctype = ["RA---SIN", "DEC--SIN"]

    # Now, write out the WCS object as a FITS header, adding additional
    # fits keyword as applied
    header = w.to_header()
    if hdr is not None:
        for key, value in hdr.iteritems():
            header[key] = value

    # Some pixel coordinates of interest.
    x, y = np.mgrid[0:dim, 0:dim]

    # Convert pixel coordinates to world coordinates
    ra, dec = w.wcs_pix2world(x, y, 0)
    valid_pix = np.isfinite(ra)
    ra *= np.pi / 180
    dec = np.pi * (dec + 90) / 180

    # Get the pixel value from the HEALPix image
    proj_map = np.zeros((dim, dim))
    proj_map[valid_pix] = multiplier * hp.get_interp_val(_hpm.map, dec[valid_pix], ra[valid_pix])

    # header is an astropy.io.fits.Header object.  We can use it to create a new
    # PrimaryHDU and write it to a file. data is the image array. Axes in 2D numpy
    # array are ordre slow then fast, opposite to fits ordering, so we have to
    # transpose our image array
    hdu = fits.PrimaryHDU(data=proj_map.T, header=header)
    hdu.writeto(fitsfile, clobber=True)
Esempio n. 51
0
    def loadDataFromHealpixMap(self, hpm, interpolate=False, hpCoords="J2000"):
        """
        @brief copy data from a Healpix map (from healpy), return a lite map
        @param hpm healpy map
        @param interpolate use interpolation when copying 
        @param hpCoords coordinates of hpm (e.g., "J2000"(RA, Dec) or "GALACTIC")

        Assumes that liteMap is in J2000 RA Dec. The Healpix map must contain the liteMap.
        """
        inds = numpy.indices([self.Nx, self.Ny])
        x = inds[0].ravel()
        y = inds[1].ravel()
        skyLinear = numpy.array(self.pixToSky(x, y))
        ph = skyLinear[:, 0]
        th = skyLinear[:, 1]
        thOut = []
        phOut = []
        if hpCoords != "J2000":
            for i in xrange(len(th)):
                crd = astCoords.convertCoords("J2000", hpCoords, ph[i], th[i], 0.0)
                phOut.append(crd[0])
                thOut.append(crd[1])
            thOut = numpy.array(thOut)
            phOut = numpy.array(phOut)
        else:
            thOut = th
            phOut = ph
        trace.issue("flipper.liteMap", 3, "theta (min, max): %f, %f" % (th.min(), th.max()))
        trace.issue("flipper.liteMap", 3, "phi (min, max): %f, %f" % (ph.min(), ph.max()))
        trace.issue("flipper.liteMap", 3, "phiOut (min, max): (%f, %f)  " % (phOut.min(), phOut.max()))
        trace.issue("flipper.liteMap", 3, "thetaOut (min, max): (%f, %f)  " % (thOut.min(), thOut.max()))
        phOut *= numpy.pi / 180
        thOut = 90.0 - thOut  # polar angle is 0 at north pole
        thOut *= numpy.pi / 180
        trace.issue("flipper.liteMap", 3, "phiOut rad (min, max): (%f, %f)  " % (phOut.min(), phOut.max()))
        trace.issue("flipper.liteMap", 3, "thetaOut rad (min, max): (%f, %f)  " % (thOut.min(), thOut.max()))
        if interpolate:
            self.data[y, x] = healpy.get_interp_val(hpm, thOut, phOut)
        else:
            ind = healpy.ang2pix(healpy.get_nside(hpm), thOut, phOut)
            trace.issue("flipper.liteMap", 3, "healpix indices (min,max): %d, %d" % (ind.min(), ind.max()))
            self.data[:] = 0.0
            self.data[[y, x]] = hpm[ind]
Esempio n. 52
0
def healpix_to_image(healpix_data, reference_image, hpx_coord_system):
    """Convert image in HEALPIX format to a normal FITS projection image (e.g. CAR or AIT).

    Parameters
    ----------
    healpix_data : `numpy.ndarray`
        HEALPIX data array
    reference_image : `astropy.io.fits.ImageHDU`
        A reference image to project to.  Must have a 'COORDSYS' keyword of
        either 'galactic' or 'icrs'
    hpx_coord_system : 'galactic' or 'icrs'
        The target coordinate system.  Should be derived from the HEALPIX
        COORDSYS keyword if it is a FITS file

    Returns
    -------
    reprojected_data : `numpy.ndarray`
        HEALPIX image resampled onto the reference image

    Examples
    --------
    >>> import healpy as hp
    >>> from astropy.io import fits
    >>> from gammapy.image.healpix import healpix_to_image
    >>> healpix_data = hp.read_map('healpix.fits')
    >>> healpix_system = fits.getheader('healpix.fits')['COORDSYS']
    >>> reference_image = fits.open('reference_image.fits')[0]
    >>> reprojected_data = healpix_to_image(healpix_data, reference_image, healpix_system)
    >>> fits.writeto('new_image.fits', reprojected_data, reference_image.header)
    """
    import healpy as hp
    lon, lat = coordinates(reference_image, lon_sym=False, radians=True)

    # If the reference image uses a different celestial coordinate system from
    # the HEALPIX image we need to transform the coordinates
    ref_coord_system = reference_image.header['COORDSYS']
    if ref_coord_system != hpx_coord_system:
        coordinate = SkyCoord(lon, lat, frame=ref_coord_system)
        coordinate = coordinate.transform_to(hpx_coord_system)
        lon, lat = coordinate.data.lon, coordinate.data.lat

    data = hp.get_interp_val(healpix_data, lon, lat)
    return data
def make_ijones_spectrum(parameters, verbose=False):
    p = Parameters(parameters)


    d = fits.open(data_dir + 'healpix_beam.fits')
    beams = d[0].data
    freqs = d[1].data

    # select only 100-200 MHz data
    freq_select = np.where((freqs >= 100) & (freqs <=200))[0]
    beams = beams[:, freq_select]
    freqs = freqs[freq_select]
    Nfreqs = len(freqs)

    # take East pol and rotate to get North pol
    beam_theta, beam_phi = hp.pix2ang(64, np.arange(64**2 * 12))
    R = hp.Rotator(rot=[0,0,-np.pi/2], deg=False)
    beam_theta2, beam_phi2 = R(beam_theta, beam_phi)
    beam_rot = np.array(map(lambda x: hp.get_interp_val(x, beam_theta2, beam_phi2), beams.T))
    beam_data = np.array([beams.T, beam_rot])
    beam_data.resize(2, Nfreqs, 49152)

    # normalize each frequency to max of 1
    for i in range(beam_data.shape[-2]):
        beam_data[:, i, :] /= beam_data[:, i, :].max()

    uJee = udgrade(np.sqrt(beam_data[0,50,:]), p.nside)

    uJnn = AzimuthalRotation(uJee)
    Jee = irf.rotate_healpix_mapHPX(uJee, [0., -np.degrees(p.z0_cza),0])
    Jee /= np.amax(Jee)
    Jnn = irf.rotate_healpix_mapHPX(uJnn, [0., -np.degrees(p.z0_cza),0])
    Jnn /= np.amax(Jnn)

    jones = np.array([
        [np.abs(Jee), np.zeros(len(Jee))],
        [np.zeros(len(Jee)), np.abs(Jnn)]
    ], dtype=np.complex).transpose(2,0,1)

    hm = horizon_mask(jones, p.z0_cza)
    return np.broadcast_to(jones * hm, (p.nfreq,) + jones.shape)
Esempio n. 54
0
    def gpower_integrand(self,theta,phi):
        """Use to calculate the total noise power due to the galaxy. Theta and phi are the zenith and az angles in radians. freq is in MHz"""

        wavelength = 299.9/self.frequency
        if(phi == 0): phi = .00001
        if(phi == np.pi): phi = np.pi - .00001

        self.aa.alt = np.pi/2.0 - theta
        self.aa.az  = np.pi/2.0 - phi

        coords = self.aa.raDec(self.__lst_current,self.location)

        coords = self.Rotator(np.pi/2 - coords.dec,coords.ra)

        Tsky = hp.get_interp_val(self.hpmap,coords[0],coords[1])*(self.frequency/408.0)**(-2.55)

        ans = self.lofasm.beam_pattern(theta,phi,[0,0,1])
        ans += self.lofasm.beam_pattern(theta,phi,[0,1,0]) 
        ans *= (Tsky*(1.3804e-23)/wavelength**2)/(1e-26)/2.0

        return ans
Esempio n. 55
0
    def get_zeropoint_offset(self, filter, ra, dec, interpolate=True):
        """
        Inputs: filter name {g, r, i, z}, arrays for ra (deg), dec (deg), and magnitude
        Return: array of corrected magnitudes, array quality flag
        Note: uses median fitted zeropoint shift for objects having (rad, dec) outside fitted or periphery pixels
        """
        pix = healpy.ang2pix(self.nside, numpy.radians(90.0 - dec), numpy.radians(ra))

        # Interpolate zeropoints
        if interpolate:
            zeropoint_shift = healpy.get_interp_val(
                self.zeropoint_shiftmap.data.field(filter), numpy.radians(90.0 - dec), numpy.radians(ra)
            )
        else:
            zeropoint_shift = self.zeropoint_shiftmap.data.field(filter)[pix]

        # Use median zeropoint shift for objects outside interpolated region
        median_fitted_zeropoint_shift = numpy.median(zeropoint_shift[numpy.fabs(zeropoint_shift) <= 10.0])
        zeropoint_shift[numpy.fabs(zeropoint_shift) > 10.0] = median_fitted_zeropoint_shift

        return zeropoint_shift
Esempio n. 56
0
def smooth_ud_grade(m, nside, nest=False):
    """Resample a sky map to a new resolution using bilinear interpolation.

    Parameters
    ----------

    m : np.ndarray
        The input HEALPix array.

    nest : bool, default=False
        Indicates whether the input sky map is in nested rather than
        ring-indexed HEALPix coordinates (default: ring).

    Returns
    -------

    new_m : np.ndarray
        The resampled HEALPix array. The sum of `m` is approximately preserved.
    """
    npix = hp.nside2npix(nside)
    theta, phi = hp.pix2ang(nside, np.arange(npix), nest=nest)
    new_m = hp.get_interp_val(m, theta, phi, nest=nest)
    return new_m * len(m) / len(new_m)
Esempio n. 57
0
def coord_x2y(map, x, y):
    """Rotate a map from galactic co-ordinates into celestial co-ordinates.

    Parameters
    ----------
    map : np.ndarray
        Healpix map.
    x, y : {'C', 'G', 'E'}
        Coordinate system to transform to/from. Celestial, 'C'; Galactic 'G'; or
        Ecliptic 'E'.

    Returns
    -------
    rotmap : np.ndarray
        The rotated map.
    """

    if x not in ['C', 'G', 'E'] or y not in ['C', 'G', 'E']:
        raise Exception("Co-ordinate system invalid.")
    
    angpos = ang_positions(healpy.npix2nside(map.size))
    theta, phi =  healpy.Rotator(coord=[y, x])(angpos[:,0], angpos[:,1])
    return healpy.get_interp_val(map, theta, phi)
Esempio n. 58
0
def map_rotation(m, ang=None, coord=None, inv=None, deg=True, eulertype='X'):
    """ Return a rotated map with Euler angle `ang`
        `m`:   origin map
        `ang`: 3-list of Euler angle
	`eulertype`: 
    """

    nside=hp.get_nside(m)

    m_new=np.zeros(len(m) )
    pixcoord=np.arange(len(m))
    theta_after, phi_after = hp.pix2ang(nside, pixcoord)

    if coord!=None:
        rot=hp.Rotator(coord=coord)
    else:
        rot=hp.Rotator(rot=ang, inv=inv, deg=deg, eulertype=eulertype) 

    theta, phi=rot.I(theta_after, phi_after)
    m_new=hp.get_interp_val(m, theta, phi)


    return m_new
Esempio n. 59
0
def EBVhp(nside, ra=None,dec=None, pixels=None, interp=False):
    """
    Read in a healpix dust map and return values for given RA, Dec values

    nside: Healpixel resolution (2^x)
    ra: RA (can take numpy array)
    dec: Dec (can take numpy array)
    pixles: Healpixel IDs
    interp: Should returned values be interpolated (True) or just nearest neighbor(False)
    """

    if (ra is None) & (dec is None) & (pixels is None):
        raise RuntimeError("Need to set ra,dec or pixels.")

    # Load the map
    if not hasattr(EBVhp, 'nside'):
        EBVhp.nside = nside

    if (not hasattr(EBVhp, 'dustmap')) | (EBVhp.nside != nside) :
        EBVhp.nside = nside
        ebvDataDir = getPackageDir('sims_maps')
        filename = 'DustMaps/dust_nside_%i.npz'%EBVhp.nside
        EBVhp.dustMap = np.load(os.path.join(ebvDataDir,filename))['ebvMap']

    # If we are interpolating to arbitrary positions
    if interp:
        result = hp.get_interp_val(EBVhp.dustMap, np.pi/2. - dec , ra )
    else:
        # If we know the pixel indices we want
        if pixels is not None:
            result = EBVhp.dustMap[pixels]
        # Look up
        else:
            pixels = radec2pix(EBVhp.nside,ra,dec)
            result = EBVhp.dustMap[pixels]

    return result