Exemple #1
0
class MagellanicStream(BaseCoordinateFrame):
    """
    A coordinate or frame aligned with the Magellanic Stream,
    as defined by Nidever et al. (2008,
    see: `<http://adsabs.harvard.edu/abs/2008ApJ...679..432N>`_).

    For more information about this class, see the Astropy documentation
    on coordinate frames in :mod:`~astropy.coordinates`.

    Example
    -------
    Converting the coordinates of the Large Magellanic Cloud:

        >>> from astropy import coordinates as coord
        >>> from astropy import units as u
        >>> from gala.coordinates import MagellanicStream

        >>> c = coord.Galactic(l=280.4652*u.deg, b=-32.8884*u.deg)
        >>> ms = c.transform_to(MagellanicStream)
        >>> print(ms)
        <MagellanicStream Coordinate: (L, B) in deg ( 359.86313884,  2.42583948)>
    """

    frame_specific_representation_info = {
        r.SphericalRepresentation: [
            RepresentationMapping('lon', 'L'),
            RepresentationMapping('lat', 'B')
        ]
    }

    default_representation = r.SphericalRepresentation
    default_differential = r.SphericalCosLatDifferential

    _ngp = Galactic(l=188.5*u.deg, b=-7.5*u.deg)
    _lon0 = Galactic(l=280.47*u.deg, b=-32.75*u.deg)
def rf_equitorial(input_coord_sys, average_velocities=None):
    """ Convert to reference frame of stellar group after subtraction of LSR (U,V,W) = (11.1,12.24,7.25) kms^-1
    defined in Schönrich et al. (2010) and convert it back to equitorial coordinates. 
    Parameters
    ----------
    input_coord_sys : ICRS
        ICRS input of group for analysis
    average_velocity : tuple
        average cartesian velocity to be subtracted if known,
        else computes it here
    Returns
    -------
    ICRS
        ICRS frame
    """

    cartesian_representation, center = rf_cartesian(input_coord_sys)
    revert = cartesian_representation.transform_to(ICRS)
    revert.representation_type = 'spherical'
    revert.differential_type = 'spherical'

    galactic_revert = Galactic(l=revert.ra,
                               b=revert.dec,
                               distance=revert.distance,
                               pm_l_cosb=revert.pm_ra,
                               pm_b=revert.pm_dec,
                               radial_velocity=revert.radial_velocity)

    rf_lsr_equitorial = galactic_revert.transform_to(ICRS)

    return rf_lsr_equitorial
Exemple #3
0
def gen_ginfo(arr):

    l = arr['param'][:, 0]
    b = arr['param'][:, 1]
    plx = arr['param'][:, 2]
    pmra = arr['param'][:, 3]
    pmdec = arr['param'][:, 4]

    # correct for 0 ~ 360 jump
    if np.max(l) - np.min(l) > 180.:
        ids = np.where(l > 180.)[0]
        l[ids] -= 360.

    l0 = np.average(l)
    b0 = np.average(b)
    pmra0 = np.average(pmra)
    pmdec0 = np.average(pmdec)
    plx0 = np.average(plx)

    g0 = Galactic(l=l0 * u.degree, b=b0 * u.degree)
    gs = Galactic(l=l * u.degree, b=b * u.degree)

    rs = g0.separation(gs).degree
    r_max = np.max(rs)

    dpm = np.sqrt((pmra - pmra0)**2 + (pmdec - pmdec0)**2)
    dpm_max = np.max(dpm)

    dplx_max = np.max(np.abs(plx - plx0))

    tpl = [len(arr), l0, b0, r_max, pmra0, pmdec0, dpm_max, plx0, dplx_max]
    return tpl
Exemple #4
0
def test_to_coord_frame():
    # simple / unitless
    x = np.random.random(size=(3, 10))
    v = np.random.random(size=(3, 10))
    o = PhaseSpacePosition(pos=x, vel=v)

    with coord.galactocentric_frame_defaults.set('v4.0'):
        with pytest.raises(u.UnitConversionError):
            o.to_coord_frame(Galactic())

    # simple / with units
    x = np.random.random(size=(3, 10)) * u.kpc
    v = np.random.normal(0., 100., size=(3, 10)) * u.km / u.s
    o = PhaseSpacePosition(pos=x, vel=v)
    with coord.galactocentric_frame_defaults.set('v4.0'):
        coo = o.to_coord_frame(Galactic())
    assert coo.name == 'galactic'

    # doesn't work for 2D
    x = np.random.random(size=(2, 10)) * u.kpc
    v = np.random.normal(0., 100., size=(2, 10)) * u.km / u.s
    o = PhaseSpacePosition(pos=x, vel=v)
    with coord.galactocentric_frame_defaults.set('v4.0'):
        with pytest.raises(ValueError):
            o.to_coord_frame(Galactic())
