Beispiel #1
0
def find_stars(stars, site):
    sources = {}
    for star in stars:
        [az, el] = source_azel(ephem.star(star), site)
        if el > 8.0:
            sources[star] = ephem.star(star)
    return sources
Beispiel #2
0
def find_stars(stars, site):
	sources = {}
	for star in stars:
		[az, el] = source_azel(ephem.star(star), site)
		if el > 8.0:
			sources[star] = ephem.star(star)
	return sources
Beispiel #3
0
def align_polaris(ra_ticks, dec_ticks):
    rho = ep.Observer()
    rho.lon, rho.lat = '-82.586203', '29.400249'
    pol = ep.star('Polaris')
    altair = ep.star('Altair')
    altair.compute(rho)
    pol.compute(rho)
    # print "Polaris:", pol.ra, pol.dec
    # print altair.name, altair.ra, altair.dec
    # print "Rho Sidereal Time:", rho.sidereal_time()
    zero = pol.ra
Beispiel #4
0
def find_stars(stars, site, disp):
	sources = {}
	for star in stars:
		[az, el] = source_azel(ephem.star(star), site)
		if disp:
			print star, az, el
		if el > 15.0:
			sources[star] = ephem.star(star)
			print star, az, el

	return sources
Beispiel #5
0
def find_stars(stars, site, disp):
    sources = {}
    for star in stars:
        [az, el] = source_azel(ephem.star(star), site)
        if disp:
            print star, az, el
        if el > 15.0:
            sources[star] = ephem.star(star)
            print star, az, el

    return sources
Beispiel #6
0
def setReferenceStars():
    starDBsize = len(ephem.stars.db.split("\n"))
    starDBnow = []
    starList = ephem.stars.db.split("\n")
    for i, star in enumerate(starList):
        if i < starDBsize - 1:
            S = ephem.star(star.split(",")[0])
            S.compute(obs)
            if S.alt > math.pi / 8:
                starDBnow.append((S.name, S.alt, S.az, S.mag))

    starDBnow = sorted(starDBnow, key=lambda star: star[3])

    star1 = ephem.star(starDBnow[0][0])
    star1.compute(obs)

    star2 = None
    nxt = 1
    while nxt < len(starDBnow) and star2 == None:
        if abs(starDBnow[nxt][1] - star1.alt) > math.pi / 8:
            azDiff = min(
                abs(starDBnow[nxt][2] - star1.az) % (2 * math.pi),
                2 * math.pi - abs(starDBnow[nxt][2] - star1.az) %
                (2 * math.pi))
            if (azDiff > math.pi / 6) and (abs(math.pi - azDiff) >
                                           math.pi / 6):
                star2 = ephem.star(starDBnow[nxt][0])
        nxt = nxt + 1

    star2.compute(obs)
    star3 = None
    nxt = 1
    while nxt < len(starDBnow) and star3 == None:
        if ((abs(starDBnow[nxt][1] - star1.alt) > math.pi / 8)
                or (abs(starDBnow[nxt][1] - star2.alt) > math.pi / 8)):
            azDiff1 = min(
                abs(starDBnow[nxt][2] - star1.az) % (2 * math.pi),
                2 * math.pi - abs(starDBnow[nxt][2] - star1.az) %
                (2 * math.pi))
            azDiff2 = min(
                abs(starDBnow[nxt][2] - star2.az) % (2 * math.pi),
                2 * math.pi - abs(starDBnow[nxt][2] - star2.az) %
                (2 * math.pi))
            azDiff = min(azDiff1, azDiff2)
            if (azDiff > math.pi / 6):
                star3 = ephem.star(starDBnow[nxt][0])
        nxt = nxt + 1

    star3.compute(obs)

    return star1, star2, star3
Beispiel #7
0
def quick_s(name, track):
    if not track:
        clear_lock()
    if hasattr(ephem, name.get()):  # Check for named planets/moons
        obj = getattr(ephem, name.get())()
        search(obj, 'Planet/Moon')
    else:
        try:
            ephem.star(name.get())  # Check if named star
        except KeyError:
            read_db(name)  # If not, read from custom objects database
        else:
            obj = ephem.star(name.get())  # If it's a star
            search(obj, 'Named Star')
Beispiel #8
0
def confirm_align(star):
    result = tkMessageBox.askyesno("Align Telescope", "Are you sure?")
    if result is True:
        # Check if encoders are available
        try:
            ra = enc.Enc('RAEncoder')
            dec = enc.Enc('DECEncoder')
        except:
            log_action('ALIGN', 'Scope', 'Encoder(s) not found')
        else:
            # Initialize encoders
            ra = enc.Enc('RAEncoder')
            success = ra.connect()
            if not success:
                log_action('Connect', 'Encoder',
                           'RAEncoder failed to initialize')
            dec = enc.Enc('DECEncoder')
            success = dec.connect()
            if not success:
                log_action('Connect', 'Encoder',
                           'DECEncoder failed to initialize')

            # Look up the star
            try:
                ephem.star(star)  # Check if 'name' is a named star
            except KeyError:
                obj = read_db(
                    star
                )  # If not, read 'name' from the custom objects database (Weird to do but w/e)
            else:
                obj = ephem.star(star)  # But if it was a star...
            obj.compute(rho)
            # Create Scope object
            scope = sc.Scope(obj, ra, dec)
            position = scope.where()  # Grab scope position to confirm align
            st = rho.sidereal_time()  # Grab RHO sidereal time
            ha = '%s' % ephem.hours(
                st - ephem.hours(position[0]))  # Calc HA of object from RHO
            s_ha.set(ha)
            s_dec.set(str(position[1]))
            s_tick_ha.set(scope.data['Ticks'][-1][0])
            s_tick_dec.set(scope.data['Ticks'][-1][1])
            log_action('Align Success', obj.name,
                       str('HA: ' + position[0] + ' | DEC: ' + position[1]))
            s_ready.set('Telescope Aligned')
            s_scope.config(fg='black')
    else:
        # Do nothing
        return
Beispiel #9
0
    def __init__(self, config, name):
        super(self.__class__, self).__init__(config)

        self.body = ephem.star(STAR_CATALOG[name]['name'])
        self.id = STAR_CATALOG[name]['id']
        self.name = STAR_CATALOG[name]['name']
        self.category = "star"
