def plot_tle( ax: matplotlib.axes.Axes, tle_filename: str, location: EarthLocation, time_start: datetime, time_stop: datetime, ) -> Tuple[datetime, datetime]: """Plot the trajectory of the first above-horizon pass within a specified time window.""" tle = [] with open(tle_filename) as tlefile: for line in tlefile: tle.append(line) target = ephem.readtle(tle[0], tle[1], tle[2]) # Create PyEphem Observer object with location information observer = ephem.Observer() observer.lat = location.lat.rad observer.lon = location.lon.rad observer.elevation = location.height.to_value(u.m) az = [] alt = [] time_rise = None time_set = None t = time_start while t < time_stop: observer.date = ephem.Date(t) target.compute(observer) if target.alt >= 0: if len(az) == 0: time_rise = t az.append(target.az) alt.append(target.alt) elif time_rise is not None: break t += timedelta(seconds=1) if len(az) > 0: time_set = t az = np.degrees(np.array(az)) alt = np.degrees(np.array(alt)) plot_trajectory(ax, az, alt, color='black', label='TLE') return time_rise, time_set
def converge(d, deg): def get_diff(d, deg, nutation_dpsi=None): diff = float(deg) * degree - get_ap_hlon(d, nutation_dpsi) if diff > pi: diff -= twopi elif diff < -pi: diff += twopi return diff # converging iterations using the get_diff() function, not fixing nutation for i in range(100): diff = get_diff(d, deg) if abs(diff) < ephem.degrees('0:00:01'): break d = d + 365.25 * diff / twopi # update d using the difference # apply the bisection method, fixing nutation nutation_dpsi = nutation(d)[1] d0, d1 = d-ephem.degrees('0:05:00'), d+ephem.degrees('0:05:00') f0, f1 = get_diff(d0, deg, nutation_dpsi), get_diff(d1, deg, nutation_dpsi) if f0 * f1 > 0.: raise AssertionError("warning: f0=%f, f1=%f" % (f0, f1)) for i in range(20): # limits the iteration number to 20. dn = (d0 + d1) / 2. fn = get_diff(dn, deg, nutation_dpsi) if fn * f0 > 0.: # the midpoint has the same sign as the left side -> select the right side d0 = dn f0 = get_diff(d0, deg, nutation_dpsi) elif fn * f1 > 0.: # the midpoint has the same sign as the right side -> select the left side d1 = dn f1 = get_diff(d1, deg, nutation_dpsi) elif fn == 0: return ephem.date(dn) else: raise AssertionError("warning: impossible") return ephem.Date((d0*abs(f1)+d1*abs(f0))/(abs(f0) + abs(f1)))
def expscript_for_json(j, status=None): ss = [] if 'approx_datetime' in j: # Expected start time of this script, in "date -u +%s" units -- seconds since unixepoch = 1970-01-01 00:00:00 unixepoch = 25567.5 tj = ephem.Date(str(j['approx_datetime'])) ss = ['# Exposure scheduled for: %s UT\n' % j['approx_datetime'], 'dt=$(($(date -u +%%s) - %i))' % (int((tj - unixepoch) * 86400))] #ss.append('echo DT: $dt\n') ss.append('if [ $dt -gt 3600 ]; then\n' + ' echo; echo "WARNING: This exposure is happening more than an hour late!";\n' + ' echo "Scheduled time: %s UT";\n' % j['approx_datetime'] + ' echo; tput bel; sleep 0.25; tput bel; sleep 0.25; tput bel;\n' + 'fi\n' + 'if [ $dt -lt -3600 ]; then\n' + ' echo; echo "WARNING: This exposure is happening more than an hour early!";\n' + ' echo "Scheduled time: %s UT";\n' % j['approx_datetime'] + ' echo; tput bel; sleep 0.25; tput bel; sleep 0.25; tput bel;\n' + 'fi\n') #ADM force exit if observation is more than 4 hours late ss.append('if [ $dt -gt 14400 ]; then\n' + ' echo; echo "ERROR: This exposure is happening more than 4 hours late!";\n' + ' echo "Scheduled time: %s UT";\n' % j['approx_datetime'] + ' echo "YOU SHOULD RERUN mosbot.py TO CREATE A NEW tonight.sh FILE!";\n' + ' touch quit\n' + ' exit 1\n' + 'fi\n') ra = j['RA'] dec = j['dec'] ss.append(jnox_moveto(ra, dec)) # exposure time et = (j['expTime']) # filter filter_name = str(j['filter']) tilename = str(j['object']) if status is None: ra = ra2hms(ra) dec = dec2dms(dec) status = "Tile %s, RA %s, Dec %s" % (tilename, ra, dec) ss.append(jnox_exposure(et, filter_name, tilename, status)) return '\n'.join(ss) + '\n'
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 get_telescope_position(self, targetName='sky'): if targetName is None or len(targetName) == 0: targetName = 'sky' response = self.sendTelescopeCommand('REQPOS\r') if response is None: return {} #split response into status fields line1, line2, airmass = response.split('\n') utc, lst = line1.split(', ') utc_title, junk, utc_day, utc_time = utc.split(' ') lst_title, junk, lst_time = lst.split(' ') ra, dec, ha = line2.split(', ') ra_title, junk, ra_val = ra.split(' ') dec_title, junk, dec_val = dec.split(' ') ha_title, junk, ha_val = ha.split(' ') airmass_title, airmass_val = airmass.split('= ') #calculate alt and az of current target target = ephem.readdb( str(targetName) + ',f|L,' + str(ra_val) + ',' + str(dec_val) + ',2000') lt = time.time() dt = datetime.datetime.utcfromtimestamp(lt) palomar = ephem.Observer() palomar.long, palomar.lat = self.lonStr, self.latStr palomar.date = ephem.Date(dt) palomar.elevation = self.elevation target.compute(palomar) alt, az = target.alt * (180. / math.pi), target.az * (180 / math.pi) return { str(utc_title): utc_time, str(lst_title): lst_time, str(ra_title): ra_val, str(dec_title): dec_val, str(ha_title): ha_val, str(airmass_title): float(airmass_val[:-1]), 'alt': alt, 'az': az }
def getTLE(self, date): date = ephem.Date(date) tleCount = len(self.tles) // 2 lo = 0 hi = tleCount while lo < hi: # equals bisect.bisect_left mid = (lo + hi) // 2 tle = ephem.readtle('foo', self.tles[mid * 2], self.tles[mid * 2 + 1]) if tle._epoch < date: lo = mid + 1 else: hi = mid tleIdx = lo - 1 # equals find_lt (rightmost TLE with epoch less than given date) return self.tles[tleIdx * 2], self.tles[tleIdx * 2 + 1]
def get_phase_on_day(year, month, day): """Returns a floating-point number from 0-1. where 0=new, 0.5=full, 1=new""" #Ephem stores its date numbers as floating points, which the following uses #to conveniently extract the percent time between one new moon and the next #This corresponds (somewhat roughly) to the phase of the moon. #Use Year, Month, Day as arguments date = ephem.Date(datetime.date(year, month, day)) nnm = ephem.next_new_moon(date) pnm = ephem.previous_new_moon(date) lunation = (date - pnm) / (nnm - pnm) #Note that there is a ephem.Moon().phase() command, but this returns the #percentage of the moon which is illuminated. This is not really what we want. return lunation
def __init__(self, timestamp=None): if isinstance(timestamp, basestring): try: timestamp = ephem.Date(timestamp.strip().replace('-', '/')) except ValueError: raise ValueError("Timestamp string '%s' not in correct format - " % (timestamp,) + "should be 'YYYY-MM-DD HH:MM:SS' or 'YYYY/MM/DD HH:MM:SS' or prefix thereof " + "(all UTC, fractional seconds allowed)") if timestamp is None: self.secs = time.time() elif isinstance(timestamp, ephem.Date): timestamp = list(timestamp.tuple()) + [0, 0, 0] int_secs = math.floor(timestamp[5]) frac_secs = timestamp[5] - int_secs timestamp[5] = int(int_secs) self.secs = time.mktime(tuple(timestamp)) - time.timezone + frac_secs else: self.secs = float(timestamp)
def compute_sun_ned(lon_deg, lat_deg, alt_m, timestamp): d = datetime.utcfromtimestamp(timestamp) #d = datetime.datetime.utcnow() ed = ephem.Date(d) #print 'ephem time utc:', ed #print 'localtime:', ephem.localtime(ed) ownship = ephem.Observer() ownship.lon = '%.8f' % lon_deg ownship.lat = '%.8f' % lat_deg ownship.elevation = alt_m ownship.date = ed sun = ephem.Sun(ownship) sun_ned = [math.cos(sun.az), math.sin(sun.az), -math.sin(sun.alt)] return sun_ned
def sunrise(d0="2018/7/1", d1="2018/12/30", place="Lutsk"): sun = eph.Sun() pl, loc = city(place) dates = pd.date_range(start=d0, end=d1, freq='D') slist = [] for i in dates: pl.date = eph.Date(i) dlist = [ pl.next_rising(sun), pl.next_transit(sun), pl.next_setting(sun) ] dlist = [h.datetime().replace(second=0, microsecond=0) for h in dlist] dlist = [loco(k, loc) for k in dlist] slist.append(dlist) df = pd.DataFrame(slist, index=dates, columns=['rise', 'trans', 'set']) df['date'] = df['rise'].apply(lambda x: x.date()) # df['yday'] = df[0].apply(lambda x: x.dayofyear) return df
def datestring(date,precision=4): """ Convert an ephem.Date object to a string with increased precision Parameters: ----------- date : ephem.Date object precision : Output precision Returns: -------- datestr : String representation of the date """ """ date = ephem.Date(date).datetime() datestr = date.strftime('%Y/%m/%d %H:%M:%S') datestr += '{:.{precision}f}'.format(date.microsecond/1.e6, precision=precision)[1:] """ if precision < 0: msg = "Precision must be positive." raise Exception(msg) # This is a bit annoying, but works better (more accurate) than # using the built-in datetime conversion date = ephem.Date(date) datetuple = date.tuple() seconds = round(datetuple[-1],precision) minutes = datetuple[-2] hours = datetuple[-3] minutes += int(seconds//60) seconds = seconds%60. hours += int(minutes//60) minutes = minutes%60 strtuple = datetuple[:-3]+(hours,minutes,seconds) width = precision+2 if precision == 0 else precision+3 #datestr = '%d/%02d/%02d %02i:%02i:%07.4f'%strtuple datestr = '{:4d}/{:02d}/{:02d} {:02d}:{:02d}:{:0{width}.{precision}f}' datestr = datestr.format(*strtuple,precision=precision,width=width) return datestr
def main(args): idf = LWA1DataFile(args[0]) nFramesFile = idf.getInfo('nFrames') srate = idf.getInfo('sampleRate') beam = idf.getInfo('beam') beampols = idf.getInfo('beampols') # Date beginDate = ephem.Date(unix_to_utcjd(idf.getInfo('tStart')) - DJD_OFFSET) # File summary print "Filename: %s" % args[0] print "Date of First Frame: %s" % str(beginDate) print "Beam: %i" % beam print "Tune/Pols: %ii" % beampols print "Sample Rate: %i Hz" % srate print "Frames: %i (%.3f s)" % (nFramesFile, 1.0 * nFramesFile / beampols * 4096 / srate) print "---"
def utc2nite(utc, observer=None): sun = ephem.Sun() if observer is None: observer = ephem.Observer() observer.lon = constants.LON_CTIO observer.lat = constants.LAT_CTIO observer.elevation = constants.ELEVATION_CTIO observer.date = utc if observer.previous_setting(sun) > observer.previous_rising(sun): # It's night time, use the date of the previous setting nite = ephem.localtime(observer.previous_setting(sun)) else: # It's daytime, use the next setting nite = ephem.localtime(observer.next_setting(sun)) return ephem.Date(nite)
def tle2eci(l1, l2): """ Function takes first and second line of tle data and returns ECI position (x, y, z) of the satellite at current UTC time. For parsing TLE data and getting current location I am using spg4 library """ satellite = twoline2rv(l1, l2, wgs84) ljubljana = timezone('Europe/Ljubljana') lj_time = datetime.datetime.now(ljubljana) a_date = ephem.Date(lj_time.strftime('%Y/%m/%d %H:%M:%S')) #print "Time in Ljubljana: ", a_date (year, month, day, hour, minute, secunde) = a_date.tuple() position, velocity = satellite.propagate(year, month, day, hour - 2, minute, secunde) #print "ECI position: ", position return position
def make_cal(): cal = np.ones((13 * border_h + 12 * max_h, 32 * border_w + 31 * max_w, 3)).astype('float32') for i in xrange(365): gatech.date = ephem.Date(d + i) moon.compute(gatech) year, month, day = gatech.date.triple() day = int(day - 0.5) m = np.ones((h, w, 3)).astype('float32') * moon.phase / 100. m[:, :, 1] = (moon.earth_distance - min_dist) / (max_dist - min_dist) m[:, :, 0] = 1 - (moon.sun_distance - min_dist_sun) / (max_dist_sun - min_dist_sun) m[0:2, :, :] = 0 m[-2:, :, :] = 0 m[:, 0:2, :] = 0 m[:, -2:, :] = 0 off_h = random.randint(0, border_h // 2) off_w = random.randint(0, border_w // 2) deg = random.randint(-15, 15) rot_m = rotate(m, deg) start_r = (month - 1) * max_h + month * border_h + off_h end_r = month * max_h + month * border_h + off_h start_c = (day - 1) * max_w + day * border_w + off_w end_c = day * max_w + day * border_w + off_w d_r = rot_m.shape[0] - (end_r - start_r) d_c = rot_m.shape[1] - (end_c - start_c) cal[start_r : end_r + d_r, start_c : end_c + d_c] = rot_m rotated = rotate(cal, 3) rotated = cv2.copyMakeBorder(rotated, top=150, bottom=200, left=50, right=50, borderType=cv2.BORDER_CONSTANT, value=[1, 1, 1]) return rotated
def localtoec(az, el, mjd): global convert getlocal = ephem.Observer() getlocal.lon = Dawodang.lon getlocal.lat = Dawodang.lat getlocal.elevation = 1110.028801 # altitude getlocal.temp = 25 getlocal.pressure = 1.01325e3 getlocal.epoch = ephem.J2000 #ct = time.gmtime(time.time()+delta_T) #ct3 = time.strftime("%Y/%m/%d %H:%M:%S",ct) jd = mjd + 2400000.5 date = ephem.julian_date('1899/12/31 12:00:00') djd = jd - date ct3 = ephem.Date(djd) print ct3 getlocal.date = ct3 # UT ra, dec = getlocal.radec_of(az, el) return ra, dec
def get_target_info(self, target, time_start=None, time_stop=None, time_interval=5): """Compute various values for a target from sunrise to sunset. """ def _set_time(dtime): # Sets time to nice rounded value y, m, d, hh, mm, ss = dtime.tuple() mm = mm - (mm % 5) return ephem.Date(datetime(y, m, d, hh, mm, 5, 0)) def _set_data_range(time_start, time_stop, t_ival): # Returns numpy array of dates ss = _set_time(ephem.Date(ephem.Date(time_start) - t_ival)) sr = _set_time(ephem.Date(ephem.Date(time_stop) + t_ival)) return np.arange(ss, sr, t_ival) if time_start is None: # default for start time is sunset on the current date time_start = self.sunset() if time_stop is None: # default for stop time is sunrise on the current date time_stop = self.sunrise(date=time_start) t_range = _set_data_range(self.date_to_utc(time_start), self.date_to_utc(time_stop), time_interval * ephem.minute) #print('computing airmass history...') history = [] # TODO: this should probably return a generator for ut in t_range: # ugh tup = ephem.Date(ut).tuple() args = tup[:-1] + (int(tup[-1]), ) ut_with_tz = datetime(*args).replace(tzinfo=self.tz_utc) info = target.calc(self, ut_with_tz) history.append(info) #print(('computed airmass history', self.history)) return history
def is_major_phase(date): """Returns a code if the date coincides with a major Moon phase, i.e. first quarter, full Moon, last quarter or new Moon. Keyword arguments: date -- a PyEphem Date object. """ # Calculate the exact date and time of each upcoming major Moon phase. next_new_moon = ephem.next_new_moon(date) next_first_quarter_moon = ephem.next_first_quarter_moon(date) next_full_moon = ephem.next_full_moon(date) next_last_quarter_moon = ephem.next_last_quarter_moon(date) # Format the major Moon phase dates by resetting their hour, minute and # second values to zero, positioning each day at midnight so that they can # be directly compared against the date argument. next_new_moon_date = helpers.set_date_to_midnight(next_new_moon) next_first_quarter_moon_date = helpers.set_date_to_midnight( next_first_quarter_moon) next_full_moon_date = helpers.set_date_to_midnight(next_full_moon) next_last_quarter_moon_date = helpers.set_date_to_midnight( next_last_quarter_moon) # Convert the `date` arugment to an Ephem Date for comparison. date = ephem.Date(date) # Return the appropriate code based on if there is a match. No matches will # return `None`. if (next_new_moon_date == date): return 'new_moon' if (next_first_quarter_moon_date == date): return 'first_quarter' if (next_full_moon_date == date): return 'full_moon' if (next_last_quarter_moon_date == date): return 'last_quarter' return None
def plotWeight(field, target_fields, weight, **kwargs): if isinstance(field,FieldArray): field = field[-1] date = ephem.Date(field['DATE']) if plt.get_fignums(): plt.cla() fig, basemap = obztak.utils.ortho.makePlot(date,name='weight') index_sort = np.argsort(weight)[::-1] proj = basemap.proj(target_fields['RA'][index_sort], target_fields['DEC'][index_sort]) weight_min = np.min(weight) basemap.scatter(*proj, c=weight[index_sort], edgecolor='none', s=50, vmin=weight_min, vmax=weight_min + 300., cmap='Spectral') #cut_accomplished = np.in1d(self.target_fields['ID'], self.accomplished_field_ids) #proj = obztak.utils.ortho.safeProj(basemap, self.target_fields['RA'][cut_accomplished], self.target_fields['DEC'][cut_accomplished]) #basemap.scatter(*proj, c='0.75', edgecolor='none', s=50) """ cut_accomplished = np.in1d(self.target_fields['ID'],self.accomplished_fields['ID']) proj = obztak.utils.ortho.safeProj(basemap, self.target_fields['RA'][~cut_accomplished], self.target_fields['DEC'][~cut_accomplished]) basemap.scatter(*proj, c=np.tile(0, np.sum(np.logical_not(cut_accomplished))), edgecolor='none', s=50, vmin=0, vmax=4, cmap='summer_r') proj = obztak.utils.ortho.safeProj(basemap, self.target_fields['RA'][cut_accomplished], self.target_fields['DEC'][cut_accomplished]) basemap.scatter(*proj, c=self.target_fields['TILING'][cut_accomplished], edgecolor='none', s=50, vmin=0, vmax=4, cmap='summer_r') """ # Draw colorbar in existing axis if len(fig.axes) == 2: colorbar = plt.colorbar(cax=fig.axes[-1]) else: colorbar = plt.colorbar() colorbar.set_label('Weight') # Show the selected field proj = basemap.proj([field['RA']], [field['DEC']]) basemap.scatter(*proj, c='magenta', edgecolor='none', s=50) #plt.draw() plt.pause(0.001)
def Compute(self): ''' 计算根数在对应日期内的 ''' end_time = ephem.Date("{}/{}/{} 23:59:59".format( self.year, self.month, self.day)) i = 1 while True: self.sat.compute(self.obs) if (self.sat.set_time < self.sat.rise_time) or (self.sat.rise_time > end_time): break else: # print "%d: %s, %s, %s" % (i, self.sat.rise_time, self.sat.transit_time, self.sat.set_time) set_time = self.sat.set_time # 开始: 输出星历文件 self.OutputFile(self.sat.rise_time, set_time, i) i = i + 1 # 结束: 输出星历文件 self.obs.date = set_time + ephem.minute * 1
def check_pass(self, passTime): if passTime == 0: self.OBS.date = ephem.now() elif passTime == 1: pass else: timeStr = time.strftime( '%Y/%m/%d %H:%M:%S', time.gmtime(passTime)) # UTC time string needed for ephem self.OBS.date = ephem.Date(timeStr) self.obj.update(self.OBS) self.SUN.compute(self.OBS) if (self.obj.alt > 0.175) & (self.SUN.alt < -0.1) & ( not self.obj.eclipsed ): # 0.175 = 10 degrees, 0.1 = 6 degrees return True return True else: return False
def calc_ephem(): """Calculate coordinates using PyEphem Code from http://stackoverflow.com/a/28096359/1033535 Check using: http://lambda.gsfc.nasa.gov/toolbox/tb_coordconv.cfm """ observer = ephem.Observer() observer.pressure = 0 observer.lon = str(LONGITUDE) observer.lat = str(LATITUDE) observer.elevation = ALTITUDE observer.date = ephem.Date(datetime.utcfromtimestamp(UTC)) ra, dec = observer.radec_of(H_AZIMUTH, H_ALTITUDE) # print 'Ephem: ', ra, dec # print 'Ephem: %10.6f %10.6f' % (ra.real, dec.real) print 'Ephem: %10.6f %10.6f' % (np.degrees( ra.real), np.degrees(dec.real))
def parseSatellite(filenameTLE, filenameSavedPass): tleFile = open(filenameTLE, "r") sat = ephem.readtle( tleFile.readline(), tleFile.readline(), tleFile.readline() ) tleFile.close() loc = ephem.Observer() savedPassFile = open(filenameSavedPass, "r") loc.lat = float(savedPassFile.readline()) * ephem.degree loc.lon = float(savedPassFile.readline()) * ephem.degree loc.elevation = float(savedPassFile.readline()) startTime = ephem.Date(savedPassFile.readline()) + ephem.second * 75 savedPassFile.close() return sat, loc, startTime
def test_encoding(binary_fmt): try: os.remove('test_encoding.db') except: pass db = Database(db='sqlite:///test_encoding.db', disk_threshold=None, binary_fmt=binary_fmt) ts = datetime( year=2018, month=5, day=1, hour=10, minute=20, second=30, microsecond=123000 ) #<--- microseconds are not saved atm so not having them set to zero will make test fail. blah1 = [ 'datetime', 'pandas Timestamp', 'ephem.Date', 'Just a string', 'bytearray' ] blah2 = [ ts, pd.to_datetime(ts), ephem.Date(ts), 'hello', bytearray([1, 2, 3, 4, 5, 6, 7, 8]) ] #<-- all of these will be encoded as strings db.put_df(table='test', df=pd.DataFrame(dict(blah1=blah1, blah2=blah2))) df = db.get_df(table='test') if not _NO_ASSERTS: for k in range(len(blah1)): assert (blah1[k] == df.blah1.iloc[k]) assert (blah2[k] == df.blah2.iloc[k]) print(df) return df
def __init__(self, auscale, timestep, time_increment=5, start_time=None): """time_increment is in days. start_time is a an ephem.Date object. """ super().__init__() self.auscale = auscale self.timestep = timestep self.stepping = True if start_time: self.time = start_time else: self.time = ephem.Date(datetime.now()) self.time_increment = ephem.hour * time_increment * 24 # Paths for each planet. Must save the full path # since we might need to redraw if the window gets covered. self.planet_paths = [[] for i in range(len(planets))] # Set up colors self.bg_color = Gdk.color_parse('black') self.planet_colors = [Gdk.color_parse(c) for c in planet_color_names] self.line_width = 3 self.drawing_area = Gtk.DrawingArea() self.set_default_size(1024, 768) self.add(self.drawing_area) GLib.timeout_add(self.timestep, self.idle_cb) self.drawing_area.connect('draw', self.draw) self.drawing_area.connect('configure-event', self.configure) self.connect("destroy", Gtk.main_quit) self.connect("key-press-event", self.key_press) # GLib.idle_add(self.idle_cb) self.show_all()
def __init__(self): #telescope location parameters self.telescope = ephem.Observer() self.telescope.lon = -67.7875 #degrees self.telescope.lat = -22.9586 #degrees self.telescope.elevation = 5190 #meters self.obs_date = ephem.Date('2018') self.telescope.date = self.obs_date.datetime() #input parameters for scan self.az_0 = 0. self.el_0 = 90. self.az_rng = 0.5 self.el_rng = 0.5 self.el_stp = 0.01 self.dt = 0.01 #data time interval self.f_data = 1. / self.dt self.t_end = 3600.0 #seconds #NET and noise settings self.NET = 480e-6 #K*sqrt(s) This is the NET value from POLARBEAR self.add_white_noise = False self.add_1f_noise = False #HWP and HWPSS settings self.f_hwp = 2 #Hz self.num_bolos = 1 #operational settings self.conduct_test = False #map settings map_dict = { 'commander': '/home/rashmi/maps/planck_commander_1024_full_test.fits', 'nilc': '/home/rashmi/maps/planck_nilc_1024_full_test.fits', 'sevem': '/home/rashmi/maps/planck_sevem_1024_full_test.fits', 'smica': '/home/rashmi/maps/planck_smica_1024_full_test.fits' } self.map_name = 'commander' #can change this to any of the four keys in the map_dict self.map_filename = map_dict.get(self.map_name)
def update(month): pl.clf() ax = fig.add_subplot(111, projection='mollweide', facecolor='black', alpha=0.1) plots(masks, surveys, clf=False, save=False) days = month * 30. RA, DEC = get_plane() plot_mwd(ax, np.array(RA), np.array(DEC), org=0, color='r', alpha=1.0) RA, DEC = get_plane(input=ephem.Ecliptic, output=ephem.Equatorial) plot_mwd(ax, np.array(RA), np.array(DEC), org=0, color='gold', alpha=1.0) ## ephem.Jupiter; ['red', 'o'] for body, props in zip([ephem.Sun, ephem.Moon], [['gold', '*'], ['gainsboro', 'o']]): body = body(ephem.now() + days) RA = np.array([hours2degs(str(body.ra), dec=False)]) DEC = np.array([hours2degs(str(body.dec), dec=True)]) plot_mwd(ax, RA, DEC, org=0, color=props[0], alpha=1.0, s=30, marker=props[1]) pl.title(ephem.Date(ephem.now() + days))
def predictNextPasses(satName, tleFile, nextPasses): #reading the TLE file file = open(tleFile) data = file.read().replace("\n","::") arr = data.split("::") for i in range(len(arr)): if satName.rstrip() == arr[i].rstrip(): tleOne= arr[i+1] tleTwo = arr[i+2] file.close() #initialise the ephem object satephem = ephem.readtle(satName,tleOne,tleTwo) home.elevation = 60 #next pass returns #0 Rise time #1 Rise azimuth #2 Maximum altitude time #3 Maximum altitude #4 Set time #5 Set azimuth for p in range(int(nextPasses)): tr, azr, tt, altt, ts, azs = home.next_pass(satephem) home.date = tr #set the observer date as rise time satephem.compute(home) #for every rise time compute the position print("Pass -->", p,"\n") print( "time rise -->",tr, "\n", "altitude -->",math.degrees(satephem.alt),"\n", "azimuth -->",math.degrees(satephem.az), "\n", "latitude-->",math.degrees(satephem.sublat), "\n", "longitude -->",math.degrees(satephem.sublong), "\n", "elevation -->",satephem.elevation/1000.) tr = ephem.Date(tr + 20.0 * ephem.second) print() home.date = tr + ephem.minute return
def night_times(datestr, verbose=True): obs = decam.copy() obs.date = datestr obs.horizon = 0.0 t_sunset, t_sunrise = night_start_end(obs) obs.date = t_sunset obs.horizon = -ephem.degrees('10') t_10start, t_10stop = night_start_end(obs) obs.horizon = -ephem.degrees('12') t_12start, t_12stop = night_start_end(obs) obs.horizon = -ephem.degrees('18') t_18start, t_18stop = night_start_end(obs) length = t_12stop - t_12start q1, q2, q3 = [ephem.Date(t_12start+x*length) for x in [0.25, 0.5, 0.75]] obs.horizon = -ephem.degrees('0') obs.date = t_sunset t_moonset, t_moonrise = night_start_end(obs, ephem.Moon(), sun=False) if verbose: print('Sunset: %s, Sunrise: %s' % (t_sunset, t_sunrise)) print('10 twi start: %s, 10 twi end: %s' % (t_10start, t_10stop)) print('12 twi start: %s, 12 twi end: %s' % (t_12start, t_12stop)) print('18 twi start: %s, 18 twi end: %s' % (t_18start, t_18stop)) print('moonset: %s, moonrise: %s' % (t_moonset, t_moonrise)) print('Q1: %s' % q1) print('Q2: %s' % q2) print('Q3: %s' % q3) return {'sunset': t_sunset, 'sunrise': t_sunrise, '10start': t_10start, '10stop': t_10stop, '12start': t_12start, '12stop': t_12stop, '18start': t_18start, '18stop': t_18stop, 'moonset': t_moonset, 'moonrise': t_moonrise, 'q1': q1, 'q2': q2, 'q3': q3}
def utc2local(ephem_time, time_zone, offset_minutes=0): """Convert time given by ephem.Date() in UTC to the local timezone. @param: utc_time date in format '2016/10/25 10:42:56' @param: time_zone tz object (tz.gettz) @param: offset_minutes +/- number of minutes Returns: Time stamp in given timezone '2016-10-25 07:42:55.550244-03:00' """ utc = ephem.Date(ephem_time).datetime().replace(tzinfo=tz.gettz('UTC')) local = utc.astimezone(TZ) local = local + timedelta(minutes=offset_minutes) if DEBUG: print("utc2local: offset '{}'".format(offset_minutes)) print("utc2local: utc '{}'".format(utc)) print("utc2local: local '{}'".format(local)) return local