Exemple #5
0
def genGalPlane():  #building galactic plane in ICRS coordinates
    """Generates galactic plane line to plot on sky map
       output: galicrs ndarray(SkyCoord)
    """
    galcoords = Galactic(l=np.arange(0, 360, 1) * u.deg,
                         b=np.zeros(360) * u.deg)
    galicrs = galcoords.transform_to(coordinates.ICRS)
    galicrs.dec[117] = np.nan * u.deg
    return galicrs
Exemple #6
0
class MagellanicStreamNidever08(BaseCoordinateFrame):
    """
    A coordinate or frame aligned with the Magellanic Stream,
    as defined by Nidever et al. (2008,
    see: `<http://adsabs.harvard.edu/abs/2008ApJ...679..432N>`_).

    For more information about this class, see the Astropy documentation
    on coordinate frames in :mod:`~astropy.coordinates`.

    Examples
    --------
    Converting the coordinates of the Large Magellanic Cloud:

        >>> from astropy import coordinates as coord
        >>> from astropy import units as u
        >>> from gala.coordinates import MagellanicStreamNidever08

        >>> c = coord.Galactic(l=280.4652*u.deg, b=-32.8884*u.deg)
        >>> ms = c.transform_to(MagellanicStreamNidever08())
        >>> print(ms)
        <MagellanicStreamNidever08 Coordinate: (L, B) in deg
            (-0.13686116, 2.42583948)>
    """

    frame_specific_representation_info = {
        r.SphericalRepresentation:
        [RepresentationMapping('lon', 'L'),
         RepresentationMapping('lat', 'B')]
    }

    default_representation = r.SphericalRepresentation
    default_differential = r.SphericalCosLatDifferential

    _ngp = Galactic(l=188.5 * u.deg, b=-7.5 * u.deg)
    _lon0 = Galactic(l=280.47 * u.deg, b=-32.75 * u.deg)

    _default_wrap_angle = 180 * u.deg

    def __init__(self, *args, **kwargs):
        wrap = kwargs.pop('wrap_longitude', True)
        super().__init__(*args, **kwargs)
        if wrap and isinstance(
                self._data,
            (r.UnitSphericalRepresentation, r.SphericalRepresentation)):
            self._data.lon.wrap_angle = self._default_wrap_angle

    # TODO: remove this. This is a hack required as of astropy v3.1 in order
    # to have the longitude components wrap at the desired angle
    def represent_as(self, base, s='base', in_frame_units=False):
        r = super().represent_as(base, s=s, in_frame_units=in_frame_units)
        if hasattr(r, "lon"):
            r.lon.wrap_angle = self._default_wrap_angle
        return r

    represent_as.__doc__ = BaseCoordinateFrame.represent_as.__doc__
Exemple #7
0
def main():

    cat_K = scutil.read_cat('../../../catalog.dat')
    cat_fof = read_cat_fof('../ginfos_merge.npy')

    #    print 'Total clusters in K13: %d' % (len(cat_K))

    id0 = np.arange(len(cat_K), dtype=int)
    ids = np.where(np.abs(cat_K['b']) < 25.)[0]
    cat_K = cat_K[ids]
    id0 = id0[ids]
    #    print 'Total cluster in K13 with |b| < 25 degree: %d' % (len(cat_K))

    c_K = Galactic(l=cat_K['l'] * u.degree, b=cat_K['b'] * u.degree)
    c_fof = Galactic(l=cat_fof[:, 1] * u.degree, b=cat_fof[:, 2] * u.degree)

    ids_K, sep2d, _ = match_coordinates_sky(c_fof, c_K)
    #    print ids_K
    #    print sep2d.degree

    r_match = sep2d.degree

    r_K = cat_K['r2'][ids_K]
    id0 = id0[ids_K]
    r_fof = cat_fof[:, 3]

    b0 = r_match < r_fof
    b1 = r_match < r_K

    ids = np.where(np.logical_and(b0, b1))[0]
    #    ids =   np.where(np.logical_not(np.logical_and(b0, b1)))[0]
    #    ids =   np.arange(len(b0))

    cls_sc = np.loadtxt('../sc_info.txt')[:, -1].astype(int)

    #    cls_sc  =   np.zeros(len(cat_fof), dtype = int)
    #    for icls in range(1, 5):
    #        arr =   np.loadtxt('c%1d/c%1d.txt' % (icls, icls))
    #        n   =   len(arr)
    #        idc =   arr[:, 0].astype(int)
    #        cls_sc[idc] =   icls

    print '# idx_in_fof    separation    r_fof    r_K13'
    for id in ids:
        print '%04d\t%.3f\t%.3f\t%.3f\t%04d\t%1d' % \
            (id, r_match[id], r_fof[id], r_K[id], id0[id], cls_sc[id])

    cls = cls_sc[ids]
    l1 = len(np.where(cls == 1)[0])
    l2 = len(np.where(cls == 2)[0])
    l3 = len(np.where(cls == 3)[0])
    print '# %d %d %d' % (l1, l2, l3)