Beispiel #10
0
def PlotStars(window, observer):
    for astroObj in config.stardb:
        star_db_element = ephem.star(astroObj)
        star_db_element.compute(observer)

        if (star_db_element.neverup):  # Makes it run faster
            continue

        [x, y] = ProjectCoordinates(star_db_element.alt,
                                    star_db_element.az)  # degrees (alt/az)

        if (config.VISIBLE and star_db_element.mag < config.MAXMAGNITUDE):
            star = Circle(Point(x, y), magnitudeScale(star_db_element))
            star.setFill(config.STARCOLOR)
            star.setOutline(config.STARCOLOR)
            star.draw(window)

            if (config.SHOWSTARNAMES):
                starName = Text(Point(x, y - 10), astroObj.upper())
                starName.setOutline(config.LABELCOLOR)
                starName.setSize(7)
                starName.draw(window)

            if (config.VERBOSE):
                print(astroObj)
                print("Mag: " + str(star_db_element.mag))
                print("alt: " + str(star_db_element.alt))
                print("az:  " + str(star_db_element.az))
                print("")

        config.VISIBLE = True

    return
Beispiel #11
0
def epoch_transmatrix(time, stdtime=2000.0):
    import ephem as eph
    coorstd = np.zeros((3, 3))
    coortime = np.zeros((3, 3))

    stars = ['Agena', 'Menkar', 'Polaris']
    xs = {}
    ys = {}
    zs = {}
    xt = {}
    yt = {}
    zt = {}

    for starname, i in zip(stars, range(len(stars))):

        star = eph.star(starname)
        star.compute('2000', epoch='%f' % stdtime)
        xs[starname] = np.cos(star.a_dec) * np.cos(star.a_ra)
        ys[starname] = np.cos(star.a_dec) * np.sin(star.a_ra)
        zs[starname] = np.sin(star.a_dec)
        coorstd[i] = [xs[starname], ys[starname], zs[starname]]

        star.compute('2000', epoch='%f' % time)
        xt[starname] = np.cos(star.a_dec) * np.cos(star.a_ra)
        yt[starname] = np.cos(star.a_dec) * np.sin(star.a_ra)
        zt[starname] = np.sin(star.a_dec)
        coortime[i] = [xt[starname], yt[starname], zt[starname]]

    return (coortime.T).dot(la.inv(coorstd.T))
Beispiel #12
0
def setupTarget(ra_deg, dec_deg, pmra=0, pmdec=0, name=None, verbose=False):
    """
    ra_deg, dec_deg : strings or scalars
      Right ascenscion and Declination, in *decimal degrees* (scalar)
      or sexagesimal (if strings)

    """
    # 2015-03-19 21:37 IJMC: Created
    target = ephem.star('Rigel')
    if name is not None:
        target.name = name
    if isNumeric(ra_deg):
        ra_deg = hms(ra_deg, output_string=True)
    if isNumeric(dec_deg):
        dec_deg = dms(dec_deg, output_string=True)

    #print ra_deg, dec_deg
    target._ra, target._dec = ra_deg, dec_deg
    #print target._ra, target._dec

    if pmra<>0:
        target._pmra = pmra
    if pmdec<>0:
        target._pmdec = pmdec

    return target
Beispiel #13
0
 def arcturus_observations(self, extra_args={}):
     self.observed_location.horizon = standard_horizon()
     arcturus = ephem.star('Arcturus')
     try:
         self.observations["previous_arcturus_rise"] = to_date_time(self.observed_location.previous_rising(arcturus))
     except Exception, e:
         self.observations["previous_arcturus_rise"] = ""
def epoch_transmatrix(time,stdtime=2000.0):
    import ephem as eph
    coorstd=np.zeros((3,3))
    coortime=np.zeros((3,3))

    stars=['Agena','Menkar','Polaris']
    xs={};ys={};zs={}
    xt={};yt={};zt={}

    for starname,i in zip(stars,range(len(stars))):

        star=eph.star(starname)
        star.compute('2000',epoch='%f'%stdtime)
        xs[starname]=np.cos(star.a_dec)*np.cos(star.a_ra)
        ys[starname]=np.cos(star.a_dec)*np.sin(star.a_ra)
        zs[starname]=np.sin(star.a_dec)
        coorstd[i]=[xs[starname],ys[starname],zs[starname]]

        star.compute('2000',epoch='%f'%time)
        xt[starname]=np.cos(star.a_dec)*np.cos(star.a_ra)
        yt[starname]=np.cos(star.a_dec)*np.sin(star.a_ra)
        zt[starname]=np.sin(star.a_dec)
        coortime[i]=[xt[starname],yt[starname],zt[starname]]


    return (coortime.T).dot(la.inv(coorstd.T))
Beispiel #15
0
def indexKnownBrightestStars(filename, lat, lon, elevation, date):
    f = file(filename)
    #we want the star positions for our current observer location to compare against
    observer = ephem.Observer()
    observer.lat = lat
    observer.lon = lon
    observer.elevation = elevation
    observer.date = date
    brightestStars = []

    #create ephem body objects for each star name in the file
    for line in f:
        starname = line.strip('\n')
        star = ephem.star(starname)
        star.compute(observer)
        if (star.alt >= 0):
            brightestStars.append(star)

    quads = []
    for star in brightestStars:
        newquad = starQuad(star)
        newquad.findQuad(brightestStars)
        if (newquad.pointsInUnitCircle):
            print star, "closest stars:", newquad.quad
            quads.append(newquad)

    return (brightestStars, quads)
Beispiel #16
0
    def __init__(self, config, name):
        super(self.__class__, self).__init__(config)

        self.body = ephem.star(STAR_CATALOG[name]['name'])
        self.id = STAR_CATALOG[name]['id']
        self.name = STAR_CATALOG[name]['name']
        self.category = "star"
Beispiel #17
0
 def vega_observations(self, extra_args={}):
     self.observed_location.horizon = standard_horizon()
     vega = ephem.star('Vega')
     try:
         self.observations["previous_vega_rise"] = to_date_time(self.observed_location.previous_rising(vega))
     except Exception, e:
         self.observations["previous_vega_rise"] = ""
Beispiel #18
0
 def capella_observations(self, extra_args={}):
     self.observed_location.horizon = standard_horizon()
     capella = ephem.star('Capella')
     try:
         self.observations["previous_capella_rise"] = to_date_time(self.observed_location.previous_rising(capella))
     except Exception, e:
         self.observations["previous_capella_rise"] = ""
Beispiel #19
0
def setupTarget(ra_deg, dec_deg, pmra=0, pmdec=0, name=None, verbose=False):
    """
    ra_deg, dec_deg : strings or scalars
      Right ascenscion and Declination, in *decimal degrees* (scalar)
      or sexagesimal (if strings)

    """
    # 2015-03-19 21:37 IJMC: Created
    target = ephem.star('Rigel')
    if name is not None:
        target.name = name
    if isNumeric(ra_deg):
        ra_deg = hms(ra_deg, output_string=True)
    if isNumeric(dec_deg):
        dec_deg = dms(dec_deg, output_string=True)

    #print ra_deg, dec_deg
    target._ra, target._dec = ra_deg, dec_deg
    #print target._ra, target._dec

    if pmra <> 0:
        target._pmra = pmra
    if pmdec <> 0:
        target._pmdec = pmdec

    return target
