def getGear(self,arg): data = {'acceleration':engine['acceleration'],\ 'pointError':str(ephem.degrees(self.m.axis1.minMotorStep)),\ 'vmax':str(ephem.degrees(self.m.axis1.vmax)),\ 'FullTurnSteps':self.m.axis1.FullTurnSteps} print data return json.dumps(data)
def __init__(self,config_file,base_directory='.'): #S want to get the site from the control class, makes easy computing #S LST and such self.base_directory = base_directory self.config_file = config_file self.dt_fmt = '%Y%m%dT%H:%M:%S' # load the config file self.load_config() # make the observer which will be used in calculations and what not self.obs = ephem.Observer() self.obs.lat = ephem.degrees(str(self.latitude)) # N self.obs.lon = ephem.degrees(str(self.longitude)) # E self.obs.horizon = ephem.degrees(str(self.sun_horizon)) self.obs.elevation = self.elevation # meters self.time = datetime.datetime(2000,1,1,12,00,00) self.obs.date = self.time # an ephem sun and moon object for tracking the sun self.sun = ephem.Sun() self.sun.compute(self.obs) self.moon = ephem.Moon() self.moon.compute(self.obs) # seconds between three obs self.sep_limit = 120.*60. # if you are using the simbad reader target list self.target_list = simbad_reader.read_simbad(self.targets_file) self.make_fixedBodies()
def planetstransit(date): """returns SHA and meridian passage for the navigational planets """ v = ephem.Venus() mars = ephem.Mars() j = ephem.Jupiter() sat = ephem.Saturn() obs = ephem.Observer() obs.date = date v.compute(date) vsha = nadeg(2 * math.pi - ephem.degrees(v.g_ra).norm) vtrans = time(obs.next_transit(v)) hpvenus = "%0.1f" % ((math.tan(6371 / (v.earth_distance * 149597870.7))) * 60 * 180 / math.pi) obs.date = date mars.compute(date) marssha = nadeg(2 * math.pi - ephem.degrees(mars.g_ra).norm) marstrans = time(obs.next_transit(mars)) hpmars = "%0.1f" % ((math.tan(6371 / (mars.earth_distance * 149597870.7))) * 60 * 180 / math.pi) obs.date = date j.compute(date) jsha = nadeg(2 * math.pi - ephem.degrees(j.g_ra).norm) jtrans = time(obs.next_transit(j)) obs.date = date sat.compute(date) satsha = nadeg(2 * math.pi - ephem.degrees(sat.g_ra).norm) sattrans = time(obs.next_transit(sat)) return [vsha, vtrans, marssha, marstrans, jsha, jtrans, satsha, sattrans, hpmars, hpvenus]
def click(event): global cnt if event.button == 3: lon,lat = map(event.xdata, event.ydata, inverse=True) lon = (180 + kwds['ra'] - lon) % 360 lon *= a.img.deg2rad; lat *= a.img.deg2rad ra,dec = ephem.hours(lon), ephem.degrees(lat) xpx = n.around(event.xdata / (kwds['d_ra'] * a.img.deg2rad)) ypx = n.around(event.ydata / (kwds['d_dec'] * a.img.deg2rad)) flx = d[ypx,xpx] if opts.mode.startswith('log'): flx = 10**flx print '#%d (RA,DEC): (%s, %s), PX: (%d,%d) Jy: %f' % \ (cnt, ra, dec, xpx, ypx, flx) cnt += 1 elif event.button == 2: p.figure(200) lon,lat = map(event.xdata, event.ydata, inverse=True) p.plot(cube[lat,lon,:]) lon = (180 + kwds['ra'] - lon) % 360 lon *= a.img.deg2rad; lat *= a.img.deg2rad ra,dec = ephem.hours(lon), ephem.degrees(lat) xpx = n.around(event.xdata / (kwds['d_ra'] * a.img.deg2rad)) ypx = n.around(event.ydata / (kwds['d_dec'] * a.img.deg2rad)) flx = d[ypx,xpx] if opts.mode.startswith('log'): flx = 10**flx p.title('#%d (RA,DEC): (%s, %s), PX: (%d,%d) Jy: %f' % \ (cnt, ra, dec, xpx, ypx, flx)) cnt += 1 else: return
def __init__(self, ra=None, dec=None, obj=None, session=None): """Tracks an object in the sky and collects data. Takes either a pyephem object, or a ra and dec (not both) Arguments: ra (radians): Right ascension of object dec (radians): Declination of object obj (ephem.Body): Pyephem object session (str): Name of observing session (name of data file) """ self.obs = ephem.Observer() self.obs.long, self.obs.lat = ephem.hours(np.deg2rad(LONG)), ephem.degrees(np.deg2rad(LAT)) logger.info("Observer set at (long, lat): {long_}, {lat}".format(long_=self.obs.long, lat=self.obs.lat)) if obj and not (ra or dec): self.source = obj elif (ra and dec) and not obj: self.source = ephem.FixedBody() self.source._ra = ephem.hours(ra) self.source._dec = ephem.degrees(dec) self.source._epoch = ephem.J2000 # for precessing else: raise Exception("Only use either (ra, dec) or an ephem obj.") self.last_home = None self.session = session
def print_pyephem_parallactic_angle(): lat = 19.826218*u.deg lon = -155.471999*u.deg time = Time('2015-01-01 00:00:00') LST = time.sidereal_time('mean', longitude=lon) desired_HA_1 = 3*u.hourangle desired_HA_2 = 19*u.hourangle # = -5*u.hourangle obs = ephem.Observer() obs.lat = '19:49:34.3848' obs.lon = '-155:28:19.1964' obs.elevation = 0 obs.date = time.datetime pyephem_target1 = ephem.FixedBody() pyephem_target1._ra = ephem.degrees((LST - desired_HA_1).to(u.rad).value) pyephem_target1._dec = ephem.degrees((-30*u.deg).to(u.rad).value) pyephem_target1.compute(obs) pyephem_q1 = (float(pyephem_target1.parallactic_angle())*u.rad).to(u.deg) pyephem_target2 = ephem.FixedBody() pyephem_target2._ra = ephem.degrees((LST - desired_HA_2).to(u.rad).value) pyephem_target2._dec = ephem.degrees((-30*u.deg).to(u.rad).value) pyephem_target2.compute(obs) pyephem_q2 = (float(pyephem_target2.parallactic_angle())*u.rad).to(u.deg) print(pyephem_q1, pyephem_q2) assert (obs.astropy_to_local_time(obs.local_to_astropy_time(dt)).replace( tzinfo=None) == dt)
def dname(dec): one = str((int(str(ephem.degrees(dec*n.pi/180)).split(':')[0])+100000))[-2::] two = str((int(str(ephem.degrees(dec*n.pi/180)).split(':')[1])+100000))[-2::] if dec < 0: add = '-' else: add = '+' ret = add + one + two return ret
def print_pyephem_vega_rise_set(): """ To run: python -c 'from astroplan.tests.test_observer import print_pyephem_vega_rise_set as f; f()' """ lat = '00:00:00' lon = '00:00:00' elevation = 0.0 * u.m pressure = 0 time = Time('2000-01-01 12:00:00') vega_ra, vega_dec = (279.23473479*u.degree, 38.78368896*u.degree) vega = SkyCoord(vega_ra, vega_dec) obs = ephem.Observer() obs.lat = lat obs.lon = lon obs.elevation = elevation obs.date = time.datetime obs.pressure = pressure target = ephem.FixedBody() target._ra = ephem.degrees(vega.ra.radian) target._dec = ephem.degrees(vega.dec.radian) target.compute(obs) next_rising = obs.next_rising(target).datetime() next_setting = obs.next_setting(target).datetime() prev_rising = obs.previous_rising(target).datetime() prev_setting = obs.previous_setting(target).datetime() print(map(repr, [next_rising, next_setting, prev_rising, prev_setting]))
def run(self): # Pegando as informações self.get_info() # Criando um Observatório self.set_observer(self.longitude, self.latitude, self.elevation) while True: now_datetime = datetime.utcnow() self.obs.date = ephem.date(now_datetime) sun = ephem.Sun(self.obs) moon = ephem.Moon(self.obs) frac = moon.moon_phase sun_alt = ephem.degrees(sun.alt) moon_alt = ephem.degrees(moon.alt) sun_elevation = "{:.2f}º".format(float(math.degrees(sun_alt))) moon_elevation = "{:.2f}º".format(float(math.degrees(moon_alt))) moon_phase = "{0:.2f}%".format(frac * 100) self.signal_update_sun_moon.emit([sun_elevation, moon_elevation, moon_phase]) time.sleep(1)
def print_pyephem_vega_sirius_transit(): """ To run: python -c 'from astroplan.tests.test_observer import print_pyephem_vega_sirius_transit as f; f()' """ lat = '47:36:34.92' lon = '122:19:59.16' elevation = 0.0 * u.m pressure = 0 time = Time('1990-01-01 12:00:00') vega_coords = SkyCoord(279.23473479*u.degree, 38.78368896*u.degree) sirius_coords = SkyCoord(101.28715533*u.degree, -16.71611586*u.degree) obs = ephem.Observer() obs.lat = lat obs.lon = lon obs.elevation = elevation obs.date = time.datetime obs.pressure = pressure vega = ephem.FixedBody() vega._ra = ephem.degrees(vega_coords.ra.radian) vega._dec = ephem.degrees(vega_coords.dec.radian) vega.compute(obs) sirius = ephem.FixedBody() sirius._ra = ephem.degrees(sirius_coords.ra.radian) sirius._dec = ephem.degrees(sirius_coords.dec.radian) sirius.compute(obs) vega_next_transit = obs.next_transit(vega).datetime() sirius_next_transit = obs.next_transit(sirius).datetime() print(map(repr, [vega_next_transit, sirius_next_transit]))
def mpcOutput(self,data): #TODO adapt data prior to invoke. import ephem out='' for d in data: fecha=d['DATETIME'][0:10].replace('-',' ') hh=float(d['DATETIME'][11:13]) mm=float(d['DATETIME'][14:16]) ss=float(d['DATETIME'][17:19]) #print d['KEY'],fecha,hh,mm,ss,ephem.hours(ephem.degrees(str(d['RA']))),ephem.degrees(str(d['DEC'])) hhdec=round((hh*3600.+mm*60.+ss)/(24*3600)*100000,0) fecha=fecha+'.'+"%05.0f" % (hhdec)+" " id=d['KEY'] ra_hh,ra_mm,ra_ss=("%11s" % ephem.hours(ephem.degrees(str(d['RA'])))).split(':') #print ra_hh,ra_mm,ra_ss ra="%02d %02d %04.1f" % (float(ra_hh),float(ra_mm),float(ra_ss)) dec_dd,dec_mm,dec_ss=("%11s" % ephem.degrees(str(d['DEC']))).split(':') #print dec_dd,dec_mm,dec_ss dec="%+03d %02d %05.2f" % (float(dec_dd),float(dec_mm),float(dec_ss)) #print ra,"/",dec #rastr="%11s" % (ephem.degrees(str(d['DEC']))) #decstr="%11s" % (ephem.degrees(str(d['DEC']))) #ra=rastr.replace(':',' ') #dec=decstr.replace(':',' ') #id=d['INT_NUMBER'][-7:] #[MPnumber,Provisional,Discovery,Note1,Note2,Date,RA,DEC,Mag,Band,Observatory] # 492A002 C2014 09 03.13366 03 57 53.26 +05 44 22.9 18.6 V J75 # K07VF3N C2014 09 14.83670 0 53 58.89 0 07 53.1 20.2 V J75 obs=('',id,'','','C',fecha,ra,dec,d['MAG'],'V','J75') out+='%5s%7s%1s%1s%1s%16s%-12s%-12s %5.1f %1s %3s\n' % obs return out
def _compute_elevations(self, date): """Compute the object and solar elevation across Earth using PyEphem""" # Sun Pyephem object sun = ephem.Sun() result = [] # list containing radiant altitudes (or NaN if daylight) for lat in self.latitudes: for lon in self.longitudes: # Create a PyEphem "Observer" object at the given lon/lat observer = ephem.Observer() observer.lat = ephem.degrees('%s' % lat) observer.long = ephem.degrees('%s' % lon) observer.date = date # Compute target and solar elevation self.target.compute(observer) target_alt = np.degrees(self.target.alt) sun.compute(observer) sun_alt = np.degrees(sun.alt) if sun_alt > -6 or target_alt < 0: result.append(np.NaN) else: result.append(target_alt) # Return the result as a matrix return np.array(result).reshape(len(self.latitudes), len(self.longitudes))
def string2RADEC(st): '''Given a string, try to convert into internal ephem angle.''' fields = map(str,st.strip().split()) if len(fields) == 2: # Try RA DEC in decimal degrees try: RA,DEC = map(float, fields) return RA,DEC except: # Try as sexadecimal notation try: RA,DEC = hours(fields[0]),degrees(fields[1]) return RA*180/pi,DEC*180/pi except: # Fail! return None,None elif len(fields) in [4,6]: # assume RA and DEC have the same number of fields try: nf = len(fields) RA = ":".join(fields[0:nf/2]) DEC = ":".join(fields[nf/2:]) RA,DEC = hours(RA)*180/pi,degrees(DEC)*180/pi return RA,DEC except: # Fail! return None,None else: # Dunno! return None,None
def extract(self): if not self.active: return default ret = default ## do some tests on the data try: if self.ra < 0.0 or self.ra >= 360.0: ret.update({'ra': None}) else: ret.update({'ra': ephem.degrees(str(self.ra))}) except: ret.update({'ra': None}) try: if self.dec < -90.0 or self.dec > 90.0: ret.update({'dec': None}) else: ret.update({'dec': ephem.degrees(str(self.dec))}) except: ret.update({'dec': None}) if ret['dec'] is not None and ret['ra'] is not None: np = ephem.Equatorial(ret['ra'],ret['dec'],epoch='2000') else: return ret g = ephem.Galactic(np) e = ephem.Ecliptic(np) ret = {'galb': rad2deg*float(g.lat), 'gall': rad2deg*float(g.long), \ 'ecb': rad2deg*float(e.lat), 'ecl': rad2deg*float(e.long), \ 'ra': rad2deg*float(np.ra), 'dec': rad2deg*float(np.dec)} return ret
def day_night(sdate, edate, alma): datet = alma.date alma.horizon = ephem.degrees(str('-20')) obj = ephem.Sun() alma.date = sdate lst_start = alma.sidereal_time() sun_set = alma.next_setting(obj) alma.date = sun_set alma.horizon = ephem.degrees(str('0')) lst_dark = alma.sidereal_time() alma.horizon = ephem.degrees(str('-20')) alma.date = edate lst_end = alma.sidereal_time() sun_rise = alma.previous_rising(obj) alma.date = sun_rise alma.horizon = ephem.degrees(str('0')) lst_dawn = alma.sidereal_time() alma.date = datet lst_start = np.rad2deg(lst_start) / 15. lst_dark = np.rad2deg(lst_dark) / 15. lst_end = np.rad2deg(lst_end) / 15. lst_dawn = np.rad2deg(lst_dawn) / 15. return pd.Series([lst_start, lst_dark, lst_end, lst_dawn], index=['lst_start', 'lst_dusk', 'lst_end', 'lst_dawn'])
def ellipse(self): # An approximation to the DECam field of view, suitable e.g. for plotting semimajor_deg = ephem.degrees('1.08') semiminor_deg = ephem.degrees('0.98') center = (self.ra, self.dec) rotation = 0 return Ellipse(center, 2*semimajor_deg, 2*semiminor_deg, rotation)
def hadec2altaz(obs, ha, dec): """Convert (ha, dec) to (alt, az) Inputs, outputs same as radec2altaz(obs, ra, dec) except replacing ra with ha ha: hour angle in RADIANS, may use ephem.hours, degrees """ lat = obs.lat x = np.cos(dec) * np.cos(ha) y = np.cos(dec) * np.sin(ha) z = np.sin(dec) vec = np.array([x,y,z]) # TODO: don't keep regenerating this matrix # Ideally we would calculate by hand the simplest possible transformation # But I'm too lazy and it doesn't really matter # Not important since I don't use this for actual observation rotmat = np.array( [[-1*np.sin(lat), 0., np.cos(lat)], [0., -1., 0.], [np.cos(lat), 0., np.sin(lat)]]) vec_rot = np.dot(rotmat, vec) alt = np.arcsin(vec_rot[2]) az = np.arctan2(vec_rot[1], vec_rot[0]) if az < 0: az = az + 2*np.pi return (ephem.degrees(alt), ephem.degrees(az))
def _createObserver(self, elevation, latitude, longitude, horizon, temp, pressure): self.long = ephem.degrees(str(longitude)) self.lat = ephem.degrees(str(latitude)) self.elevation = float(elevation) self.horizon = str(horizon) self.temp = float(temp) #temperature will be corrected by PLC later self.pressure = float(pressure)
def get_schedule_by_priority(src_data, config): N_src = np.shape(src_data)[0] print "Using schedule by priority algorithm for %s sources" % N_src src_data = np.column_stack((src_data, np.zeros(N_src, dtype=int))) start_date_time, end_date_time = obsim.get_start_end_dates(config) tz_offset = config['time_zone'] * ephem.hour wait_time = config['priority_wait_time'] * ephem.second loc = obsim.init_loc(config) src = obsim.init_src() # Initializing current position and time curr_time = start_date_time curr_tel_pos = [ ephem.degrees(str(config["telescope_azimuth"])), ephem.degrees(str(config["telescope_altitude"])) ] slew_rate = [ config["slew_rate_az"], config["slew_rate_alt"] ] schedule = [] while (curr_time < end_date_time): schedule, status = get_next_src(src_data, N_src, src, loc, curr_time, tz_offset, curr_tel_pos, slew_rate, schedule) if (status[0]): src_data[status[1]][7] = 1 curr_time = status[2] curr_tel_pos = [status[3], status[4]] else: from_time_local = ephem.Date(curr_time + tz_offset) curr_time = ephem.Date(curr_time + wait_time) if (curr_time > end_date_time): curr_time = end_date_time curr_time_local = ephem.date(curr_time + tz_offset) time_diff = (curr_time_local - from_time_local)*24.*3600 schedule.append( [ 'Wait', str(from_time_local), str(curr_time_local), int(round(time_diff)), '0', '0' ] ) return schedule
def __init__(self, name, timezone=None, longitude=None, latitude=None, elevation=None, pressure=None, temperature=None, date=None, description=None): super(Observer, self).__init__() self.name = name self.timezone = timezone self.longitude = longitude self.latitude = latitude self.elevation = elevation self.pressure = pressure self.temperature = temperature self.date = date self.horizon = -1 * np.sqrt(2 * elevation / ephem.earth_radius) if timezone is None: # default to UTC timezone = pytz.timezone('UTC') self.tz_local = timezone self.tz_utc = pytz.timezone('UTC') self.site = self.get_site(date=date) # used for sunset, sunrise calculations self.horizon6 = -1.0 * ephem.degrees('06:00:00.0') self.horizon12 = -1.0 * ephem.degrees('12:00:00.0') self.horizon18 = -1.0 * ephem.degrees('18:00:00.0') self.sun = ephem.Sun() self.moon = ephem.Moon() self.sun.compute(self.site) self.moon.compute(self.site)
def calc_airmass(self, alt): """Compute airmass""" if alt < ephem.degrees('03:00:00'): alt = ephem.degrees('03:00:00') sz = 1.0/np.sin(alt) - 1.0 xp = 1.0 + sz*(0.9981833 - sz*(0.002875 + 0.0008083*sz)) return xp
def secz(alt): """Compute airmass""" if alt < E.degrees('03:00:00'): alt = E.degrees('03:00:00') sz = 1.0/np.sin(alt) - 1.0 xp = 1.0 + sz*(0.9981833 - sz*(0.002875 + 0.0008083*sz)) return xp
def click(event): global cnt if event.button == 3: lon,lat = map(event.xdata, event.ydata, inverse=True) print event.xdata,type(event.xdata) if opts.osys == 'eq': lon = (360 - lon) % 360 lon *= a.img.deg2rad; lat *= a.img.deg2rad ra,dec = ephem.hours(lon), ephem.degrees(lat) x,y,z = a.coord.radec2eq((ra,dec)) flx = h[(x,y,z)] print '#%d (RA,DEC): (%s, %s), Jy: %f' % (cnt, ra, dec, flx) cnt += 1 elif event.button==2: lon,lat = map(event.xdata, event.ydata, inverse=True) if opts.osys == 'eq': lon = (360 - lon) % 360 lon *= a.img.deg2rad; lat *= a.img.deg2rad ra,dec = ephem.hours(lon), ephem.degrees(lat) x,y,z = a.coord.radec2eq((ra,dec)) #flx = h[(x,y,z)] crd = [mk_arr(c, dtype=n.double) for c in (x,y,z)] px,wgts = h.crd2px(*crd, **{'interpolate':1}) flx = n.sum(h[px],axis=-1) print '#%d (RA,DEC): (%s, %s), Jy: %f (4px sum)' % (cnt, ra, dec, flx) cnt += 1 else: return
def lbdeg2radec(l, b): """Takes galactic coords in degrees (floats), output ephem.Angle() ra/dec """ l_r = ephem.degrees(str(l)) b_r = ephem.degrees(str(b)) c = ephem.Equatorial(ephem.Galactic(l_r, b_r, epoch=ephem.J2000)) return c.ra, c.dec
def compute_chip(rockra, rockdec, expra, expdec): deltara = 180/np.pi*ephem.degrees(rockra-expra).znorm # compute difference in degrees (normalized between -180, +180) deltadec = 180/np.pi*ephem.degrees(rockdec-expdec).znorm # the 180/pi is because ephem.Angle objects are natively in radians ccdname = 'None' for k in ccdBounds.keys(): if deltara > ccdBounds[k][0] and deltara < ccdBounds[k][1] and deltadec > ccdBounds[k][2] and deltadec < ccdBounds[k][3]: ccdname = k return ccdname
def main(): # Try some SN fields: C1 = ephem.readdb("C1,f,03:37:05.83,-27:06:41.8,23.0,2000") C1.compute() C1field = DECamField(C1.ra, C1.dec) print C1field.ra, C1field.dec print C1field.contains(C1.ra, C1.dec+ephem.degrees('0.979')) print C1field.contains(ephem.degrees('04:00:00'),ephem.degrees('-30:00:00'))
def make_cat(infile): df = pd.read_csv(infile) # rename some columns: df.rename(columns={'date_obs':'date', 'snobjid':'objid', 'snfake_id':'fakeid'}, inplace=True) df['ra'] = df.apply(lambda row: hours(degrees(str(row['ra']))), axis=1) df['dec'] = df.apply(lambda row: degrees(str(row['dec'])), axis=1) df['date'] = df.apply(lambda row: toDateTime(row['date']), axis=1) return df
def riseset(year, month, day, position): thob = ephem.Observer() thob.long = ephem.degrees("-119.1773417") thob.lat = ephem.degrees("34.467028") thob.elevation = 504.4 #thob.date = "2017/8/21" #sun = ephem.Sun(thob) a = [] t = range(0,1440) #np.array([datetime.datetime(2016,4,6,i,m,0) for i in range(24) for m in range(60)]) for d in [datetime.datetime(year,month,day,i,m,0) for i in range(24) for m in range(60)]: thob.date = d sun = ephem.Sun(thob) #put coordinate of star here a.append(sun.alt + np.radians(0.25)) a = np.array(a) t = np.array(t) pl.title('The Altitude of the Sun') pl.ylabel('Time in minutes',) pl.xlabel('Altitude') pl.plot(a, t, 'ro')#, xnew, ynew, '-') pl.axvline(x=0, color = 'b',linestyle = 'dashdot') pl.axvline(x=-0.20943951,color = 'b',linestyle = 'dashdot') pl.axvline(x=-0.314159265, color = 'b',linestyle = 'dashdot') inds, = np.where((a>-0.4) & (a<0.1)) pl.plot(a[inds],t[inds],'ko') pl.show() m = np.diff(a[inds]) rinds = np.where(m > 0) risea = a[inds][rinds] riset = t[inds][rinds] risefunc = interpolate.interp1d(risea, riset) risetime = risefunc(np.radians(position)) risehour = risetime//60 riseminute = risetime % 60 risesecond = int((risetime - int(risetime))*60) sunrise = '%d:%d:%d' % (risehour, riseminute, risesecond) sinds = np.where(m < 0) seta = a[inds][sinds] sett = t[inds][sinds] setfunc = interpolate.interp1d(seta, sett) settime = setfunc(np.radians(position)) sethour = settime//60 setminute = settime % 60 setsecond = int((settime - int(settime))*60) sunset = '%d:%d:%d' % (sethour, setminute, setsecond) return sunrise, sunset
def createVisibleSatsFile(observer, satSystem, listSat, predDates, elevation, azimuth, cutoff, verbose=False): ''' createVisibleSatsFile writes info to a file Parameters: observer: info about the observation station and date satSystem: used satellite system listSat: list of satellites predDates: contains the prediction dates elevation, azimuth contain the angles (elevation only if greater than cutoff angle) ''' filename = observer.name + '-' + satSystem.replace(',', '-') + '-%04d%02d%02d.txt' % (observer.getYMD()) if verbose: print(' Creating visibility file: %s' % filename) try: fid = open(filename, 'w') # write the observer info out fid.write('Observer: %s\n' % observer.name) fid.write(' lat: %s\n' % ephem.degrees(observer.lat)) fid.write(' lon: %s\n' % ephem.degrees(observer.lon)) fid.write(' date: %04d/%02d/%02d' % observer.getYMD()) fid.write(' cutoff: %2d\n\n' % cutoff) # write the sat IDs on first line satLine1 = '' satLine2 = '' for j, sat in enumerate(listSat): if len(sat.name) < 11: satLine1 += ' %10s' % sat.name else: satLine1 += ' %10s' % sat.name[:10] endChar = min(20, len(sat.name)) satLine2 += ' %10s' % sat.name[10:endChar] fid.write(' |#Vis|%s' % satLine1) fid.write('\n') if len(satLine2) > 0: fid.write(' %s' % satLine2) fid.write('\n') fid.write('\n') # print the number of visible SVs and their elev/azim for i, predDate in enumerate(predDates): fid.write('%02d:%02d' % (predDate.hour, predDate.minute)) # number of visible satellites fid.write(' | %2d |' % np.count_nonzero(~np.isnan(elevation[i, :]))) for j, sat in enumerate(listSat): if math.isnan(elevation[i, j]): fid.write(' ---- -----') else: fid.write(' %4.1f %5.1f' % (elevation[i, j], azimuth[i, j])) fid.write('\n') # close the file fid.close() except IOError: print(' Access to file %s failed' % filename)
def __init__(self, latitude, longitude, elevation, horizon, output_base): self.proc = None self.frequency = None self.observer = ephem.Observer() self.observer.lat = ephem.degrees(latitude) self.observer.long = ephem.degrees(longitude) self.observer.elevation = float(elevation) self.observer.horizon = ephem.degrees(horizon) self.output_base = output_base
def extend(target, year='Y4', chisq_cut=10, teff_min=0.3): ''' Identifies matches to the target object in the SE catalog from the given year and returns them as a dataframe. :param target: dataframe of observations :param year: DES observing year to be searched, e.g. 'Y4' :param chisq_cut: delta_chisq cut for matches, default=10 :param teff_min: minimum t_eff of exposures to consider :return: dataframe of matches ''' matched_good = pd.DataFrame() orbit = getOrbit(target) search_exps = search_exposures(target, orbit, year=year, teff_min=teff_min) if len(search_exps): print 'Number of exposures to be searched: ', len(search_exps) print (search_exps[['expnum', 'date','band','ccd','nite','t_eff','fwhm_asec']]).head(20) matched_obs = find_observations(search_exps, target, orbit, year=year, nsigma=5) else: matched_obs = [] print 'No exposures to search' if len(matched_obs): matched_obs['ccd'] = matched_obs.apply(lambda row: get_ccd(row, search_exps), axis=1) matched_obs['ccd'] = matched_obs['ccd'].astype(int) matched_good = matched_obs[matched_obs['delta_chisq'] < chisq_cut] print 'Number of good matches: ', len(matched_good) if len(matched_good) > 0: matched_good['date'] = matched_good.apply(lambda row: str(ephem.date(row['date'])), axis=1) matched_good['ra'] = matched_good.apply(lambda row: str(ephem.hours(np.radians(row['ra']))), axis=1) matched_good['dec'] = matched_good.apply(lambda row: str(ephem.degrees(np.radians(row['dec']))), axis=1) try: matched_good['mag'] = matched_good.apply(lambda row: round(mag_calib(row), 2), axis=1) except TypeError as e: print e return matched_good
def xy2radec(x, y): lon, lat = map(x, y, inverse=True) lon = (180 + kwds['ra'] - lon) % 360 #lon = (360 - lon) % 360 lon *= a.img.deg2rad lat *= a.img.deg2rad ra, dec = ephem.hours(lon), ephem.degrees(lat) return ra, dec
def above_horizon(target, observer, horizon=20.0, duration=0.0): """Check target visibility. Utility function to calculate ephem horizontal coordinates """ # use local copies so you do not overwrite target time attribute horizon = ephem.degrees(str(horizon)) # must be celestial target (ra, dec) # check that target is visible at start of track start_ = timestamp2datetime(time.time()) [azim, elev] = _horizontal_coordinates(target, observer, start_) user_logger.trace( "TRACE: target at start (az, el)= ({}, {})".format(azim, elev) ) if not elev > horizon: return False # check that target will be visible at end of track if duration: end_ = timestamp2datetime(time.time() + duration) [azim, elev] = _horizontal_coordinates(target, observer, end_) user_logger.trace( "TRACE: target at end (az, el)= ({}, {})".format(azim, elev) ) return elev > horizon return True
def getBearingFromPoint(ra1, dec1, ra2, dec2, ): """ Given ephem.Angle instances for two sets of RA/dec values, compute the initial bearing and distance of the second point from the first. From: http://www.movable-type.co.uk/scripts/latlong.html """ # Distance (via PyEphem) distance = ephem.separation((ra1,dec1), (ra2,dec2)) # Bearing bearing = math.atan2(math.sin(ra2-ra1)*math.cos(dec2), math.cos(dec1)*math.sin(dec2)-math.sin(dec1)*math.cos(dec2)*math.cos(ra2-ra1)) return ephem.degrees(bearing), ephem.degrees(distance)
def test_observer(self): """Test the ephem.Observer portion of an LWAStation.""" lwa1 = stations.lwa1 jov = ephem.Jupiter() lwa1.date = '2013/7/10 22:07:07' lwa1.compute(jov) # RA/Dec self.assertAlmostEqual(jov.ra, ephem.hours('6:14:41.01'), 6) self.assertAlmostEqual(jov.dec, ephem.degrees('23:11:49.1'), 6) #Az/Alt self.assertAlmostEqual(jov.az, ephem.degrees('274:40:27.7'), 6) self.assertAlmostEqual(jov.alt, ephem.degrees('37:24:10.5'), 6)
def doSteps(self, delta): #Distribute steps on #delta is in radians. Calculate actual steps steps = delta / self.minMotorStep + self.stepsRest Isteps = round(steps) #acumultate the fractional part to the next step self.stepsRest = steps - Isteps if self.log: motorBeta = float(self.motorBeta) * self.minMotorStep self.saveDebug(self.stepTarget - self.motorBeta, motorBeta) #self.saveDebug(self.deltavFine,motorBeta) #self.saveDebug(self.stepTarget,motorBeta) #calculate direction of motion '''Now is done in setPWMSpeed() ''' #calculate target steps self.stepTarget = self.stepTarget + Isteps self.deltavFine = ephem.degrees(self.beta - self.motorBeta * self.minMotorStep) self.setPWMspeed(self.v + self.deltavFine) #self.setPWMspeed(self.v) '''
def __init__(self, site_info, date): """Computes an astronomical almanac for a given site and date""" self.site_info = site_info self.site = site_info.observer() self.localdate = date self.ltz = timezone(self.site_info.timezone) self.utc = timezone('UTC') self.date = self.local2utc(date) self.site.date = self.date self.horizon = self.site.horizon self.horizon12 = -1.0 * E.degrees('12:00:00.0') self.horizon18 = -1.0 * E.degrees('18:00:00.0') self.sun = E.Sun() self.moon = E.Moon() self.sun.compute(self.site) self.moon.compute(self.site)
def gearInit(self): self.socketHUBCmd.send('@getGear') reply = self.socketHUBCmd.recv() print(reply) reply = json.loads(reply) self.pointError = ephem.degrees(str(reply['pointError'])) print(self.pointError)
def above_horizon(target, observer, horizon=20.0, duration=0.0): """Check target visibility.""" # use local copies so you do not overwrite target time attribute horizon = ephem.degrees(str(horizon)) if type(target) is not ephem.FixedBody: # anticipate katpoint special target for AzEl targets if 'alt' not in vars(target): raise RuntimeError('Unknown target type, exiting...') # 'StationaryBody' objects do not have RaDec coordinates # check pointing altitude is above minimum elevation limit return bool(target.alt >= horizon) # must be celestial target (ra, dec) # check that target is visible at start of track start_ = timestamp2datetime(time.time()) [azim, elev] = __horizontal_coordinates__(target, observer, start_) user_logger.trace("TRACE: target at start (az, el)= ({}, {})".format( azim, elev)) if not elev > horizon: return False # check that target will be visible at end of track if duration: end_ = timestamp2datetime(time.time() + duration) [azim, elev] = __horizontal_coordinates__(target, observer, end_) user_logger.trace("TRACE: target at end (az, el)= ({}, {})".format( azim, elev)) return elev > horizon return True
def test_drx_alt_update(self): """Test updating TRK_RADEC values with other phase centers.""" project = idf.parse_idf(altFile) project.runs[0].scans[0].start = "MST 2011 Feb 23 17:00:15" project.runs[0].scans[0].duration = timedelta(seconds=15) project.runs[0].scans[0].frequency1 = 75e6 project.runs[0].scans[0].frequency2 = 76e6 project.runs[0].scans[0].ra = ephem.hours('5:30:00') project.runs[0].scans[0].dec = ephem.degrees('+22:30:00') project.runs[0].scans[0].alt_phase_centers[0].ra = ephem.hours( '5:35:00') project.runs[0].scans[0].alt_phase_centers[1].ra = ephem.hours( '5:25:00') self.assertEqual(project.runs[0].scans[0].mjd, 55616) self.assertEqual(project.runs[0].scans[0].mpm, 15000) self.assertEqual(project.runs[0].scans[0].dur, 15000) self.assertEqual(project.runs[0].scans[0].freq1, 1643482384) self.assertEqual(project.runs[0].scans[0].freq2, 1665395482) self.assertAlmostEqual(project.runs[0].scans[0].ra, 5.5, 6) self.assertAlmostEqual(project.runs[0].scans[0].dec, 22.5, 6) self.assertAlmostEqual( project.runs[0].scans[0].alt_phase_centers[0].ra, 5.583333, 6) self.assertAlmostEqual( project.runs[0].scans[0].alt_phase_centers[1].ra, 5.416667, 6)
def make_fixedBodies(self): for target in self.target_list: target['fixedbody'] = ephem.FixedBody() target['fixedbody']._ra = ephem.hours(target['ra']) target['fixedbody']._dec = ephem.degrees(target['dec']) # target['fixedbody']._epoch = 2000.0 target['fixedbody'].compute(self.obs)
def arduinoToStellarium(pAzimuth, pAltitude): s = str( home.radec_of(float(ephem.degrees(pAzimuth)), float(ephem.degrees(pAltitude)))) home.date = datetime.datetime.utcnow() pos = home.radec_of(float(ephem.degrees(str(pAzimuth))), float(ephem.degrees(str(pAltitude)))) if args.verbose: print('arduinoToStellarium Az/pAltitude: ' + str(pAzimuth) + ' / ' + str(pAltitude)) print('arduinoToStellarium Ra/Dec: ' + str(pos[0]) + ' / ' + str(pos[1])) #print(float(pos[0])*180/M_PI) #print(float(pos[1])*180/M_PI) return angleToStellarium(pos[0]), angleToStellarium(pos[1])
def solve_coordinates(self, index): self.observer = Observer() (lon, lat, ele) = self.get_location() self.observer.lon = degrees(lon) self.observer.lat = degrees(lat) self.observer.elevation = ele self.observer.date = now() self.observer.epoch = now() for i in range(index): self.pyephem_routine(self.show_satellite_list[i], self.tle_first_line_list[i], self.tle_second_line_list[i])
def genStars(star_table): """pyephem_objs = genStars(star_table) given a star_table returned by parseCodex (or initStarTable) returns a list of pyephem objects for every object in the table Inputs star_table - astropy Table that must have the RA and Dec in sexigresimal format with each column for each part of the coordinates separate """ stars = [] if 'name' in star_table.colnames: for i in range(0, len(star_table['name'])): star = ephem.FixedBody() star.name = star_table['name'][i] star._ra = ephem.hours( str(":".join([ star_table["RA hr"][i], star_table["RA min"][i], star_table["RA sec"][i] ]))) star._dec = ephem.degrees( str(":".join([ star_table["Dec deg"][i], star_table["Dec min"][i], star_table["Dec sec"][i] ]))) stars.append(star) return stars
def ephem_string(self): string = [] string.append(self.name) try: string.append("f|" + sac_to_ephem_dict[self.body_type]) except KeyError: string.append("f|T") string.append(str(ephem.hours(self.ra))) string.append(str(ephem.degrees(self.dec))) string.append(str(self.mag)) string.append("2000") max_s = self.size_max if len(max_s) == 0: fp = 0 elif max_s[-1] == 'm': #arcmin fp = float(max_s[:-1]) / 3437.74677078 elif max_s[-1] == 's': #arcsec fp = float(max_s[:-1]) / 206264.806247 elif max_s[-1] == 'd': #degree fp = float(max_s[:-1]) / 57.2957795131 else: raise ValueError("Unkwnown format for size_max: " + max_s) string.append(str(fp * 206264.806247)) return ','.join(string)
def get_pyephem_instance_for_type(target): """ Constructs a pyephem body corresponding to the proper object type in order to perform positional calculations for the target :returns: FixedBody or EllipticalBody :raises Exception: When a target type other than sidereal or non-sidereal is supplied """ if target.type == target.NON_SIDEREAL: body = ephem.EllipticalBody() body._inc = ephem.degrees( target.inclination) if target.inclination else 0 body._Om = target.lng_asc_node if target.lng_asc_node else 0 body._om = target.arg_of_perihelion if target.arg_of_perihelion else 0 body._a = target.semimajor_axis if target.semimajor_axis else 0 body._M = target.mean_anomaly if target.mean_anomaly else 0 if target.ephemeris_epoch: epoch_M = Time(target.ephemeris_epoch, format='jd') epoch_M.format = 'datetime' body._epoch_M = ephem.Date(epoch_M.value) else: body._epoch_M = ephem.Date(DEFAULT_VALUES['epoch']) body._epoch = target.epoch if target.epoch else ephem.Date( DEFAULT_VALUES['epoch']) body._e = target.eccentricity if target.eccentricity else 0 return body else: raise Exception( "Object type is unsupported for visibility calculations")
def test_attributes(self): """Test aipy.phs.RadioFixedBody attributes""" epoch = ephem.B1950 s = a.phs.RadioFixedBody('0:00', '0:00', mfreq=.200, name='src1', epoch=epoch, ionref=(.0, .0), srcshape=(.003, .005, .6)) self.assertEqual(s._ra, ephem.hours('0:00')) self.assertEqual(s._dec, ephem.degrees('0:00')) self.assertEqual(s.mfreq, .200) self.assertEqual(s.src_name, 'src1') self.assertAlmostEqual(s._epoch, epoch, 3) self.assertEqual(s.ionref, [.0, .0]) self.assertEqual(s.srcshape, [.003, .005, .6]) self.assertRaises(RuntimeError, lambda: s.ra) self.assertRaises(RuntimeError, lambda: s.dec) self.assertRaises(AttributeError, lambda: s.map) o = a.phs.ArrayLocation(('0:00', '0:00')) o.set_ephemtime(epoch) s.compute(o) self.assertEqual(len(s.get_crds('eq', ncrd=2)), 2) self.assertEqual(len(s.get_crds('top', ncrd=2)), 2) self.assertEqual(len(s.get_crds('eq', ncrd=3)), 3) self.assertEqual(len(s.get_crds('top', ncrd=3)), 3) self.assertEqual(s.map.shape, (3, 3))
def observation_info(self, observer): p_object = self.fixed_body p_object.compute(observer) up = True if ephem.degrees(p_object.alt) > 0 else False info = { 'alt': str(p_object.alt), 'az': str(p_object.az), 'up': up, 'neverup': p_object.neverup } try: next_rising = observer.next_rising(p_object) next_setting = observer.next_setting(p_object) info.update({ 'rise': timezone.make_aware(next_rising.datetime(), pytz.UTC) if next_rising else None, 'set': timezone.make_aware(next_setting.datetime(), pytz.UTC) if next_setting else None }) except ephem.AlwaysUpError: info.update({'alwaysup': True}) except: pass return info
def parseStarlist(starlist): """ Parse a scriptobs-compatible starlist for the scheduler. names, star_table, lines, stars = parseStarlist(starlist) starlist - a filename names - a list of stars in the starlist star_table - a numpy array lines - a list of strings that can be used for scriptobs input stars - a list of pyEphem objects """ names = [] lines = [] stars = [] star_table = [] try: f = open(starlist, 'r') except IOError: apflog("Warning: Could not open %s. No target can be selected." % starlist, echo=True) return None else: for line in f: if not re.search("\A\#", line): ls = line.split() names.append(ls[0]) row = [] # RA value in radians row.append(getRARad(ls[1], ls[2], ls[3])) # Dec value in radians row.append(getDECRad(ls[4], ls[5], ls[6])) # PM RA row.append(float(ls[8].split('=')[-1])) # PM Dec row.append(float(ls[9].split('=')[-1])) # V mag row.append(float(ls[10].split('=')[-1])) # Exposure time row.append(float(ls[11].split('=')[-1])) # Desired Counts row.append(float(ls[16].split('=')[-1])) # Filler not used here row.append(0.) row.append(0.) # Number of exposures row.append(int(ls[19].split('=')[-1])) star_table.append(row) # Save the scriptobs line for later lines.append(line) # Generate a pyEphem object for this target star = ephem.FixedBody() star._ra = ephem.hours(":".join([ls[1], ls[2], ls[3]])) star._dec = ephem.degrees(":".join([ls[4], ls[5], ls[6]])) stars.append(star) return names, np.array(star_table), lines, stars
def basic_skysurvey_plot_setup(from_plane=ephem.degrees('0')): # # EmulateApJ columnwidth=245.26 pts # fig_width_pt = 246.0 # inches_per_pt = 1.0 / 72.27 # golden_mean = (sqrt(5.) - 1.0) / 2.0 # fig_width = fig_width_pt * inches_per_pt # fig_height = fig_width * golden_mean * 1.5 # fig_size = [fig_width, fig_height] fig = plt.figure() ax = fig.add_subplot(111) # , aspect="equal") handles = [ ] # this handles the creation of the legend properly at the end of plotting labels = [] handles, labels = plot_galactic_plane(handles, labels) # handles, labels = plot_ecliptic_plane(handles, labels) handles, labels = plot_invariable_plane(handles, labels, from_plane) fontP = FontProperties() fontP.set_size('small') # make the fonts smaller plt.xlabel('RA (deg)') plt.ylabel('Declination (deg)') plt.grid(True, which='both') # plot_fanciness.remove_border(ax) return handles, labels, ax, fontP
def main(): day_local = '2020/8/03 21:00:00' moon = ephem.Moon() wild_horse = ephem.Observer() wild_horse.date = day_local wild_horse.lat = ephem.degrees('46.968359') wild_horse.lon = ephem.degrees('-119.966648') wild_horse.elevation = 330 output(wild_horse, moon, wild_horse.date, inc=0.5, iterations=120, time_offset=7)
def is_observable(self, ra, dec, restrictions={}): result = False # Create the object, Moon and Sun obj = ephem.readdb( "Object,f|S,%s,%s,0.0,2000.0" % (ephem.hours(deg2rad(ra)), ephem.degrees(deg2rad(dec)))) moon = ephem.Moon() sun = ephem.Sun() date = ephem.now() print ra, dec, restrictions # Simulate the next 24 hours for t in (0.01 * x + date for x in xrange(0, 100)): self.obs.date = t obj.compute(self.obs) moon.compute(self.obs) sun.compute(self.obs) # Is it night time? if rad2deg(sun.alt) < -10: # Now let's check the restrictions, if any if (rad2deg(obj.alt) >= restrictions.get('min_altitude', 0.0) and rad2deg(ephem.separation(obj, moon)) >= restrictions.get('min_moon_distance', 0.0) and moon.alt <= restrictions.get( 'max_moon_altitude', 90.0)): result = True break return result
def equatorial(data): """ Returns the J2000 right ascension and declination Taken from keyed data or computed from from ecliptic or galactic coordinates, whatever is given. @return: hours (float), degrees (float) """ ra = get(data, 'RAJ') if ra != '': decl = get(data, 'DECJ') ra = E.hours(data['RAJ']) # E.Angle(data['RAJ'], A.u.hourangle) decl = E.degrees(data['DECJ']) # E.Angle(data['DECJ'], A.u.deg) return ra, decl else: elong = get(data, 'ELONG') module_logger.debug("equatorial: elong is %s", elong) if elong != '': elat = float(get(data, 'ELAT')) try: mjd = float(get(data, 'POSEPOCH')) except (IndexError, ValueError): try: mjd = float(get(data, 'PEPOCH')) except (IndexError, ValueError): # default to J2000 mjd = 51544 ra, decl = A.ecliptic_to_J2000(elong, elat, mjd) return ra * 12 / math.pi, decl * 180 / math.pi else: # try galactic coordinates return "", "" # for now return None
def searchPass(aoi, satInfo, startdate, enddate, maxOffNadir): sat = satInfo.sat osat = satInfo.osat orbitOffset = satInfo.orbitOffset aoi.date = startdate sat.compute(aoi) passes = [] i = 0 while True: (_, _, mat, _, st, _) = aoi.next_pass(sat) if mat > enddate: break # Move sat to Max Alt Time aoi.date = mat sat.compute(aoi) # Compute off-nadir angle alt = sat.alt h = sat.elevation / 1000 offNadir = ephem.degrees(asin(R / (R + h) * cos(alt))) eclipsed = sat.eclipsed if offNadir < maxOffNadir and not eclipsed: i = i + 1 orbit = osat.get_orbit_number(jday2datetime(mat)) + orbitOffset apass = Pass(sat, aoi, orbit, offNadir) passes.append(apass) # Move sat to end of pass + 1 sec. aoi.date = st + ephem.second sat.compute(aoi) return passes
def isSafelyUp(obj): exam_venue.date = ephem.now() obj.compute(exam_venue) # if not(obj.alt > ephem.degrees(MIN_ALTITUDE)) : # print obj.name # print obj.alt return obj.alt > ephem.degrees(MIN_ALTITUDE)
def calcOrbit(self): #converts every coordinate into correct units #time0 = time.time() mag = max([x.mag for x in self.dets]) errs = 0.1 if mag <= 21: errs = 0.1 else: errs = 0.1 + (mag - 21.0) / 10.0 ralist = [ephem.hours(np.deg2rad(det.ra)) for det in self.dets] #time1 = time.time() declist = [ephem.degrees(np.deg2rad(det.dec)) for det in self.dets] #time2 = time.time() datelist = [ ephem.date((Time(det.mjd, format='mjd')).datetime) for det in self.dets ] #time3 = time.time() orbit = Orbit(dates=datelist, ra=ralist, dec=declist, obscode=np.ones(len(self.dets), dtype=int) * 807, err=errs) self.orbit = orbit #time4 = time.time() #print('time1: ' + str(time1-time0)) #print('time2: ' + str(time2-time1)) # print('time3: ' + str(time3-time2)) #print('time4: ' + str(time4-time3)) orbit.get_elements() self.chiSq = orbit.chisq self.elements, self.errs = orbit.get_elements() return self.elements, self.errs
def updateMoonInfo(self): """ """ self.moon.compute(self.site) self.moon_alt = self.moon.alt self.moon_dms = np.degrees(ephem.degrees(self.moon_alt)) self.moonphase = self.moon.moon_phase
def vis_strip(): site = salt_site() cat = hr_catalog(site) good = [] upper = ephem.degrees('65.0') lower = ephem.degrees('43.0') for key, star in cat.items(): lst = site.sidereal_time() ha = ephem.hours(lst - star.ra) if star.alt < upper and star.alt > lower: good.append(key) good.sort(lambda x, y: cmp(cat[x].mag, cat[y].mag)) return good
def planetsGHA(date): # used in planetstab(m) # this function returns a tuple of strings with ephemerids in the format used by the nautical almanac. # following are objects and their values: #Aries gha #Venus gha dec #Mars gha dec #Jupiter gha dec #Saturn gha dec obs = ephem.Observer() obs.date = date #Aries, First Point of deg = ephem.degrees(obs.sidereal_time()).norm ghaa = nadeg(deg) #Venus ephem_venus.compute(date, epoch=date) deg = ephem.degrees(obs.sidereal_time() - ephem_venus.g_ra).norm ghav = nadeg(deg) degv = ephem_venus.g_dec decv = nadeg(degv, 2) #Mars ephem_mars.compute(date, epoch=date) deg = ephem.degrees(obs.sidereal_time() - ephem_mars.g_ra).norm ghamars = nadeg(deg) degmars = ephem_mars.g_dec decmars = nadeg(degmars, 2) #Jupiter ephem_jupiter.compute(date, epoch=date) deg = ephem.degrees(obs.sidereal_time() - ephem_jupiter.g_ra).norm ghaj = nadeg(deg) degj = ephem_jupiter.g_dec decj = nadeg(degj, 2) #Saturn ephem_saturn.compute(date, epoch=date) deg = ephem.degrees(obs.sidereal_time() - ephem_saturn.g_ra).norm ghasat = nadeg(deg) degsat = ephem_saturn.g_dec decsat = nadeg(degsat, 2) # degv, degmars, degj, degsat have been added for the planetstab function return ghaa, ghav, decv, ghamars, decmars, ghaj, decj, ghasat, decsat, degv, degmars, degj, degsat
def radecFromStr(txt): """ Takes a string that contains ra in decimal degrees or in hh:mm:ss.s and dec in decimal degrees or dd:mm:ss.s returns (ra, dec) in decimal degrees """ def check_str(text, rem_char=None): if not isinstance(rem_char, str): raise Exception("rem_char argument must be a string") reps = {} for elmt in rem_char: reps.update({elmt: ""}) text = replace_multi(text, reps) return text def replace_multi(text, reps): """ Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. """ rep = dict((re.escape(k).lower(), v) for k, v in reps.iteritems()) pattern = re.compile("|".join(rep.keys()), re.IGNORECASE) return pattern.sub(lambda m: rep[re.escape(m.group(0)).lower()], text) deli = check_str(txt, rem_char="+-.,0123456789abcdefghijklmnopqrstuvwxyz") if len(deli) == 1: ra, dec = txt.split(deli) elif len(deli) < 5: raise ValueError("Could not understand ra-dec formating") elif len(deli) == 5 or (deli[0] == deli[1] and deli[3] == deli[4]): ra = txt[:txt.find(deli[2], txt.find(deli[0], txt.find(deli[0]) + 1) + 1)].strip() txt = txt.replace(ra, "") dec = txt[txt.find(deli[2]) + 1:].strip() else: raise ValueError("Could not understand ra-dec formating") try: ra = E.degrees(float(ra)) # test si decmal degrees except: try: ra = Angle(ra + 'h').deg # hourangle except: raise ValueError("Could not understand ra-dec formating") try: dec = E.degrees(dec) # decimal degrees or hms except: raise ValueError("Could not understand ra-dec formating") return ra, dec