How to use the astropy.coordinates.Angle 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 consensys-space / trusat-orbit / tests / test_iod.py View on Github external
self.assertAlmostEqual(angle.EL,el_iod4.deg,6, msg="IOD Format 4 failed in EL")
        self.assertEqual(angle.Epoch,2000)

        # 		 5: AZ/EL  = DDDMMmm+DDMMmm MX   (MX in minutes of arc)
        #              IOD 5 1835170-081148 (1855 epoch)
        az_iod5  = Angle('183d51.70m')  # (DDDMMmm)
        el_iod5 = Angle('-08d11.48m') # (DDMMmm)

        angle = iod.Angle(5,5,'1835170-081148',0,"","IOD")
        self.assertAlmostEqual(angle.AZ,az_iod5.deg,6, msg="IOD Format 5 failed in AZ")
        self.assertAlmostEqual(angle.EL,el_iod5.deg,6, msg="IOD Format 5 failed in EL")
        self.assertEqual(angle.Epoch,2000)

        # 		 6: AZ/EL  = DDDdddd+DDdddd MX   (MX in degrees of arc)
        #              IOD 6 0214030+732900
        az_iod6  = Angle('021.4030d')  # (DDDdddd)
        el_iod6 = Angle('73.2900d')   # (DDdddd)

        angle = iod.Angle(6,5,'0214030+732900',0,"","IOD")
        self.assertAlmostEqual(angle.AZ,az_iod6.deg,6, msg="IOD Format 6 failed in AZ")
        self.assertAlmostEqual(angle.EL,el_iod6.deg,6, msg="IOD Format 6 failed in EL")
        self.assertEqual(angle.Epoch,2000)

        # 		 7: RA/DEC = HHMMSSs+DDdddd MX   (MX in degrees of arc)
        #              IOD 7 2047449+293762
        ra_iod7  = Angle('20h47m44.9s')  # (HHMMSSs)
        dec_iod7 = Angle('29.3762d')     # (DDdddd)

        angle = iod.Angle(7,5,'2047449+293762',0,"","IOD")
        self.assertAlmostEqual(angle.RA,ra_iod7.deg,6, msg="IOD Format 7 failed in RA")
        self.assertAlmostEqual(angle.DEC,dec_iod7.deg,6, msg="IOD Format 7 failed in DEC")
        self.assertEqual(angle.Epoch,2000)
github glue-viz / glue / glue / external / pvextractor / pvregions.py View on Github external
coordre = re.compile("^[a-z]*\((.*)\)")
    coord_list = coordre.findall(rs)
    if len(coord_list) != 1:
        raise ValueError("Invalid region")

    coords = coord_list[0].split(",")

    outcoords = []
    for ii,cs in enumerate(coords):
        if coord_format in csystems:
            if ":" in cs:
                # sexagesimal
                if coord_format in cel_systems and ii % 2 == 0:
                    # odd, celestial = RA = hours
                    crd = coordinates.Angle(cs, unit=u.hour)
                else:
                    crd = coordinates.Angle(cs, unit=u.deg)
            else:
                try:
                    # if it's a float, it's in degrees
                    crd = float(cs) * u.deg
                except ValueError:
                    crd = coordinates.Angle(cs)
        else:
            # assume pixel units
            crd = float(cs)
        outcoords.append(crd)

    reg = SimpleRegion(coord_list=outcoords, coord_format=coord_format,
                       name=rtype)
github lofar-astron / prefactor / scripts / make_clean_mask.py View on Github external
"""
    with open(filename, 'r') as f:
        lines = f.readlines()

    polys = []
    for line in lines:
        if line.startswith('poly'):
            poly_str_temp = line.split('[[')[1]
            poly_str = poly_str_temp.split(']]')[0]
            poly_str_list = poly_str.split('], [')
            ra = []
            dec = []
            for pos in poly_str_list:
                RAstr, Decstr = pos.split(',')
                ra.append(Angle(RAstr, unit='hourangle').to('deg').value)
                dec.append(Angle(Decstr.replace('.', ':', 2), unit='deg').to('deg').value)
            poly_vertices = [np.array(ra), np.array(dec)]

            # Convert to image-plane polygon
            xvert = []
            yvert = []
            for RAvert, Decvert in zip(np.array(ra), np.array(dec)):
                try:
                    pixels = image.topixel([0, 1, Decvert*np.pi/180.0,
                                               RAvert*np.pi/180.0])
                except:
                    pixels = image.topixel([1, 1, Decvert*np.pi/180.0,
                                               RAvert*np.pi/180.0])
                xvert.append(pixels[2]) # x -> Dec
                yvert.append(pixels[3]) # y -> RA
            polys.append(Polygon(xvert, yvert))
github gammapy / gammapy / gammapy / makers / background / reflected.py View on Github external
This assumes that the center lies outside the group of pixel

        Parameters
        ----------
        pixels : `~astropy.regions.PixCoord`
            the pixels coordinates
        center : `~astropy.regions.PixCoord`
            the center coordinate in pixels

        Returns
        -------
        angular_size : `~astropy.coordinates.Angle`
            the maximum angular size
        """
        newX, newY = center.x - pixels.x, center.y - pixels.y
        angles = Angle(np.arctan2(newX, newY), "rad")
        angular_size = np.max(angles) - np.min(angles)

        if angular_size.value > np.pi:
            angular_size = np.max(angles.wrap_at(0 * u.rad)) - np.min(
                angles.wrap_at(0 * u.rad)
            )

        return angular_size