Exemple #8
0
def transform_to_galactic(icrs_coords):
    """
    For the input astrometry plus radial velocity in the ICRS system calculate the barycentric Galactic
    coordinates as well as Galactocentric coordinates.

    Parameters
    ----------

    icrs_coords: astropy.coordinates.ICRS
        ICRS instance constructed from the 5-parameter Gaia DR2 astrometry and the radial velocity.

    Returns
    -------

    Galactic and Galactocentric objects containing the astrometry in Galactic coordinates, the
    galactocentric Cartesian coordinates, and the galactocentric cylindrical coordinates.
    """

    galactic_coords = icrs_coords.transform_to(Galactic())
    sun_motion = CartesianDifferential(_Usun, _vc + _Vsun, _Wsun)
    galactocentric_cartesian = icrs_coords.transform_to(
        Galactocentric(galcen_distance=_Rsun,
                       z_sun=_zsun,
                       galcen_v_sun=sun_motion))
    galactocentric_cartesian.set_representation_cls(base='cartesian')
    galactocentric_cylindrical = icrs_coords.transform_to(
        Galactocentric(galcen_distance=_Rsun,
                       z_sun=_zsun,
                       galcen_v_sun=sun_motion))
    galactocentric_cylindrical.set_representation_cls(base='cylindrical')

    return galactic_coords, galactocentric_cartesian, galactocentric_cylindrical
    def get_space_frame(self, element):
            #ref_location = self.table_mapper.search_instance_by_role("coords:StdRefLocation.position", 
            #                                                root_element=ele)[0]['@value']
            #print(ref_location)               
            frame_instance = self.table_mapper.search_instance_by_type("coords:SpaceFrame", 
                                                            root_element=element)[0]
                                                            
            ref_frame = self.table_mapper.search_instance_by_role("coords:SpaceFrame.spaceRefFrame", 
                                                            root_element=frame_instance)[0]['@value'].upper()  
            if ref_frame == "Galactic":
                retour =  Galactic()
            elif ref_frame == "ICRS":
                retour =  ICRS()
            else :
                ref_equinox = self.table_mapper.search_instance_by_role("coords:SpaceFrame.equinox", 
                                                            root_element=frame_instance)[0]['@value'] 
                         
                if ref_frame == "FK4":
                    if not ref_equinox :
                        retour = FK4()
                    else:
                        retour = FK4(equinox=ref_equinox)

                elif ref_frame == "FK5":
                    if not ref_equinox :
                        retour = FK5()
                    else:
                        retour = FK5(equinox=ref_equinox)
                else:
                    raise Exception ( "unsupported frame: " + ref_frame)    
            return retour   
Exemple #10
0
 def backwards(self, l_deg, b_deg, d_kpc):
     with galactocentric_frame_defaults.set('pre-v4.0'):
         gal = Galactic(l=l_deg * u.deg,
                        b=b_deg * u.deg,
                        distance=d_kpc * u.kpc).transform_to(Galactocentric)
     return gal.x.to(u.kpc).value, gal.y.to(u.kpc).value, gal.z.to(
         u.kpc).value
