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 _isVisible(self, coord, startTime, duration): """ For a given source and datetime, check if the source is visible during the specified duration. Not that the horizon here is the elevation specified by the user. Note that the coordinate of source is specified as 'RA;Dec' """ endTime = startTime + datetime.timedelta(hours=duration) time = startTime while time < endTime: lofar = Observer() lofar.lon = '6.869882' lofar.lat = '52.915129' lofar.elevation = 15. lofar.date = time target = FixedBody() target._epoch = '2000' coordTarget = SkyCoord('{} {}'.format(coord.split(';')[0], \ coord.split(';')[1]), \ unit=(u.hourangle, u.deg)) target._ra = coordTarget.ra.radian target._dec = coordTarget.dec.radian target.compute(lofar) targetElevation = float(target.alt) * 180. / np.pi if targetElevation < self.elevation: return False time += datetime.timedelta(minutes=15) # Turns out this source is above the horizon return True
def init_groundstation(): # Ground station stuff gs_lat = 39.50417 gs_lon = -80.218615 gs_el_meters = 359.664 gs_tzname = 'US/Eastern' groundstation_name = 'Fairmont' gs_minimum_elevation_angle = 10.0 gs_observer = Observer() gs_observer.lat = gs_lat * math.pi / 180.0 gs_observer.lon = gs_lon * math.pi / 180.0 gs_observer.elevation = gs_el_meters # Times we need now = datetime.now() tomorrow = now + timedelta(1) gs_observer.date = now #now += timedelta(hours=14) # testing #tomorrow = now + timedelta(hours=4) # testing gs_tz = timezone(gs_tzname) gs_start = gs_tz.localize(now) gs_end = gs_tz.localize(tomorrow) #print(gs_start) #print(gs_end) gs = GroundStation.from_location(gs_lat, gs_lon, \ gs_el_meters, \ gs_tzname, \ groundstation_name, \ gs_minimum_elevation_angle) return [gs, gs_observer, gs_tz, gs_start, gs_end]
def iridium_tle(fn,T,sitella,svn): assert isinstance(svn,int) assert len(sitella)==3 assert isinstance(T[0],datetime),'parse your date' fn = Path(fn).expanduser() #%% read tle with fn.open('r') as f: for l1 in f: if int(l1[2:7]) == svn: l2 = f.readline() break sat = readtle('n/a',l1,l2) #%% comp sat position obs = Observer() obs.lat = str(sitella[0]); obs.lon = str(sitella[1]); obs.elevation=float(sitella[2]) ecef = DataFrame(index=T,columns=['x','y','z']) lla = DataFrame(index=T,columns=['lat','lon','alt']) aer = DataFrame(index=T,columns=['az','el','srng']) for t in T: obs.date = t sat.compute(obs) lat,lon,alt = degrees(sat.sublat), degrees(sat.sublong), sat.elevation az,el,srng = degrees(sat.az), degrees(sat.alt), sat.range x,y,z = geodetic2ecef(lat,lon,alt) ecef.loc[t,:] = column_stack((x,y,z)) lla.loc[t,:] = column_stack((lat,lon,alt)) aer.loc[t,:] = column_stack((az,el,srng)) return ecef,lla,aer
def test_moon_day_calculation_twelve(self, observer: Observer, moon: Moon, dt, number): moon.use_twelve_algorithm = True observer.date = dt moon.compute(observer) assert moon.get_day()['number'] == number, (dt, moon.get_day()['number'], number)
def findHBACalibrator(self, time, exclude=None): """ For a given datetime, return the ``best'' flux density calibrator for an HBA observation. """ # Create the telescope object # The following values were taken from otool.py which is part of the # LOFAR source visibility calculator. lofar = Observer() lofar.lon = '6.869882' lofar.lat = '52.915129' lofar.elevation = 15. lofar.date = time # Create a target object # If multiple targets are specified, use the first one target = FixedBody() target._epoch = '2000' coordTarget = SkyCoord('{} {}'.format(\ self.targetRA[0], self.targetDec[0]), unit=(u.hourangle, u.deg)) target._ra = coordTarget.ra.radian target._dec = coordTarget.dec.radian target.compute(lofar) targetElevation = float(target.alt) * 180. / np.pi # Create the calibrator object calibrator = FixedBody() calibrator._epoch = '2000' calName = [] calibElevation = [] if exclude is not None: self.validCalibs.remove(exclude) for item in self.validCalibs: myCoord = self._getCalPointing(item) calibrator._ra = myCoord.split(';')[0] calibrator._dec = myCoord.split(';')[1] calibrator.compute(lofar) tempElevation = float(calibrator.alt) * 180. / np.pi #print 'Temp is', tempElevation #if tempElevation > self.elevation: # calName.append(item) # calibElevation.append(tempElevation) #print calibElevation calName.append(item) calibElevation.append(tempElevation) if calibElevation[np.argmax(calibElevation)] < self.elevation: showWarningPopUp('One of the chosen calibrator is below user '+\ 'specified elevation [{} degrees].'.format(self.elevation) +\ ' Will generate text file anyway.') return calName[np.argmax(calibElevation)]
def rise_and_set(lat, lon, horizon=0): sun = Sun() date = None while True: loc = Observer() loc.horizon = str(horizon) loc.lat = str(lat) loc.lon = str(lon) loc.date = clock.now() #if date: # loc.date = date #loc.date = loc.date.datetime().date() # strip time t_rise = loc.next_rising(sun) t_set = loc.next_setting(sun) #date = yield localtime(t_rise), localtime(t_set) yield localtime(t_rise), localtime(t_set)
def findCalibrator(self, time): """ For a given datetime, return a list of calibrators that are above the minimum elevation limit. """ # Create the telescope object # The following values were taken from otool.py which is part of the # LOFAR source visibility calculator. lofar = Observer() lofar.lon = '6.869882' lofar.lat = '52.915129' lofar.elevation = 15.*u.m lofar.date = time # Create the target object target = FixedBody() target._epoch = '2000' target._ra = self.coordPoint1.ra.radian target._dec = self.coordPoint1.dec.radian target.compute(lofar) targetElevation = float(target.alt)*180./np.pi # Create the calibrator object calibrator = FixedBody() calibrator._epoch = '2000' calName = [] distance = [] for item in self.validCals: myCoord = getCalPointing(item) calibrator._ra = myCoord.split(';')[0] calibrator._dec = myCoord.split(';')[1] calibrator.compute(lofar) tempElevation = float(calibrator.alt)*180./np.pi if tempElevation > self.elevation: calName.append(item) distance.append(np.absolute(tempElevation-targetElevation)) return calName[np.argmin(distance)]
initial_date = f[0].header['DATE-OBS'] ##Change in to oskar date format date, time = initial_date.split('T') year, month, day = date.split('-') oskar_date = "%s-%s-%s %s" % (day, month, year, time) time_int = float(options.time_int) low_freq = float(options.low_freq) ##ephem Observer class, use this to compute LST from the date of the obs MRO = Observer() ##Set the observer at Boolardy MRO.lat, MRO.long, MRO.elevation = '-26:42:11.95', '116:40:14.93', 0 date, time = initial_date.split('T') MRO.date = '/'.join(date.split('-')) + ' ' + time intial_lst = float(MRO.sidereal_time()) * R2D initial_ra_point = float(f[0].header['RA']) dec_point = float(f[0].header['DEC']) healpix = options.healpix telescope_dir = options.telescope telescope_name = options.telescope.split('/')[-1] #template_uvfits = fits.open("%s/template_%s.uvfits" %(telescope_dir,telescope_name)) #template_data = template_uvfits[0].data #template_baselines = template_uvfits[0].data['BASELINE'].copy() #num_baselines = len(template_data) num_stations = 512 num_baselines = (num_stations - 1) * (num_stations / 2)
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.")
def whats_up( start: datetime.datetime, end: datetime.datetime, location: ephem.Observer, magnitude: float = 6.) -> dict: """ Find all objects that will be "up" between start and end time. Takes a location, start and end time, and limiting magnitude. """ body_list = [] start_e, end_e = ephem.Date(start), ephem.Date(end) location.date = start_e for o,body_type in filter(lambda x: x[1] != 'planetary_moon', OBJECT_DICT.values()): o.compute(location) circumpolar = False rising, setting = None, None if body_type != 'satellite': try: rising = location.next_rising(o, start = location.previous_antitransit(o)) setting = location.next_setting(o, start = rising) except ephem.AlwaysUpError: circumpolar = True except ephem.NeverUpError: pass elif body_type == 'satellite': info = list(location.next_pass(o)) rising, setting = info[0], info[4] # the logic here is as follows: # 1. Is object bright enough? # 2. Is it in the sky now? # a. Is it circumpolar (does it never set)? # b. Does it rise during the given timeframe? # c. Does it set during the given timeframe? # d. Does it rise before the given timeframe and set after the given timeframe? if o.mag < -30: # something's wrong with the data--skip it. continue if o.mag < magnitude and (circumpolar or \ (rising and start_e < rising < end_e) or \ (setting and start_e < setting < end_e) or \ (rising and setting and (rising < start_e) and \ (setting > end_e))): # If it's in the sky and bright enough, add the entry to the list if rising or setting or circumpolar: body_list.append({ 'name': o.name.split('|') if o.name.find('|') >= 0 else o.name, 'magnitude': o.mag }) # If it has a rise time, add that to the most recently added item if rising: body_list[-1]['rise_time'] = rising.datetime() # If it has a set time, add that to the most recently added item if setting: body_list[-1]['set_time'] = setting.datetime() if o.name == 'Moon': body_list[-1]['phase'] = o.moon_phase * 100 body_list.sort(key = lambda x: x['magnitude']) return { 'start_time': start, # start of timeframe 'end_time': end, # end of timeframe 'objects': body_list # all items visible during timeframe, as computed above }
nargs = len(sys.argv) el = float(sys.argv[1]) print 'Calculating galactic coordinates for elevation ' + str(el) + ' deg' # first define the observer location me = Observer() me.lon = '-79.8397' me.lat = '38.4331' me.elevation = 800 # height in meters # reformat the time into ephemerus format. now = datetime.datetime.utcnow() strnow = now.isoformat() dates = strnow.split('T') datestr = dates[0] + ' ' + dates[1] me.date = datestr timestrfull = str(dates[1]) times = timestrfull.split('.') outname = dates[0] + '_' + times[0] + '.txt' #print(outname) # check the LST as a test #print('UTC = ' + datestr + ' -> ' + str(me.sidereal_time()) + ' LST ') #now compute the ra,dec from the azimuth,elevation, time and location ra_a, dec_a = me.radec_of(az, str(el)) print('Horn Ra,Dec = %s,%s for Az,El %s,%s of %s' % (ra_a, dec_a, az, str(el), datestr)) #radec_a = Equatorial( ra_a, dec_a, me.date) radec = Equatorial(ra_a, dec_a, epoch=datestr) print(radec.ra, radec.dec) #finally calculate the galactic coordiates for the ra, dec coordinates
# 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') plt.xlim(-12,12) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ticks = ax.get_xticks() ticks[ticks <0] += 24
def test_moon_day_calculation_simple(self, observer: Observer, moon: Moon, dt, number): observer.date = dt moon.compute(observer) assert moon.get_day()['number'] == number, (moon.get_day()['number'], number)
def test_optimization_day_calculation_simple(self, observer: Observer, moon: Moon): observer.date = datetime(2017, 4, 3, 23) for i in range(10000): moon.compute(observer) assert moon.get_day()['number'] == 7, (moon.get_day()['number'], 7)