def distanceToSun(self): """ Find the distance between the Sun and the target pointings """ lofar = Observer() lofar.lon = '6.869882' lofar.lat = '52.915129' lofar.elevation = 15.*u.m lofar.date = self.startTime # Create Sun object sun = Sun() sun.compute(lofar) # Create the target object target = FixedBody() target._epoch = '2000' target._ra = self.coordPoint1.ra.radian target._dec = self.coordPoint1.dec.radian target.compute(lofar) print 'INFO: Sun is {:0.2f} degrees away from {}'.format(\ float(separation(target, sun))*180./np.pi, self.namePoint1) target._ra = self.coordPoint2.ra.radian target._dec = self.coordPoint2.dec.radian target.compute(lofar) print 'INFO: Sun is {:0.2f} degrees away from {}'.format(\ float(separation(target, sun))*180./np.pi, self.namePoint2)
def _findDistanceToSun(self, coord): """ Print the distance between the specified pointing center and the Sun. """ # Find the coordinates of the Sun at the start of the observing run sun = Sun() sun.compute(self.startTime) coordSun = SkyCoord('{} {}'.format(sun.ra, sun.dec), unit=(u.hourangle, u.deg)) coordTarget = SkyCoord('{} {}'.format(coord.split(';')[0], \ coord.split(';')[1]), \ unit=(u.hourangle, u.deg)) # Find the separation between the Sun and the target return coordSun.separation(coordTarget).deg
def get_elevation_solar(obs_date, offender): """For a given observation date and bright solar system object, return its elevation over the course of that day. Input parameters: * obs_date: Observation date in datetime.datetime format * offender: Name of the solar system object. Allowed names are Sun, Moon, and Jupiter. Returns: List of elevations in degrees. If offender is invalid, return None. """ # Create the telescope object lofar = get_dutch_lofar_object() if offender == 'Sun': obj = Sun() elif offender == 'Moon': obj = Moon() elif offender == 'Jupiter': obj = Jupiter() else: return None yaxis = [] for time in obs_date: lofar.date = time obj.compute(lofar) elevation = float(obj.alt)*180./np.pi if elevation < 0: elevation = np.nan yaxis.append(elevation) return yaxis
def from_observer(obs=None, date=None, yaw=0., theta_t=0., phi_t=0.): """ Creates sky using an Ephem observer (Requires Ephem library) :param obs: the observer (location on Earth) :param date: the date of the observation :param yaw: the heading orientation of the observer :param theta_t: the heading tilt (pitch) :param phi_t: the heading tilt (roll) :return: """ from ephem import Sun from datetime import datetime from utils import get_seville_observer sun = Sun() if obs is None: obs = get_seville_observer() obs.date = datetime(2017, 6, 21, 10, 0, 0) if date is None else date sun.compute(obs) theta_s, phi_s = np.pi/2 - sun.alt, (sun.az - yaw + np.pi) % (2 * np.pi) - np.pi return Sky(theta_s=theta_s, phi_s=phi_s, theta_t=theta_t, phi_t=phi_t)
def __setup_next_alarm (self): '''Switch to the next alarm ''' if dt.now().hour > ALARM_MORNING_H : self._observer.date = self.__get_current_date () # sunset = YYYY:MM/DD HH:MM:SS sunset = self._observer.next_setting (Sun (), use_center = True) sunset = str(sunset).split(' ')[1] self._alarm_hour = sunset.split(':')[0] self._alarm_minute = sunset.split(':')[1] else: self._alarm_hour = ALARM_MORNING_H self._alarm_minute = ALARM_MORNING_M
def determine_nighttime(gs_observer): sun = Sun() gs_observer.horizon = '-6' # Civil twilight, stars should start appearing rapidly next_set = utc.localize( gs_observer.next_setting(sun, use_center=True).datetime()) following_rise = utc.localize( gs_observer.next_rising(sun, use_center=True, start=next_set).datetime()) civil_night = [next_set, following_rise] #print(civil_night) gs_observer.horizon = '-12' # Nautical twilight, it's dark next_set = utc.localize( gs_observer.next_setting(sun, use_center=True).datetime()) following_rise = utc.localize( gs_observer.next_rising(sun, use_center=True, start=next_set).datetime()) nautical_night = [next_set, following_rise] #print(nautical_night) return [civil_night, nautical_night]
def get_distance_solar(target, obs_date, offender): """Compute the angular distance in degrees between the specified target and the offending radio source in the solar system on the specified observing date. Input parameters: * target - Coordinate of the target as an Astropy SkyCoord object * obs_date - Observing date in datetime.datetime format * offender - Name of the offending bright source. Allowed values are Sun, Moon, Jupiter. Returns: For Moon, the minimum and maximum separation are returned. For others, distance,None is returned.""" # Get a list of values along the time axis d = obs_date.split('-') start_time = datetime(int(d[0]), int(d[1]), int(d[2]), 0, 0, 0) end_time = start_time + timedelta(hours=24) taxis = [] temp_time = start_time while temp_time < end_time: taxis.append(temp_time) temp_time += timedelta(hours=1) angsep = [] if offender == 'Sun': obj = Sun() elif offender == 'Moon': obj = Moon() elif offender == 'Jupiter': obj = Jupiter() else: pass # Estimate the angular distance over the entire time axis for time in taxis: obj.compute(time) coord = SkyCoord('{} {}'.format(obj.ra, obj.dec), unit=(u.hourangle, u.deg)) angsep.append(coord.separation(target).deg) # Return appropriate result if offender == 'Moon': return np.min(angsep), np.max(angsep) else: return np.mean(angsep), None
def main(): # arguments from argparse import ArgumentParser args = ArgumentParser( epilog= """This script will compute the local coordinates (altitude and azimuth) for Jupiter and Saturn for the given date. Altitude is degrees above the horizon and azimuth is degrees eastwards from North. Locate North by finding the Polaris, the pole star.""") args.add_argument( "-x", "--longitude", type=float, default=-74.151494, help= "East longitude of the observer in decimal degrees. West is negative.") args.add_argument( "-y", "--latitude", type=float, default=40.373545, help="North latitude of the observer. South is negative.") args.add_argument("-t", "--timezone", type=str, default='US/Eastern', help="The local time-zone of the observer.") args.add_argument("-e", "--elevation", type=float, default=20e0, help="Elevation in metres above sea level.") args.add_argument( "time", nargs='?', default=datetime.now().strftime("%H:%M:%S"), help="Local time for calculation, default is current time, as HH:MM:SS." ) args.add_argument( "date", nargs='?', default=datetime.now().strftime("%Y-%m-%d"), help= "Local date for calculation, default is current date, as YYYY-MM-DD.") args = args.parse_args() # time localtime = timezone(args.timezone) utc = timezone('UTC') timestamp = localtime.localize( datetime.strptime(args.date + ' ' + args.time, '%Y-%m-%d %H:%M:%S')) observer = Observer() observer.lat = args.latitude * pi / 180.0 observer.lon = args.longitude * pi / 180.0 observer.date = timestamp.astimezone(utc) observer.elevation = args.elevation print( "Calculation of the location of Jupiter and Saturn for an observer at %.4f° %s, %.4f° %s, %.4f m above sea level.\n" % (abs(args.longitude), "E" if args.longitude > 0 else "W", abs(args.latitude), "N" if args.latitude > 0 else "S", args.elevation)) print("Computed for local time %s." % timestamp.astimezone(localtime).strftime('%Y-%m-%d %H:%M:%S')) # Sun sun = Sun(observer) sunlight = max(0e0, cos(pi / 2 - sun.alt)) * 1e2 if sunlight > 0: print( "The Sun is currently above the horizon, with light at %.2f %%, at %.2f° %s." % (sunlight, (sun.az - pi if sun.az > pi else sun.az) * 180e0 / pi, "E" if sun.az < pi else "W" if sun.az > pi else "S")) sunset = utc.localize( datetime.strptime(str( observer.next_setting(sun)), "%Y/%m/%d %H:%M:%S")).astimezone( localtime) if observer.next_setting(sun) != None else None if sunset != None: print("The Sun will set at %s." % sunset.strftime("%H:%M:%S")) else: print("The Sun has set.") sunrise = utc.localize( datetime.strptime(str( observer.next_rising(sun)), "%Y/%m/%d %H:%M:%S")).astimezone( localtime) if observer.next_rising(sun) != None else None print("The Sun will rise at %s." % sunrise.strftime("%H:%M:%S")) # Moon moon = Moon(observer) moonlight = max(0e0, cos(pi / 2 - moon.alt)) * 1e2 if moonlight > 0: print( "The Moon is currently above the horizon, with light at %.2f %%." % moonlight) # Jupiter jupiter = Jupiter(observer) if jupiter.alt > 0e0: print( "Jupiter is %.2f° above the horizon, %.2f° %s." % (jupiter.alt * 180e0 / pi, (2 * pi - jupiter.az if jupiter.az > pi else jupiter.az) * 180e0 / pi, "W" if jupiter.az > pi else "E" if jupiter.az < pi else "S")) else: print("Jupiter is not above the horizon.") # Jupiter saturn = Saturn(observer) if saturn.alt > 0e0: print("Saturn is %.2f° above the horizon, %.2f° %s." % (saturn.alt * 180e0 / pi, (2 * pi - saturn.az if saturn.az > pi else saturn.az) * 180e0 / pi, "W" if saturn.az > pi else "E" if saturn.az < pi else "S")) else: print("Saturn is not above the horizon.") # done print("Done.")
outline = ' Az Ra Dec G-Lon G-Lat \n' outfile.write(outline) #for all azimuths, assuming a fixed elevation for azimuth in range(0, 360, 10): az = str(azimuth) ra_a, dec_a = me.radec_of(az, str(el)) radec = Equatorial(ra_a, dec_a, epoch=datestr) gal = Galactic(radec) print('%6s %12s %12s %12s %12s' % (az, ra_a, dec_a, gal.lon, gal.lat)) outline = '%6s %12s %12s %12s %12s \n' % (az, ra_a, dec_a, gal.lon, gal.lat) outfile.write(outline) # perform a sanity check by computeing the solar positions in az,el and lon,lat sun = Sun(me) outline = 'Sun = %12s,%12s (ra,dec)' % (sun.a_ra, sun.a_dec) print(outline) outfile.write(outline + '\n') outline = 'Sun = %12s,%12s (alt,az)' % (sun.alt, sun.az) print(outline) outfile.write(outline + '\n') sunradec = Equatorial(sun.a_ra, sun.a_dec, epoch=datestr) sungal = Galactic(sunradec) outline = 'Sun = %12s,%12s (lon,lat)' % (sungal.lon, sungal.lat) print(outline) outfile.write(outline + '\n')
def plot_ephemeris(obs, dt=10): sun = Sun() delta = timedelta(minutes=dt) azi, azi_diff, ele = [], [], [] for month in xrange(12): obs.date = datetime(year=2018, month=month + 1, day=13) cur = obs.next_rising(sun).datetime() + delta end = obs.next_setting(sun).datetime() if cur > end: cur = obs.previous_rising(sun).datetime() + delta while cur <= end: obs.date = cur sun.compute(obs) a, e = sun.az, np.pi / 2 - sun.alt if len(azi) > 0: d = 60. / dt * np.absolute((a - azi[-1] + np.pi) % (2 * np.pi) - np.pi) if d > np.pi / 2: azi_diff.append(0.) else: azi_diff.append(d) else: azi_diff.append(0.) azi.append(a % (2 * np.pi)) ele.append(e) # increase the current time cur = cur + delta ele = np.rad2deg(ele) azi = np.rad2deg(azi) azi_diff = np.rad2deg(azi_diff) azi = azi[ele < 90] azi_diff = azi_diff[ele < 90] ele = ele[ele < 90] ele_nonl = np.exp(.1 * (54 - ele)) x = np.array([9 + np.exp(.1 * (54 - ele)), np.ones_like(azi_diff)]).T # w = np.linalg.pinv(x).dot(azi_diff) w = np.array([1., 0.]) y = x.dot(w) error = np.absolute(y - azi_diff) print "Error: %.4f +/- %.4f" % (error.mean(), error.std() / np.sqrt(len(error))), print "| N = %d" % len(error) plt.figure(figsize=(10, 10)) plt.subplot(221) plt.scatter(azi, ele, c=azi_diff, cmap='Reds', marker='.') plt.ylabel(r'$\theta_s (\circ)$') plt.xlim([0, 360]) plt.ylim([85, 0]) plt.xticks([0, 45, 90, 135, 180, 225, 270, 315, 360], [""] * 9) plt.yticks([0, 15, 30, 45, 60, 75]) plt.subplot(222) plt.scatter(azi_diff, ele, c=azi, cmap='coolwarm', marker='.') xx = np.linspace(0, 90, 100, endpoint=True) yy = 9 + np.exp(.1 * (54 - xx)) plt.plot(yy, xx, 'k-') plt.ylim([85, 0]) plt.xlim([7, 60]) plt.xticks([10, 20, 30, 40, 50, 60], [""] * 6) plt.yticks([0, 15, 30, 45, 60, 75], [""] * 6) plt.subplot(223) plt.scatter(azi, x[:, 0], c=azi_diff, cmap='Reds', marker='.') plt.xlabel(r'$\phi_s (\circ)$') plt.ylabel(r'$\Delta\phi_s (\circ/h)$ -- prediction') plt.xlim([0, 360]) plt.ylim([7, 65]) plt.xticks([0, 45, 90, 135, 180, 225, 270, 315, 360]) plt.yticks([10, 20, 30, 40, 50, 60]) plt.subplot(224) plt.scatter(azi_diff, x[:, 0], c=azi, cmap='coolwarm', marker='.') plt.plot([w[0] * 7 + w[1], w[0] * 65 + w[1]], [7, 65], 'k-') plt.xlabel(r'$\Delta\phi_s (\circ/h)$ -- true') plt.xlim([7, 60]) plt.xticks([10, 20, 30, 40, 50, 60]) plt.ylim([7, 65]) plt.yticks([10, 20, 30, 40, 50, 60], [""] * 6) return plt
def add_sun_rise_and_set_times(obs_date, n_int, elevation_fig): """ For a given obs_date, find the sun rise and set times. Add these to the supplied elevation_fig and return the modified elevation_fig. """ d = obs_date.split('-') start_time = datetime(int(d[0]), int(d[1]), int(d[2]), 0, 0, 0) sun = Sun() sun._epoch = '2000' if n_int == 0: # Only Dutch array is being used. Calculate Sun rise and set times in NL lofar = get_dutch_lofar_object() lofar.date = start_time sun_rise = lofar.next_rising(sun).datetime() sun_set = lofar.next_setting(sun).datetime() # Define a 1 hour window around Sun rise and Sun set. sun_rise_beg = sun_rise - timedelta(minutes=30) sun_rise_end = sun_rise + timedelta(minutes=30) sun_set_beg = sun_set - timedelta(minutes=30) sun_set_end = sun_set + timedelta(minutes=30) else: # Calculate sun rise and set times using Latvian and Irish stations lv = get_lv_lofar_object() ie = get_ie_lofar_object() lv.date = start_time ie.date = start_time lv_sun_rise = lv.next_rising(sun).datetime() lv_sun_set = lv.next_setting(sun).datetime() ie_sun_rise = ie.next_rising(sun).datetime() ie_sun_set = ie.next_setting(sun).datetime() # Define a window around sun rise and sun set. sun_rise_beg = lv_sun_rise - timedelta(minutes=30) sun_rise_end = ie_sun_rise + timedelta(minutes=30) sun_set_beg = lv_sun_set - timedelta(minutes=30) sun_set_end = ie_sun_set + timedelta(minutes=30) # Add to elevation_fig elevation_fig['layout']['shapes'].append({ 'type': "rect", 'xref': 'x', 'yref': 'y', 'x0' : sun_rise_beg, 'x1' : sun_rise_end, 'y0' : 0, 'y1' : 90, 'fillcolor': 'LightSkyBlue', 'opacity': 0.4, 'line': {'width': 0,} }) elevation_fig['layout']['shapes'].append({ 'type': "rect", 'xref': 'x', 'yref': 'y', 'x0' : sun_set_beg, 'x1' : sun_set_end, 'y0' : 0, 'y1' : 90, 'fillcolor': 'LightSkyBlue', 'opacity': 0.4, 'line': {'width': 0,} }) return elevation_fig
#data['time'] = data[pd.to_numeric(data['time'], errors=coerce)] #data.astype({'time':'int32'}).dtypes # print data.dtypes # print int(data['time'][0]) # print(data['time']) # plt.figure(figsize=(14,10)) # #plt.scatter(data['t2'],data['mag']) # n, bins, patches = plt.hist(data['t2'], bins=96) # plt.xlim(-12,12) # plt.show() dt = '2016/5/27 00:00' sun = Sun() sun.compute(dt) elginfield = Observer() elginfield.lat = 43.19237 elginfield.lon = -81.31799 elginfield.date = dt ra, dec = elginfield.radec_of('0', '-90') print('RA_sun:',sun.ra) print('Elgin nadir', ra) print('Solar time:', hours((ra-sun.ra)%(2*pi)), 'hours') fig, ax = plt.subplots(figsize=(14,10)) n, bins, patches = ax.hist(data['t2'], bins=192, rwidth=0.9, edgecolor='black') ax.axvline(0, color='red')
from environment import get_seville_observer # from environment.utils import sun2lonlat from compoundeye.geometry import fibonacci_sphere from compoundeye.evaluation import evaluate from ephem import Sun from datetime import datetime, timedelta import numpy as np import matplotlib.pyplot as plt if __name__ == "__main__": # mode = "ephemeris" mode = "res2ele" # mode = "res2azi" sun = Sun() obs = get_seville_observer() obs.date = datetime.strptime("2018-06-21", "%Y-%m-%d") dt = 10 delta = timedelta(minutes=dt) cur = obs.next_rising(sun).datetime() + delta end = obs.next_setting(sun).datetime() if cur > end: cur = obs.previous_rising(sun).datetime() + delta if mode is "res2ele": samples = 1000 ele, azi, azi_diff, res = [], [], [], []