Exemple #11
0
 def reproject(self, new_wcs, new_shape):
     '''
     Implement nearest-neighbour reprojection of data from one wcs to another
     wcs 'grid' image.
     CURRENTLY: only HEALPIX -> WCS supported
         work will be done to allow WCS -> WCS in future
     '''
     new_x, new_y = np.meshgrid(np.arange(new_shape[0]),
                                np.arange(new_shape[1]),
                                sparse=True)
     new_coords = new_wcs.pixel_to_world(new_x, new_y)
     if type(self.wcs) is dict:
         #HEALPIX projection
         hp = HEALPix(nside=self.wcs['nside'],
                      order=self.wcs['order'],
                      frame=Galactic())
         new_coords_hpx = hp.lonlat_to_healpix(new_coords.l, new_coords.b)
         new_map = np.zeros(new_shape)
         new_map[:] = np.nan
         new_map = self.map[new_coords_hpx]
     else:
         print('Not yet supported')
     new_map_obj = AstroMap(self.name,
                            self.freq,
                            self.freqrange,
                            self.beamwidth,
                            new_map,
                            wcs=new_wcs)
     return new_map_obj
Exemple #12
0
    def convert_to_gal_coord(self, az_el, time=None):
        """Converts an AzEl Tuple into a Galactic Tuple from Location

        Parameters
        ----------
        az_el : (float, float)
            Azimuth and Elevation to Convert
        time : AstroPy Time Obj
            Time of Conversion

        Returns
        -------
        (float, float)
            Galactic Latitude and Longitude
        """
        if time is None:
            time = Time.now()
        az, el = az_el
        start_frame = AltAz(obstime=time,
                            location=self.location,
                            alt=el * u.deg,
                            az=az * u.deg)
        end_frame = Galactic()
        result = start_frame.transform_to(end_frame)
        g_lat = float(result.b.degree)
        g_lng = float(result.l.degree)
        return g_lat, g_lng
Exemple #13
0
    def setup_method(self, method):

        self.gal = Galactic([49.4, 49.3, 49.] * u.deg,
                            [-0.4, -0.1, 0.] * u.deg)

        self.icrs = ICRS([290.77261, 290.70523, 290.71415] * u.deg,
                         [14.638866, 14.30515, 14.012249] * u.deg)
Exemple #14
0
    def load_RGES_footprint(self):

        # Location of the RGES survey field in Galactic Coordinates.
        # This is defined as a single pointing, since the survey
        # region will be ~2sq deg and fully encompassed within a single Rubin pointing
        l_center = 2.216
        b_center = -3.14
        l_width = 3.5
        b_height = 3.5
        n_points = 50

        # Represent coordinate pointings within this region as a meshgrid
        halfwidth_l = l_width / 2.0
        halfheight_b = b_height / 2.0

        l_min = max((l_center - halfwidth_l), 0)
        l_max = min((l_center + halfwidth_l), 360.0)
        b_min = max((b_center - halfheight_b), -90.0)
        b_max = min((b_center + halfheight_b), 90.0)

        l = np.linspace(l_min, l_max, n_points) * u.deg
        b = np.linspace(b_min, b_max, n_points) * u.deg

        LL, BB = np.meshgrid(l, b)

        coords = SkyCoord(LL, BB, frame=Galactic())

        # Calculate the corresponding HEALpixels
        pixels = self.ahp.skycoord_to_healpix(coords)
        self.RGES_pixels = np.unique(pixels.flatten())
Exemple #15
0
def test_match_catalog_nan():
    from astropy.coordinates import SkyCoord, Galactic

    sc1 = SkyCoord(1, 2, unit="deg")
    sc_with_nans = SkyCoord(1, np.nan, unit="deg")

    cat = SkyCoord([1.1, 3], [2.1, 5], unit="deg")
    cat_with_nans = SkyCoord([1.1, np.nan], [2.1, 5], unit="deg")
    galcat_with_nans = Galactic([1.2, np.nan] * u.deg, [5.6, 7.8] * u.deg)

    with pytest.raises(ValueError) as excinfo:
        sc1.match_to_catalog_sky(cat_with_nans)
    assert 'Catalog coordinates cannot contain' in str(excinfo.value)
    with pytest.raises(ValueError) as excinfo:
        sc1.match_to_catalog_3d(cat_with_nans)
    assert 'Catalog coordinates cannot contain' in str(excinfo.value)

    with pytest.raises(ValueError) as excinfo:
        sc1.match_to_catalog_sky(galcat_with_nans)
    assert 'Catalog coordinates cannot contain' in str(excinfo.value)
    with pytest.raises(ValueError) as excinfo:
        sc1.match_to_catalog_3d(galcat_with_nans)
    assert 'Catalog coordinates cannot contain' in str(excinfo.value)

    with pytest.raises(ValueError) as excinfo:
        sc_with_nans.match_to_catalog_sky(cat)
    assert 'Matching coordinates cannot contain' in str(excinfo.value)
    with pytest.raises(ValueError) as excinfo:
        sc_with_nans.match_to_catalog_3d(cat)
    assert 'Matching coordinates cannot contain' in str(excinfo.value)
