def print_constellation(constellation):
    for el in constellation:

        #print(el[0] , " and " , el[1])
        star = Star.from_dataframe(df.loc[el[0]])
        star_prev = Star.from_dataframe(df.loc[el[1]])

        astrometric_star = earth.at(t).observe(star)
        ra_s, dec_s, distance_s = astrometric_star.radec()
        astrometric_star_p = earth.at(t).observe(star_prev)
        ra_s_p, dec_s_p, distance_s_p = astrometric_star_p.radec()

        hours_s = list()
        hours_s.append(ra_s.hours)
        hours_s.append(ra_s_p.hours)
        deg_s = list()
        deg_s.append(dec_s.degrees)
        deg_s.append(dec_s_p.degrees)
        #print(hours_s[0], " and " , deg_s[0])
        #print(hours_s[1], " and " , deg_s[1])

        plt.plot(hours_s, deg_s, 'bo-', linewidth=2)
        #plt.scatter(ra.hours, dec.degrees, 8 - df['magnitude'], 'k')

    plt.show()
Ejemplo n.º 2
0
def icrs_to_cirs(ra, dec, epoch, apparent=True):
    """Convert a set of positions from ICRS to CIRS at a given data.

    Parameters
    ----------
    ra, dec : float or np.ndarray
        Positions of source in ICRS coordinates including an optional
        redshift position.
    epoch : time_like
        Time to convert the positions to. Can be any type convertible to a
        time using `caput.time.ensure_unix`.
    apparent : bool
        Calculate the apparent position (includes abberation and deflection).

    Returns
    -------
    ra_cirs, dec_cirs : float or np.ndarray
        Arrays of the positions in *CIRS* coordiantes.
    """
    positions = Star(ra=Angle(degrees=ra), dec=Angle(degrees=dec))

    epoch = ctime.unix_to_skyfield_time(ctime.ensure_unix(epoch))

    earth = ctime.skyfield_wrapper.ephemeris["earth"]
    positions = earth.at(epoch).observe(positions)

    if apparent:
        positions = positions.apparent()

    ra_cirs, dec_cirs, _ = positions.cirs_radec(epoch)

    return ra_cirs._degrees, dec_cirs._degrees
