def moon_position(DJD): nb = len(DJD) ra_arr = []; dec_arr = [] for i in range(nb): time = ephem.Date(DJD[i]) moon = ephem.Moon(time) ra_arr.append(float(repr(moon.ra))) dec_arr.append(float(repr(moon.dec))) return np.array(ra_arr), np.array(dec_arr)
def moonPhase(astroData, Config, *largs): """ Calculate the moon phase for the current time in station timezone INPUTS: astroData Dictionary holding moonrise and moonset data Config Station configuration OUTPUT: astroData Dictionary holding moonrise and moonset data """ # Get current time in UTC Tz = pytz.timezone(Config['Station']['Timezone']) UTC = datetime.now(pytz.utc) # Get date of next full moon in station time zone FullMoon = astroData['FullMoon'][1].astimezone(Tz) # Get date of next new moon in station time zone NewMoon = astroData['NewMoon'][1].astimezone(Tz) # Calculate phase of moon Moon = ephem.Moon() Moon.compute(UTC.strftime('%Y/%m/%d %H:%M:%S')) # Define Moon phase icon if FullMoon < NewMoon: PhaseIcon = 'Waxing_' + '{:.0f}'.format(Moon.phase) elif NewMoon < FullMoon: PhaseIcon = 'Waning_' + '{:.0f}'.format(Moon.phase) # Define Moon phase text if astroData['NewMoon'] == '[color=ff8837ff]Today[/color]': PhaseTxt = 'New Moon' elif astroData['FullMoon'] == '[color=ff8837ff]Today[/color]': PhaseTxt = 'Full Moon' elif FullMoon < NewMoon and Moon.phase < 49: PhaseTxt = 'Waxing crescent' elif FullMoon < NewMoon and 49 <= Moon.phase <= 51: PhaseTxt = 'First Quarter' elif FullMoon < NewMoon and Moon.phase > 51: PhaseTxt = 'Waxing gibbous' elif NewMoon < FullMoon and Moon.phase > 51: PhaseTxt = 'Waning gibbous' elif NewMoon < FullMoon and 49 <= Moon.phase <= 51: PhaseTxt = 'Last Quarter' elif NewMoon < FullMoon and Moon.phase < 49: PhaseTxt = 'Waning crescent' # Define Moon phase illumination Illumination = '{:.0f}'.format(Moon.phase) # Define Kivy Label binds astroData['Phase'] = [PhaseIcon, PhaseTxt, Illumination] # Return dictionary containing moon phase data return astroData
def get_next_fullmoon_dusk(self): """ Return the date and time of the dusk of the next fullmoon @return : the next dusk daytime """ self.mycity.date = self._get_next_fullmoon() dusk = ephem.localtime(self.mycity.next_setting(ephem.Moon(), \ use_center = True)) return dusk
def _getMoonPos(observer, pole=True): moon = ephem.Moon(observer) if pole: return np.asarray([ moon.az + np.deg2rad(float(observer.lon)), moon.alt, moon.moon_phase ]) else: return np.asarray([moon.az, moon.alt, moon.moon_phase])
def main(): """Go Main Go""" m = ephem.Moon() out = open('/tmp/wxc_moon.txt', 'w') out.write("""Weather Central 001d0300 Surface Data 8 4 Station 30 Location 6 Lat 8 Lon 8 MOON_RISE 8 MOON_SET 30 MOON_PHASE 2 BOGUS """) for station in nt.sts: ia = ephem.Observer() ia.lat = str(nt.sts[station]['lat']) ia.long = str(nt.sts[station]['lon']) ia.date = '%s 00:00' % ( datetime.datetime.utcnow().strftime("%Y/%m/%d"), ) r1 = mydate(ia.next_rising(m)) s1 = mydate(ia.next_setting(m)) p1 = m.moon_phase ia.date = '%s 00:00' % ( (datetime.datetime.utcnow() - datetime.timedelta(days=1)).strftime("%Y/%m/%d"), ) r2 = mydate(ia.next_rising(m)) s2 = mydate(ia.next_setting(m)) p2 = m.moon_phase mp = figurePhase(p1, p2) find_d = datetime.datetime.now().strftime("%Y%m%d") my_rise = r2 if r1.strftime("%Y%m%d") == find_d: my_rise = r1 my_set = s2 if s1.strftime("%Y%m%d") == find_d: my_set = s1 out.write(("K%s %-30.30s %6.3f %8.3f %8s %8s %30s AA\n") % (station, nt.sts[station]['name'], nt.sts[station]['lat'], nt.sts[station]['lon'], my_rise.strftime("%-I:%M %P"), my_set.strftime("%-I:%M %P"), mp)) out.close() pqstr = "data c 000000000000 wxc/wxc_moon.txt bogus text" cmd = "/home/ldm/bin/pqinsert -p '%s' /tmp/wxc_moon.txt" % (pqstr, ) subprocess.call(cmd, shell=True) os.remove("/tmp/wxc_moon.txt")
def getAzEl(self, d, name, ra=-99.0, dec=-99): if (name == None and ra == -99 and dec == -99): return None self.observer.date = d obj = None if (name != None): if (name.lower() == "sun"): obj = ephem.Sun() elif (name.lower() == "moon"): obj = ephem.Moon() elif (name.lower() == "casa"): obj = ephem.FixedBody() obj._ra = 23.391 * math.pi / 180.0 * 15.0 obj._dec = 58.808 * math.pi / 180.0 elif (name.lower() == "cyga"): obj = ephem.FixedBody() obj._ra = 19.991 * math.pi / 180.0 * 15.0 obj._dec = 40.734 * math.pi / 180.0 elif (name.lower() == "taua"): obj = ephem.FixedBody() obj._ra = 5.575 * math.pi / 180.0 * 15.0 obj._dec = 22.016 * math.pi / 180.0 elif (name.lower() == "vira"): obj = ephem.FixedBody() obj._ra = 12.514 * math.pi / 180.0 * 15.0 obj._dec = 12.391 * math.pi / 180.0 elif (name.lower() == "goes-16"): obj = ephem.FixedBody() ra, dec = self.observer.radec_of(121.998 * math.pi / 180.0, 23.598 * math.pi / 180.0) obj._ra = ra obj._dec = dec elif (name.lower() == "radec"): obj = ephem.FixedBody() obj._ra = ra * math.pi / 180.0 * 15.0 obj._dec = dec * math.pi / 180.0 name = "%f,%f" % (ra, dec) else: obj = ephem.FixedBody() obj._ra = ra * math.pi / 180.0 * 15.0 obj._dec = dec * math.pi / 180.0 name = "%f,%f" % (ra, dec) obj.compute(self.observer) return { 'name': name, 'az': obj.az * 180.0 / math.pi, 'el': obj.alt * 180.0 / math.pi, 'ra': obj.ra / ephem.degree / 15.0, 'dec': obj.dec / ephem.degree } return None
def getmoonstate(d, lat): # populate the moon state (visible or not) for the specified date & latitude # note: the first parameter 'd' is already an ephem date 30 seconds before midnight # note: getmoonstate is called when there is neither a moonrise nor a moonset on 'd' i = 1 + config.lat.index(lat) # index 0 is reserved to enable an explicit setting latitude = ephem.degrees('{}:00:00.0'.format(lat)) obs = ephem.Observer() #d = ephem.date(date) - 30 * ephem.second obs.pressure = 0 obs.horizon = '-0:34' m = ephem.Moon(obs) err = False obs.date = d obs.lat = latitude m.compute(d) nextrising = d + 100.0 # in case moonset but no next moonrise nextsetting = d + 100.0 # in case moonrise but no next moonset try: nextrising = obs.next_rising(m) except ephem.NeverUpError: err = True #print("nr NeverUp") moonvisible[i] = False except ephem.AlwaysUpError: err = True #print("nr AlwaysUp") moonvisible[i] = True except Exception: flag_msg("Oops! moon nextR {}: {} occured, line: {}".format(i,sys.exc_info()[1],sys.exc_info()[2].tb_lineno)) #sys.exc_clear() # only in Python 2 obs.date = d if not(err): # note - 'nextrising' above *should* fail try: nextsetting = obs.next_setting(m) except ephem.NeverUpError: err = True #print("ns NeverUp") moonvisible[i] = False except ephem.AlwaysUpError: err = True #print("ns AlwaysUp") moonvisible[i] = True except Exception: flag_msg("Oops! moon nextS {}: {} occured, line: {}".format(i,sys.exc_info()[1],sys.exc_info()[2].tb_lineno)) #sys.exc_clear() # only in Python 2 if not(err): # note - "err == True" *is* expected... # however if we found both, which occured first? moonvisible[i] = False if nextrising > nextsetting: moonvisible[i] = True #print("{}".format(i), nextrising, nextsetting, moonvisible[i]) return
def find_planet(bot, update): d = datetime.datetime.now().strftime('%Y/%m/%d') planet = update.message.text.split()[1] update.message.reply_text(planet) if planet == 'Moon': moon = ephem.Moon(d) update.message.reply_text(ephem.constellation(moon)) if planet == 'Mars': mars = ephem.Mars(d) update.message.reply_text(ephem.constellation(mars))
def moon_radec(year=2017, month=1, day=1, epoch=2000): """ Returns the apparent geocentric Right Ascension and Declination of the Moon for the given year, month and day """ m = ephem.Moon() datestr = str(year) + '/' + str(month) + '/' + str(day) m.compute(datestr, epoch=str(epoch)) return str(m.g_ra), str(m.g_dec)
def comp_moon_dist(self, ob, t): """compute moon distance to an object at t time ob = line coord. object t = time to compute""" obj = ep.readdb(ob) self.oadm.date = t obj.compute(self.oadm) moon = ep.Moon(self.oadm) moon_dist = ep.separation(moon, obj) return moon_dist
def m_psetting(self): try: moon = ephem.Moon() self.observat() sett = self.__observatory__.previous_setting(moon).datetime() self.etc.log("Previous moonrise in the {} will be @ '{}'".format( self.obs_name(), sett)) return (sett) except Exception as e: self.etc.log(e)
def Dmoon(observer): """ The moon's apparante diameter changes by ~10% during over a year, and an x% error in Dmoon leads to systemtic error in Thot scaling as 2*x/lambda! @param observer: either an ephem.Observer or a suitable date (then at earth's centre). @return [rad] diameter of the moon, from the earth on the specified date (ephem.Observer)""" observer = observer if isinstance(observer, ephem.Observer) else ephem.Date(observer) moon = ephem.Moon(observer) D = moon.size / 3600. # deg return D * np.pi / 180. # rad
def getmoonpos(): offset = request.args.get("offset") if offset == None: offset = 0 moon = ephem.Moon(datetime.datetime.utcnow() + datetime.timedelta(hours=float(offset))) moon_ra = str(moon.ra) moon_dec = str(moon.dec) moon_ra = process_ra([moon_ra]) moon_dec = process_dec([moon_dec]) return str(moon_ra[0]) + "," + str(moon_dec[0])
def moon_rise_pre(self): """ @brief: This function calculates the last rising time of the Moon. """ moon = ephem.Moon() moon.compute(self.song_site) rise_moon = self.song_site.previous_rising(moon) return rise_moon
def moon_dec(self, timestamp=""): """ @brief: This function calculates the azimuth of the Moon. """ if timestamp != "": song_site.date = time_stamp ########################## NEED TO FIGURE THIS ONE OUT!!!! moon = ephem.Moon() moon.compute(self.song_site) return moon.dec
def get_events(date=datetime.now().strftime('%Y-%m-%d'), lat='0', lon='0'): """Calculates all astronomical events on a given day at a given location. The returned events containin information about: - the Sun; - the Moon; - visible planets for the night; - any oppositions, conjunctions and elongations; - any current meteor showers; and - if the given day is a solstice or equinox. Keyword arguments: date -- a YYYY-MM-DD string. lat -- a floating-point latitude string. (positive/negative = North/South) lon -- a floating-point longitude string. (positive/negative = East/West) """ # Determine the hemisphere based on the latitude. if float(lat) > 0: hemisphere = 'north' else: hemisphere = 'south' # Create a location and all body objects. location = helpers.define_location(date, lat, lon) # Create all of the PyEphem objects that will be used. sun = ephem.Sun(location) moon = ephem.Moon(location) mercury = ephem.Mercury(location) venus = ephem.Venus(location) mars = ephem.Mars(location) jupiter = ephem.Jupiter(location) saturn = ephem.Saturn(location) uranus = ephem.Uranus(location) neptune = ephem.Neptune(location) pluto = ephem.Pluto(location) # Create lists for referencing in later loops. planets = [mercury, venus, mars, jupiter, saturn, uranus, neptune, pluto] bodies = [moon] + planets # Define a list to store all events that occur on the given day. events = { 'sun': get_sun_data(sun, date, lat, lon), 'moon': get_moon_data(moon, date, lat, lon), 'planets': get_planet_data(planets, date, lat, lon), 'events': [] } events['events'] += get_planetary_events(planets, date, lat, lon) events['events'] += get_separation_events(bodies, date) events['events'] += get_celestial_events(date) return events
def get_moon_segments(config_struct, segmentlist, observer, fxdbdy, radec): if "moon_constraint" in config_struct: moon_constraint = float(config_struct["moon_constraint"]) else: moon_constraint = 20.0 moonsegmentlist = segments.segmentlist() dt = 1.0 / 24.0 tt = np.arange(segmentlist[0][0], segmentlist[-1][1] + dt, dt) ra2 = radec.ra.radian d2 = radec.dec.radian # Where is the moon? moon = ephem.Moon() for ii in range(len(tt) - 1): observer.date = ephem.Date(Time(tt[ii], format='mjd', scale='utc').iso) moon.compute(observer) fxdbdy.compute(observer) alt_target = float(repr(fxdbdy.alt)) * (360 / (2 * np.pi)) az_target = float(repr(fxdbdy.az)) * (360 / (2 * np.pi)) #print("Altitude / Azimuth of target: %.5f / %.5f"%(alt_target,az_target)) alt_moon = float(repr(moon.alt)) * (360 / (2 * np.pi)) az_moon = float(repr(moon.az)) * (360 / (2 * np.pi)) #print("Altitude / Azimuth of moon: %.5f / %.5f"%(alt_moon,az_moon)) ra_moon = (180 / np.pi) * float(repr(moon.ra)) dec_moon = (180 / np.pi) * float(repr(moon.dec)) # Coverting both target and moon ra and dec to radians ra1 = float(repr(moon.ra)) d1 = float(repr(moon.dec)) # Calculate angle between target and moon cosA = np.sin(d1) * np.sin(d2) + np.cos(d1) * np.cos(d2) * np.cos(ra1 - ra2) angle = np.arccos(cosA) * (360 / (2 * np.pi)) #print("Angle between moon and target: %.5f"%(angle)) #if angle >= 50.0*moon.moon_phase**2: if angle >= moon_constraint: segment = segments.segment(tt[ii], tt[ii + 1]) moonsegmentlist = moonsegmentlist + segments.segmentlist([segment]) moonsegmentlist.coalesce() moonsegmentlistdic = segments.segmentlistdict() moonsegmentlistdic["observations"] = segmentlist moonsegmentlistdic["moon"] = moonsegmentlist moonsegmentlist = moonsegmentlistdic.intersection(["observations", "moon"]) moonsegmentlist.coalesce() return moonsegmentlist
def run(self): self.refresh_data() obs = self.ObserverFactory.create_observer(longitude=self.longitude, latitude=self.latitude, elevation=self.elevation) self.controller = True self.shootOn = False c = 0 try: while self.controller: obs.date = ephem.date(datetime.datetime.utcnow()) sun = ephem.Sun(obs) moon = ephem.Moon(obs) frac = moon.moon_phase a = ephem.degrees(sun.alt) b = ephem.degrees(str(moon.alt)) # Variavel de controle do shooter t = 0 if float(math.degrees(a)) < self.max_solar_elevation or t == 1: if (not self.ignore_lunar_position and float(math.degrees(b)) < self.max_lunar_elevation and frac < self.max_lunar_phase ) or self.ignore_lunar_position: if not self.shootOn: if not c: self.signal_started_shooting.emit() c = 1 self.signal_temp.emit() time.sleep(5) if self.wait_temperature: # Iniciar as Observações self.start_taking_photo() self.shootOn = True else: if self.shootOn: # Finalizar as Observações self.stop_taking_photo() c = 0 self.t = False self.shootOn = False time.sleep(5) except Exception as e: self.console.raise_text("Exception no Ephemeris Shooter -> " + str(e))
def get_moon(self): lat, lng = self.get_lat_lng() observer = ephem.Observer() observer.lat = radians(lat) observer.lon = radians(lng) moon = ephem.Moon(observer) elevation = degrees(moon.alt) azimuth = degrees(moon.az) distance = moon.earth_distance * AU altitude = distance - EARTH_RADIUS return to_xyz(lat, lng, elevation, azimuth, altitude)
def moonPath(self): p = [] m = ephem.Moon() olddate = self.sobserver.date obs = self.sobserver for t in range(0, 5): obs.date += ephem.hour * 24 * t m.compute(obs) p.append((m.ra * 180 / pi, m.dec * 180 / pi)) self.sobserver.date = olddate return p
def m_nrising(self): try: moon = ephem.Moon() self.observat() rise = ephem.localtime(self.__observatory__.next_rising(moon)) rise = self.time_formatter(rise) self.logger.log("Next moonrise in the {} will be @ '{}'".format( self.obs_name(), rise)) return(rise) except Exception as e: self.logger.log(e)
def test_always_up(self): m = ephem.Moon() o = ephem.Observer() o.lon = '0' o.date = '2022/9/7' o.lat = '-60' self.assertEqual(str(o.next_rising(m)), '2022/9/7 12:11:26') o.lat = '-70' self.assertRaises(ephem.AlwaysUpError, o.next_rising, m)
def MoonPosition(self): MAA = [] Times = [] moon = ephem.Moon() for i in range(self.NightDisc): self.obs.date = self.NightBeg + (i + 0.5) * self.Interval print self.obs.date moon.compute(self.obs) Times.append(self.obs.date) MAA.append([moon.ra, moon.dec]) return [np.array(Times), np.array(MAA)]
def m_nsetting(self): try: moon = ephem.Moon() self.observat() sett = ephem.localtime(self.__observatory__.next_setting(moon)) sett = self.time_formatter(sett) self.etc.log("Next moonrise in the {} will be @ '{}'".format( self.obs_name(), sett)) return (sett) except Exception as e: self.etc.log(e)
def m_prising(self): try: moon = ephem.Moon() self.observat() rise = ephem.localtime(self.__observatory__.previous_rising(moon)) rise = self.time_formatter(rise) self.etc.log("Previous moonrise in the {} will be @ '{}'".format( self.obs_name(), rise)) return (rise) except Exception as e: self.etc.log(e)
def get_moon_phase_phrase(self): """Get a phrase (e.g. waxing crescent) to describe the moon phase. Returns a tuple (waxwan, full_phrase) -- both strings. waxwan is simply the first word in the phrase, for use in determing rotation. This function is more efficient if self.moon has already been set, but will set it if not. """ # the tolerance for exact moon phases new, full, quarter tolerance = 0.05 try: moon = self.moon except AttributeError: moon = ephem.Moon(self.ephem) self.moon = moon # take care of new and full if moon.phase < tolerance: return '', 'new moon' if 100 - moon.phase < tolerance: return '', 'full moon' # otherwise it's in between next_new = ephem.next_new_moon(self.ephem.date) next_full = ephem.next_full_moon(self.ephem.date) if next_new < next_full: growth = 'waning' else: growth = 'waxing' # is it a quarter? if abs(moon.phase - 50) < tolerance: if growth == 'waxing': return growth, 'first quarter' # otherwise it's waning: third quarter return growth, 'third quarter' # most likely: an in between state if moon.phase < 50: phase = 'crescent' else: phase = 'gibbous' full_phrase = '{} {}: {:.1f}'.format(growth, phase, moon.phase) return growth, full_phrase
def external_data(self): lastfile = sorted(glob('/Users/Desktop/asc/TARGET__*.fit'))[-1] curfits = fits.open(lastfile) expt = curfits[0].header['EXPTIME'] seqnum = lastfile[29:32] dct = ephem.Observer() dct.lat, dct.lon = '34.7443', '-111.4223' dct.elevation = 2361 utcdate = curfits[0].header['DATE-OBS'][0:10] utctime = curfits[0].header['DATE-OBS'][11:19] dct.date = utcdate + ' ' + utctime lst = dct.sidereal_time() moon = ephem.Moon() moon.compute(dct.date, epoch=dct.date) moon_loc = ephem.Moon() moon_loc.compute(dct) moon_alt = (moon_loc.alt) moondms = np.degrees(ephem.degrees(moon_alt)) moonflt = '{0:02.1f}'.format(moondms) mphase = (moon.phase) mphaseflt = '{0:04.1f}'.format(mphase) sun = ephem.Sun() sun.compute(dct) sun_alt = (sun.alt) sundms = np.degrees(ephem.degrees(sun_alt)) sunflt = '{0:02.1f}'.format(sundms) self.exposure = expt self.date = utcdate self.time = utctime self.lst = str(lst)[0:8] self.moon_illum = mphaseflt self.moon_elev = moonflt self.sun_elev = sunflt self.seqnum = seqnum return self.obsname, self.location, self.temperature, self.rel_humidity, self.exposure, self.date, self.time, \ self.lst, self.moon_illum, self.moon_elev, self.sun_elev, self.seqnum, self.heatstat
def calc_moon(self, site, body): """Compute Moon altitude""" site.date = ephem.Date(self.date_utc) moon = ephem.Moon(site) #moon.compute(site) moon_alt = math.degrees(float(moon.alt)) # moon.phase is % of moon that is illuminated moon_pct = moon.moon_phase # calculate distance from target moon_sep = ephem.separation(moon, body) moon_sep = math.degrees(float(moon_sep)) return (moon_alt, moon_pct, moon_sep)
def moon_phase(self): """ @brief: This function calculates the phase of the Moon. """ song_site = ephem.Observer() song_site.lat = self.obs_lat song_site.long = self.obs_lon song_site.elev = self.obs_elev moon = ephem.Moon() moon.compute(song_site) return moon.phase
def get_moon_phase(self, date): '''Get the Moon Phase around 6pm of any date.''' date = date.replace(hour=18, minute=0) elong = self.get_degrees(ephem.Moon(date).elong) phase = round(elong / 90.0) * 90 if phase == -90: return RuleLunar.moon_3q elif phase == 0: return RuleLunar.moon_new elif phase == 90: return RuleLunar.moon_1q return RuleLunar.moon_full