Beispiel #20
0
 def rigel_observations(self, extra_args={}):
     self.observed_location.horizon = standard_horizon()
     rigel = ephem.star('Rigel')
     try:
         self.observations["previous_rigel_rise"] = to_date_time(self.observed_location.previous_rising(rigel))
     except Exception, e:
         self.observations["previous_rigel_rise"] = ""
Beispiel #21
0
	def set_star(self, star):
		print("try to set star to {0}".format(star))
		try:
			self.obj=ephem.star(star)
		except KeyError:
			print("Apparently this is not a valid name of a star and can therefore not be set!")
			return
		print("succesfully set star to {0}".format(self.obj.name))
Beispiel #22
0
def quick_s(name, track):
    if not track:  # If variable 'track' is False, clear the tracking because it's a new object being searched.
        clear_lock()
    if hasattr(ephem,
               name.get()):  # Check if variable 'name' is a named planet/moon
        obj = getattr(ephem, name.get())()  # If so, grab it
        search(obj, 'GET Planet/Moon')  # Object search and log detail
    else:
        try:
            ephem.star(name.get())  # Check if 'name' is a named star
        except KeyError:
            read_db(
                name)  # If not, read 'name' from the custom objects database
        else:
            obj = ephem.star(name.get())  # But if it was a star...
            search(obj, 'GET Named Star'
                   )  # ...Send it along with the correct log detail
Beispiel #23
0
def make_all_bodies():
    sun = ephem.Sun()
    moon = ephem.Moon()
    planets = [planet() for planet in PLANETS]
    stars = [ephem.star(name) for name in STARS]
    comet_dct = Comets()
    comets = [comet_dct[name] for name in COMETS]
    return [sun, moon] + planets + comets + stars
Beispiel #24
0
def RA_DEC(ob,latt,long,ele): 
    obs=ephem.Observer()
    obs.lat=latt
    obs.lon=long
    obs.elevation=float(ele)
    obj=ephem.star(ob)
    obj.compute(obs)
    print('\n',ob)
    print('RA:',obj.ra.real,' DEC:', obj.dec.real)
Beispiel #25
0
def get_all_stars():
    """ Return all the stars of ephem module."""
    stars_dict={}
    for star in ephem.stars.db.split("\n"):
        key=star.split(",")[0]
        #print key
        if key:
            stars_dict[key]=ephem.star(key)
    return stars_dict
Beispiel #26
0
def print_stars():
    for name in sorted(stars):
        star = ephem.star(name)
        star.compute()
        print(
            "{0.mag:+.1f} {0.name:20} {1:>16} {2:>16} {3}".format(
                star,
                _(star.ra, astro.utils.HMS),
                _(star.dec),
                ephem.constellation(star)[1]))
Beispiel #27
0
def Test():
    # px = 986.444
    # py = 439.240

    # print( "px: %f py: %f" % (px,py) )

    # (azim,elev) = PixelToAzEl(px, py)
    # (azim,elev) = RadToDeg(azim, elev)

    # print( "Az: %f El: %f" % (azim,elev))

    # azim,elev = DegToRad(azim,elev)
    # px,py,dist = AzElToPixel( azim,elev )

    # print( "px: %f py: %f dist: %f" % (px,py,dist) )

    # maxDist = 0.0
    # maxAzim = 0.0
    # maxElev = 0.0

    # for i in range(10000):
    #     azim = uniform(0.0,360.0)
    #     elev = uniform(0.0,90.0)

    #     azim2,elev2 = DegToRad(azim,elev)
    #     px,py,dist = AzElToPixel( azim2,elev2 )

    #     if dist > maxDist:
    #         maxDist = dist
    #         maxAzim = azim
    #         maxElev = elev

    # print("Max dist: %f at azim: %f elev: %f" % (maxDist,maxAzim,maxElev))

    vega = ephem.star("Vega")
    #vega.compute("2019/9/5")

    abq = ephem.Observer()
    abq.lon = "-106.5428"
    abq.lat = "35.1497"
    abq.elevation = 1690.0
    abq.date = "2019/9/9 09:00:00"

    print("Date: %s" % abq.date)

    vega.compute(abq)
    alt = float(vega.alt) * 180.0 / pi
    az = float(vega.az) * 180.0 / pi

    print("Alt: %f Az: %f" % (alt, az))

    azim, elev = DegToRad(az, alt)
    px, py, dist = AzElToPixel(azim, elev)

    print("px: %f py: %f dist: %f" % (px, py, dist))
Beispiel #28
0
def star_state(time, latitude, longitude):
    global STAR_NAMES
    observer = ephem.Observer()
    observer.date = time
    observer.lat = latitude
    observer.lon = longitude
    ephem_planets = [ephem.Sun(observer), ephem.Moon(observer), ephem.Mercury(observer),\
                     ephem.Venus(observer), ephem.Mars(observer), ephem.Jupiter(observer), ephem.Saturn(observer)]
    ephem_stars = [ephem.star(star_name, observer) for star_name in STAR_NAMES]
    return qt.Qobj(
        ALTITUDEaZIMUTH_v([(planet.alt, planet.az)
                           for planet in ephem_planets])).unit()
Beispiel #29
0
    def __init__(self, aplon, aplat, target="sunll", Hs=0, time="2012", elev=0, temp=20, press=1013):
        self.aplon=(aplon)
        self.aplat=(aplat)
        self.target=target
        self.Hs=Hs
        self.time=ephem.date(time)
        self.elev = elev
        self.temperature = temp
        self.pressure = press



        self.ap = ephem.Observer()
        self.ap.lon = self.aplon
        self.ap.lat = self.aplat
        self.ap.elevation = self.elev
        self.ap.date = self.time
        self.ap.temp = self.temperature
        self.ap.pressure = self.pressure

        if self.target == ("sunll"):
            self.o = ephem.Sun()
            self.cordir = -1
        elif self.target == ("sunul"):
            self.o = ephem.Sun()
            self.cordir = 1
        elif self.target ==("moonll"):
            self.o = ephem.Moon()
            self.cordir = -1
        elif self.target ==("moonul"):
            self.o = ephem.Moon()
            self.cordir = 1
        elif self.target == "venus":
            self.o = ephem.Venus()
            self.cordir = 0
        elif self.target == "Mars":
            self.o = ephem.Mars()
            self.cordir = 0
        elif self.target == "Jupiter":
            self.o = ephem.Jupiter()
            self.cordir = 0
        elif self.target == "Saturn":
            self.o = ephem.Saturn()
            self.cordir = 0
        else:
            self.o = ephem.star(self.target)
            self.cordir = 0


        self.o.compute(self.ap)
        self.Dip = 1.76*math.pi/10800*math.sqrt(self.elev)
        self.Ho = self.Hs - self.Dip