github astropy / regions / regions / io / core.py View on Github external
if isinstance(region, SkyRegion):
                coordsys = coord[0].name
            else:
                coordsys = 'image'

        frame = coordinates.frame_transform_graph.lookup_name(coordsys)

        new_coord = []
        for val in coord:
            if isinstance(val, Angle) or isinstance(val, u.Quantity) or isinstance(val, numbers.Number):
                new_coord.append(val)
            elif isinstance(val, PixCoord):
                new_coord.append(u.Quantity(val.x, u.dimensionless_unscaled))
                new_coord.append(u.Quantity(val.y, u.dimensionless_unscaled))
            else:
                new_coord.append(Angle(val.transform_to(frame).spherical.lon))
                new_coord.append(Angle(val.transform_to(frame).spherical.lat))

        meta = dict(region.meta)
        meta.update(region.visual)

        if reg_type == 'text':
            meta['text'] = meta.get('text', meta.pop('label', ''))

        include = region.meta.pop('include', True)

        shape_list.append(Shape(coordsys, reg_type, new_coord, meta, False,
                                include))

    return shape_list
github henrysky / milkyway_plot / mw_plot / mw_plot_classes.py View on Github external
def radec_unit_check(self, ra, dec):
        if not type(ra) == u.quantity.Quantity or not type(dec) == u.quantity.Quantity:
            raise TypeError("Both RA and DEC must carry astropy's unit")
        else:
            if ra.unit is not None and dec.unit is not None:
                ra = ra.to(self._unit)
                dec = dec.to(self._unit)
                c_icrs = coord.SkyCoord(ra=ra, dec=dec, frame='icrs')
                if self.__projection == 'equirectangular':
                    ra = coord.Angle(-c_icrs.galactic.l).wrap_at(180 * u.degree).value
                    dec = coord.Angle(c_icrs.galactic.b).value
                else:  # projection requires radian instead of degree
                    ra = coord.Angle(-c_icrs.galactic.l).wrap_at(180 * u.degree).to(u.radian).value
                    dec = coord.Angle(c_icrs.galactic.b).to(u.radian).value
            else:
                raise TypeError("Both x, y, center and radius must carry astropy's unit")

        return ra, dec
github gammapy / gammapy / gammapy / irf / psf_3d.py View on Github external
def plot_containment_vs_energy(
        self, fractions=[0.68, 0.95], thetas=Angle([0, 1], "deg"), ax=None
    ):
        """Plot containment fraction as a function of energy.
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax

        energy = MapAxis.from_energy_bounds(
            self.energy_lo[0], self.energy_hi[-1], 100
        ).edges

        for theta in thetas:
            for fraction in fractions:
                radius = self.containment_radius(energy, theta, fraction)
                label = f"{theta.deg} deg, {100 * fraction:.1f}%"
                ax.plot(energy.value, radius.value, label=label)
github jrthorstensen / thorsky / thorskyutil.py View on Github external
alt : Angle
       desired altitude.
   tguess : Time
       initial guess; this needs to be fairly close.
   location : EarthLocation

   Returns 
       a Time, or None if non-convergent.
   """

   # tguess is a Time, location is an EarthLocation 
           
   moonpos, topodist = accumoon(tguess,location)
   #print "npos entering",moonpos
   #print "tguess.jd, longit:",tguess.jd, location.lon.hour
   tolerance = Angle(1.0e-4,unit=u'rad')

   delt = TimeDelta(0.002, format = 'jd')   # timestep
   #print "sidereal: ",lpsidereal(tguess, location)
   #print "moonpos.ra: ",moonpos.ra

   ha = lpsidereal(tguess,location) - moonpos.ra
   #print "ha entering",ha
   alt2,az,parang = altazparang(moonpos.dec,Angle(ha,unit=u.hourangle),location.lat)
   #print "alt2",alt2
   tguess = tguess + delt
   moonpos, topodist = accumoon(tguess,location)
   #print "moonpos with delt",moonpos
   alt3,az,parang = altazparang(moonpos.dec,lpsidereal(tguess,location) - moonpos.ra,
            location.lat)
   err = alt3 - alt;
   #print "alt3, alt, err",alt3,alt,err
github gammapy / gammapy / gammapy / maps / plotting.py View on Github external
def _set_ax_fov(self, ax, panel):
        left, bottom, width, height = self._get_ax_extend(ax, panel)

        # set fov
        xlim = Angle([left, left - width])
        ylim = Angle([bottom, bottom + height])
        xlim_pix, ylim_pix = ax.wcs.wcs_world2pix(xlim.deg, ylim.deg, 1)

        ax.set_xlim(*xlim_pix)
        ax.set_ylim(*ylim_pix)
        return ax
github jrthorstensen / thorsky / thorskyutil.py View on Github external
Parameters :
   dec : Angle
       Declination of source.
   lat : Angle
       Latitude of site.
   alt : Angle
       Height above horizon for computation.
   """

  # Arguments are all angles.
  # returns hour angle at which object at dec is at altitude alt for a
  # latitude lat.
    
   minalt, maxalt =  min_max_alt(lat,dec) 
   if alt < minalt :  return Angle(-1000., unit = u.rad)
   if alt > maxalt :  return Angle( 1000., unit = u.rad)
   rightang = Angle(np.pi / 2, unit = u.rad)
   codec = rightang - dec
   colat = rightang - lat 
   zdist = rightang - alt 
   x = (np.cos(zdist) - np.cos(codec)*np.cos(colat)) / (np.sin(codec)*np.sin(colat));
   return Angle(np.arccos(x), unit = u.rad)