Exemple #16
0
def test_calc_healpix_for_region():

    ahp = HEALPix(nside=NSIDE, order='ring', frame=TETE())
    ahp_test = HEALPix(nside=NSIDE, order='ring', frame=TETE())

    for target_params in [LMC_params, SMC_params]:
        r = generate_sky_maps.CelestialRegion(target_params)
        r.calc_healpixels_for_region(ahp)
        region_pixels = np.unique(r.pixels)

        corners = calc_box_corners_astropy(target_params)

        n_points = 500
        l = np.linspace(corners[0], corners[1], n_points) * u.deg
        b = np.linspace(corners[2], corners[3], n_points) * u.deg

        LL, BB = np.meshgrid(l, b)
        coords = np.stack((LL.flatten(), BB.flatten()), axis=1)
        pointings = SkyCoord(coords[:, 0], coords[:, 1], frame=Galactic())

        coords_in_region = calc_points_in_circle_original(
            target_params, coords)

        pixels = ahp_test.skycoord_to_healpix(coords_in_region)
        test_pixels = np.unique(pixels.flatten())

        assert np.all(region_pixels == test_pixels)
Exemple #17
0
def main():

    cat = scutil.read_B19('../../../Bica.txt')
    cat_fof = read_cat_fof('../ginfos_merge.npy')

    #    print 'Total clusters in K13: %d' % (len(cat_K))

    id0 = np.arange(len(cat), dtype=int)
    ids = np.where(np.abs(cat['b']) < 25.)[0]
    cat = cat[ids]
    id0 = id0[ids]
    print('# Total cluster in B19 with |b| < 25 degree: %d' % (len(cat)))

    c = Galactic(l=cat['l'] * u.degree, b=cat['b'] * u.degree)
    c_fof = Galactic(l=cat_fof[:, 1] * u.degree, b=cat_fof[:, 2] * u.degree)

    ids, sep2d, _ = match_coordinates_sky(c_fof, c)
    #    print ids_K
    #    print sep2d.degree

    r_match = sep2d.degree

    r = cat['r'][ids]
    id0 = id0[ids]
    r_fof = cat_fof[:, 3]

    b0 = r_match < r_fof
    b1 = r_match < r

    ids = np.where(np.logical_and(b0, b1))[0]
    #    ids =   np.where(np.logical_not(np.logical_and(b0, b1)))[0]

    #    ids =   np.where(np.logical_or(b0, b1))[0]
    #    ids =   np.where(np.logical_not(np.logical_or(b0, b1)))[0]

    cls_sc = np.loadtxt('../sc_info.txt')[:, -1].astype(int)

    print('# idx_in_fof    separation    r_fof    r_B19')
    for id in ids:
        print ('%04d\t%.3f\t%.3f\t%.3f\t%04d\t%1d' % \
            (id, r_match[id], r_fof[id], r[id], id0[id], cls_sc[id]))

    cls = cls_sc[ids]
    l1 = len(np.where(cls == 1)[0])
    l2 = len(np.where(cls == 2)[0])
    l3 = len(np.where(cls == 3)[0])
    print('# %d %d %d' % (l1, l2, l3))
Exemple #18
0
 def test_add_point_invalid(self):
     path = Path(self.pixel)
     with pytest.raises(TypeError) as exc:
         path.add_point(Galactic(49.5 * u.deg, -0.5 * u.deg))
     assert exc.value.args[0] == ("Path is defined as a list of pixel "
                                  "coordinates, so `xy_or_coord` "
                                  "should be a tuple of `(x,y)` "
                                  "pixel coordinates.")
    def calc_ap_healpixels_for_region(self, ahp):

        if not self.predefined_pixels:
            self.skycoord = SkyCoord(self.l_center * u.deg,
                                     self.b_center * u.deg,
                                     frame=Galactic())
            self.pixels = ahp.cone_search_skycoord(self.skycoord,
                                                   self.halfwidth)
Exemple #20
0
def bono_survey_regions():

    n_points = 500
    l = np.linspace(-20.0, 20.0, n_points) * u.deg
    b = np.linspace(-15.0, 10.0, n_points) * u.deg
    LL, BB = np.meshgrid(l, b)
    coords = SkyCoord(LL, BB, frame=Galactic())
    shallow_pix = ahp.skycoord_to_healpix(coords)

    n_points = 100
    l = np.linspace(-20.0, 20.0, n_points) * u.deg
    b = np.linspace(-3.0, 3.0, n_points) * u.deg
    LL, BB = np.meshgrid(l, b)
    coords = SkyCoord(LL, BB, frame=Galactic())
    deep_pix = ahp.skycoord_to_healpix(coords)

    return shallow_pix, deep_pix