def compute(target, o=None):
    if o is None:
        o = ephem.city('Atlanta')
        o.date = '2009/09/06 17:00'
    if isinstance(target, str):
        target = ephem.star(target)
    target.compute(o)
    # Pyephem use Dublin JD, ephemeride uses Modified JD!
    mjd = o.date + 15020 - 0.5
    print('        {"%s", %.8f, %.8f, %.8f,\n'
          '         %.8f, %.8f, %.8f, %.8f, %.8f, %.8f},') % (
              target.name, mjd, o.lon * R2D, o.lat * R2D, target.a_ra * R2D,
              target.a_dec * R2D, target.ra * R2D, target.dec * R2D,
              target.alt * R2D, target.az * R2D)
Beispiel #31
0
def give_it_a_spin():
    """
    Tests basic functionality of Astrorobot
    
    See: https://github.com/Stellarium/stellarium/blob/585dcacdf71372de845b81420e1b9d1b80369263/src/core/RefractionExtinction.cpp
        for calculations on
            Extinction = amount of light absorbed by atmosphere vs altitude (NB also causes redenning of objects as blue light absorbed more)
            Refraction = bending of light by atmosphere vs altitude (more bending nearer horizon
            
    This is the refraction calculating code used by libastro (which ephem uses):
        https://fossies.org/dox/xephem-3.7.7/refract_8c_source.html
    """
    dt = datetime(2016,12,31,17,25,00)
    ob = Observer(location="Bracknell,UK", timestamp=dt)
    ob.get_weather()
    print(ob.get_twilight())
    s = Target(ob, "Betelgeuse")
    print("Betelgeuse:")
    print("\tEphem a-RADec: %s, Dec: %s  (expected: 5:56:6 / 7:24:32)" % (s.a_ra, s.a_dec))
    print("\tEphem RADec: %s, Dec: %s" % (s.ra, s.dec))
    print("\tEphem AzAlt: Az: %s, Alt: %s" % (s.az, s.alt))
    print("\tAstrorobot RADec apparent: %s" % unicode(s.ra_dec))
    print("\tAstrorobot HADec apparent: %s  (expected: 18:08:28 / 7:30:10)" % unicode(s.ha_dec))
    print("\tAstrorobot AzAlt apparent: %s  (expected: 86:56:56 / 7:10:32)" % unicode(s.az_alt))
    #And now check directly
    e_o = ephem.Observer()
    e_o.lat = 51.410684
    e_o.lon = -0.728876
    e_o.elev = 50
    e_o.horizon = 0
    e_o.date = dt.strftime(settings.EPHEM_OBSERVER_DATE_FORMAT)
    e_o.pressure = 0 #Set to zero
    e_o.temp = 10.0
    t = ephem.star("Betelgeuse")
    t.compute(e_o)
    print("Ephem pressure 0 AzAlt: %.12f, %.12f  |  RADec: %.12f, %.12f" % (t.az, t.alt, t.ra, t.dec))
    e_o.pressure = 12000000.0
    t.compute(e_o)
    print("Ephem pressure 1200mBar AzAlt: %.12f, %.12f  |  RADec: %.12f, %.12f" % (t.az, t.alt, t.ra, t.dec))
    e_o.compute_pressure()
    print("ephem_observer pressure computed: %.12f" % e_o.pressure)
    t.compute(e_o)
    print("Ephem pressure computed AzAlt: %.12f, %.12f  |  RADec: %.12f, %.12f" % (t.az, t.alt, t.ra, t.dec))
    print("--")
    back_ra, back_dec = e_o.radec_of(t.az, t.alt)
    print("Ephem AzAlt > RADec norm pressure: %s, %s  |  %.12f, %.12f" % (back_ra, back_dec, back_ra, back_dec))
    e_o.pressure = 0
    t.compute(e_o)
    back_ra, back_dec = e_o.radec_of(t.az, t.alt)
    print("Ephem AzAlt > RADec ZERO pressure: %s, %s  |  %.12f, %.12f" % (back_ra, back_dec, back_ra, back_dec))
    def setup_object(self):
        """Method to generate an ephem.star object from the target coordinates.

        """
        object = ephem.star('Rigel')
        if self.name is not None:
            object.name = self.name
        ra = utils.hms(self.ra)
        dec = utils.dms(self.dec)

        object._ra, object._dec = ra, dec

        #self.object = object
        return object
Beispiel #33
0
def ALT_AZ(ob,latt,long,ele): 
    obs=ephem.Observer()
    obs.lat=latt
    obs.lon=long
    obs.elevation=float(ele)
    obj=ephem.star(ob)
    obj.compute(obs)
    
    alt=obj.alt.real
    az=obj.az.real
    altdeg=alt*180/math.pi
    azdeg=az*180/math.pi
    print('\n',ob)
    print('ALT:',altdeg,' AZ:', azdeg)
    return altdeg, azdeg
Beispiel #34
0
def _get_ephem_body(heavenly_body):
    # The library 'ephem' refers to heavenly bodies using a capitalized
    # name. For example, the module used for 'mars' is 'ephem.Mars'.
    cap_name = heavenly_body.capitalize() 
    
    # If the heavenly body is a star, or if the body does not exist, then an
    # exception will be raised. Be prepared to catch it.
    try:
        ephem_body = getattr(ephem, cap_name)()
    except AttributeError:
        # That didn't work. Try a star. If this doesn't work either,
        # then a KeyError exception will be raised.
        ephem_body = ephem.star(cap_name)

    return ephem_body
Beispiel #35
0
def _get_ephem_body(heavenly_body):
    # The library 'ephem' refers to heavenly bodies using a capitalized
    # name. For example, the module used for 'mars' is 'ephem.Mars'.
    cap_name = heavenly_body.capitalize()

    # If the heavenly body is a star, or if the body does not exist, then an
    # exception will be raised. Be prepared to catch it.
    try:
        ephem_body = getattr(ephem, cap_name)()
    except AttributeError:
        # That didn't work. Try a star. If this doesn't work either,
        # then a KeyError exception will be raised.
        ephem_body = ephem.star(cap_name)

    return ephem_body
Beispiel #36
0
def star(star_name):
    star = ephem.star(star_name)
    south_bend = ephem.Observer()
    date_class = datetime.now()
    south_bend.lat = lat
    south_bend.lon = lon
    south_bend.date = date_class
    star.compute(south_bend)
    print "Date ", date_class
    print "Mag ", star.mag
    print "RA ", star.ra
    print "Dec ", star.dec

    next = raw_input('Would you like to look up another object?')
    if next.strip() in 'y Y yes Yes YES'.split():
        choice()
