How to use the astropy.coordinates.SkyCoord function in astropy

To help you get started, weā€™ve selected a few astropy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lsst / afw / tests / test_skyWcs.py View on Github external
def astropySkyToPixels(self, astropyWcs, skyPosList):
        """Use an astropy wcs to convert pixels to sky

        @param[in] astropyWcs  a celestial astropy.wcs.WCS with 2 axes in RA, Dec order
        @param[in] skyPosList ICRS sky coordinates as a list of lsst.geom.SpherePoint
        @returns a list of lsst.geom.Point2D, 0-based pixel positions

        Converts the input from ICRS to the coordinate system of the wcs
        """
        skyCoordList = [astropy.coordinates.SkyCoord(c[0].asDegrees(),
                                                     c[1].asDegrees(),
                                                     frame="icrs",
                                                     unit="deg") for c in skyPosList]
        xyArr = [astropy.wcs.utils.skycoord_to_pixel(coords=sc,
                                                     wcs=astropyWcs,
                                                     origin=0,
                                                     mode="all") for sc in skyCoordList]
        # float is needed to avoid truncation to int
        return [lsst.geom.Point2D(float(x), float(y)) for x, y in xyArr]
github TOMToolkit / tom_base / tom_alerts / brokers / gaia.py View on Github external
response.raise_for_status()

        html_data = response.text.split('\n')
        for line in html_data:
            if 'var alerts' in line:
                alerts_data = line.replace('var alerts = ', '')
                alerts_data = alerts_data.replace('\n', '').replace(';', '')

        alert_list = json.loads(alerts_data)

        if parameters['cone'] is not None and len(parameters['cone']) > 0:
            cone_params = parameters['cone'].split(',')
            parameters['cone_ra'] = float(cone_params[0])
            parameters['cone_dec'] = float(cone_params[1])
            parameters['cone_radius'] = float(cone_params[2])*u.deg
            parameters['cone_centre'] = SkyCoord(float(cone_params[0]),
                                                 float(cone_params[1]),
                                                 frame="icrs", unit="deg")

        filtered_alerts = []
        if parameters['target_name'] is not None and \
                len(parameters['target_name']) > 0:
            for alert in alert_list:
                if parameters['target_name'] in alert['name']:
                    filtered_alerts.append(alert)

        elif 'cone_radius' in parameters.keys():
            for alert in alert_list:
                c = SkyCoord(float(alert['ra']), float(alert['dec']),
                             frame="icrs", unit="deg")
                if parameters['cone_centre'].separation(c) <= parameters['cone_radius']:
                    filtered_alerts.append(alert)
github AstroJacobLi / mrf / mrf / download.py View on Github external
from astropy.coordinates import SkyCoord
    from .utils import save_to_fits
    import subprocess

    ## Download survey-brick.fits
    URL = 'https://portal.nersc.gov/project/cosmo/data/legacysurvey/dr8/survey-bricks.fits.gz'

    if os.path.isfile('_survey_brick.fits'):
        os.remove('_survey_brick.fits')
    urllib.request.urlretrieve(URL, filename='_survey_brick.fits', data=None)

    # Find nearby bricks 
    bricks_cat = Table.read('_survey_brick.fits', format='fits')
    bricks_sky = SkyCoord(ra=np.array(bricks_cat['RA']), 
                          dec=np.array(bricks_cat['DEC']), unit='deg')
    object_coord = SkyCoord(ra, dec, unit='deg')
    to_download = bricks_cat[bricks_sky.separation(object_coord) <= radius]
    print('# You have {} bricks to be downloaded.'.format(len(to_download)))
    filenameset = []
    for obj in to_download:
        file = '_brick_' + obj['BRICKNAME'] + '_{}.fits'.format(band)
        filenameset.append(os.path.join(output_dir, file))
        if not os.path.isfile(file):
            download_decals_brick(obj['BRICKNAME'], band.lower(), output_name='_brick', 
                                output_dir=output_dir, verbose=verbose)
            hdu = fits.open(os.path.join(output_dir, file))
            img = hdu[1].data
            hdr = hdu[1].header
            hdr['XTENSION'] = 'IMAGE'
            hdu.close()
            save_to_fits(img, os.path.join(output_dir, file), header=hdr);
github astropy / astroquery / astroquery / utils / commons.py View on Github external
def ICRSCoordGenerator(*args, **kwargs):
    return coord.SkyCoord(*args, frame='icrs', **kwargs)
github cta-observatory / ctapipe / ctapipe / tools / muon_reconstruction.py View on Github external
def get_pixel_coords(self, tel_id):
        """Get pixel coords in telescope frame for telescope with id `tel_id`"""
        # memoize transformation
        if tel_id not in self.pixels_in_tel_frame:
            telescope = self.source.subarray.tel[tel_id]
            cam = telescope.camera.geometry
            camera_frame = CameraFrame(
                focal_length=telescope.optics.equivalent_focal_length,
                rotation=cam.cam_rotation,
            )
            cam_coords = SkyCoord(x=cam.pix_x, y=cam.pix_y, frame=camera_frame)
            tel_coord = cam_coords.transform_to(TelescopeFrame())
            self.pixels_in_tel_frame[tel_id] = tel_coord

        coords = self.pixels_in_tel_frame[tel_id]
        return coords.fov_lon, coords.fov_lat
