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 import ephem 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 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) import ephem 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 gcDAR(): iraf.noao() obs = iraf.noao.observatory # Set up Keck observatory info obs(command="set", obsid="keck") keck = ephem.Observer() keck.long = math.radians(-obs.longitude) keck.lat = math.radians(obs.latitude) keck.elev = obs.altitude keck.pressure = 800.0 keck.temp = 278.0 # Date of Observations: 06maylgs1 keck.date = '2006/05/03 %d:%d:%f' % (obs.timezone + 3, 28, 46.33) # Set up the galactic center target sgra = ephem.FixedBody() sgra._ra = ephem.hours("17:45:40") sgra._dec = ephem.degrees("-29:00:10") sgra._epoch = 2000 sgra.compute() pos2 = ephem.FixedBody() pos2._ra = ephem.hours("17:45:40") pos2._dec = ephem.degrees("-29:00:00") pos2._epoch = 2000 pos2.compute() print 'Date of Obs: ', keck.date sgra.compute(keck) pos2.compute(keck) print 'Azimuth of Objects: %s vs. %s' % (sgra.az, pos2.az) for ii in range(15): keck.lat = math.radians(obs.latitude - (ii * 2)) sgra.compute(keck) pos2.compute(keck) angAbs = ephem.separation((sgra.ra, sgra.dec), (pos2.ra, pos2.dec)) angAbs *= 206265.0 angRel = ephem.separation((sgra.az, sgra.alt), (pos2.az, pos2.alt)) angRel *= 206265.0 angDiff = angAbs - angRel print 'Sgr A*: %s vs. %s deltaR = %5d (muas)' % \ (sgra.alt, pos2.alt, angDiff*1e6)
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 calculate_airmass(textlist_files): """ Calculates AIRMASS for the list of all FITS files and appends respective details in the headers. Args: textlist_files : List of all FITS files whose headers have to be edited Returns: None """ list_files = text_list_to_python_list(textlist_files) for file_name in list_files: hdulist = fits.open(file_name, mode='update') file_header = hdulist[0].header date_obs = file_header[DATE_keyword] if RA_keyword in file_header.keys(): object_ra = file_header[RA_keyword] else: object_ra = OBJECT_RA if DEC_keyword in file_header.keys(): object_dec = file_header[DEC_keyword] else: object_dec = OBJECT_DEC datetime_utc = date_obs + '00:00:00' jd = ephem.julian_date(datetime_utc) telescope = ephem.Observer() telescope.lon = OBS_LONG telescope.lat = OBS_LAT telescope.elevation = OBS_ALT telescope.pressure = 0 telescope.epoch = ephem.J2000 telescope.date = datetime_utc obj_pos = ephem.FixedBody() obj_pos._ra = object_ra obj_pos._dec = object_dec obj_pos._epoch = ephem.J2000 obj_pos.compute(telescope) time_sidereal = telescope.sidereal_time() object_alt = Angle(str(obj_pos.alt) + ' degrees').degree airmass = 1 / math.cos(math.radians(90 - object_alt)) list_keywords = ['OBSERVAT', 'OBS_LAT', 'OBS_LONG', 'OBS_ALT', 'TIMEZONE', 'DATE_OBS', 'JD', 'ST', 'RA', 'DEC', 'ALT', 'AZ', 'AIRMASS'] dict_header = {'OBSERVAT': OBS_NAME, 'OBS_LAT': OBS_LAT, 'OBS_LONG': OBS_LONG, 'OBS_ALT': OBS_ALT, 'TIMEZONE': OBS_TIMEZONE, 'DATE_OBS': date_obs, 'JD': jd, 'ST': time_sidereal, 'RA': object_ra, 'DEC': object_dec, 'ALT': obj_pos.alt, 'AZ': obj_pos.az, 'AIRMASS': airmass} for keyword in list_keywords: if keyword in file_header.keys(): file_header.remove(keyword, remove_all=True) file_header.append(card=(keyword, dict_header[keyword])) hdulist.flush() hdulist.close()
def checkVPAatTime(location, otime, targ): # Create an observer at the start location/date/time of SOFIA sofia = ephem.Observer() # SOFIA mission-type parameters airtemp = -50.0 # Decent average flight altitude temperature altitude = 12100 # 12100 meters ~= 39700 ft horizon = 20 # 20 degrees is lower limit of vignetting # Pyephem needs string inputs. Annoying, but whatevs. sofia.lat = location[0] sofia.lon = location[1] sofia.elevation = altitude sofia.temp = airtemp sofia.date = otime sofia.horizon = horizon sofia.compute_pressure() sofia.name = "eSOFIA" targetpos = ephem.FixedBody() targetpos._ra = targ[0] targetpos._dec = targ[1] targetpos._pmra = targ[2] targetpos._pmdec = targ[3] targetpos.name = targ[4] targetpos._epoch = "2000" targetpos.compute(sofia) print(targetpos._ra, targetpos._dec) print(targetpos.alt, targetpos.az) return targetpos.parallactic_angle().real * 180./ephem.pi
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 star_rise_pre(self, star_ra, star_dec): """ @brief: This function calculates when the object with given coordinates was rising last time. @param star_ra: The right ascension of a star given in the format: HH:MM:SS. @param star_dec: The declination of a star given in the format: DD:MM:SS. """ song_site = ephem.Observer() song_site.lat = self.obs_lat song_site.long = self.obs_lon song_site.elev = self.obs_elev # star = ephem.readdb('star,f|A0,'+str(star_ra)+','+str(star_dec)+',2000') if len(str(star_ra).split(":")) == 1: star_ra = song_convert_coor.COOR_CONVERTER().convert_ra(star_ra) star_dec = song_convert_coor.COOR_CONVERTER().convert_dec(star_dec) star = ephem.FixedBody() star._ra = star_ra star._dec = star_dec star.compute(song_site) rise_star = song_site.previous_rising(star) return rise_star
def calc_az_alt(longitude, latitude, ra, dec, datetime_utc): """ Returns azimuth and altitude for sky position (RA and Dec) at a given earth longitude and Latitude, at a given date and time (in UTC). :param longitude: longitude of earth position, in degrees east=positive [float]. :param latitude: latitude of earth position, in degrees north=positive [float]. :param ra: right ascension of sky position, in degrees [float]. :param dec: declination of sky position, in degrees [float]. :param datetime_utc: date and time for which to calculate az and alt, in UTC [datetime object]. :return: 2-tuple of azimuth, altitude in degrees [2-tuple of floats]. adapted from photrix August 2018. """ # return 1.0, 2.0 # dummy line for testing only. obs = ephem.Observer() # for local use. obs.lon = degrees_as_hex(longitude) obs.lat = degrees_as_hex(latitude) obs.date = datetime_utc target_ephem = ephem.FixedBody( ) # so named to suggest restricting its use to ephem. target_ephem._epoch = '2000' target_ephem._ra = ra_as_hours(ra) target_ephem._dec = degrees_as_hex(dec) target_ephem.compute(obs) return target_ephem.az * 180 / math.pi, target_ephem.alt * 180 / math.pi
def __init__(self, obj=None, ra=None, dec=None, epoch=2000.0, domepos=None, objid=''): """Create a new instance. If passed any kind of Position object in the 'obj' attribute, extract its coordinates and use them to initialise the object, otherwise use the ra, dec, epoch, etc parameters. """ Position.__init__(self, ra=ra, dec=dec, epoch=epoch, domepos=domepos, objid=objid) self.Time = EphemTime() self.observer = self.Time.observer if (isinstance(obj, ephem.Body) or isinstance(obj, ephem.Planet) or isinstance(obj, ephem.PlanetMoon) or isinstance(obj, ephem.EllipticalBody) or isinstance(obj, ephem.ParabolicBody) or isinstance(obj, ephem.HyperbolicBody) or isinstance(obj, ephem.EarthSatellite)): self.body = obj if self.body.name: self.ObjID = self.body.name else: self.body = ephem.FixedBody() self.body._ra = self.Ra * ephem.pi / (180 * 3600) self.body._dec = self.Dec * ephem.pi / (180 * 3600) self.body._epoch = (self.Epoch - 2000.0) * 365.246 + ephem.J2000 self.body.compute(self.observer) self.update()
def radec_to_azel(ra, dec, lat, lon, alt, caldate): body = ephem.FixedBody() print("BODY: ", ra, dec) body._ra = ra body._dec = dec #body._epoch=ephem.J2000 obs = ephem.Observer() obs.lat = ephem.degrees(lat) obs.lon = ephem.degrees(lon) obs.date = caldate print("CALDATE:", caldate) obs.elevation = float(alt) body.compute(obs) az = str(body.az) el = str(body.alt) (d, m, s) = az.split(":") dd = float(d) + float(m) / 60 + float(s) / (60 * 60) az = dd (d, m, s) = el.split(":") dd = float(d) + float(m) / 60 + float(s) / (60 * 60) el = dd #az = ephem.degrees(body.az) return (az, el)
def __init__(self, object_name, object_ra, object_dec): self.name = str(object_name) self.object = ephem.FixedBody() self.object._epoch = ephem.J2000 self.object._ra = str(object_ra) self.object._dec = str(object_dec) self.list_alt = []
def _convert_radec_to_altaz(ra, dec, lon, lat, height, time): """Convert a single position. (PyEphem doesn't support arrays of positions.) """ # We need to create a "Body" in pyephem, which represents the coordinate # http://stackoverflow.com/questions/11169523/how-to-compute-alt-az-for-given-galactic-coordinate-glon-glat-with-pyephem body = ephem.FixedBody() body._ra = np.radians(ra) body._dec = np.radians(dec) # Set observer parameters obs = ephem.Observer() obs.lon = np.radians(lon) obs.lat = np.radians(lat) obs.elevation = (height * u.km).to(u.m).value obs.date = time # Turn refraction off by setting pressure to zero obs.pressure = 0 # Compute alt / az of the body for that observer body.compute(obs) az, alt = np.degrees([body.az, body.alt]) return dict(az=az, alt=alt)
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 fixed_body(self): object = ephem.FixedBody() object._ra = "{0}:{1}:{2}".format(self.ra_hours, self.ra_minutes, self.ra_seconds) object._dec = "{0}{1}:{2}:{3}".format(self.dec_sign, self.dec_deg, self.dec_min, self.dec_seconds) return object
def calcaltaz(scanlist, sc, sr, format='str', intchunk=2): """ Calculates a single (alt,az) per scan in scanlist. """ vla = ephem.Observer() vla.lat = '34:04:43.497' vla.long = '-107:37:03.819' vla.elevation = 2124 src = ephem.FixedBody() altaz = [] for scan in scanlist: inttime = (sc[scan]['endmjd'] - sc[scan]['startmjd']) * 24 * 3600 / sc[1]['nints'] src._ra, src._dec = [(sr[srn]['ra'], sr[srn]['dec']) for srn in sr.keys() if sc[scan]['source'] == sr[srn]['source']][0] for nskip in range(0, sc[scan]['nints'] - intchunk + 1, intchunk): vla.date = ephem.date( jd_to_date(sc[scan]['startmjd'] + nskip * inttime / (24 * 3600) + 2400000.5)) src.compute(vla) if format == 'str': altaz.append('(%.1f, %.1f)' % (n.degrees(src.alt), n.degrees(src.az))) elif format == 'float': altaz.append((n.degrees(src.alt), n.degrees(src.az))) return n.array(altaz)
def star_alt_at(self, star_ra='', star_dec='', time_stamp='', unit='s'): """ @brief: This function will calculate the altitude of an object with given coordinates at a given time seem from Teide. @param star_ra: The right ascension of a star given in the format: HH:MM:SS. @param star_dec: The declination of a star given in the format: DD:MM:SS. @param time_stamp: Time of when the altitude should be calculated in the format: YYYY-MM-DD hh:mm:ss """ song_site = ephem.Observer() song_site.lat = self.obs_lat song_site.long = self.obs_lon song_site.elev = self.obs_elev song_site.date = time_stamp # star = ephem.readdb('star,f|A0,'+str(star_ra)+','+str(star_dec)+',2000') if len(str(star_ra).split(":")) == 1: star_ra = song_convert_coor.COOR_CONVERTER().convert_ra(star_ra) star_dec = song_convert_coor.COOR_CONVERTER().convert_dec(star_dec) star = ephem.FixedBody() star._ra = star_ra star._dec = star_dec star.compute(song_site) alt_star = star.alt if unit == 's': # 's' for string return alt_star else: # return float value return float(str(alt_star).split(":")[0]) + float( str(alt_star).split(":")[1]) / 60. + float( str(alt_star).split(":")[2]) / 3600.
def radec_to_azel(ra,dec,lat,lon,alt, caldate): body = ephem.FixedBody() print ("BODY: ", ra, dec) body._ra = ra body._dec = dec #body._epoch=ephem.J2000 ep_date = ephem.Date(caldate) obs = ephem.Observer() obs.lat = ephem.degrees(lat) obs.lon = ephem.degrees(lon) obs.date =ep_date print ("OBS DATE:", obs.date) print ("LOCAL DATE:", ephem.localtime(ep_date)) print ("LAT:", lat) print ("LON:", lon) print ("LAT:", Decdeg2DMS(lat)) print ("LON:", Decdeg2DMS(lon)) print ("CALDATE:", caldate) obs.elevation=float(alt) body.compute(obs) az = str(body.az) el = str(body.alt) print ("AZ/EL", az, el) (d,m,s) = az.split(":") dd = float(d) + float(m)/60 + float(s)/(60*60) az = dd (d,m,s) = el.split(":") dd = float(d) + float(m)/60 + float(s)/(60*60) el = dd #az = ephem.degrees(body.az) return(az,el)
def sun_dist(self, star_ra, star_dec): """ @brief: This function calculates projected distance from the Sun to a given object on the sky. @param star_ra: The right ascension of a star given in the format: HH:MM:SS. @param star_dec: The declination of a star given in the format: DD:MM:SS. """ song_site = ephem.Observer() song_site.lat = self.obs_lat song_site.long = self.obs_lon song_site.elev = self.obs_elev sun = ephem.Sun() sun.compute(song_site) # star = ephem.readdb('star,f|A0,'+str(star_ra)+','+str(star_dec)+',2000') if len(str(star_ra).split(":")) == 1: star_ra = song_convert_coor.COOR_CONVERTER().convert_ra(star_ra) star_dec = song_convert_coor.COOR_CONVERTER().convert_dec(star_dec) star = ephem.FixedBody() star._ra = star_ra star._dec = star_dec star.compute(song_site) sun_d = ephem.separation(star, sun) return sun_d
def construct_radec_target(ra, dec): """Convenience function to create unnamed fixed target (*radec* body type). The input parameters will also accept :class:`ephem.Angle` objects, as these are floats in radians internally. The epoch is assumed to be J2000. Parameters ---------- ra : string or float Right ascension, either in 'H:M:S' or decimal degree string format, or as a float in radians dec : string or float Declination, either in 'D:M:S' or decimal degree string format, or as a float in radians Returns ------- target : :class:`Target` object Constructed target object """ body = ephem.FixedBody() # First try to interpret the string as decimal degrees if isinstance(ra, basestring): try: ra = deg2rad(float(ra)) except ValueError: pass ra, dec = angle_from_hours(ra), angle_from_degrees(dec) body.name = "Ra: %s Dec: %s" % (ra, dec) body._epoch = ephem.J2000 body._ra = ra body._dec = dec return Target(body, 'radec')
def radec_obj_dist(obs, ra, dec, obj): b = ephem.FixedBody() b._ra = np.radians(ra) b._dec = np.radians(dec) b.compute(obs) obj.compute(obs) return np.degrees(ephem.separation(b, obj))
def pyephem_declaration(self,ObsPyephem): ''' Define the star in Pyephem to make astrometric calculations ''' pyephem_star = ephem.FixedBody() pyephem_star = ephem.readdb('"'+str(self.name)+'"'+",f|S|A0,"+str(self.RA1950)+'|0'+\ ","+str(self.DEC1950)+'|0'+","+str(self.Vmag)+',1950,0"') pyephem_star.compute(ObsPyephem) return pyephem_star
def moon_dist(star_ra, star_dec, time_stamp): """ @brief: This function calculates projected distance from the Moon to a given object on the sky. @param star_ra: The right ascension of a star given in the format: HH:MM:SS. @param star_dec: The declination of a star given in the format: DD:MM:SS. """ song_site = ephem.Observer() song_site.lat = conf.lat_obs song_site.long = conf.long_obs song_site.elev = conf.elev_obs song_site.date = time_stamp moon = ephem.Moon() moon.compute(song_site) # star = ephem.readdb('star,f|A0,'+str(star_ra)+','+str(star_dec)+',2000') if len(str(star_ra).split(":")) == 1: star_ra = song_convert_coor.COOR_CONVERTER().convert_ra(star_ra) star_dec = song_convert_coor.COOR_CONVERTER().convert_dec(star_dec) star = ephem.FixedBody() star._ra = star_ra star._dec = star_dec star.compute(song_site) m_d = ephem.separation(star, moon) moon_d = float(str(m_d).split(":")[0]) return moon_d
def calculate_source_positions(self, source, date): """ calculate the horizon coordinates for a source returns a dict with source info """ cdscc.date = date source_dict = {} rc('grid', color='#316931', linewidth=1, linestyle='-') rc('xtick', labelsize=10) rc('ytick', labelsize=10) for key, value in source.items(): #Compute the Az-Alt from RA-DEC for CDSCC source = ephem.FixedBody() source._ra = value[0] #source_ra source._dec = value[1] #source_dec source._epoch = ephem.J2000 source_flux = value[2] source_velo = value[3] source.compute(cdscc) #Create a new 6df dictionary source_dict[key] = ([ source.ra, source.dec, source.az, source.alt, source_flux, source_velo ]) return source_dict
def nextTransit(date, ra, dec, lat=-30.721527777777776, lon=21.428305555555557, elev=1000.): """ Construct observer object (default PAPER site) and ask when the next transit of a given RA/Dec is. Output time is Universal Time (UT). Paramters --------- date | str: in form YYYY/MM/DD ra, dec, lat and lon | float: in degrees elevation | float: meters """ #define where and when we are observing site = ephem.Observer() site.lat, site.long, site.elevation = str(lat), str(lon), elev site.date = date tp = ephem.FixedBody() # this is the point we are asking about tp._ra = np.radians(ra) tp._dec = np.radians(dec) tp._epoch = date tp.compute() tp_transit = site.next_transit(tp) return str(tp_transit)
def main(): # for s in stars: # print(mandi.radec_of(s[0], s[1])) stars_ephem = [] i = 1 for s in stars: star = ephem.FixedBody() star.name = "Star" + str(i) i += 1 (star._ra, star._dec) = mandi.radec_of(s[0], s[1]) stars_ephem.append(star) star.compute() places = [["Mandi", mandi], ["London", london], ["New York", ny], ["Los Angeles", losAngeles], ["Chicago", chicago], ["Boston", boston], ["Seattle", seattle], ["Las Vegas", lasVegas], ["Greenwich", greenwich]] mandi.date = '2018/3/30 12:00:00' for place in places: alt = [] az = [] for s in stars_ephem: s.compute(place[1]) alt.append(np.degrees(s.alt)) az.append(np.degrees(s.az)) print(s.name, np.degrees(s.alt), np.degrees(s.az), place[0], str(place[1].date)) draw_graph(alt, az, place[0], place[1].date)
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) import ephem 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 __init__(self, observatory: Type[Observatory], target_ra_dec: Tuple[float, float], start_datetime: Type[datetime.datetime], duration_ms: float): """ TargetTimeSeries constructor Args: observarory (Observatory): Where observation is taking place start_datetime (datetime.datetime): start of the observation duration_ms: (float): how long the observation will last target_ra_dec (tuple): ra and dec of the target of the observation Returns: TargetTimeSeries """ super().__init__() ''' print("observatory [" ,type(observatory).__name__, "] :", observatory) print("target_ra_dec [" ,type(target_ra_dec).__name__, "] :", target_ra_dec) print("start_time [" ,type(start_time).__name__, "] :", start_time) print("duration_ms [" ,type(duration_ms).__name__, "] :", duration_ms) ''' self.index_target_map = {} self.start_datetime = start_datetime self.duration_ms = int(duration_ms) self.observatory = observatory target_ra, target_dec = target_ra_dec target_body = ephem.FixedBody() target_body._ra = target_ra target_body._dec = target_dec self.target_body = target_body self.cache_misses = 0 self.cache_hits = 0
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.SIDEREAL: body = ephem.FixedBody() body._ra = Angle(str(target.ra) + 'd').to_string(unit=units.hourangle, sep=':') body._dec = Angle(str(target.dec) + 'd').to_string(unit=units.degree, sep=':') body._epoch = target.epoch if target.epoch else ephem.Date(DEFAULT_VALUES['epoch']) return body elif 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 calcdelays(phase_center,uvws,times): print "phasing to xyz ", delays = [] O = ephem.Observer() O.lat = '-26:42:11.95' O.lon = '116:40:14.93' S = ephem.FixedBody() S._ra = phase_center[0] * n.pi/180 S._dec = phase_center[1]*n.pi/180 O.date = times[0] - 2415020 #convert from julian to dublin julian S.compute(O) #print S._dec #print S.dec #print S._ra #print S.ra ##print S.ra,S.dec #print S.alt,S.az print bodyxyz(S) for i,uvw in enumerate(uvws): O.date = times[0] - 2415020 S.compute(O) s = bodyxyz(S) delays.append(n.dot(uvw,s)) delays = n.array(delays) return delays