Ejemplo n.º 3
0
def get_star_position( recv_time, star_name, star_name2, user_longlatdist=geographic_position):
  # if not star_name:  
  # 	star_name = 57632             #Denebola
  # if not star_name2: 
  #   star_name2 = 109074         #Sadalmelik
  
  user_longlatdist = np.array(user_longlatdist)#46.07983746062874, 26.232615661106784, 659.5100082775696
  with load.open(hipparcos.URL) as f:
    df = hipparcos.load_dataframe(f)

  planets = load('de421.bsp')
  earth = planets['earth']
  user_position = earth + Topos('{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) #user_longlatdist      user_longlatdist[0],user_longlatdist[1]
  terrestrial_time = format_time(recv_time)
  ts = load.timescale()
  t = ts.tt(terrestrial_time[0], terrestrial_time[1], terrestrial_time[2], terrestrial_time[3], terrestrial_time[4], terrestrial_time[5])
  
  denebola = Star.from_dataframe(df.loc[star_name])
  astrometric_denebola = user_position.at(t).observe(denebola)
  alt_d, az_d, distance_d = astrometric_denebola.apparent().altaz()#astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
  print('Location: ', '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1]))
  print('S1 (alt/az):   ',alt_d, az_d)
  star_pos_d = pm.aer2ecef( az_d.degrees,alt_d.degrees, distance_d.m,user_longlatdist[0],user_longlatdist[1],user_longlatdist[2])
  
  sadalmelik = Star.from_dataframe(df.loc[star_name2])
  astrometric_sadalmelik = user_position.at(t).observe(sadalmelik)
  alt_s, az_s, distance_s = astrometric_sadalmelik.apparent().altaz()
  print('S2 (alt/az):   ',alt_s, az_s)
  star_pos_s = pm.aer2ecef( az_s.degrees,alt_s.degrees, distance_s.m,user_longlatdist[0],user_longlatdist[1],user_longlatdist[2])
  
  stars_pos=[star_pos_d,star_pos_s]
  return stars_pos
Ejemplo n.º 4
0
    def get_stars_azimut_altitude(self, constellation):

        azimut_alt = list()

        for el in constellation:

            t = self.ts.now()

            #print(el[0] , " and " , el[1])
            star = Star.from_dataframe(self.df.loc[el[0]])
            star_next = Star.from_dataframe(self.df.loc[el[1]])

            astro = self.position.at(t).observe(star)
            astro_next = self.position.at(t).observe(star_next)

            app = astro.apparent()
            app_next = astro_next.apparent()

            alt, az, distance = app.altaz()
            alt_next, az_next, distance_next = app_next.altaz()

            azimut_alt.append(
                ((az.dstr().split("deg", 1)[0], alt.dstr().split("deg", 1)[0]),
                 (az_next.dstr().split("deg",
                                       1)[0], alt_next.dstr().split("deg",
                                                                    1)[0])))

        return azimut_alt
Ejemplo n.º 5
0
    def draw(self, ax, when):
        """
        Draw on a matplotlib axis.

        Draw a representation of the constellation at a certain time
        projected onto the observation disk.

        This will look a bit strange with our given projection... they'll 
        look kind of upside down.
        """
        plotted = []  # don't repeat star points

        for (ra1, dec1), (ra2, dec2) in self._radec_pairs:
            star1 = Star(ra_hours=ra1, dec_degrees=dec1)
            star2 = Star(ra_hours=ra2, dec_degrees=dec2)
            azi1, alt1 = self._sky.compute_position(star1, when)
            azi2, alt2 = self._sky.compute_position(star2, when)
            # alt1 = 90 - alt1
            # alt2 = 90 - alt2
            if alt1 > 90 and alt1 > 90:
                # skip constellations that are not visible
                continue

            if (azi1, alt1) not in plotted:
                ax.scatter(
                    azi1,
                    alt1,
                    s=10,
                    alpha=0.1,
                    color="black",
                    edgecolor="black",
                )
                plotted.append((azi1, alt1))

            if (azi2, alt2) not in plotted:
                ax.scatter(
                    azi2,
                    alt2,
                    s=10,
                    alpha=0.1,
                    color="black",
                    edgecolor="black",
                )
                plotted.append((azi2, alt2))

            # avoid wrap-arounds azimuthally
            if azi2 - azi1 > math.pi:
                azi1 += math.pi * 2
            elif azi1 - azi2 > math.pi:
                azi2 += math.pi * 2
            ax.plot(
                np.linspace(azi1, azi2, 10),
                np.linspace(alt1, alt2, 10),
                "-",
                color="k",
                linewidth=1,
                alpha=0.1,
            )
Ejemplo n.º 6
0
def cirs_radec(body, date=None, deg=False, obs=chime):
    """Converts a Skyfield body in CIRS coordinates at a given epoch to
    ICRS coordinates observed from CHIME

    Parameters
    ----------
    body : skyfield.api.Star
        Skyfield Star object with positions in CIRS coordinates.

    Returns
    -------
    new_body : skyfield.api.Star
        Skyfield Star object with positions in ICRS coordinates
    """

    from skyfield.positionlib import Angle
    from skyfield.api import Star

    ts = skyfield_wrapper.timescale

    epoch = ts.tt_jd(np.median(body.epoch))

    pos = obs.skyfield_obs().at(epoch).observe(body)

    # Matrix CT transforms from CIRS to ICRF (https://rhodesmill.org/skyfield/time.html)
    r_au, dec, ra = skyfield.functions.to_polar(
        np.einsum("ij...,j...->i...", epoch.CT, pos.position.au))

    return Star(ra=Angle(radians=ra, preference="hours"),
                dec=Angle(radians=dec),
                epoch=epoch)
Ejemplo n.º 7
0
    def transform_to_altaz(self, tf=None, sky=None, mount_set_icrs=None):
        # use ev. other refraction methods
        if sky is None:
            tem = pre = hum = 0.
        else:
            tem = sky.temperature
            pre = sky.pressure
            hum = sky.humidity

        ra = Angle(radians=tf.ra.radian * u.radian)
        dec = Angle(radians=tf.dec.radian * u.radian)
        star = Star(ra=ra, dec=dec)
        t = self.ts.utc(tf.obstime.datetime.replace(tzinfo=utc))

        if mount_set_icrs:
            # Apparent GCRS ("J2000.0") coordinates
            alt, az, distance = self.obs.at(t).observe(star).apparent().altaz()
        else:
            # is already apparent
            #
            alt, az, distance = self.obs.at(t).observe(star).apparent().altaz()

        aa = SkyCoord(az=az.to(u.radian),
                      alt=alt.to(u.radian),
                      unit=(u.radian, u.radian),
                      frame='altaz',
                      location=tf.location,
                      obstime=tf.obstime,
                      pressure=pre,
                      temperature=tem,
                      relative_humidity=hum)
        return aa
Ejemplo n.º 8
0
def _convert_radec_to_altaz(ra, dec, lon, lat, height, time):
    """Convert a single position.

    This is done for easy code sharing with other tools.
    Skyfield does support arrays of positions.
    """
    load = Loader('.')
    # Skyfield uses FTP URLs, but FTP doesn't work on Github Actions so
    # we use alternative HTTP URLs.
    load.urls['finals2000A.all'] = 'https://datacenter.iers.org/data/9/'
    load.urls['.bsp'] = [
        ('*.bsp',
         'https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/')
    ]

    radec = Star(ra=Angle(degrees=ra), dec=Angle(degrees=dec))

    earth = load(EPHEMERIS)['earth']
    location = earth + wgs84.latlon(longitude_degrees=lon,
                                    latitude_degrees=lat,
                                    elevation_m=height * 1000.0)

    ts = load.timescale(builtin=False)
    with load.open('finals2000A.all') as f:
        finals_data = iers.parse_x_y_dut1_from_finals_all(f)
    iers.install_polar_motion_table(ts, finals_data)
    obstime = ts.from_astropy(Time(time, scale='utc'))

    alt, az, _ = location.at(obstime).observe(radec).apparent().altaz(
        pressure_mbar=0)

    return dict(az=az.degrees, alt=alt.degrees)
Ejemplo n.º 9
0
def galactic_Sun_north_directions( recv_time, user_longlatdist=geographic_position):
  user_longlatdist = np.array(user_longlatdist)#46.07983746062874, 26.232615661106784, 659.5100082775696
  with load.open(hipparcos.URL) as f:
    df = hipparcos.load_dataframe(f)

  planets = load('de421.bsp')
  earth = planets['earth']
  user_position = earth + Topos('{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) #user_longlatdist      user_longlatdist[0],user_longlatdist[1]
  terrestrial_time = format_time(recv_time)
  ts = load.timescale()
  t = ts.tt(terrestrial_time[0], terrestrial_time[1], terrestrial_time[2], terrestrial_time[3], terrestrial_time[4], terrestrial_time[5])
  
  sun = planets['sun']
  astrometric_sun = user_position.at(t).observe(sun)
  alt_sun, az_sun, distance_sun = astrometric_sun.apparent().altaz()#astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
  print('Location: ', '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1]))
  print('Sun (alt/az):   ',alt_sun, az_sun)
  sun_position = pm.aer2ecef( az_sun.degrees, alt_sun.degrees, distance_sun.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2])
  
  # Északi Galaktikus Pólus (RA: 12h 51.42m; D: 27° 07.8′, epocha J2000.0) 
  coma_berenices = Star(ra_hours=(12, 51, 25.2), dec_degrees=(27, 7, 48.0))
  astrometric_berenice = user_position.at(t).observe(coma_berenices)
  alt_b, az_b, distance_b = astrometric_berenice.apparent().altaz()
  print('Coma Berenice (alt/az):   ',alt_b, az_b)
  berenice_position = pm.aer2ecef( az_b.degrees, alt_b.degrees, distance_b.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2])
  
  stars_pos=[sun_position, berenice_position]
  return stars_pos
Ejemplo n.º 10
0
    def __init__(self, object_name, session):
        super().__init__(object_name, session)
        if type(object_name) == ongc.Dso:
            self.dso = object_name  # If class initialized directly with a Dso, use it, else create a new one.
        else:
            try:
                self.dso = ongc.Dso(object_name)
            except Exception as e:
                logging.warning(e)
        #print("DSO:", self.dso, type(self.dso))

        #self.kind = 'Deep Space object'  # TODO: distinguish between stars, galaxies...
        #self.constellation = ''
        ra_arr, dec_arr = self.dso.getCoords()
        self.ra, self.dec = tuple(ra_arr), tuple(dec_arr)
        self.alt_ids = self.dso.getIdentifiers()
        self.constellation = self.dso.getConstellation()
        self.kind = self.dso.getType()
        self.star = Star(ra_hours=self.ra, dec_degrees=self.dec)
        self.star_astro_now = self.astrometric = self.session.here.at(
            self.session.start).observe(self.star)
        self.apparent = self.astrometric.apparent()

        self.alt, self.az, self.distance = self.apparent.altaz('standard')

        ra_arr, dec_arr = self.dso.getCoords()
        self.ra, self.dec = tuple(ra_arr), tuple(dec_arr)
        self.alt_ids = self.dso.getIdentifiers()
        self.messier = self.alt_ids[0]
        self.constellation = self.dso.getConstellation()
        self.kind = self.dso.getType()
Ejemplo n.º 11
0
 def make_chart_sdss(self,
                     ra,
                     de,
                     pmra,
                     pmde,
                     name,
                     outdir='findercharts_1d/'):
     ra_ang = Angle(degrees=ra)
     de_ang = Angle(degrees=de)
     star_obj = Star(ra=ra_ang,
                     dec=de_ang,
                     ra_mas_per_year=pmra,
                     dec_mas_per_year=pmde)
     astrometric = self.earth.at(self.t).observe(star_obj)
     astrometric_old = self.earth.at(self.t_2000).observe(star_obj)
     ra_out, dec_out, dist_out = astrometric.radec()
     ra_out1, dec_out1, dist_out1 = astrometric_old.radec()
     ra_new = ra_out.to(u.degree).value
     de_new = dec_out.to(u.degree).value
     ra_old = ra_out1.to(u.degree).value
     de_old = dec_out1.to(u.degree).value
     raline = [ra_old, ra_new]
     deline = [de_old, de_new]
     cc = astropy.coordinates.SkyCoord(ra, de, unit=(u.degree, u.degree))
     cc_new = astropy.coordinates.SkyCoord(ra_new,
                                           de_new,
                                           unit=(u.degree, u.degree))
     cc_old = astropy.coordinates.SkyCoord(ra_old,
                                           de_old,
                                           unit=(u.degree, u.degree))
     fig = figure(figsize=(10, 12))
     fovrad = astropy.coordinates.Angle('0d4m0s')
     oo, oh = astroplan.plots.plot_finder_image(cc_old,
                                                reticle=True,
                                                survey='2MASS-K')
     oo.set_autoscale_on(False)
     oo.plot(raline, deline, transform=oo.get_transform('icrs'))
     oo.set_title(name, fontsize=20)
     ra_s = cc_new.ra.to_string(unit=u.hour, sep=':')
     de_s = cc_new.dec.to_string(unit=u.degree, sep=':')
     #ra_s = [alltargs_uniq.loc[i,'cc'].ra.to_string(unit=u.hour,sep=':') for i in ai]
     #oo.text(0,-.1,'TEST',transform=oo.transAxes)
     oo.text(0,
             -.1,
             'RA (ICRS): ' + ra_s,
             transform=oo.transAxes,
             fontsize=20)
     oo.text(0,
             -.15,
             'DEC (ICRS): ' + de_s,
             transform=oo.transAxes,
             fontsize=20)
     fig.savefig(outdir + name + '.pdf')
     close(fig)
Ejemplo n.º 12
0
    def __init__(self):
        # load the planetary positions and our position
        self.planets = load('de421.bsp')
        self.earth = self.planets['earth']
        self.Cas_A = Star(ra_hours=(23, 23, 5.00),
                           dec_degrees=(58, 46, 0.00),
                           epoch=1992.5)

        self.sources = {"CAS_A":self.Cas_A,
                        "SUN":self.planets['sun'],
                        "MOON":self.planets['moon']}
Ejemplo n.º 13
0
    def radec_with_proper_motion(self, ra, de, pmra, pmde, verbose=False):
        """
        Calculate the

        INPUT:
        - ra in degrees
        - dec in degrees
        - pmra - in mas/yr
        - pmdec - in mas/yr

        OUTPUT:
        - Angle

        NOTES:
        - Built on Ryan's code
        """
        ra_ang = Angle(degrees=ra)
        de_ang = Angle(degrees=de)
        star_obj = Star(ra=ra_ang,
                        dec=de_ang,
                        ra_mas_per_year=pmra,
                        dec_mas_per_year=pmde)
        astrometric = self.earth.at(self.t).observe(star_obj)
        astrometric_old = self.earth.at(self.t_2000).observe(star_obj)
        ra_out, dec_out, dist_out = astrometric.radec()
        ra_out1, dec_out1, dist_out1 = astrometric_old.radec()
        ra_new = ra_out.to(u.degree).value
        de_new = dec_out.to(u.degree).value
        ra_old = ra_out1.to(u.degree).value
        de_old = dec_out1.to(u.degree).value
        raline = [ra_old, ra_new]
        deline = [de_old, de_new]
        cc = astropy.coordinates.SkyCoord(ra, de, unit=(u.degree, u.degree))
        cc_new = astropy.coordinates.SkyCoord(ra_new,
                                              de_new,
                                              unit=(u.degree, u.degree))
        cc_old = astropy.coordinates.SkyCoord(ra_old,
                                              de_old,
                                              unit=(u.degree, u.degree))
        self.cc_old = cc_old
        self.cc_new = cc_new
        self.ra_s_new = cc_new.ra.to_string(unit=u.hour, sep=':')
        self.de_s_new = cc_new.dec.to_string(unit=u.degree, sep=':')
        self.ra_s_old = cc_old.ra.to_string(unit=u.hour, sep=':')
        self.de_s_old = cc_old.dec.to_string(unit=u.degree, sep=':')

        if verbose:
            print("Coordinates at {:f}: RA={} DEC={}".format(
                self.epoch_old, self.ra_s_old, self.de_s_old))
            print("with  PMRA={} PMDEC={}".format(pmra, pmde))
            print("Coordinates at {:f}: RA={} DEC={}".format(
                self.epoch_new, self.ra_s_new, self.de_s_new))
            print("")
        return cc_new
Ejemplo n.º 14
0
    def transform_to_hadec(self, tf=None, sky=None, mount_set_icrs=None):
        tem = sky.temperature
        pre = sky.pressure
        hum = sky.humidity

        ra = Angle(radians=tf.ra.radian * u.radian)
        dec = Angle(radians=tf.dec.radian * u.radian)
        star = Star(ra=ra, dec=dec)
        #HA= self.obs.sidereal_time() - star.ra
        #ha=SkyCoord(ra=HA,dec=star.dec, unit=(u.radian,u.radian), frame='cirs',location=tf.location,obstime=tf.obstime,pressure=pre,temperature=tem,relative_humidity=hum)
        self.lg.error('not  yet implemented')
        sys.exit(1)
Ejemplo n.º 15
0
    def predict_without_uncertainties(self, mjd, complain=True):
        """Predict the object position at a given MJD.

        The return value is a tuple ``(ra, dec)``, in radians, giving the
        predicted position of the object at *mjd*. Unlike :meth:`predict`, the
        astrometric uncertainties are ignored. This function is therefore
        deterministic but potentially misleading.

        If *complain* is True, print out warnings for incomplete information.

        This function relies on the external :mod:`skyfield` package.

        """
        import sys
        from skyfield.api import Star

        self.verify(complain=complain)

        planets, ts = load_skyfield_data(
        )  # might download stuff from the internet
        earth = planets['earth']
        t = ts.tdb(jd=mjd + 2400000.5)

        # "Best" position. The implementation here is a bit weird to keep
        # parallelism with predict().

        args = {
            'ra_hours': self.ra * R2H,
            'dec_degrees': self.dec * R2D,
        }

        if self.pos_epoch is not None and self.pos_epoch != 51544.5:
            print_(
                'AstrometryInfo.predict_without_uncertainties(): '
                'ignoring epoch of position!',
                file=sys.stderr)
            ### o.promoepoch = self.pos_epoch + 2400000.5
        ###else:
        ###    if complain:
        ###        print_ ('AstrometryInfo.predict(): assuming epoch of position is J2000.0', file=sys.stderr)
        ###    o.promoepoch = 2451545.0 # J2000.0

        if self.promo_ra is not None:
            args['ra_mas_per_year'] = self.promo_ra
            args['dec_mas_per_year'] = self.promo_dec
        if self.parallax is not None:
            args['parallax_mas'] = self.parallax
        if self.vradial is not None:
            args['radial_km_per_s'] = self.vradial

        bestra, bestdec, _ = earth.at(t).observe(Star(**args)).radec()
        return bestra.radians, bestdec.radians
Ejemplo n.º 16
0
def get_probe_coords(hip_id, distance):
    # set timezone + load planet info
    utcTZ = timezone("UTC")
    local_tz = get_localzone()
    ts = load.timescale()
    planets = load('de421.bsp')

    # get time of observation and locations of observation
    t = ts.from_datetime(datetime(2020, 11, 9, 00, 00, tzinfo=utcTZ))
    sun = planets['sun']
    earth = planets['earth']

    # load in the hipparcos data
    with load.open(hipparcos.URL) as f:
        df = hipparcos.load_dataframe(f)

    # # match on star coords
    # ra_inds = []
    # for ind, cat_ra in enumerate(df['ra_degrees'].values):
    #     if isclose(cat_ra, ra_star, rel_tol=1e-2):
    #         ra_inds.append(ind)

    # dec_inds = []
    # for ind, cat_dec in enumerate(df['dec_degrees'].values):
    #     if isclose(cat_dec, dec_star, rel_tol=1e-2):
    #         dec_inds.append(ind)

    # # find where ra & dec match within tolerance
    # sets = set(ra_inds).intersection(set(dec_inds))
    # inds = [x for x in iter(sets)]
    # print(inds)

    # just take the first one for now
    the_star = Star.from_dataframe(df.loc[hip_id])

    # "observe" the star from Earth
    starPosObj = earth.at(t).observe(the_star)
    ra, dec, dist = starPosObj.radec()

    # get coords of opposite point on the sky
    ra = ((ra._degrees + 180.0) % 360) * (24.0 / 360.0)
    dec = -1.0 * dec._degrees

    # get coords of the probe and return ra dec in degree
    probe = position_of_radec(ra, dec, distance, t=t)
    sunPosObj = earth.at(t).observe(sun)
    inverseSunCoord = -1.0 * sunPosObj.position.au
    probeCoord = probe.position.au
    probeDir = ICRF(probeCoord + inverseSunCoord).radec()
    return probeDir[0]._degrees, probeDir[1]._degrees
def calc_radec_w_proper_motion(ra, de, pmra, pmde, epoch=2018.):
    planets = load('/Users/gks/Dropbox/mypylib/notebooks/GIT/HETobs/de421.bsp')
    ts = load.timescale()
    earth = planets['earth']
    t = ts.utc(epoch)
    t_2000 = ts.utc(2000)
    ra_ang = Angle(degrees=ra)
    de_ang = Angle(degrees=de)
    star_obj = Star(ra=ra_ang,
                    dec=de_ang,
                    ra_mas_per_year=pmra,
                    dec_mas_per_year=pmde)
    astrometric = earth.at(t).observe(star_obj)
    ra_out, dec_out, dist_out = astrometric.radec()
    ra_new = ra_out.to(u.degree).value
    de_new = dec_out.to(u.degree).value
    print("Old:", ra, de)
    print("New:", ra_new, de_new)
    return ra_new, de_new
Ejemplo n.º 18
0
def load_stars(max_magnitude, verbose=False):
    """Load the Hipparcos catalog data and find all applicable stars.  Returns a
    list of StarObs, one per star.
    """
    if verbose:
        print("[  CATALOG] Loading star catalog data.")
    with load.open(hipparcos.URL) as f:
        df = hipparcos.load_dataframe(f)

        df = df[df['magnitude'] <= max_magnitude]
        df = df[df['ra_degrees'].notnull()]

        if verbose:
            print(
                f'[  CATALOG] Found {len(df)} stars brighter than magnitude {max_magnitude:.4f}.'
            )
        return [
            StarObs(str(idx), Star.from_dataframe(df.loc[idx]),
                    df.loc[idx].magnitude) for idx in df.index
        ]
Ejemplo n.º 19
0
def _convert_radec_to_altaz(ra, dec, lon, lat, height, time):
    """Convert a single position.

    This is done for easy code sharing with other tools.
    Skyfield does support arrays of positions.
    """

    radec = Star(ra=Angle(degrees=ra), dec=Angle(degrees=dec))

    earth = load(EPHEMERIS)['earth']
    location = earth + Topos(longitude_degrees=lon,
                             latitude_degrees=lat,
                             elevation_m=height * 1000.0)

    ts = load.timescale()
    obstime = ts.from_astropy(Time(time, scale='utc'))

    alt, az, _ = location.at(obstime).observe(radec).apparent().altaz(pressure_mbar=0)

    return dict(az=az.degrees, alt=alt.degrees)
Ejemplo n.º 20
0
def stellar_info(d):  # used in starstab
    # returns a list of lists with name, SHA and Dec all navigational stars for epoch of date.

    t12 = ts.ut1(d.year, d.month, d.day, 12, 0, 0)  #calculate at noon
    out = []

    for line in db.strip().split('\n'):
        x1 = line.index(',')
        name = line[0:x1]
        HIPnum = line[x1 + 1:]

        star = Star.from_dataframe(df.loc[int(HIPnum)])
        astrometric = earth.at(t12).observe(star).apparent()
        ra, dec, distance = astrometric.radec(epoch='date')

        sha = fmtgha(0, ra.hours)
        decl = fmtdeg(dec.degrees)

        out.append([name, sha, decl])
    return out
Ejemplo n.º 21
0
def Star_cirs(ra, dec, epoch):
    """Wrapper for skyfield.api.star that creates a position given CIRS
    coordinates observed from CHIME

    Parameters
    ----------
    ra, dec : skyfield.api.Angle
        RA and dec of the source in CIRS coordinates
    epoch : skyfield.api.Time
        Time of the observation

    Returns
    -------
    body : skyfield.api.Star
        Star object in ICRS coordinates
    """

    from skyfield.api import Star

    return cirs_radec(Star(ra=ra, dec=dec, epoch=epoch))
Ejemplo n.º 22
0
def mp_stellar_info(d, ts, df, n):  # used in starstab
    # returns a list of lists with name, SHA and Dec all navigational stars for epoch of date.

    # load the Hipparcos catalog as a 118,218 row Pandas dataframe.
    #with load.open(hipparcos.URL) as f:
    #hipparcos_epoch = ts.tt(1991.25)
    #    df = hipparcos.load_dataframe(f)

    eph = load(config.ephemeris[config.ephndx][0])  # load chosen ephemeris
    earth = eph['earth']

    t00 = ts.ut1(d.year, d.month, d.day, 0, 0, 0)  #calculate at midnight
    #t12 = ts.ut1(d.year, d.month, d.day, 12, 0, 0)  #calculate at noon
    out = []

    if n == 0: db = db1
    elif n == 1: db = db2
    elif n == 2: db = db3
    elif n == 3: db = db4
    elif n == 4: db = db5
    else: db = db6

    for line in db.strip().split('\n'):
        x1 = line.index(',')
        name = line[0:x1]
        HIPnum = line[x1 + 1:]

        star = Star.from_dataframe(df.loc[int(HIPnum)])
        astrometric = earth.at(t00).observe(star).apparent()
        ra, dec, distance = astrometric.radec(epoch='date')

        sha = fmtgha(0, ra.hours)
        decl = fmtdeg(dec.degrees)

        out.append([name, sha, decl])
    return out
Ejemplo n.º 23
0
edges = [edge for name, edges in constellations for edge in edges]
edges_star1 = [star1 for star1, star2 in edges]
edges_star2 = [star2 for star1, star2 in edges]

# We will center the chart on the comet's middle position.

center = earth.at(t).observe(comet)
projection = build_stereographic_projection(center)
field_of_view_degrees = 45.0
limiting_magnitude = 7.0

# Now that we have constructed our projection, compute the x and y
# coordinates that each star and the comet will have on the plot.

star_positions = earth.at(t).observe(Star.from_dataframe(stars))
stars['x'], stars['y'] = projection(star_positions)

comet_x, comet_y = projection(earth.at(t_comet).observe(comet))

# Create a True/False mask marking the stars bright enough to be
# included in our plot.  And go ahead and compute how large their
# markers will be on the plot.

bright_stars = (stars.magnitude <= limiting_magnitude)
magnitude = stars['magnitude'][bright_stars]
marker_size = (0.5 + limiting_magnitude - magnitude) ** 2.0

# The constellation lines will each begin at the x,y of one star and end
# at the x,y of another.  We have to "rollaxis" the resulting coordinate
# array into the shape that matplotlib expects.
Ejemplo n.º 24
0
    c1 = T_pos((t, t0, coord), pmra, pmdec, plx, vrad)

    Ricky_coord = SkyCoord(ra=ricky[0, 1],
                           dec=ricky[0, 4],
                           unit='deg',
                           frame='icrs')
    #print 'new - ricky:', c1.separation(Ricky_coord).arcsec[0] * 1000.

    #print 'new - ricky (acosd):', (c1.ra.deg[0] - Ricky_coord.ra.deg) * np.cos(coord.dec.rad) * 3E6
    #print 'new - ricky (d):', (c1.dec.deg[0] - Ricky_coord.dec.deg)*3E6

    from skyfield.api import load, Star, Angle
    lens = Star(ra=Angle(degrees=coord.ra.deg),
                dec=Angle(degrees=coord.dec.deg),
                ra_mas_per_year=pmra * 1000.,
                dec_mas_per_year=pmdec * 1000.,
                parallax_mas=plx * 1000.)
    ts = load.timescale()
    ts1 = ts.utc(t.jyear[0] - 15.)
    planets = load('de421.bsp')
    earth = planets['earth']
    astrometric = earth.at(ts1).observe(lens)
    rai, deci, distancesa = astrometric.radec()
    skyfield_coord = SkyCoord(ra=rai._degrees,
                              dec=deci._degrees,
                              unit='deg',
                              frame='icrs')
    #print 'skyfield - ricky:', skyfield_coord.separation(Ricky_coord).arcsec * 1000.
    #print 'skyfield - new:', skyfield_coord.separation(c1[0]).arcsec * 1000.
boston = earth + Topos('42.3583 N', '71.0603 W')
astro = boston.at(ts.utc(1980, 3, 1)).observe(mars)
app = astro.apparent()

alt, az, distance = app.altaz()
print(alt.dstr())
print(az.dstr())
print(distance)

# Measure a star

with load.open(hipparcos.URL) as f:
    df = hipparcos.load_dataframe(f)

barnards_star = Star.from_dataframe(df.loc[87937])

planets = load('de421.bsp')
earth = planets['earth']

ts = load.timescale()
t = ts.now()
astrometric = boston.at(t).observe(barnards_star)
app_b = astrometric.apparent()

alt_b, az_b, distance_b = app_b.altaz()
print("Bernard star")
print(alt_b.dstr())
print(az_b.dstr())
print(distance)
Ejemplo n.º 26
0
import numpy as np

ts = load.timescale()
t = ts.utc(2022, 1, 1)

eph = load('../../de421.bsp')
sun = eph['sun']
earth = eph['earth']

df = pd.read_csv('bs_hip_all_selected cols.csv').set_index('hip')
df = df.loc[orion_stars]

ra = Angle(degrees=df['ra'].values)
dec = Angle(degrees=df['dec'].values)

stars = Star(ra=ra, dec=dec)

star_positions = earth.at(t).observe(stars)

#========================================

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from hypatie.plots import plot_radec, plot_altaz
from hypatie.transform import radec_to_altaz
from hypatie.data import cities

lon, lat = cities['strasbourg'][:2]

marker_size = (0.5 + 7 - df['Vmag'].values)**2.0
def galactic_Sun_north_center_SD_directions(
        measurement_date,
        recv_time,
        user_longlatdist=geographic_position,
        prints=False):
    user_longlatdist = np.array(user_longlatdist)
    with load.open(hipparcos.URL) as f:
        df = hipparcos.load_dataframe(f)

    planets = load('de421.bsp')
    earth = planets['earth']
    user_position = earth + Topos(
        '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])
    )  #user_longlatdist      user_longlatdist[0],user_longlatdist[1]
    terrestrial_time = format_time_auto(measurement_date, recv_time)
    ts = load.timescale()
    t = ts.tt(terrestrial_time[0], terrestrial_time[1], terrestrial_time[2],
              terrestrial_time[3], terrestrial_time[4], terrestrial_time[5])

    sun = planets['sun']
    astrometric_sun = user_position.at(t).observe(sun)
    alt_sun, az_sun, distance_sun = astrometric_sun.apparent().altaz(
    )  #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
    sun_position = pm.aer2ecef(az_sun.degrees, alt_sun.degrees, distance_sun.m,
                               user_longlatdist[0], user_longlatdist[1],
                               user_longlatdist[2])

    # Északi Galaktikus Pólus (RA: 12h 51.42m; D: 27° 07.8′, epocha J2000.0)
    coma_berenices = Star(ra_hours=(12, 51, 25.2), dec_degrees=(27, 7, 48.0))
    astrometric_berenice = user_position.at(t).observe(coma_berenices)
    alt_b, az_b, distance_b = astrometric_berenice.apparent().altaz()
    berenice_position = pm.aer2ecef(az_b.degrees, alt_b.degrees, distance_b.m,
                                    user_longlatdist[0], user_longlatdist[1],
                                    user_longlatdist[2])

    # Galaktikus Center (RA: 12h 51.42m; D: 27° 07.8′, epocha J2000.0) 17h 45.6m  −28.94°
    galactic_center = Star(ra_hours=(17, 45, 36.0),
                           dec_degrees=(-28, 56, 24.0))
    astrometric_center = user_position.at(t).observe(galactic_center)
    alt_c, az_c, distance_c = astrometric_center.apparent().altaz()
    center_position = pm.aer2ecef(az_c.degrees, alt_c.degrees, distance_c.m,
                                  user_longlatdist[0], user_longlatdist[1],
                                  user_longlatdist[2])

    nunki = Star.from_dataframe(df.loc[92855])
    astrometric_nunki = user_position.at(t).observe(nunki)
    alt_n, az_n, distance_n = astrometric_nunki.apparent().altaz(
    )  #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
    star_pos_n = pm.aer2ecef(az_n.degrees, alt_n.degrees, distance_n.m,
                             user_longlatdist[0], user_longlatdist[1],
                             user_longlatdist[2])

    capella = Star.from_dataframe(df.loc[24608])
    astrometric_capella = user_position.at(t).observe(capella)
    alt_ca, az_ca, distance_ca = astrometric_capella.apparent().altaz(
    )  #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
    star_pos_ca = pm.aer2ecef(az_ca.degrees, alt_ca.degrees, distance_ca.m,
                              user_longlatdist[0], user_longlatdist[1],
                              user_longlatdist[2])

    denebola = Star.from_dataframe(df.loc[57632])
    astrometric_denebola = user_position.at(t).observe(denebola)
    alt_d, az_d, distance_d = astrometric_denebola.apparent().altaz(
    )  #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz()
    star_pos_d = pm.aer2ecef(az_d.degrees, alt_d.degrees, distance_d.m,
                             user_longlatdist[0], user_longlatdist[1],
                             user_longlatdist[2])

    sadalmelik = Star.from_dataframe(df.loc[109074])
    astrometric_sadalmelik = user_position.at(t).observe(sadalmelik)
    alt_s, az_s, distance_s = astrometric_sadalmelik.apparent().altaz()
    star_pos_s = pm.aer2ecef(az_s.degrees, alt_s.degrees, distance_s.m,
                             user_longlatdist[0], user_longlatdist[1],
                             user_longlatdist[2])
    if prints:
        print('Time:  ', terrestrial_time)
        print('Location: ', '{} N'.format(user_longlatdist[0]),
              '{} E'.format(user_longlatdist[1]))
        print('Sun (alt/az):   ', alt_sun, az_sun)
        print('Coma Berenice (alt/az):   ', alt_b, az_b)
        print('Galactic Center (alt/az):   ', alt_c, az_c)
        print('Nunki (alt/az):   ', alt_n, az_n)
        print('Capella (alt/az):   ', alt_ca, az_ca)
        print('Denebola (alt/az):   ', alt_d, az_d)
        print('Sadalmelik (alt/az):   ', alt_s, az_s)

    stars_pos = [
        sun_position, berenice_position, center_position, star_pos_n,
        star_pos_ca, star_pos_d, star_pos_s
    ]
    return stars_pos
Ejemplo n.º 28
0
earth = ephem['earth']
sun = ephem['sun']
moon = ephem['moon']
mars = ephem['mars barycenter']
venus = ephem['venus']

plain_greenwich = Topos(latitude='51.5 N', longitude='0 W')
greenwich = earth + plain_greenwich

iss_tle = """\
1 25544U 98067A   18161.85073725  .00003008  00000-0  52601-4 0  9993
2 25544  51.6418  50.3007 0003338 171.6979 280.7366 15.54163173117534
"""
ISS = EarthSatellite(*iss_tle.splitlines())

sirius = Star(ra_hours=(6, 45, 8.91728), dec_degrees=(-16, 42, 58.0171))

minute = 1 / 24 / 60
sec = minute / 60
ms = sec / 1000


def compare(value, expected_value, epsilon):
    if hasattr(value, '__len__') or hasattr(expected_value, '__len__'):
        assert max(abs(value - expected_value)) <= epsilon
    else:
        assert abs(value - expected_value) <= epsilon


def is_root(f, times, target_f, epsilon):
    left_times = times - epsilon
Ejemplo n.º 29
0
    while True:
        #check if rotor is moving
        print Rotor.isMoving()
        if Rotor.isMoving():
            print "Rotor moving, sleeping"
            time.sleep(5)
        else:
            print "Rotor stopped, calculating"

            alt, az, dist = Tracker.calcAltAz()
            Rotor.move(alt.degrees, az.degrees)


#setup location
planets = load('de421.bsp')
earth = planets['earth']

location = earth + Topos('36.31205 N', '81.35347 W')

#setup test target
#barnard = Star(ra_hours=(17,57,48.49803), dec_degrees(4,41,36.2072))
testTarget = Star(ra_hours=(22, 57, 39.52), dec_degrees=(-29, 37, 24))
Tracker = Tracking(testTarget, location)

Tracker.calcAltAz()

Rotor = RotorController()
Rotor.connect("/dev/ttyACM0")
Rotor.move(0, 0)
__start()
Ejemplo n.º 30
0
    def predict(self, mjd, complain=True, n=20000):
        """Predict the object position at a given MJD.

        The return value is a tuple ``(ra, dec, major, minor, pa)``, all in
        radians. These are the predicted position of the object and its
        uncertainty at *mjd*. If *complain* is True, print out warnings for
        incomplete information. *n* is the number of Monte Carlo samples to
        draw for computing the positional uncertainty.

        The uncertainty ellipse parameters are sigmas, not FWHM. These may be
        converted with the :data:`S2F` constant.

        This function relies on the external :mod:`skyfield` package.

        """
        import sys
        from skyfield.api import Star
        from . import ellipses

        self.verify(complain=complain)

        planets, ts = load_skyfield_data(
        )  # might download stuff from the internet
        earth = planets['earth']
        t = ts.tdb(jd=mjd + 2400000.5)

        # "Best" position.

        args = {
            'ra_hours': self.ra * R2H,
            'dec_degrees': self.dec * R2D,
        }

        if self.pos_epoch is not None and self.pos_epoch != 51544.5:
            print_('AstrometryInfo.predict(): ignoring epoch of position!',
                   file=sys.stderr)
            ### o.promoepoch = self.pos_epoch + 2400000.5
        ###else:
        ###    if complain:
        ###        print_ ('AstrometryInfo.predict(): assuming epoch of position is J2000.0', file=sys.stderr)
        ###    o.promoepoch = 2451545.0 # J2000.0

        if self.promo_ra is not None:
            args['ra_mas_per_year'] = self.promo_ra
            args['dec_mas_per_year'] = self.promo_dec
        if self.parallax is not None:
            args['parallax_mas'] = self.parallax
        if self.vradial is not None:
            args['radial_km_per_s'] = self.vradial

        bestra, bestdec, _ = earth.at(t).observe(Star(**args)).radec()
        bestra = bestra.radians
        bestdec = bestdec.radians

        # Monte Carlo to get an uncertainty. As always, astronomy position
        # angle convention requires that we treat declination as X and RA as
        # Y. First, we check sanity and generate randomized parameters:

        if self.pos_u_maj is None and self.promo_u_maj is None and self.u_parallax is None:
            if complain:
                print_(
                    'AstrometryInfo.predict(): no uncertainties '
                    'available; cannot Monte Carlo!',
                    file=sys.stderr)
            return (bestra, bestdec, 0., 0., 0.)

        if self.pos_u_maj is not None:
            sd, sr, cdr = ellipses.ellbiv(self.pos_u_maj, self.pos_u_min,
                                          self.pos_u_pa)
            decs, ras = ellipses.bivrandom(self.dec, self.ra, sd, sr, cdr, n).T
        else:
            ras = np.zeros(n) + self.ra
            decs = np.zeros(n) + self.dec

        if self.promo_ra is None:
            pmras = np.zeros(n)
            pmdecs = np.zeros(n)
        elif self.promo_u_maj is not None:
            sd, sr, cdr = ellipses.ellbiv(self.promo_u_maj, self.promo_u_min,
                                          self.promo_u_pa)
            pmdecs, pmras = ellipses.bivrandom(self.promo_dec, self.promo_ra,
                                               sd, sr, cdr, n).T
        else:
            pmras = np.zeros(n) + self.promo_ra
            pmdecs = np.zeros(n) + self.promo_dec

        if self.parallax is None:
            parallaxes = np.zeros(n)
        elif self.u_parallax is not None:
            parallaxes = np.random.normal(self.parallax, self.u_parallax, n)
        else:
            parallaxes = np.zeros(n) + self.parallax

        if self.vradial is None:
            vradials = np.zeros(n)
        elif self.u_vradial is not None:
            vradials = np.random.normal(self.vradial, self.u_vradial, n)
        else:
            vradials = np.zeros(n) + self.vradial

        # Now we compute the positions and summarize as an ellipse:

        results = np.empty((n, 2))

        for i in range(n):
            args['ra_hours'] = ras[i] * R2H
            args['dec_degrees'] = decs[i] * R2D
            args['ra_mas_per_year'] = pmras[i]
            args['dec_mas_per_year'] = pmdecs[i]
            args['parallax_mas'] = parallaxes[i]
            args['radial_km_per_s'] = vradials[i]
            ara, adec, _ = earth.at(t).observe(Star(**args)).radec()
            results[i] = adec.radians, ara.radians

        maj, min, pa = ellipses.bivell(*ellipses.databiv(results))

        # All done.

        return bestra, bestdec, maj, min, pa