github lsst / sims_featureScheduler / bin.src / animate_night.py View on Github external
def is_NES(nside=64, width=15, dec_min=0., fill_gap=True):
    """
    Define the North Ecliptic Spur region. Return a healpix map with NES pixels as true.
    """
    ra, dec = ra_dec_hp_map(nside=nside)
    result = np.zeros(ra.size)
    coord = SkyCoord(ra=ra*u.rad, dec=dec*u.rad)
    eclip_lat = coord.barycentrictrueecliptic.lat.radian
    good = np.where((np.abs(eclip_lat) <= np.radians(width)) & (dec > dec_min))
    result[good] += 1

    if fill_gap:
        good = np.where((dec > np.radians(dec_min)) & (ra < np.radians(180)) &
                        (dec < np.radians(width)))
        result[good] = 1

    NES_indx = (result==1)

    return NES_indx
github fermiPy / fermipy / fermipy / validate / tools.py View on Github external
def calc_sep(self, tab, src_list):

        print('calculating separations')

        src_tab = catalog.Catalog3FGL().table
        m = utils.find_rows_by_string(
            src_tab, src_list, ['Source_Name', 'ASSOC1', 'ASSOC2'])
        rows = src_tab[m]
        src_skydir = SkyCoord(rows['RAJ2000'], rows['DEJ2000'], unit='deg')
        evt_skydir = SkyCoord(tab['RA'], tab['DEC'], unit='deg')
        lat_skydir = SkyCoord(tab['PtRaz'], tab['PtDecz'], unit='deg')
        evt_sep = evt_skydir.separation(src_skydir[:, None]).deg
        evt_ebin = utils.val_to_bin(self._energy_bins, tab['ENERGY'])
        evt_xsep = evt_sep / self._psf_scale[evt_ebin][None, :]
        evt_ctheta = np.cos(lat_skydir.separation(src_skydir[:, None]).rad)

        return evt_sep, evt_xsep, evt_ctheta
github fermiPy / fermipy / fermipy / sourcefind.py View on Github external
peaks : list
           List of peak objects.

        sources : list
           List of source objects.

        """
        timer = Timer.create(start=True)
        self.logger.info('Starting.')

        schema = ConfigSchema(self.defaults['sourcefind'],
                              tsmap=self.defaults['tsmap'],
                              tscube=self.defaults['tscube'])

        schema.add_option('search_skydir', None, '', SkyCoord)
        schema.add_option('search_minmax_radius', [None, 1.0], '', list)

        config = utils.create_dict(self.config['sourcefind'],
                                   tsmap=self.config['tsmap'],
                                   tscube=self.config['tscube'])
        config = schema.create_config(config, **kwargs)

        # Defining default properties of test source model
        config['model'].setdefault('Index', 2.0)
        config['model'].setdefault('SpectrumType', 'PowerLaw')
        config['model'].setdefault('SpatialModel', 'PointSource')
        config['model'].setdefault('Prefactor', 1E-13)

        o = {'sources': [], 'peaks': []}

        for i in range(config['max_iter']):
github xinglunju / tdviz / TDViz3.py View on Github external
bar_y = [self.yrang-10, self.yrang-10]
            bar_z = np.array([5, 5+vspan_pix])*self.zscale
            mlab.plot3d(bar_x, bar_y, bar_z, color=tcolor, tube_radius=1.)
            mlab.text3d(self.xrang,self.yrang-25,10,'{:.1f} km/s'.format(vspan),scale=fontsize,orient_to_camera=False,color=tcolor,orientation=(0,90,0))
        
        # Label the coordinates of the corners
        # Lower left corner
        ra0 = self.extent[0]; dec0 = self.extent[2]
        c = SkyCoord(ra=ra0*u.degree, dec=dec0*u.degree, frame='icrs')
        RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s'
        mlab.text3d(0,-10,self.zrang+5,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
        DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s'
        mlab.text3d(-40,0,self.zrang+5,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
        # Upper right corner
        ra0 = self.extent[1]; dec0 = self.extent[3]
        c = SkyCoord(ra=ra0*u.degree, dec=dec0*u.degree, frame='icrs')
        RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s'
        mlab.text3d(self.xrang,-10,self.zrang+5,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
        DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s'
        mlab.text3d(-40,self.yrang,self.zrang+5,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
        # V axis
        if self.extent[5] > self.extent[4]:
            v0 = self.extent[4]; v1 = self.extent[5]
        else:
            v0 = self.extent[5]; v1 = self.extent[4]
        mlab.text3d(-10,-10,self.zrang,str(round(v0,1)),scale=fontsize,orient_to_camera=True,color=tcolor)
        mlab.text3d(-10,-10,0,str(round(v1,1)),scale=fontsize,orient_to_camera=True,color=tcolor)
        
        mlab.axes(self.field, ranges=self.extent, x_axis_visibility=False, y_axis_visibility=False, z_axis_visibility=False)
        mlab.outline()
github gammapy / gammapy / gammapy / data / event_list.py View on Github external
def pointing_radec(self):
        """Pointing RA / DEC sky coordinates (`~astropy.coordinates.SkyCoord`)."""
        info = self.table.meta
        lon, lat = info["RA_PNT"], info["DEC_PNT"]
        return SkyCoord(lon, lat, unit="deg", frame="icrs")