Beispiel #37
0
def star(star_name):
    star = ephem.star(star_name)
    south_bend = ephem.Observer()
    date_class = datetime.now()
    south_bend.lat = lat
    south_bend.lon = lon
    south_bend.date = date_class
    star.compute(south_bend)
    print "Date ", date_class
    print "Mag ", star.mag
    print "RA ", star.ra
    print "Dec ", star.dec
    
    next = raw_input('Would you like to look up another object?')
    if next.strip() in 'y Y yes Yes YES'.split():
        choice()
Beispiel #38
0
def find_ephem_obj(str):
    if (not str):
        return
    if (str == "moon"):
        return ephem.Moon()
    elif (str == "sun"):
        return ephem.Sun()
    elif (str == "mars"):
        return ephem.Mars()
    elif (str == "andromeda" or str == "m31"):
        return ephem.readdb("M31,f|G,0:42:44,+41:16:8,4.16,2000,11433|3700|35")
    else:
        try:
            obj = ephem.star(str)
        except KeyError:
            return None
Beispiel #39
0
    def compute_GHA_DEC(self):
        # sun
        if self.body == 'SunLL' or self.body == 'SunUL':
            celestial_body = ephem.Sun()
        # insert moon here
        elif self.body == 'MoonLL' or self.body == 'MoonUL':
            celestial_body = ephem.Moon()
        # planets
        elif self.body == 'Mars':
            celestial_body = ephem.Mars()
        elif self.body == 'Venus':
            celestial_body = ephem.Venus()
        elif self.body == 'Jupiter':
            celestial_body = ephem.Jupiter()
        elif self.body == 'Saturn':
            celestial_body = ephem.Saturn()
        elif self.body == 'Uranus':
            celestial_body = ephem.Uranus()
        elif self.body == 'Mercury':
            celestial_body = ephem.Mercury()
        # anything else must be a star, and its body can be interpreted via the string argument in ephem.star('')
        else:
            celestial_body = ephem.star(self.body)

        obs = ephem.Observer()
        # disable a correction for pressure, since we do this later
        obs.pressure = 0

        # format strings from datetime object
        date = self.datetime.strftime('%Y/%m/%d')
        time = self.datetime.strftime('%H:%M:%S')
        date_string = date + ' ' + time
        obs.date = date_string

        celestial_body.compute(date_string, epoch=date_string)

        deg = ephem.degrees(obs.sidereal_time() - celestial_body.g_ra).norm
        ghas = nadeg(deg)
        deg = celestial_body.g_dec
        decs = nadeg(deg)

        # convert GHA and DEC to Angle objects
        self.GHA = Angle(ghas, unit=u.deg)
        self.DEC = Angle(decs, unit=u.deg)
        print('GHA and DEC for body {} are {:.3f} / {:.3f}'.format(
            self.body, self.GHA.deg, self.DEC.deg))
        return
Beispiel #40
0
    def __init__(self):

        self.logger = logging.getLogger(__name__)

        # initialize the motors
        self.motors = [
            Motor("Azimuth", self.az_pins, positive=1),
            Motor("Altitude", self.alt_pins, positive=-1),
        ]

        # initialize observer and target
        self._observer = ephem.Observer()
        self._target = ephem.FixedBody()

        # insteresting objects in our solar system and main stars
        self._sky_objects = [
            ephem.Sun(),
            ephem.Moon(),
            ephem.Mercury(),
            ephem.Venus(),
            ephem.Mars(),
            ephem.Jupiter(),
            ephem.Saturn(),
        ]
        for star in sorted(
            [x.split(",")[0] for x in ephem.stars.db.split("\n") if x]):
            self._sky_objects.append(ephem.star(star))

        # set boolean variable indicating tracking
        self._is_tracking = False
        self.restart = [False, False]
        self.running = [False, False]

        # initialize angles/steps lists for calibration
        self._angles_steps = [[], []]

        # initialize motor threads
        self._motor_threads = [None, None]

        az_default_spr = 1293009
        alt_default_spr = 1560660

        self.motors[0].steps_per_rev = az_default_spr
        self.motors[1].steps_per_rev = alt_default_spr

        # at startup no client is connected
        self._client_connected = False
Beispiel #41
0
 def _test_body(self, name, sha, dec, date=NP314_DATE):
     obj = ephem.star(name)
     obs = ephem.Observer()
     obs.date = date
     obj.compute(obs)
     exp_sha = ephem.degrees(sha)
     err_sha = math.degrees(2 * ephem.pi - obj.g_ra - exp_sha)
     self.assertTrue(
         abs(err_sha) < self.MAX_ERROR_DEGREES,
         'SHA fail: {0!s:} !< {1!s:}'.format(abs(err_sha),
                                             self.MAX_ERROR_DEGREES))
     exp_dec = ephem.degrees(dec)
     err_dec = math.degrees(obj.g_dec - exp_dec)
     self.assertTrue(
         abs(err_dec) < self.MAX_ERROR_DEGREES,
         'Dec. fail: {0!s:} !< {1!s:}'.format(abs(err_dec),
                                              self.MAX_ERROR_DEGREES))
Beispiel #42
0
def close_star_approaches(year=None):
    if year is None:
        year = ephem.now().triple()[0]
    starting_date = ephem.Date(str(year))
    stars_list = [ephem.star(name) for name in stars.keys()]
    # Stars don't move, so just compute them once
    [star.compute(starting_date) for star in stars_list]

    planets = [planet() for planet in PLANETS]
    for day in range(365):
        date = ephem.Date(starting_date + day)
        [body.compute(date) for body in planets]
        for body in planets:
            for star in stars_list:
                sep = ephem.separation(body, star)
                if sep < ephem.degrees('3'):
                    print(date, body.name, star.name, sep)
Beispiel #43
0
 def _test_body(self, name, sha, dec, date=NP314_DATE):
     obj = ephem.star(name)
     obs = ephem.Observer()
     obs.date = date
     obj.compute(obs)
     exp_sha = ephem.degrees(sha)
     err_sha = math.degrees(2 * ephem.pi - obj.g_ra - exp_sha)
     self.assertTrue(
         abs(err_sha) < self.MAX_ERROR_DEGREES,
         'SHA fail: {0!s:} !< {1!s:}'.format(abs(err_sha), self.MAX_ERROR_DEGREES) 
     )
     exp_dec = ephem.degrees(dec)
     err_dec = math.degrees(obj.g_dec - exp_dec)
     self.assertTrue(
         abs(err_dec) < self.MAX_ERROR_DEGREES,
         'Dec. fail: {0!s:} !< {1!s:}'.format(abs(err_dec), self.MAX_ERROR_DEGREES) 
     )