Exemple #21
0
class MagellanicStream(BaseCoordinateFrame):
    """
    A coordinate or frame aligned with the Magellanic Stream,
    as defined by Nidever et al. (2008,
    see: `<http://adsabs.harvard.edu/abs/2008ApJ...679..432N>`_).

    For more information about this class, see the Astropy documentation
    on coordinate frames in :mod:`~astropy.coordinates`.

    Example
    -------
    Converting the coordinates of the Large Magellanic Cloud:

        >>> from astropy import coordinates as coord
        >>> from astropy import units as u
        >>> from gala.coordinates import MagellanicStream

        >>> c = coord.Galactic(l=280.4652*u.deg, b=-32.8884*u.deg)
        >>> ms = c.transform_to(MagellanicStream)
        >>> print(ms)
        <MagellanicStream Coordinate: (L, B) in deg
            (-0.13686116, 2.42583948)>
    """

    frame_specific_representation_info = {
        r.SphericalRepresentation: [
            RepresentationMapping('lon', 'L'),
            RepresentationMapping('lat', 'B')
        ]
    }

    default_representation = r.SphericalRepresentation
    default_differential = r.SphericalCosLatDifferential

    _ngp = Galactic(l=188.5*u.deg, b=-7.5*u.deg)
    _lon0 = Galactic(l=280.47*u.deg, b=-32.75*u.deg)

    _default_wrap_angle = 180*u.deg

    def __init__(self, *args, **kwargs):
        wrap = kwargs.pop('wrap_longitude', True)
        super().__init__(*args, **kwargs)
        if wrap and isinstance(self._data, (r.UnitSphericalRepresentation,
                                            r.SphericalRepresentation)):
            self._data.lon.wrap_angle = self._default_wrap_angle
Exemple #22
0
def _wcs_to_celestial_frame_builtin(wcs):

    # Import astropy.coordinates here to avoid circular imports
    from astropy.coordinates import (FK4, FK4NoETerms, FK5, ICRS, ITRS,
                                     Galactic, SphericalRepresentation)

    # Import astropy.time here otherwise setup.py fails before extensions are compiled
    from astropy.time import Time

    if wcs.wcs.lng == -1 or wcs.wcs.lat == -1:
        return None

    radesys = wcs.wcs.radesys

    if np.isnan(wcs.wcs.equinox):
        equinox = None
    else:
        equinox = wcs.wcs.equinox

    xcoord = wcs.wcs.ctype[wcs.wcs.lng][:4]
    ycoord = wcs.wcs.ctype[wcs.wcs.lat][:4]

    # Apply logic from FITS standard to determine the default radesys
    if radesys == '' and xcoord == 'RA--' and ycoord == 'DEC-':
        if equinox is None:
            radesys = "ICRS"
        elif equinox < 1984.:
            radesys = "FK4"
        else:
            radesys = "FK5"

    if radesys == 'FK4':
        if equinox is not None:
            equinox = Time(equinox, format='byear')
        frame = FK4(equinox=equinox)
    elif radesys == 'FK4-NO-E':
        if equinox is not None:
            equinox = Time(equinox, format='byear')
        frame = FK4NoETerms(equinox=equinox)
    elif radesys == 'FK5':
        if equinox is not None:
            equinox = Time(equinox, format='jyear')
        frame = FK5(equinox=equinox)
    elif radesys == 'ICRS':
        frame = ICRS()
    else:
        if xcoord == 'GLON' and ycoord == 'GLAT':
            frame = Galactic()
        elif xcoord == 'TLON' and ycoord == 'TLAT':
            # The default representation for ITRS is cartesian, but for WCS
            # purposes, we need the spherical representation.
            frame = ITRS(representation_type=SphericalRepresentation,
                         obstime=wcs.wcs.dateobs or None)
        else:
            frame = None

    return frame
