def __init__(self, ts): dt = datetime.datetime.fromtimestamp(ts) self.dt = datetime.datetime(dt.year, dt.month, dt.day, tzinfo=eastern) # Setup some of the basics, yes it's redundant self.day = self.dt.day self.month = self.dt.month self.year = self.dt.year self.week_number = self.dt.isocalendar()[1] self.beg_ts = time.mktime(self.dt.timetuple()) self.end_ts = self.beg_ts + 86400 #secs in a day # Now some more complicated stuff, get the sunset and sunrise, # both as datetimes and timestamps self.sunset = ephem.city('New York').next_setting(ephem.Sun(), start=self.dt).datetime().replace( tzinfo=utc).astimezone(eastern) self.sunset_ts = time.mktime(self.sunset.timetuple()) self.sunrise = ephem.city('New York').next_rising(ephem.Sun(), start=self.dt).datetime().replace( tzinfo=utc).astimezone(eastern) self.sunrise_ts = time.mktime(self.sunrise.timetuple()) # An array for each type of reading, one per hour hourly_values = dict.fromkeys(CLASSIFICATIONS) for classification in hourly_values.iterkeys(): hourly_values[classification] = [] hourly_values[classification][:] = [[0,0,False] for hour_index in range(24)] # Some daily readings daily_values = dict.fromkeys(CLASSIFICATIONS) for classfication in daily_values.iterkeys(): daily_values[classification] = [0, None] return
def solarcalculator_test(): import ephem import pytz from datetime import datetime, timedelta import numpy as np from solarcalculator import SolarCalculator print("Testing SolarCalculator interface.") sc = SolarCalculator(("65:01", "25:28")) # Passing coordinates of Oulu to constructor assert sc is not None, 'SolarCalculator initialization returned None' print(" Initialization ok.") hel = ephem.city('Helsinki') sc.observer = hel assert (int(sc.observer.lat/3.14159*180*1e5)/1e5) == 60.16986, 'Observer coordinates (lat) incorrect: {}'.format(sc.observer.lat/3.14159*180) assert (int(sc.observer.long/3.14159*180*1e5)/1e5) == 24.93826, 'Observer coordinates (long) incorrect: {}'.format(sc.observer.long/3.14159*180) print(" Observer setting ok.") sc.coords = ('37.8044', '-122.2697', 3.0) assert np.round(np.rad2deg(sc.observer.lat),4) == 37.8044, 'Changing observer (lat) coordinates failed: {}'.format(np.rad2deg(sc.observer.lat)) assert np.round(np.rad2deg(sc.observer.long),4) == -122.2697, 'Changing observer (long) coordinates failed: {}'.format(np.rad2deg(sc.observer.long)) print(" Coordinate setting ok.") time_str = '2012/11/16 20:34:56' time_fmt = '%Y/%m/%d %H:%M:%S' dt = datetime.strptime(time_str, time_fmt).replace(tzinfo=pytz.utc) assert dt.strftime(time_fmt) == time_str, 'Initializing a datetime object failed: {}'.format(dt.strftime(time_fmt)) print(" Initialized datetime object ok.") sc.date = dt assert sc.localized_date(tz=pytz.utc).strftime(time_fmt) == time_str, 'Initializing date to solarcalculator failed: {}'.format(sc.localized_date(tz=pytz.utc).strftime(time_fmt)) print(" Changed observer date ok.") tz = sc.timezone assert str(tz) == 'America/Los_Angeles', 'Timezone is incorrect: {}'.format(tz) print(" Timezone found ok.") assert sc.date.strftime(time_fmt) == '2012/11/16 12:34:56', 'Observer date did not return a proper result: {}'.format(sc.date.strftime(time_fmt)) print(" Conversion to local timezone ok.") sdt = sc.solartime assert sdt.strftime(time_fmt) == '2012/11/16 12:40:55', 'Solartime did not return proper result: {}'.format(sdt.strftime(time_fmt)) assert sdt.strftime("%z") == '-0754', 'Timezone offset incorrect: {}'.format(sdt.strftime("%z")) obs = ephem.city('Helsinki') sc.observer = obs assert sc.coords == (1.0501613384326405, 0.43525439939787997), 'Coordinates were not set properly: {}'.format(sc.coords) sc.coords = ('60:10:11.3', '24.9') dt = pytz.timezone('Europe/Stockholm').localize(datetime(2016, 1, 6, 20, 41, 31, 0)) sc.date = dt assert sc.date.strftime(time_fmt) == '2016/01/06 21:41:31', 'Setting time from wrong local timezone failed: {}'.format(sc.date.strftime(time_fmt)) print(" Date and time changed from wrongly localized time ok.") assert sc.solartime.strftime(time_fmt) == '2016/01/06 21:15:22', 'Calculating solar time in east failed: {}'.format(sc.solartime.strftime(time_fmt)) print(" Solar time calculated ok.") tz = sc.timezone assert str(tz) == 'Europe/Helsinki', 'Timezone location failed: {}'.format(tz) print(" Timezone located ok.")
def observer_for_city(city): try: observer = ephem.city(city) return observer except KeyError: # Add some cities pyephem doesn't know: if city == 'San Jose': # San Jose, CA at Houge Park observer = ephem.Observer() observer.name = "San Jose" observer.lon = '-121:56.8' observer.lat = '37:15.55' observer.elevation = 100 return observer elif city == 'Los Alamos': # Los Alamos, NM Nature Center observer = ephem.Observer() observer.name = "Los Alamos" observer.lon = '-106:18.36' observer.lat = '35:53.09' observer.elevation = 2100 return observer elif city == 'White Rock': # White Rock, NM Visitor Center observer = ephem.Observer() observer.name = "White Rock" observer.lon = '-106:12.75' observer.lat = '35:49.61' observer.elevation = 1960 return observer return None
def __init__(self, year, observer=ephem.city('Copenhagen'), weekly=True, on_days=range(7), outformat=None): self.sun_rise_sun_set = {} start = ephem.Date((year, 1, 1, 0)) for i in range(367): d = ephem.date(start + (24 * ephem.hour * i)) if weekly: on_days = [0] if (d.datetime().weekday() in on_days): observer.date = d sunrise = observer.next_rising(ephem.Sun()) sunset = observer.next_setting(ephem.Sun()) if d.datetime().year == year: if outformat == 'text': self.sun_rise_sun_set[d.datetime()] = 'sol %s-%s' \ % (utc2localtime(sunrise.datetime(), format='hhmm'), utc2localtime(sunset.datetime(), format='hhmm')) elif outformat == 'symbols': self.sun_rise_sun_set[d.datetime()] = '🌞 %s-%s' \ % (utc2localtime(sunrise.datetime(), format='hhmm'), utc2localtime(sunset.datetime(), format='hhmm'))
def get_sun_data(): rise_t = [None, None] set_t = [None, None] data = [None, None] import ephem, datetime moscow = ephem.city('Moscow') obs = ephem.Observer() obs.lat = moscow.lat #'55.7522222' obs.long = moscow.long #'37.6155556' sun = ephem.Sun() obs.date = datetime.date.today() rise_time = obs.next_rising(sun) set_time = obs.next_setting(sun) rise_t[0] = ephem.localtime(rise_time).ctime() set_t[0] = ephem.localtime(set_time).ctime() obs.date = datetime.date.today() + datetime.timedelta(days=1) rise_time = obs.next_rising(sun) set_time = obs.next_setting(sun) rise_t[1] = ephem.localtime(rise_time).ctime() set_t[1] = ephem.localtime(set_time).ctime() data[0] = rise_t data[1] = set_t return data
def rescheduler(): """ After an event happens, it's added to the reschedule queue so that the next time it occurs can be added to the event queue. For example, after Moon rise, this function calculates the date of the next Moon rise and puts it on the event queue. """ logger.debug("Startup") while True: logger.debug("{:4d} {:4d} get".format( reschedule_queue.qsize(), len(events))) ev = reschedule_queue.get() logger.debug("Rescheduling:{}".format(ev)) del events[ev.key] observer = ephem.city(CITY) next_method = { 'rise_time': observer.next_rising, 'transit_time': observer.next_transit, 'set_time': observer.next_setting, }[ev.event_name] body = bodies[ev.body_name] # should I make a copy? body.compute(ephem.now()) start_date = ephem.Date(ev.date + ephem.minute) date = next_method(body, start=start_date) if date is not None: altaz = getattr(body, { 'rise_time': 'rise_az', 'transit_time': 'transit_alt', 'set_time': 'set_az', }[ev.event_name]) new_ev = Event(ev.body_name, date, ev.event_name, altaz) event_queue.put(new_ev) events[new_ev.key] = new_ev logger.debug("Rescheduled: {}".format(new_ev)) reschedule_queue.task_done()
def compute_asteroid(name, data, t, precision_radec=15, precision_azalt=120): R2D = 180. / pi o = ephem.city('Atlanta') o.date = t target = ephem.EllipticalBody() target._inc = data['i'] target._Om = data['Node'] target._om = data['Peri'] target._a = data['a'] target._M = data['M'] target._epoch_M = data['Epoch'] - 2415020.0 target._e = data['e'] target._epoch = '2000' target.compute(o) # Pyephem use Dublin JD, ephemeride uses Modified JD! mjd = o.date + 15020 - 0.5 return dict( name=name, planet=0, utc=mjd, longitude=o.lon * R2D, latitude=o.lat * R2D, ra=target.ra * R2D, dec=target.dec * R2D, alt=target.alt * R2D, az=target.az * R2D, precision_radec=precision_radec, precision_azalt=precision_azalt, klass='mpc_asteroid', json=dict(model_data=data), )
def test_observer_copy(self): c = city('Boston') c.date = '2015/5/30 10:09' d = c.copy() self._check_observer(c, d) d = copy(c) self._check_observer(c, d)
def get_sun_data(): import ephem as sun import datetime sun.Observer().date = 99999999999999 sun.Observer().lat = sun.city('Moscow').lat sun.Observer().long = sun.city('Moscow').long sun.Observer().date = datetime.date.today() data[0] = sun.localtime(sun.Observer().next_rising(sun.Sun())).ctime() # data[1] = sun.localtime(sun.Observer().next_setting(sun.Sun())).ctime() # sun.Observer().date = datetime.datetime.today() + datetime.timedelta(days=1) # data[2] = sun.localtime(sun.Observer().next_rising(sun.Sun())).ctime() # data[3] = sun.localtime(sun.Observer().next_setting(sun.Sun())).ctime() return data
def determine_day_and_night(self): s = ephem.Sun() sf = ephem.city('Toronto') s.compute(sf) twilight = -12 * ephem.degree if s.alt > twilight: return 1 return 7.5 / 8
def lookup_observer(city): try: return ephem.city(city) except KeyError: try: return cities.lookup(city) except ValueError: raise RuntimeError("I don't know where %s is, sorry" % city)
def __init__(self, gui): self.gui = gui self.motor_DEC = Smartmotor('COM8', gui) self.motor_RA = Smartmotor('COM9', gui) self.motor_DEC.Acceleration(120) self.motor_RA.Acceleration(120) self.ephem = ephem.city('San Francisco') self.sky_angle = self.siderial_angle()
def test(): bodies = get_solar_system_objects() obs = epm.city("London") compute_properties(bodies, obs) data = [] for body in bodies: line = " ".join([str(n) for n in [body.name, body.alt, body.az, body.mag, body.radius, obs.date]]) #, body.rise_time, body.transit_time, body.set_time data.append(line) return data
def day_or_night_pi(): sunlight = ephem.Sun() city = ephem.city('Boston') sunlight.compute(city) twilight = -12 * ephem.degree if sunlight.alt > twilight: return "DAY_PI" else: return "NIGHT_PI"
def get_observer_from_city(city): """ Returns an ephem.Observer that corresponds to the given city name. """ try: obs = ephem.city(city) except Exception as e: raise AttributeError('City, {}, could not be found in database.'.format(city)) return obs
def sun_altitude(date): """ Return the altitude, in radians, of the Sun on a given date ant time as observed from London. """ london = ephem.city('London') london.date = date return ephem.Sun(london).alt
def get_next_pass_from_tle(tle, loc_str): loc = ephem.city(loc_str) obj = calc_obj_from_tle(tle, loc) rise_time, rise_az, max_time, max_alt, set_time, set_az = loc.next_pass( obj) rise_time = rise_time.datetime().replace(microsecond=0) max_time = max_time.datetime().replace(microsecond=0) set_time = set_time.datetime().replace(microsecond=0) return rise_time, rise_az, max_time, max_alt, set_time, set_az
def test_tles(): import termiteOS.astronomy.internetcatalogues as cat import ephem observer = ephem.city('Madrid') observer.date = ephem.Date('2018/07/06 20:00') i = cat.internetCatalogue() geo = i.geo('HISPASAT') geo.compute(observer) print(geo.ra, geo.dec)
def _day_or_night(self): # noinspection PyUnresolvedReferences sun = ephem.Sun() location = ephem.city(self._city) sun.compute() if location.next_rising(sun) < location.next_setting(sun): return 'night' else: return 'day'
def test(): obs = epm.city('London') s = epm.Saturn() s.compute(obs) print s.alt print s.az print s.mag
def sun(): location = ephem.city('Warsaw') body = ephem.Sun(location) rising, setting = get_rise_and_set_time(body, location) body.compute(location) return jsonify( rising=str(rising), setting=str(setting), altitude=(180 * body.alt / ephem.pi), )
def __init__(self, line, epoch=DEFAULT_EPOCH, epoch_utc_offset=0): """ Instantiates a CronExpression object with an optionally defined epoch. If the epoch is defined, the UTC offset can be specified one of two ways: as the sixth element in 'epoch' or supplied in epoch_utc_offset. The epoch should be defined down to the minute sorted by descending significance. """ self._special = False for key in SPECIALS: if line.startswith(key): self._special = True # build the city object self._city = ephem.city('Brussels') # store the original input self.orig_line = line # parse the input if not self._special: for key, value in SUBSTITUTIONS.items(): if line.startswith(key): line = line.replace(key, value) break fields = line.split(None, 5) if len(fields) == 5: fields.append('') minutes, hours, dom, months, dow, self.comment = fields dow = dow.replace('7', '0').replace('?', '*') dom = dom.replace('?', '*') for monthstr, monthnum in MONTH_NAMES: months = months.lower().replace(monthstr, str(monthnum)) for dowstr, downum in DAY_NAMES: dow = dow.lower().replace(dowstr, str(downum)) self.string_tab = [ minutes, hours, dom.upper(), months, dow.upper() ] self.compute_numtab() else: self.string_tab = line.split(' ')[0] self.comment = None # handle epoch if len(epoch) == 5: y, mo, d, h, m = epoch self.epoch = (y, mo, d, h, m, epoch_utc_offset) else: self.epoch = epoch
def bright_night(ephemdate, city='Copenhagen'): """Determine if the upcoming night a bright night""" cph = ephem.city(city) cph.horizon = '-18' # Astronomical twillight cph.date = ephemdate try: # Twillight defined by center of the sun cph.next_setting(ephem.Sun(), use_center=True) return False except: return True
def test_get_pyephem_instance_for_non_sidereal(self): hb = ephem.readdb( 'C/1995 O1 (Hale-Bopp),e,89.4245,282.4515,130.5641,183.6816,' '0.0003959,0.995026,0.1825,07/06.0/1998,2000,g -2.0,4.0') target_ephem = get_pyephem_instance_for_type(self.nst) location = ephem.city('Los Angeles') location.date = ephem.date(datetime.now()) hb.compute(location) target_ephem.compute(location) self.assertLess(math.fabs(target_ephem.ra - hb.ra), 0.5) self.assertLess(math.fabs(target_ephem.dec - hb.dec), 0.5)
def get_sun(country, date): """Return sunlight hours""" city = ephem.city("Amsterdam" if country == "nl" else "Lisbon" if country == "pt" else "Amsterdam" if country == "be" else "") if city == "": sys.exit("Unknown country") sun = ephem.Sun() # pylint: disable=E1101 city.date = date date_rise = city.next_rising(sun).datetime() date_set = city.next_setting(sun).datetime() print(date_rise, date_set) return (date_set - date_rise).seconds / 3600.
def get_solar_system_body_properties(): properties = ['name', 'alt', 'az', 'mag', 'radius','rise_time', 'transit_time', 'set_time'] bodies = get_solar_system_objects() obs = epm.city("London") compute_properties(bodies, obs) data = {'date':str(obs.date)} body_data_list = [] for body in bodies: body_data = {n: str(getattr(body, n)) for n in properties} body_data_list.append(body_data) data['bodies'] = body_data_list return data
def get_nit_r_day(emphem_city): #Generate observer object with location observer = ephem.city(emphem_city) #Generate sun object with observer sun = ephem.Sun(observer) #Check if sun is currently up sun_is_up = observer.previous_rising(sun) > observer.previous_setting(sun) #Return boolean value depending on time of day if sun_is_up: return True else: return False
def test_observer_copy(self): c = city('Boston') c.date = '2015/5/30 10:09' d = c.copy() assert c is not d self.assertEqual(c.date, d.date) self.assertEqual(c.lat, d.lat) self.assertEqual(c.lon, d.lon) self.assertEqual(c.elev, d.elev) self.assertEqual(c.horizon, d.horizon) self.assertEqual(c.epoch, d.epoch) self.assertEqual(c.temp, d.temp) self.assertEqual(c.pressure, d.pressure)
def __init__(self, line, epoch=DEFAULT_EPOCH, epoch_utc_offset=0): """ Instantiates a CronExpression object with an optionally defined epoch. If the epoch is defined, the UTC offset can be specified one of two ways: as the sixth element in 'epoch' or supplied in epoch_utc_offset. The epoch should be defined down to the minute sorted by descending significance. """ self._special = False for key in SPECIALS: if line.startswith(key): self._special = True # build the city object self._city = ephem.city('Brussels') # store the original input self.orig_line = line # parse the input if not self._special: for key, value in SUBSTITUTIONS.items(): if line.startswith(key): line = line.replace(key, value) break fields = line.split(None, 5) if len(fields) == 5: fields.append('') minutes, hours, dom, months, dow, self.comment = fields dow = dow.replace('7', '0').replace('?', '*') dom = dom.replace('?', '*') for monthstr, monthnum in MONTH_NAMES: months = months.lower().replace(monthstr, str(monthnum)) for dowstr, downum in DAY_NAMES: dow = dow.lower().replace(dowstr, str(downum)) self.string_tab = [minutes, hours, dom.upper(), months, dow.upper()] self.compute_numtab() else: self.string_tab = line.split(' ')[0] self.comment = None # handle epoch if len(epoch) == 5: y, mo, d, h, m = epoch self.epoch = (y, mo, d, h, m, epoch_utc_offset) else: self.epoch = epoch
def unpackFile(self, source="savedata.txt", folder=""): directory = os.getcwd() if folder == "": pass else: directory = os.path.join(directory, folder) lines = [ ] actions = [ ] if source not in os.listdir(directory): return 1 #TODO:popup saying "not available, chk filename savedata.txt" info = readFile(os.path.join(directory, source)).splitlines() date = None screenPos = None shift = None for index in xrange(len(info)): action = info[index] if action == "": continue if index == 0: #datetime date = datetime.datetime.strptime(action, "%Y %m %d %H %M") continue elif index == 1: #screenPos and shift action = action.split(".") screenPos = (int(action[0]), int(action[1])) shift = int(action[2]) city = action[3] if city == "Pittsburgh": city = self.pgh else: city = ephem.city(city) city.date = date continue action = action.split(".") typeof = action[0] line = action[1] line = line.split("|") (star1Name, star2Name) = (line[0], line[1]) (star1, star2) = (None, None) for star in self.starList: if star.name == star1Name: star1 = star elif star.name == star2Name: star2 = star star1.calculate(city, shift) star2.calculate(city, shift) newLine = Line(star1, screenPos) newLine.setEnd(star2, screenPos) lines += [ newLine ] actions += [ (typeof, lines[-1]) ] self.date = date self.screenPos = screenPos self.shift = shift self.lines = copy.copy(lines) self.actions = copy.copy(actions)
def runTest(self): boston = ephem.city("Boston") boston.pressure = 1010.0 # undo pressure auto-adjustment mars = ephem.Mars() cur_date = ephem.Date("2009/6/29 07:00:00") cur_date = boston.next_rising(mars, start=cur_date) self.assertEqual(str(cur_date), '2009/6/30 06:17:37') cur_date = boston.next_rising(mars, start=cur_date) self.assertEqual(str(cur_date), '2009/7/1 06:15:45') cur_date = boston.next_rising(mars, start=cur_date) self.assertEqual(str(cur_date), '2009/7/2 06:13:53')
def runTest(self): boston = ephem.city("Boston") boston.pressure = 1010.0 # undo pressure auto-adjustment mars = ephem.Mars() cur_date = ephem.Date("2009/6/29 07:00:00") cur_date = boston.next_rising(mars, start=cur_date) self.assertEqual(str(cur_date), '2009/6/30 06:17:36') cur_date = boston.next_rising(mars, start=cur_date) self.assertEqual(str(cur_date), '2009/7/1 06:15:44') cur_date = boston.next_rising(mars, start=cur_date) self.assertEqual(str(cur_date), '2009/7/2 06:13:53')
def keyPressed(self, keyCode, modifier): if self.mode == "options" and self.selectedButton != None: val = None if keyCode == pygame.K_UP: val = self.selectedButton.up() elif keyCode == pygame.K_DOWN: val = self.selectedButton.down() if val != None: if val == "Pittsburgh": self.city = self.pgh self.cityName = val else: self.city = ephem.city(val) self.cityName = val
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)
def __get_lightness(self, date = datetime.date.today()): """""" hki = ephem.city('Helsinki') hki.date = date sun = ephem.Sun() nsr = ephem.localtime(hki.next_rising(sun)) nss = ephem.localtime(hki.next_setting(sun)) dt = nss - nsr seconds = float(dt.seconds) part_of_day = seconds / (24*60*60) lightness = (part_of_day * 100) + np.random.normal(0, 40) lightness = 20 if lightness < 20 else lightness lightness = 100 if lightness > 100 else lightness return lightness
def planetary_body(body, update_rate): logger.debug("Startup") observer = ephem.city(CITY) body.compute(observer) for fieldname, azalt in zip(FIELDS, AZALT): date = getattr(body, fieldname) azalt = getattr(body, azalt) if date is not None: ev = Event(body.name, date, fieldname, azalt) event_queue.put(ev) while True: observer.date = ephem.now() body.compute(observer) position_queue.put("{0.name} {0.alt} {0.az}".format(body)) time.sleep(update_rate)
def __init__(self, paper=landscape(A3), magLim=3.5, projection="merc", output='output/proj_output_example.pdf', costellation_list='', altaz=0, city='Madrid', date=ephem.now()): self.paper = paper self.altaz = altaz self.observer = ephem.city(city) self.observer.date = date self.s = solarsystem.SolarSystem(self.observer) self.magLim = magLim self.projection = projection self.paperwidth, self.paperheight = self.paper self.c = canvas.Canvas(output, pagesize=self.paper) from reportlab.lib.colors import Color self.c.setFillColor(Color(0., 0., 0., alpha=1)) # self.c.rect(0,0,self.paperwidth,self.paperheight,fill=1,stroke=0) if altaz != 0: ra, dec = self.observer.radec_of(0, '90') ra = ra * 180 / pi dec = dec * 180 / pi zenit = " +lon_0=" + str(ra) + " +lat_0=" + str(dec) print zenit self.prj = pyproj.Proj("+proj=" + self.projection + zenit) else: self.prj = pyproj.Proj("+proj=" + self.projection) self.prj_ra_dec = pyproj.Proj("+proj=lonlat +ellps=sphere") self.xfactor = 5.8 self.yfactor = self.xfactor * self.paperheight / self.paperwidth self.scale = 1 (self.lonmin, self.latmin), ( self.lonmax, self.latmax) = self.getCostellationsLimits(costellation_list) print(self.lonmin, self.latmin), (self.lonmax, self.latmax) x0, y0 = self.p(self.lonmin, self.latmin) x1, y1 = self.p(self.lonmax, self.latmax) self.scale = max((x1 - x0) / self.paperwidth, (y1 - y0) / self.paperheight) print x0, y0, self.scale
def __init__(self, year, observer=ephem.city('Copenhagen'), weekly=True, on_days=range(7)): self.sun_rise_sun_set = {} start = ephem.Date((year, 1, 1, 0)) for i in range(367): d = ephem.date(start + (24*ephem.hour*i)) if weekly: on_days = [0] if (d.datetime().weekday() in on_days): observer.date = d sunrise = observer.next_rising(ephem.Sun()) sunset = observer.next_setting(ephem.Sun()) if d.datetime().year == year: self.sun_rise_sun_set[d.datetime()] = 'sol %s-%s' \ % (utc2localtime(sunrise.datetime(), format='hhmm'), utc2localtime(sunset.datetime(), format='hhmm'))
def main(): '''Exemple d'utilisation de la fonction d'affichage d'un astre phase vue depuis la Terre''' w,h = pylab.figaspect(1.) fig = pylab.figure(figsize = (int(2. * w), int(2. * h))) ax = fig.add_subplot(111, axisbg = '0.1') # 0.1 c'est gris fonce pylab.xlabel('alt') pylab.ylabel('az') astre = ephem.Moon() obs = ephem.city('Paris') obs.date = '2013/3/16 21:000:00' astre.compute(obs) pylab.title('Moon Phase ('+str(astre.phase)+') - '+str(obs.date)) # ra_dec = False : Apparent topocentric position represented by the properties : ra and dec, and alt and az. object_phase (ax, obs, False, astre, astre.alt * 180. / math.pi, astre.az * 180. / math.pi, astre.size / 1000., '0.2', '0.85') pylab.autoscale() pylab.show()
def in_time_of_day(city, pass_time, time_of_day): '''Returns sunset and sunrise times for the given city at date''' location = ephem.city(city) location.date = pass_time sun = ephem.Sun() if time_of_day == "day": previous_rising = location.previous_rising(sun).datetime() next_setting = location.next_setting(sun, start=pass_time.date()).datetime() return previous_rising.date() == pass_time.date() and pass_time <= next_setting elif time_of_day == "night": previous_rising = location.previous_rising(sun).datetime() previous_setting = location.previous_setting(sun).datetime() next_rising = location.next_rising(sun).datetime() return (previous_setting.date() == pass_time.date() and pass_time <= next_rising) or (next_rising.date() == pass_time.date() and pass_time <= next_rising) else: return True
def test_get_visibility_sidereal(self, mock_observer_for_site, mock_get_rise_set, mock_facility): mock_facility.return_value = {'Fake Facility': FakeFacility} mock_get_rise_set.return_value = [] mock_observer_for_site.return_value = ephem.city('Los Angeles') start = self.time end = start + timedelta(minutes=60) expected_airmass = [ 3.6074370614681017, 3.997263815883785, 4.498087520663738, 5.162731916462906, 6.083298253498044, 7.4363610371608475, 9.607152214891583 ] airmass_data = get_visibility(self.st, start, end, 10, 10)['(Fake Facility) Los Angeles'][1] self.assertEqual(len(airmass_data), len(expected_airmass)) for i in range(0, len(expected_airmass)): self.assertEqual(airmass_data[i], expected_airmass[i])
def test_get_visibility_non_sidereal(self, mock_observer_for_site, mock_get_rise_set, mock_facility): mock_facility.return_value = {'Fake Facility': FakeFacility} mock_get_rise_set.return_value = [] mock_observer_for_site.return_value = ephem.city('Los Angeles') start = datetime(1997, 4, 1, 0, 0, 0) end = start + timedelta(minutes=60) expected_airmass = [ 1.225532769770131, 1.2536644126634366, 1.2843810879053679, 1.3179084796712417, 1.3545030240774714, 1.3944575296459614, 1.4381124914948578 ] airmass_data = get_visibility(self.nst, start, end, 10, 10)['(Fake Facility) Los Angeles'][1] self.assertEqual(len(airmass_data), len(expected_airmass)) for i in range(0, len(expected_airmass)): self.assertLess(math.fabs(airmass_data[i] - expected_airmass[i]), 0.05)
def nextTenEvents(trackedObjs, Location): """ Returns a lists of lists, first list is the next ten events for use by the rest of the program TODO: Searching for passes should not be arbitrary number""" atl = ephem.city(Location) # Antenna Location currentTime = ephem.now() # UTC time object atl.date = currentTime minimumElevation = 50 # 50 Degrees minimum elevation for pass satPass = [] tabsat = [] for i in xrange(0, len(trackedObjs)): # Run through all currently tracked objects atl.date = currentTime for j in xrange(0, 100): # Check individual object's next 60 passes(arbitrary) TODO fix to be smarter if float(atl.next_pass(trackedObjs[i])[3]) * 180 / 3.14159 > minimumElevation: # Create individuals pass list [name,start of pass time object, end of pass time object, elevation deg, tracked object reference] satPass.append( [ trackedObjs[i].name, atl.next_pass(trackedObjs[i])[0], atl.next_pass(trackedObjs[i])[4], float(atl.next_pass(trackedObjs[i])[3]) * 180 / 3.14159, "TRACK", trackedObjs[i], ] ) # Create pass list for printing to terminal with tabulate [float start time, name, string start time, str end time, elevation deg] # tabsat.append([float(atl.next_pass(trackedObjs[i])[0]), trackedObjs[i].name,str(atl.next_pass(trackedObjs[i])[0]),str(atl.next_pass(trackedObjs[i])[4]),float(atl.next_pass(trackedObjs[i])[3])*180/3.14159]) atl.date = atl.next_pass(trackedObjs[i])[4] + 0.00000001 satPass = sorted(satPass, key=lambda pa: pa[1]) # Sort passes by start pass time satPass = satPass[0:10] # save only the top ten passes # tabsat = sorted(tabsat, key=lambda pa: pa[0])# Sort passes by start pass time # for x in tabsat: #delete the float start pass time in tabsat, was only needed for sorting purpose, not really human readable # del x[0] # tabsat = tabsat[0:30] # save only the top ten passes # atl.date = currentTime return satPass
def main(): year = ephem.now().triple()[0] start_date = ephem.Date(str(year)) end_date = ephem.Date('{}/12/31'.format(year)) print(year, start_date, end_date) rs = [] for body in (ephem.Sun(), ephem.Moon()): for info in generate_rise_set(body, ephem.city(CITY), start_date, end_date): rs.append(info) print(len(rs)) print("Sun and Moon setting azimuths") for i in sorted(rs, key=operator.attrgetter('set_az')): print("{0.name:6} {0.set_az} {0.set_time}".format(i)) print("Sun and Moon rising azimuths") for i in sorted(rs, key=operator.attrgetter('rise_az')): print("{0.name:6} {0.rise_az} {0.rise_time}".format(i))
def sun_rise_set(city, year): ''' Calculate sun rise and set for whole year ''' sea = ephem.city(city) sea.date = ephem.Date("{}/01/01 12:00:00".format(year)) sun = ephem.Sun() earlest_dec = 12.0 latest_dec = 12.0 longest_len = 8.0 for day in range(1, days_year + 1): sunrise = sea.next_rising(sun) sunset = sea.next_setting(sun) sol = ephem.localtime(sunrise) set = ephem.localtime(sunset) rise_dec = float(sol.hour) + (float(sol.minute) / 60.0) + (float(sol.second) / 60.0 / 60.0) set_dec = float(set.hour) + (float(set.minute) / 60.0) + (float(set.second) / 60.0 / 60.0) if rise_dec < earlest_dec: earlest_dec = rise_dec earlest_sol = sol if set_dec > latest_dec: latest_dec = set_dec latest_sunset = set day_length = set_dec - rise_dec if day_length > longest_len: longest_len = day_length longest_day = sol longest_set = set if day in SolEqn: label = 'SolEqn' # This day is an Soltice or Equinox else: label = 'Sol' print("{:d} {:6.4f} {:7.4f} {} %% Sun Rise/Set: {} {} PST".format( day, rise_dec, set_dec, label, sol.strftime("%b-%d %H:%M:%S"), set.strftime("%H:%M:%S"))) sea.date += 1 sys.stderr.write("Ealest Sun Rise: {}\n".format( earlest_sol.strftime("%b-%d %H:%M:%S"))) sys.stderr.write("Longest Day {} {}\n".format( longest_day.strftime("%b-%d %H:%M:%S"), longest_set.strftime(" %H:%M:%S"))) sys.stderr.write("Latest Sun Set : {}\n".format( latest_sunset.strftime("%b-%d %H:%M:%S")))
def getMoonPosition(date, ipp_alt=300): """ Sebasitjan Mrak """ moon = ephem.Moon() obs = ephem.Observer() obs.date = date boston = ephem.city('Boston') obs.lat = boston.lat obs.long = boston.long obs.elev = boston.elev moon.compute(obs) r = ipp_alt / np.sin(moon.alt) lla_vector = np.array(aer2geodetic(np.rad2deg(moon.az), np.rad2deg(moon.alt), r, np.rad2deg(obs.lat), np.rad2deg(obs.lon), np.rad2deg(obs.elev))) return lla_vector
def process_location(location): if not isinstance(location, ephem.Observer): if isinstance(location, list) and len(location) == 2: # interpret as a latlong pair passed in ll = location location = ephem.Observer() location.lat = str(ll[0]) location.lon = str(ll[1]) else: try: location = ephem.city(unicode(location)) except: try: location = get_location_from_wikipedia(unicode(location)) except: location = False return location
def test_properties_computed(): start_time = datetime(2012,1,1) times = planner.hour_sequence(start_time) observer = ephem.city('London') body = ephem.Sun() body.compute = mock.MagicMock(name='compute') builder = mock.MagicMock(name='builder') builder.return_value = {} plan = planner.create_plan_day(observer, [body], times, builder) expected_compute_calls = [mock.call(observer)]*24 compute_calls = body.compute.mock_calls expected_build_calls = [mock.call(body)]*24 build_calls = builder.mock_calls eq_(len(plan), 24)
def sun_times(self): import datetime home = ephem.Observer() sun = ephem.Sun() #@UndefinedVariable SEC30 = timedelta(seconds=30) home = ephem.city(self.config['city']) sun.compute(home) midnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=self.utczone) nextrise = (home.next_rising(sun, start=midnight) .datetime().replace(tzinfo=self.utczone).astimezone(self.timezone)) nextset = (home.next_setting(sun, start=midnight) .datetime().replace(tzinfo=self.utczone).astimezone(self.timezone)) return nextrise,nextset
def alert_next_passes(self, acc_cloud_cover, timeofday, device_id, count=10, city=None, coord=(0.0, 0.0)): '''Sets up alerts for up to the next 10 passes of the ISS over the given city or lat/lon. Alerts will be sent to the device that registered for them''' try: # Cancel previous timers. for t in TIMERS[city]: t.cancel() except KeyError: pass finally: TIMERS[city] = [] location = ephem.city(city) url = API_URLS['iss'].format(degrees(location.lat), degrees(location.lon), int(location.elevation), count) #print url #r = requests.get(url) #result = json.loads(r.text) result = self.get_next_visible_passes(degrees(location.lat), degrees(location.lon), int(location.elevation), count) next_passes = result['response'] # For every pass, set up a trigger for 10 minutes earlier and send it # to the 'space' channel real_response = [] for p in next_passes: risetime = datetime.utcfromtimestamp(p['risetime']) weather_data = WeatherData(city) # Skip if the pass is at the wrong time of day if not in_time_of_day(city, risetime, timeofday): continue riseminus10 = risetime - timedelta(minutes=10) delay = (riseminus10 - datetime.utcnow()).total_seconds() print "Running in {0} seconds...".format(delay) def f(): weather_data = WeatherData(city) cloud_cover = weather_data.current_cloud_cover() if cloud_cover <= acc_cloud_cover: print "Cloud cover acceptable" self.acs.push_to_ids_at_channel('space', [device_id], json.dumps({'location': city, 'cloudcover': cloud_cover})) t = threading.Timer(delay, f) TIMERS[city].append(t) t.start() cloud_forecast = weather_data.cloud_forecast(datetime.utcfromtimestamp(p['risetime'])) real_response.append({'location': city, 'time_str': str(risetime), 'time': p['risetime'], 'cloudcover': cloud_forecast, 'trigger_time': str(riseminus10)}) #print real_response print "Length:", len(real_response) return real_response
def __init__(self,paper=landscape(A3),magLim=3.5,projection="merc",output='output/proj_output_example.pdf', costellation_list='', altaz=0, city='Madrid', date=ephem.now()): self.paper=paper self.altaz=altaz self.observer=ephem.city(city) self.observer.date=date self.s=solarsystem.SolarSystem(self.observer) self.magLim=magLim self.projection=projection self.paperwidth, self.paperheight = self.paper self.c = canvas.Canvas(output, pagesize=self.paper) from reportlab.lib.colors import Color self.c.setFillColor(Color( 0.,0., 0., alpha=1)) # self.c.rect(0,0,self.paperwidth,self.paperheight,fill=1,stroke=0) if altaz!=0: ra,dec=self.observer.radec_of(0,'90') ra=ra*180/pi dec=dec*180/pi zenit=" +lon_0="+str(ra)+" +lat_0="+str(dec) print zenit self.prj=pyproj.Proj("+proj="+self.projection+zenit) else: self.prj=pyproj.Proj("+proj="+self.projection) self.prj_ra_dec=pyproj.Proj("+proj=lonlat +ellps=sphere") self.xfactor=5.8 self.yfactor=self.xfactor*self.paperheight/self.paperwidth self.scale=1 (self.lonmin,self.latmin),(self.lonmax,self.latmax)=self.getCostellationsLimits(costellation_list) print (self.lonmin,self.latmin),(self.lonmax,self.latmax) x0,y0=self.p(self.lonmin,self.latmin) x1,y1=self.p(self.lonmax,self.latmax) self.scale=max((x1-x0)/self.paperwidth,(y1-y0)/self.paperheight) print x0,y0,self.scale
def parse_file(self, filename): f = open(filename) l = f.readline() while not (l == ''): if l[0] == '#': pass else: l = l.rstrip() try: self.observatories.append(ephem.city(l)) except KeyError, ke: obs = ephem.Observer() le = l.split() if len(le) == 4: obs.name = le[0] obs.long = le[1] obs.lat = le[2] obs.elevation = float(le[3]) self.observatories.append(obs) l = f.readline()
def get_sun_data(): rise_t = [None, None] set_t = [None, None] data = [None, None] import ephem, datetime moscow = ephem.city('Moscow') obs = ephem.Observer() obs.lat = moscow.lat #'55.7522222' obs.long = moscow.long #'37.6155556' sun = ephem.Sun() obs.date = datetime.date.today() rise_time = obs.next_rising(sun) set_time = obs.next_setting(sun) rise_t[0] = ephem.localtime(rise_time).ctime() set_t[0] = ephem.localtime(set_time).ctime() obs.date = datetime.date.today() + datetime.timedelta(days=1) rise_time = obs.next_rising(sun) set_time = obs.next_setting(sun) rise_t[1] = ephem.localtime(rise_time).ctime() set_t[1] = ephem.localtime(set_time).ctime() now = datetime.datetime.today() for i in range(0, 2): if now < datetime.datetime.strptime(rise_t[i], '%a %b %d %H:%M:%S %Y'): data[0] = rise_t[i] break for i in range(0, 2): if now < datetime.datetime.strptime(set_t[i], '%a %b %d %H:%M:%S %Y'): data[1] = set_t[i] break return data
def __init__(self, observer=None, theta_poi=None, phi_poi=None, turbidity=-1, gradation=-1, indicatrix=-1, sky_type=-1, nside=NSIDE): self.__sun = ephem.Sun() self.__obs = observer if observer is None: self.__obs = ephem.city("Edinburgh") self.__obs.date = datetime(2017, 6, 21, 10, 0, 0) self.sun.compute(self.obs) self.lon, self.lat = sun2lonlat(self.__sun) # atmospheric condition if 1 <= sky_type <= 15: gradation = get_sky_gradation(sky_type) indicatrix = get_sky_indicatrix(sky_type) if gradation < 0 and indicatrix < 0 and turbidity < 0: turbidity = self.turbidity_default if turbidity >= 1: # initialise atmospheric coefficients wrt turbidity # A: Darkening or brightening of the horizon # B: Luminance gradient near the horizon # C: Relative intensity of the circumsolar region # D: Width of the circumsolar region # E: relative backscattered light params = self.luminance_coefficients(turbidity) self.A, self.B, self.C, self.D, self.E = params self.gradation = get_sky_gradation(params) self.indicatrix = get_sky_indicatrix(params) else: self.gradation = gradation if 1 <= gradation <= 6 else self.gradation_default # default self.indicatrix = indicatrix if 1 <= indicatrix <= 6 else self.indicatrix_default # default # set A and B parameters for gradation luminance self.A = STANDARD_PARAMETERS["gradation"][self.gradation]["a"] self.B = STANDARD_PARAMETERS["gradation"][self.gradation]["b"] # set C, D and E parameters for scattering indicatrix self.C = STANDARD_PARAMETERS["indicatrix"][self.indicatrix]["c"] self.D = STANDARD_PARAMETERS["indicatrix"][self.indicatrix]["d"] self.E = STANDARD_PARAMETERS["indicatrix"][self.indicatrix]["e"] sky_type = get_sky_type(self.gradation, self.indicatrix) self.turbidity = self.turbidity_from_coefficients( self.A, self.B, self.C, self.D, self.E) self.description = get_sky_description(sky_type) if sky_type > 0 else [ "" ] if theta_poi is None or phi_poi is None: # calculate the pixel indices i = np.arange(hp.nside2npix(nside)) # get the longitude and co-latitude with respect to the zenith self.__theta_z, self.__phi_z = hp.pix2ang( nside, i) # return longitude and co-latitude in radians else: self.__theta_z = theta_poi self.__phi_z = phi_poi # we initialise the sun at the zenith # so the angular distance between the sun and every point is equal to their distance from the zenith self.theta_s, self.phi_s = self.theta_z.copy(), self.phi_z.copy() self.mask = None self.nside = nside self.is_generated = False
import ephem import datetime tokyo = ephem.city('Tokyo') tokyo.date = datetime.datetime.utcnow() sun = ephem.Sun() print("次の東京の日の出時刻: ", ephem.localtime(tokyo.next_rising(sun))) print("次の東京の日の入り時刻: ", ephem.localtime(tokyo.next_setting(sun)))
def setUp(self): self.iss = ephem.readtle(*tle_lines) self.atlanta = ephem.city('Atlanta')