Beispiel #44
0
def _main(args):

    if args['get']:
        values = {}
        template = "ha={ha}\nde={de}"
        #@TODO angle formats
        if args['raw']:
            values = get_raw()
        elif args['normalised']:
            values = get_normalised()
        elif args['internal']:
            values = get_internal()
        elif args['ring']:
            values = get_ring()
        elif args['local']:
            values = get_local()
        elif args['celest']:
            values = get_celest()
            template = "ra={ra}\nde={de}"
        elif args['altaz']:
            values = get_altaz()
            template = "alt={alt}\naz={az}"
        elif args['chirality']:
            values = {'chirality': get_chirality()}
            template = "{chirality}"
        print template.format(**values)

    elif args['set']:
        if args['internal']:
            ha = float(args['<HA>'])
            de = float(args['<DE>'])
            set_internal({'ha': ha, 'de': de}, args['blind'])
        elif args['celest']:
            ra = float(args['<RA>'])
            de = float(args['<DE>'])
            set_internal(celest_to_internal({'ra': ra, 'de': de}), args['blind'])
        elif args['star']:
            star = ephem.star(args['<NAME>'])
            star.compute(tican())
            set_internal(celest_to_internal({'ra': star.ra / math.pi * 12, 'de': star.dec / math.pi * 180}), args['blind'])
        elif args['cat']:
            celest = dagor_catalog.get_celest(args['<NAME>'], args['<CATALOG>'])
            set_internal(celest_to_internal(celest), args['blind'])
Beispiel #45
0
def _get_ephem_body(heavenly_body):
    # The library 'ephem' refers to heavenly bodies using a capitalized
    # name. For example, the module used for 'mars' is 'ephem.Mars'.
    cap_name = heavenly_body.title()

    # If the heavenly body is a star, or if the body does not exist, then an
    # exception will be raised. Be prepared to catch it.
    try:
        ephem_body = getattr(ephem, cap_name)()
    except AttributeError:
        # That didn't work. Try a star. If this doesn't work either,
        # then a KeyError exception will be raised.
        ephem_body = ephem.star(cap_name)
    except TypeError:
        # Heavenly bodies added by a ephem.readdb() statement are not functions.
        # So, just return the attribute, without calling it:
        ephem_body = getattr(ephem, cap_name)

    return ephem_body
Beispiel #46
0
def current_separations():
    stars_list = [ephem.star(name) for name in stars.keys()]
    planets = [planet() for planet in PLANETS]
    solar_system = [ephem.Moon()] + planets
    [body.compute() for body in solar_system + stars_list]
    print(type(stars_list[0]))
    angles = []
    # Separations between solar system bodies and stars
    for body in solar_system:
        for star in stars_list:
            angles.append(
                Separation(body, star, ephem.separation(body, star)))
    # more separations
    for a, b in itertools.combinations(solar_system, 2):
        angles.append(Separation(a, b, ephem.separation(a, b)))

    for sep in sorted(angles, key=operator.attrgetter('angle')):
        if sep.angle > MAX_ANGLE:
            break
        print(sep)
Beispiel #47
0
class position:

	#position of the HESS Site
	HESS_site = ephem.Observer()
	HESS_site.lat  = ephem.degrees("-23.271536")
	HESS_site.long = ephem.degrees("16.500974")

	#object we observe
	obj = ephem.star("Acrux")
	
	#sets the observed object to an new star
	def set_star(self, star):
		print("try to set star to {0}".format(star))
		try:
			self.obj=ephem.star(star)
		except KeyError:
			print("Apparently this is not a valid name of a star and can therefore not be set!")
			return
		print("succesfully set star to {0}".format(self.obj.name))
	
	#returns the position of the observed object in Ra, Dec coordinates
	def get_ra_dec(self):
		return (self.obj.ra, self.obj.dec)
	
	def get_az_alt(self):
		self.HESS_site.date = ephem.Date(datetime.utcnow())
		self.obj.compute(self.HESS_site)
		#print("Time: {0} , Alt: {1} , Az: {2}".format(datetime.utcnow(), self.obj.az/np.pi*180, self.obj.alt/np.pi*180))
		return self.obj.az/np.pi*180, self.obj.alt/np.pi*180
		
	def get_star_list(self):
		return [
		"Acrux",
		"Peacock",
		"Alnair",
		"Mimosa",
		"Test"
		]

	def get_name(self):
		return self.obj.name
Beispiel #48
0
    def GetStarInfo(self, starName):
        try:
            s = ephem.star(starName)
            s.compute(self.myObserver)

            star_rightascension = s._ra
            star_declination = s._dec
            star_magnitude = s.mag
            star_elongation = s.elong  # angle to sun
            star_circumpolar = s.circumpolar  # stays above horizon?
            star_neverup = s.neverup  # never rises?
            star_altitude = s.alt
            star_azimuth = s.az
            star_compass = AU.AzimuthToCompassDirection(star_azimuth)
            star_constellation = str(ephem.constellation(s)[1])
            star_visible = True if star_altitude > 0 else False

            dictionaryData = {}
            dictionaryData["Name"] = str(starName)
            dictionaryData["RightAscension"] = str(star_rightascension)
            dictionaryData["Declination"] = str(star_declination)
            dictionaryData["Magnitude"] = str(star_magnitude)
            dictionaryData["Elongation"] = str(star_elongation)
            dictionaryData["Circumpolar"] = star_circumpolar
            dictionaryData["NeverUp"] = star_neverup
            dictionaryData["Altitude"] = str(star_altitude)
            dictionaryData["Azimuth"] = str(star_azimuth)
            dictionaryData["Compass"] = str(star_compass)
            dictionaryData["IsVisible"] = star_visible

            if self.prettyprint == True:
                json_string = json.dumps(dictionaryData, sort_keys=True, indent=4, separators=(",", ": "))
            else:
                json_string = json.dumps(dictionaryData, sort_keys=True, separators=(",", ": "))

            return json_string

        except Exception as ex:
            print str(ex)
            return "{ }"