Exemple #23
0
def _wcs_to_celestial_frame_builtin(wcs):

    # Import astropy.coordinates here to avoid circular imports
    from astropy.coordinates import FK4, FK4NoETerms, FK5, ICRS, ITRS, Galactic

    # Import astropy.time here otherwise setup.py fails before extensions are compiled
    from astropy.time import Time

    # Keep only the celestial part of the axes
    wcs = wcs.sub([WCSSUB_LONGITUDE, WCSSUB_LATITUDE])

    if wcs.wcs.lng == -1 or wcs.wcs.lat == -1:
        return None

    radesys = wcs.wcs.radesys

    if np.isnan(wcs.wcs.equinox):
        equinox = None
    else:
        equinox = wcs.wcs.equinox

    xcoord = wcs.wcs.ctype[0][:4]
    ycoord = wcs.wcs.ctype[1][:4]

    # Apply logic from FITS standard to determine the default radesys
    if radesys == '' and xcoord == 'RA--' and ycoord == 'DEC-':
        if equinox is None:
            radesys = "ICRS"
        elif equinox < 1984.:
            radesys = "FK4"
        else:
            radesys = "FK5"

    if radesys == 'FK4':
        if equinox is not None:
            equinox = Time(equinox, format='byear')
        frame = FK4(equinox=equinox)
    elif radesys == 'FK4-NO-E':
        if equinox is not None:
            equinox = Time(equinox, format='byear')
        frame = FK4NoETerms(equinox=equinox)
    elif radesys == 'FK5':
        if equinox is not None:
            equinox = Time(equinox, format='jyear')
        frame = FK5(equinox=equinox)
    elif radesys == 'ICRS':
        frame = ICRS()
    else:
        if xcoord == 'GLON' and ycoord == 'GLAT':
            frame = Galactic()
        elif xcoord == 'TLON' and ycoord == 'TLAT':
            frame = ITRS(obstime=wcs.wcs.dateobs or None)
        else:
            frame = None

    return frame
Exemple #24
0
def is_overlap(g0, g1):

    fac = 1.0

    p0 = Galactic(l=g0[1] * u.degree, b=g0[2] * u.degree)
    p1 = Galactic(l=g1[1] * u.degree, b=g1[2] * u.degree)
    dr = p0.separation(p1).degree
    if dr > (g0[3] + g1[3]) * fac:
        return False

    dpm = np.sqrt((g0[4] - g1[4])**2 + (g0[5] - g1[5])**2)
    if dpm > (g0[6] + g1[6]) * fac:
        return False

    dplx = np.abs(g0[7] - g1[7])
    if dplx > (g0[8] + g1[8]) * fac:
        return False

    return True
Exemple #25
0
def make_frame(frame):
    if isinstance(frame, BaseCoordinateFrame):
        return frame
    elif isinstance(frame, str):
        if frame == 'icrs':
            return ICRS()
        elif frame == 'galactic':
            return Galactic()
        else:
            raise ValueError(f'Invalid value for frame: {frame!r}')
    else:
        raise TypeError(f'Invalid type for frame: {type(frame)}')
    def calc_hp_healpixels_for_region(self):

        if not self.predefined_pixels:
            self.skycoord = SkyCoord(self.l_center * u.deg,
                                     self.b_center * u.deg,
                                     frame=Galactic())
            self.skycoord = self.skycoord.transform_to('icrs')
            phi = np.deg2rad(self.skycoord.ra.deg)
            theta = (np.pi / 2.0) - np.deg2rad(self.skycoord.dec.deg)
            radius = np.deg2rad(self.halfwidth.data)
            xyz = hp.ang2vec(theta, phi)
            self.pixels = hp.query_disc(self.NSIDE, xyz, radius)
Exemple #27
0
    def _interpolate(cls, coords, hpmap, nside, order):
        hp = HEALPix(nside=nside, order=order, frame=Galactic())

        i = hp.interpolate_bilinear_skycoord(coords, hpmap)

        if np.any(np.isnan(i)):
            warnings.warn(
                "Result contains NaN values corresponding to UNSEEN coordinates.",
                AstropyWarning,
            )

        return i
Exemple #28
0
def CheckCoord(Coord, CoordType):
  degtorad = math.pi/180
  Coord = Coord.strip()
  if "," in Coord:
    lon = Coord.split(",")[0].strip()
    lat = Coord.split(",")[1].strip()
    if len(lon.split()) == 3:
      lon_hr = float (lon.split()[0])
      lon_min = float (lon.split()[1])
      lon_sec = float (lon.split()[2])
      lat_deg = float (lat.split()[0])
      lat_min = float (lat.split()[1])
      lat_sec = float (lat.split()[2])
      lon = lon_hr*15. + lon_min/60. + lon_sec/3600.
      lat = lat_deg + lat_min/60. + lat_sec/3600.
    else:
      lon = float(lon)
      lat = float(lat)
  else:
    lon = Coord.split()[0]
    lat = Coord.split()[1]
    lon = float (lon)
    lat = float (lat)
  if CoordType == "J2000":