Beispiel #49
0
def compare_pyephem_with_my_code():
    """
    Compares my CoordinatePairs to the Pyephem library
    
    17 Toll Gardens, Bracknell location = 51°24'38.5"N 0°43'44.0"W (51.410684, -0.728876)
    
    Betelgeuse @ 2016-12-23 17:05:
        RA = Decimal('1.5538093862003428125007076232577674090862274169921875')  <radians>
        Dec = Decimal('0.1292627123113075648941361350807710550725460052490234375') <radians>
    """
    latitude = "51:24.385"
    longitude = "-0:43.44"
    my_latlon = LatLon(d("51.410684"), d("-0.728876"))
    my_time = datetime.utcnow()
    #
    # PyEphem's calculations
    observer = ephem.Observer()
    observer.lat = latitude
    observer.lon = longitude
    observer.date = my_time.strftime("%Y/%m/%d %H:%M:%S")
    betelgeuse = ephem.star("Betelgeuse")
    betelgeuse.compute(observer)
    #
    #My calculations - we'll start with Betelgeuse's apparent RADec
    my_radec = ApparentRADec(d(float(betelgeuse.ra)), d(float(betelgeuse.dec)), mode="rad")
    my_radec.apparent = True
    
    #Lets look at output:
    #RA
    print("PyEphem - Betelgeuse RADec = %.6f, %.6f  [%s, %s]" % (betelgeuse.ra, betelgeuse.dec.norm, betelgeuse.ra, betelgeuse.dec))
    print("My - RADec = %.6f, %.6f  %s" % (my_radec.ra.norm, my_radec.dec.norm, my_radec))
    
    #Az alt
    print("PyEphem - Betelgeuse AzAlt = %.6f, %.6f  [%s, %s]" % (betelgeuse.az, betelgeuse.alt, betelgeuse.az, betelgeuse.alt))
    print("My - AzAlt = %s" % my_radec.to_az_alt(latitude=my_latlon.latitude, longitude=my_latlon.longitude, timestamp=my_time))
    
    print("Sidereal RA > %s" % sidereal.raToHourAngle(betelgeuse.ra, my_time, eLong=observer.lon))
    
    print(dir(betelgeuse))
    print(dir(observer))
Beispiel #50
0
def planetsStarsAbove(qth):
    """Calculate whether certain planets or stars are visible above or not.

    Of course, it's going to be hard to see things if it's daytime!.
    """

    planetsStarsAbove = {}

    location = ephem.Observer()
    location.lat = qth[0]
    location.lon = qth[1]
    location.elevation = float(qth[2])

    for body in solar_system_bodies:
        e = getattr(ephem, body)

        setting = location.next_setting(e()).datetime()
        rising = location.next_rising(e()).datetime()

        if setting < rising:
            planetsStarsAbove[body] = True
        else:
            planetsStarsAbove[body] = False

    for star in stars:
        e = ephem.star(star)

        try:
            setting = location.next_setting(e).datetime()
        except ephem.AlwaysUpError:
            continue

        rising = location.next_rising(e).datetime()

        if setting < rising:
            planetsStarsAbove[star] = True
        else:
            planetsStarsAbove[star] = False

    return planetsStarsAbove
Beispiel #51
0
def position_finder(inputs):
    start = inputs.find("[")
    end = inputs.find("]")
    last = inputs.find("/")
    observer = ephem.Observer()
    observer.lat = ephem.degrees(inputs[end+1:last])
    observer.lon = ephem.degrees(inputs[start+1:end])
    observer.elevation = 100#by defualt it will change later 
    observer.date = ephem.now()
    observer.epoch = '2020'
    if int(inputs[last+1:]) >16:
        star = ephem.star(inputs[:start])
        star.compute(observer)
        a = format(math.cos(float(star.alt)),"4.6f")
        b = format((float(star.az)*180)/math.pi,"4.6f")
        string = str(a) + "_" +str(b) 
    else:
        planet = getattr(ephem,inputs[:start])
        x = planet(observer)
        a = format(math.cos(float(x.alt)),"4.6f")
        b = format((float(x.az)*180)/math.pi,"4.6f")
        string = str(a) + "_" +str(b) 
    return string
Beispiel #52
0
 def astronomical_update(self):
     observer = ephem.Observer()
     observer.date = self.time
     observer.lat = self.latitude
     observer.lon = self.longitude
     ephem_planets = [
         ephem.Sun(observer),
         ephem.Moon(observer),
         ephem.Mercury(observer),
         ephem.Venus(observer),
         ephem.Mars(observer),
         ephem.Jupiter(observer),
         ephem.Saturn(observer)
     ]
     ephem_stars = [
         ephem.star(star_name, observer) for star_name in STAR_NAMES
     ]
     self.fixed_stars = [
         altitudeAzimuth_hermitian(fixed_star.alt, fixed_star.az)
         for fixed_star in ephem_stars
     ]
     self.state = ALTITUDEaZIMUTH_v([(planet.alt, planet.az)
                                     for planet in ephem_planets])
     self.touched = True
mars =    PyEph_body(ephem.Mars(), color.cmyk.Red)
jupiter = PyEph_body(ephem.Jupiter(), color.cmyk.Magenta)
saturn =  PyEph_body(ephem.Saturn(), color.cmyk.Yellow)
uranus =  PyEph_body(ephem.Uranus(), color.cmyk.SpringGreen)
neptune = PyEph_body(ephem.Neptune(), color.cmyk.ForestGreen)
# some messier objects
m13 = PyEph_body(ephem.readdb("M13,f|C,16:41:42,36:28,5.9,2000,996"),
        symbol='m13', tsize='tiny')
m31 = PyEph_body(ephem.readdb("M31,f|G,0:42:44,+41:16:8,4.16,2000,11433|3700|35"),
        symbol='m31', tsize='tiny')
m42 = PyEph_body(ephem.readdb("M42,f|U,05:35:18,-05:23,4,2000,3960"),
        symbol='m42', tsize='tiny')
m45 = PyEph_body(ephem.readdb("M45,f|U,03:47:0,24:07,1.2,2000,6000"),
        symbol='m45', tsize='tiny')
# some bright stars
sirius     = PyEph_body(ephem.star('Sirius'), symbol='Sir', tsize='tiny')
antares    = PyEph_body(ephem.star('Regulus'), symbol='Ant', tsize='tiny')
deneb      = PyEph_body(ephem.star('Deneb'), symbol='Den', tsize='tiny')
betelgeuse = PyEph_body(ephem.star('Betelgeuse'), symbol='Bet', tsize='tiny')
pollux     = PyEph_body(ephem.star('Pollux'), symbol='Pol', tsize='tiny')
arcturus   = PyEph_body(ephem.star('Arcturus'), symbol='Arc', tsize='tiny')

mercury.rising_text = [
[0.04, '~', 'Merk. doğ.', -1, True],
[0.30, 'Merkür doğuyor', '~', -1, False],
[0.63, 'Merkür', 'doğuyor', -1, True],
[0.85, 'Merkür', 'doğuyor', -1, False]
]
venus.rising_text = [
[0.06, 'Venüs doğuyor', '~', -1, True]
]
Beispiel #54
0
def convertCelestialToHorizonNow(job, location):
	bodyName = job['body']

	dt = datetime.datetime.now();
	dt = str(dt.year) +'/'+ str(dt.month) +'/'+ str(dt.day)  +' '+ str(dt.hour-1) + ':' +str(dt.minute)
	gatech = ephem.Observer()
	gatech.epoch = dt

	if bodyName == "Sun":
		body = ephem.Sun()
	elif bodyName == "Moon":
		body = ephem.Moon()
	elif bodyName == "Mercury":
		body = ephem.Mercury()
	elif bodyName == "Venus":
		body = ephem.Venus()
	elif bodyName == "Mars":
		body = ephem.Mars()
	elif bodyName == "Phobos":
		body = ephem.Phobos()
	elif bodyName == "Deimos":
		body = ephem.Deimos()
	elif bodyName == "Jupiter":
		body = ephem.Jupiter()
	elif bodyName == "Io":
		body = ephem.Io()
	elif bodyName == "Europa":
		body = ephem.Europa()
	elif bodyName == "Ganymede":
		body = ephem.Ganymede()
	elif bodyName == "Callisto":
		body = ephem.Callisto()
	elif bodyName == "Saturn":
		body = ephem.Saturn()
	elif bodyName == "Mimas":
		body = ephem.Mimas()
	elif bodyName == "Enceladus":
		body = ephem.Enceladus()
	elif bodyName == "Tethys":
		body = ephem.Tethys()
	elif bodyName == "Dione":
		body = ephem.Dione()
	elif bodyName == "Rhea":
		body = ephem.Rhea()
	elif bodyName == "Titan":
		body = ephem.Titan()
	elif bodyName == "Iapetus":
		body = ephem.Iapetus()
	elif bodyName == "Hyperion":
		body = ephem.Hyperion()
	elif bodyName == "Uranus":
		body = ephem.Uranus()
	elif bodyName == "Miranda":
		body = ephem.Miranda()
	elif bodyName == "Ariel":
		body = ephem.Ariel()
	elif bodyName == "Umbriel":
		body = ephem.Umbriel()
	elif bodyName == "Titania":
		body = ephem.Titania()
	elif bodyName == "Oberon":
		body = ephem.Oberon()
	elif bodyName == "Neptune":
		body = ephem.Neptune()
	elif bodyName == "Pluto":
		body = ephem.Pluto()
	else:
		body = ephem.star(bodyName)

	geolocator = Nominatim()
	location = geolocator.geocode(location)
	gatech.lon, gatech.lat = str(location.longitude), str(location.latitude)
	gatech.date = dt
	body.compute(gatech)
	return body
Beispiel #55
0
                    event_queue.put(ev)
                    events[ev.key] = ev
            body_queue.task_done()
        except queue.Empty:
            break

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG,
        format="%(asctime)s %(levelname)s %(threadName)s %(message)s")
    # Load the body queue before we start things up
    LONG_LIST = False  # long list useful when debugging to have a lot of bodies
    comets = Comets()
    sun_and_moon = [ephem.Sun(), ephem.Moon()]
    planets = [planet() for planet in PLANETS]
    if LONG_LIST:
        star_list = [ephem.star(name) for name in stars.keys()]
        comet_list = list(comets.values())
    else:
        star_list = []
        comet_list = [comets[name] for name in COMETS]
    all_bodies = sun_and_moon + planets + star_list + comet_list
    for body in all_bodies:
        body_queue.put(body)
        bodies[body.name] = body
    bt = threading.Thread(target=body_consumer, name='BodyConsumer')
    bt.start()
    logger.debug('BodyConsumer started')
    bt.join()  # wait for all of them to be added
    threading.Thread(target=event_consumer, name='EventConsumer').start()
    threading.Thread(target=rescheduler, name='Rescheduler').start()
Beispiel #56
0
 def select_body(self, name):
     """Return solar system bodies and stars for USNO computations."""
     if hasattr(ephem, name):
         return getattr(ephem, name)()
     else:
         return ephem.star(name)
Beispiel #57
0
# list out planets
data_planets = {}
planetrybodies = ['Moon','Sun','Mercury','Venus','Mars','Jupiter','Saturn','Uranus','Neptune','Pluto']
for entity in planetrybodies:
    spaceentity = getattr(ephem, entity)()
    spaceentity.compute(home)
    spaceentity_data = {}
    spaceentity_data['elevation']   = "%4.1f" % (spaceentity.alt * degrees_per_radian);
    spaceentity_data['azimuth']     = "%4.1f" % (spaceentity.az * degrees_per_radian);
    data_planets[entity] = spaceentity_data
apiresult['planets']=data_planets

# list out stars
data_stars = {}
stars = ['Polaris','Mizar','Alioth','Megrez','Phecda','Merak','Dubhe']
for entity in stars:
    spaceentity = ephem.star(entity)
    spaceentity.compute(home)
    spaceentity_data = {}
    spaceentity_data['elevation']   = "%4.1f" % (spaceentity.alt * degrees_per_radian);
    spaceentity_data['azimuth']     = "%4.1f" % (spaceentity.az * degrees_per_radian);
    data_stars[entity] = spaceentity_data
apiresult['stars']=data_stars

# output

print "Access-Control-Allow-Origin: *"
print "Content-type: application/json\n\n"
print json.dumps(apiresult)
Beispiel #58
0
def compute_star(name):
    star = ephem.star(name)
    star.compute()
    return star
Beispiel #59
0
import ephem

gatech = ephem.Observer()               
gatech.lon, gatech.lat = '45.54593', '-62.6034'
gatech.date = '2013/09/10 03:13:56' 
vega = ephem.star('Vega')
vega.compute(gatech)  
vega.az

gatech.date = '2013/09/10 03:23:56' 
kochab = ephem.star('Kochab') 
kochab.compute(gatech) 
kochab.az

gatech.date = '2013/09/10 03:33:56' 
altair = ephem.star('Altair')
altair.compute(gatech) 
altair.az

gatech.date = '2013/09/10 03:43:56' 
alde = ephem.star('Aldebaran')
alde.compute(gatech) 
alde.az

gatech.date = '2013/09/10 03:53:56' 
fom = ephem.star('Fomalhaut')
fom.compute(gatech) 
fom.az
		myLocation.lat = '32:54.0'
		myLocation.elevation = 2000
	else:
		sys.exit("Unknown location.");

# Range of acceptable alt and az for stars
minAltitude = 40.
maxAltitude = 85.

# Read a list of the known bright star names
f = open('/Users/dragonfly/Dropbox/src/catalog/stars.txt','r')
lines = f.readlines()
starNames = [n.rstrip() for n in lines]

# Create a list with Star objects
stars = [ephem.star(s) for s in starNames]

# Create a list of altitudes and azimuths. I want these to be stored as
# floats rather than as ephem.Angle types, so I add 0.0 to them. They
# are in units of radians.
alt = []
az = []
for s in stars:
	s.compute(myLocation)
	alt.append(s.alt + 0.0)
	az.append(s.az + 0.0)

# Create a new list of stars at least minAltitude degrees above the horizon but
# less than maxAltitude degrees above the horizon. Sort this list by azimuth.
goodStars = [s for s in stars if (s.alt > minAltitude*math.pi/180. and s.alt < maxAltitude*math.pi/180.)]