#mjd for 2000-01-01
    #(elon,elat) = slalib.sla_eqecl(lon*degtorad, lat*degtorad, 51544.0)
    gc = FK5(ra=lon*u.degree, dec=lat*u.degree)
    hec = gc.transform_to(BarycentricTrueEcliptic)
    (elon,elat) = (hec.lon.value*degtorad, hec.lat.value*degtorad)
  elif CoordType == "Galactic":
    #(ra,dec) = slalib.sla_galeq(lon*degtorad, lat*degtorad)
    #(elon,elat) = slalib.sla_eqecl(ra,dec,51544.0)
    gc = Galactic(l=lon*u.degree,b=lat*u.degree)
    hec = gc.transform_to(BarycentricTrueEcliptic)
    (elon,elat) = (hec.lon.value*degtorad, hec.lat.value*degtorad)
  else:
    elon = lon*degtorad
    elat = lat*degtorad
#    return (elon, elat)
  return (elon, elat)
Exemple #29
0
def _wcs_to_celestial_frame_builtin(wcs):

    from astropy.coordinates import FK4, FK4NoETerms, FK5, ICRS, Galactic
    from astropy.time import Time
    from astropy.wcs import WCSSUB_CELESTIAL

    # Keep only the celestial part of the axes
    wcs = wcs.sub([WCSSUB_CELESTIAL])

    if wcs.wcs.lng == -1 or wcs.wcs.lat == -1:
        return None

    radesys = wcs.wcs.radesys

    if np.isnan(wcs.wcs.equinox):
        equinox = None
    else:
        equinox = wcs.wcs.equinox

    xcoord = wcs.wcs.ctype[0][:4]
    ycoord = wcs.wcs.ctype[1][:4]

    # Apply logic from FITS standard to determine the default radesys
    if radesys == '' and xcoord == 'RA--' and ycoord == 'DEC-':
        if equinox is None:
            radesys = "ICRS"
        elif equinox < 1984.:
            radesys = "FK4"
        else:
            radesys = "FK5"

    if radesys == 'FK4':
        if equinox is not None:
            equinox = Time(equinox, format='byear')
        frame = FK4(equinox=equinox)
    elif radesys == 'FK4-NO-E':
        if equinox is not None:
            equinox = Time(equinox, format='byear')
        frame = FK4NoETerms(equinox=equinox)
    elif radesys == 'FK5':
        if equinox is not None:
            equinox = Time(equinox, format='jyear')
        frame = FK5(equinox=equinox)
    elif radesys == 'ICRS':
        frame = ICRS()
    else:
        if xcoord == 'GLON' and ycoord == 'GLAT':
            frame = Galactic()
        else:
            frame = None

    return frame
Exemple #30
0
 def coordinates(self):
     if type(self.wcs) is dict:
         hp = HEALPix(nside=self.wcs['nside'],
                      order=self.wcs['order'],
                      frame=Galactic())
         coords = hp.healpix_to_skycoord(np.arange(self.map.shape[0]))
         return coords
     else:
         x, y = np.meshgrid(np.arange(self.map.shape[1]),
                            np.arange(self.map.shape[0]),
                            sparse=True)
         coords = self.wcs.pixel_to_world(x, y)
         return coords
Exemple #31
0
def gal2fk5(l, b):
    c = Galactic(l * u.deg, b * u.deg)
    out = c.transform_to(FK5)
    return out.ra.degree, out.dec.degree
Exemple #32
0
"""
Resample test.hpx into Galactic coordinates, and create test_gal.hpx
"""
import numpy as np
import healpy as hp
from astropy.coordinates import Galactic, FK5
import astropy.units as u

nest = True
map = hp.read_map('test.hpx', nest=nest)

theta, phi = hp.pix2ang(64, np.arange(map.size), nest)
l, b = phi, np.pi / 2 - theta

g = Galactic(l, b, unit=(u.rad, u.rad))
f = g.transform_to(FK5)
ra, dec = f.ra.rad, f.dec.rad

map = hp.get_interp_val(map, np.pi / 2 - dec, ra, nest)

hp.write_map('test_gal.hpx', map, nest=nest, coord='G',
             fits_IDL=False)