def triangulate(self, v2_v1, v3_v2): """ Used to triangulate the true latitude and longitude corresponding to the norm of the telescope position. Input ------ v2_v1: list [args,len=2,dtype=float] The difference in [azimuth,altitude] between object 2 and object 1 v3_v2: list [args,len=2,dtype=float] The difference in [azimuth,altitude] between object 3 and object 2 """ ra = cp.Angle(self.cel_calib["RA"], unit=u.hourangle) dec = cp.Angle(self.cel_calib["DEC"], unit=u.deg) v = np.array([ra.rad, dec.rad]).T out = self.triangulation_class.triangulate(v[0], v[1], v[2], v2_v1, v3_v2) n = cp.SkyCoord(out[0][0], out[0][1], unit=u.rad, frame='icrs') npr = cp.EarthLocation(lon=0 * u.deg, lat=90 * u.deg, height=0 * u.m) n.location = npr n.obstime = self.time [self.lon, self.lat] = [180 - n.altaz.az.deg, n.altaz.alt.deg] self.home = [self.lon, self.lat] h = cp.EarthLocation(self.home[0] * u.deg, self.home[1] * u.deg) self.tel_frame = cp.AltAz(location=h, obstime=self.time) v3 = cp.SkyCoord(v[2][0], v[2][1], unit=u.rad) self.tel_pos = v3
def test_station_functions(): """Tests the Station functions. """ sefds = {'18': 100, '6': 40, '0.1': 200} a_station = stations.Station('name', 'Nm', 'VLBI', coord.EarthLocation(3839348.973*u.m, 430403.51*u.m, 5057990.099*u.m), sefds, 20) assert isinstance(a_station.name, str) assert isinstance(a_station.fullname, str) assert a_station.fullname == a_station.name assert a_station.network == 'VLBI' assert a_station.all_networks == a_station.network assert isinstance(a_station.country, str) assert isinstance(a_station.diameter, str) assert isinstance(a_station.real_time, bool) assert isinstance(a_station.location, coord.EarthLocation) assert a_station.location == coord.EarthLocation(3839348.973*u.m, 430403.51*u.m, 5057990.099*u.m) assert list(a_station.bands) == ['18', '6', '0.1'] assert isinstance(a_station.sefds, dict) assert a_station.sefds == sefds assert a_station.has_band('18') assert not a_station.has_band('45') assert a_station.sefd('18') == 100 with pytest.raises(KeyError): a_station.sefd('45') times1 = Time('2020-03-21 1:00') + np.arange(0, 4*60, 10)*u.min times2 = Time('2020-03-21 3:00') + np.arange(0, 4*60, 10)*u.min src1 = FixedTarget(coord=coord.SkyCoord('0h0m0s 30d0m0s'), name='testSrc') # a_station.elevation(times1, src1) # Should have elevation ranging -5 to 16.8 deg. # a_station.elevation(times1, src1) # Should have elevation ranging 3.7 to 34 deg. assert len(a_station.is_visible(times1, src1)[0]) == 0 assert len(a_station.is_visible(times2, src1)[0]) == 10 assert len(a_station.elevation(times2, src1)) == len(times1) assert np.equal(a_station.elevation(times2, src1).value, a_station.altaz(times2, src1).alt.value)[0]
def to_ecef(self, val=None, prop=False): """ Converts from geodetic to geocentric coordinates Parameters ---------- val: list with [lon, lat] A specific geodetic position prop: bool use True on lists of propagated source positions, default is False Returns ------- x, y, z: 1darrays Positions in geocentric coordinates """ if prop is True: quant = ac.EarthLocation(self.lon_prop, self.lat_prop).to_geocentric() else: quant = ac.EarthLocation([self.lon], [self.lat]).to_geocentric() if val is not None: quant = ac.EarthLocation([val[0]], [val[1]]).to_geocentric() x = quant[0].value y = quant[1].value z = quant[2].value return x, y, z
def calc_uvw_astropy(datetime, radec, xyz, telescope='VLA', takeants=None): """ Calculates and returns uvw in meters for a given time and pointing direction. datetime is time (astropy.time.Time) to calculate uvw. radec is (ra,dec) as tuple in radians. Can optionally specify a telescope other than the VLA. """ if telescope == 'JVLA' or 'VLA': telescope = 'VLA' phase_center = coordinates.SkyCoord(*radec, unit='rad', frame='icrs') if takeants is not None: antpos = coordinates.EarthLocation(x=xyz[takeants, 0], y=xyz[takeants, 1], z=xyz[takeants, 2], unit='m') else: antpos = coordinates.EarthLocation(x=xyz[:, 0], y=xyz[:, 1], z=xyz[:, 2], unit='m') if isinstance(datetime, str): datetime = time.Time(datetime.replace('/', '-', 2).replace('/', ' '), format='iso') tel_p, tel_v = coordinates.EarthLocation.of_site( telescope).get_gcrs_posvel(datetime) antpos_gcrs = coordinates.GCRS(antpos.get_gcrs_posvel(datetime)[0], obstime=datetime, obsgeoloc=tel_p, obsgeovel=tel_v) uvw_frame = phase_center.transform_to(antpos_gcrs).skyoffset_frame() antpos_uvw = antpos_gcrs.transform_to(uvw_frame).cartesian nant = len(antpos_uvw) antpairs = [(i, j) for j in range(nant) for i in range(j)] nbl = len(antpairs) u = np.empty(nbl, dtype='float32') v = np.empty(nbl, dtype='float32') w = np.empty(nbl, dtype='float32') for ibl, ant in enumerate(antpairs): bl = antpos_uvw[ant[1]] - antpos_uvw[ant[0]] u[ibl] = bl.y.value v[ibl] = bl.z.value w[ibl] = bl.x.value return u, v, w
def satellite_position(): """not used""" # Hardcoded for one satellite satellite_name = "ODIN" satellite_line1 = '1 26702U 01007A 19291.79098765 -.00000023 00000-0 25505-5 0 9996' satellite_line2 = '2 26702 97.5699 307.6930 0011485 26.4207 333.7604 15.07886437 19647' current_time = datetime.datetime.now() satellite = twoline2rv(satellite_line1, satellite_line2, wgs72) position, velocity = satellite.propagate( current_time.year, current_time.month, current_time.day, current_time.hour, current_time.minute, current_time.second) now = Time.now() # position of satellite in GCRS or J20000 ECI: cartrep = coord.CartesianRepresentation(x=position[0], y=position[1], z=position[2], unit=u.m) gcrs = coord.GCRS(cartrep, obstime=now) itrs = gcrs.transform_to(coord.ITRS(obstime=now)) loc = coord.EarthLocation(*itrs.cartesian.xyz) return jsonify({ 'eci': {'x': position[0], 'y': position[1], 'z': position[2]}, 'geodetic': {'latitude': loc.lat.deg, 'longitude': loc.lon.deg, 'height': loc.height.to(u.m).value} })
def _calc(self, datetime, lat: str, lon: str, height=0.0): """Calculate the azimuth and elevation of the sun. Calculates the azimuth and elevation of the sun as seen from the specified time and place (latitude, longitude, sea level). Args: datetime (datetime): datetime to calculate. (aware instance) lat (str): latitude. lon (str): longitude. height (float, optional): height above sea level. Default to 0.0 Returns: az (float): azimuth of sun. el (float): elevation of sun. """ time = ap_t.Time(datetime) loc = ap_crd.EarthLocation( lat=ap_crd.Angle(lat), lon=ap_crd.Angle(lon), height=height ) sun = ap_crd.get_sun(time).transform_to( ap_crd.AltAz(obstime=time, location=loc) ) az = sun.az.degree el = sun.alt.degree return az, el
def gen_mock_obs(self): """ Generates fake observation data based on possible errors of +/- 5deg. Output: ------ obs: list [args,len=2,dtype=float] Difference in altitude and azimuth for three points, used in triangulation. """ # creates class object based on random errors in telescope placement self.mock_home = [self.lon_est + np.random.uniform(-5,5)*u.deg, self.lat_est + np.random.uniform(-5,5)*u.deg] # creates objects based on errors mock_loc = cp.EarthLocation(self.mock_home[0],self.mock_home[1]) surf = cp.AltAz(location=mock_loc,obstime=self.time) pts = self.altaz_calib.transform_to(surf) # calculate angular differences in altitude and azimuth for points self.v2_v1 = [pts[1].az.rad - pts[0].az.rad, pts[1].alt.rad - pts[0].alt.rad] self.v3_v2 = [pts[2].az.rad - pts[1].az.rad, pts[2].alt.rad - pts[1].alt.rad] return [self.v2_v1, self.v3_v2]
def _perform(self): """ Returns an Argument() with the parameters that depends on this operation. """ self.log.info(f"Running {self.__class__.__name__} action") lat=c.Latitude(self.action.args.kd.get('SITELAT'), unit=u.degree) lon=c.Longitude(self.action.args.kd.get('SITELONG'), unit=u.degree) height=float(self.action.args.kd.get('ALT-OBS')) * u.meter loc = c.EarthLocation(lon, lat, height) temperature=float(self.action.args.kd.get('AMBTEMP'))*u.Celsius pressure=self.cfg['Telescope'].getfloat('pressure', 700)*u.mbar altazframe = c.AltAz(location=loc, obstime=self.action.args.kd.obstime(), temperature=temperature, pressure=pressure) moon = c.get_moon(Time(self.action.args.kd.obstime()), location=loc) sun = c.get_sun(Time(self.action.args.kd.obstime())) moon_alt = ((moon.transform_to(altazframe).alt).to(u.degree)).value moon_separation = (moon.separation(self.action.args.header_pointing).to(u.degree)).value\ if self.action.args.header_pointing is not None else None # Moon illumination formula from Meeus, ÒAstronomical # Algorithms". Formulae 46.1 and 46.2 in the 1991 edition, # using the approximation cos(psi) \approx -cos(i). Error # should be no more than 0.0014 (p. 316). moon_illum = 50*(1 - np.sin(sun.dec.radian)*np.sin(moon.dec.radian)\ - np.cos(sun.dec.radian)*np.cos(moon.dec.radian)\ * np.cos(sun.ra.radian-moon.ra.radian)) self.action.args.moon_alt = moon_alt self.action.args.moon_separation = moon_separation self.action.args.moon_illum = moon_illum return self.action.args
def getSunPos(latitude, longitude, t): loc = coord.EarthLocation(lon=longitude * u.deg, lat=latitude * u.deg) now = Time(t) altaz = coord.AltAz(location=loc, obstime=now) sun = coord.get_sun(now) result = sun.transform_to(altaz) return result
def solarzenithangle(t, glat, glon, alt_m): """ Parameters ---------- t : datetime time of observation glat : float latitude glon : float longitude alt_m : float observer altitude [meters] Returns ------- sza : float solar zenith angle [degrees] """ obs = ac.EarthLocation(lat=glat * u.deg, lon=glon * u.deg, height=alt_m * u.m) times = astropy.time.Time(t, scale="ut1") sun = ac.get_sun(times) sunobs = sun.transform_to(ac.AltAz(obstime=times, location=obs)) return 90.0 - sunobs.alt.degree
def test_horizontal_to_equatorial_astropy(self): from astropy import coordinates as coord from astropy import units as u from astropy import time from astropy.time import Time utc_date = datetime.datetime.utcnow() loc = Dunedin obstime = time.Time(utc_date, scale="utc") eloc = coord.EarthLocation( lat=loc.latitude_deg() * u.deg, lon=loc.longitude_deg() * u.deg, height=loc.alt * u.m, ) altaz_frame = coord.AltAz(obstime=obstime, location=eloc) for el, az in zip(np.linspace(0, 90, 10), np.linspace(0, 259, 10)): elaz = coord.SkyCoord(alt=el * u.deg, az=az * u.deg, frame=altaz_frame) radec = elaz.transform_to(coord.ICRS) ra, dec = loc.horizontal_to_equatorial(utc_date, angle.from_dms(el), angle.from_dms(az)) self.assertAlmostEqual( radec.ra.degree, ra.to_degrees(), -1) # TODO better agreement should be possible. self.assertAlmostEqual( radec.dec.degree, dec.to_degrees(), 1) # TODO better agreement should be possible.
def stations_from_file(filename): """The file must contain the following columns: name_observer code_observer X Y Z The header of this file should be "station code x y z", matching the previous fields Returns a dict with the observers. The keys are the code_observer. """ file_with_stations = ascii.read(filename) # Getting the frequencies with SEFD values sefds = [ acol for acol in file_with_stations.colnames if 'SEFD-' in acol ] stations = {} for a_line in file_with_stations: a_loc = coord.EarthLocation(a_line['x'] * u.m, a_line['y'] * u.m, a_line['z'] * u.m) stat_sefds = {} for a_sefd in sefds: if a_line[a_sefd] != -1: stat_sefds[a_sefd.split('-')[1]] = a_line[a_sefd] stations[a_line['code']] = Station(a_line['station'], a_line['code'], a_loc, stat_sefds) return stations
def __init__(self, centers, time, indices=None): self.centers = centers self.time = time self.indices = indices # figure out where the sun is self.solar_coord = ac.get_sun(time) # subset by the provided indices, if specified if indices is None: lats = centers.lat lons = centers.lon else: lats = centers.lat[indices] lons = centers.lon[indices] # calculate the solar zenith angle at each pixel center. # neglect refraction and height above geoid. pixels = ac.EarthLocation(lons, lats, ellipsoid='GRS80') solar_vecs = self.solar_coord.transform_to( ac.AltAz(obstime=time, location=pixels)) # mask out the non earth pixels, unless the user specified which pixels to calculate if indices is None: mask = ma.getmask(centers.lon) else: mask = None self.solar_zenith = ma.array(solar_vecs.zen.to_value(u.deg), mask=mask) self.solar_az = ma.array(solar_vecs.az.to_value(u.deg), mask=mask)
def get_sun_state(lat: float, lon: float, t: datetime): """Given a time and location get the sun position relative to this location. Args: lat (float): latitude lon (float): longitude t (datetime): query time Returns: tuple: zenith and azimuth angles """ loc = coord.EarthLocation(lon=lon * u.deg, lat=lat * u.deg) query_time_string = t.strftime("%Y-%m-%dT%H:%M:%S.%f") t = Time(query_time_string, format="isot", scale="utc") altaz = coord.AltAz(location=loc, obstime=t) sun = coord.get_sun(t) transformer = sun.transform_to(altaz) theta_z = transformer.zen theta_A = transformer.az return theta_z.degree, theta_A.degree
def nancay(): """ NenuFAR's position Returns ------- Coordinate object """ return coord.EarthLocation(lat=47.376511 * u.deg, lon=2.1924002 * u.deg)
def JD2RA(JD, longitude=21.42830, latitude=-30.72152, epoch='current'): """ Convert from Julian date to Equatorial Right Ascension at zenith during a specified epoch. Parameters: ----------- JD : type=float, a float or an array of Julian Dates longitude : type=float, longitude of observer in degrees east, default=HERA longitude latitude : type=float, latitude of observer in degrees north, default=HERA latitutde This only matters when using epoch="J2000" epoch : type=str, epoch for RA calculation. options=['current', 'J2000']. The 'current' epoch is the epoch at JD. Note that LST is defined as the zenith RA in the current epoch. Note that epoch='J2000' corresponds to the ICRS standard. Output: ------- RA : type=float, right ascension [degrees] at zenith JD times in the specified epoch. """ # get JD type if isinstance(JD, list) or isinstance(JD, np.ndarray): _array = True else: _array = False JD = [JD] # setup RA list RA = [] # iterate over jd for jd in JD: # use current epoch calculation if epoch == 'current': ra = JD2LST(jd, longitude=longitude) * 180 / np.pi RA.append(ra) # use J2000 epoch elif epoch == 'J2000': loc = crd.EarthLocation(lat=latitude * unt.deg, lon=longitude * unt.deg) t = Time(jd, format='jd', scale='utc') zen = crd.SkyCoord(frame='altaz', alt=90 * unt.deg, az=0 * unt.deg, obstime=t, location=loc) RA.append(zen.icrs.ra.degree) else: raise ValueError("didn't recognize {} epoch".format(epoch)) RA = np.array(RA) if _array: return RA else: return RA[0]
def get_radec_ephemeris(eph_json_single, start_time, end_time, interval, observing_facility, observing_site): observing_facility_class = facility.get_service_class(observing_facility) sites = observing_facility_class().get_observing_sites() observer = None for site_name in sites: obs_site = sites[site_name] if obs_site['sitecode'] == observing_site: observer = coordinates.EarthLocation( lat=obs_site.get('latitude') * units.deg, lon=obs_site.get('longitude') * units.deg, height=obs_site.get('elevation') * units.m) if observer is None: # this condition occurs if the facility being requested isn't in the site list provided. return (None, None, None, None, -1) ra = [] dec = [] mjd = [] for i in range(len(eph_json_single)): ra.append(float(eph_json_single[i]['R'])) dec.append(float(eph_json_single[i]['D'])) mjd.append(float(eph_json_single[i]['t'])) ra = np.array(ra) dec = np.array(dec) mjd = np.array(mjd) fra = interp.interp1d(mjd, ra) fdec = interp.interp1d(mjd, dec) start = Time(start_time) end = Time(end_time) time_range = time_grid_from_range(time_range=[start, end], time_resolution=interval * units.hour) tr_mjd = time_range.mjd airmasses = [] sun_alts = [] for i in range(len(tr_mjd)): c = SkyCoord(fra(time_range[i].mjd), fdec(time_range[i].mjd), frame="icrs", unit="deg") t = Time(tr_mjd[i], format='mjd') sun = coordinates.get_sun(t) altaz = c.transform_to(AltAz(obstime=t, location=observer)) sun_altaz = sun.transform_to(AltAz(obstime=t, location=observer)) airmass = altaz.secz airmasses.append(airmass) sun_alts.append(sun_altaz.alt.value) airmasses = np.array(airmasses) sun_alts = np.array(sun_alts) if np.min(tr_mjd) >= np.min(mjd) and np.max(tr_mjd) <= np.max(mjd): return (tr_mjd, fra(tr_mjd), fdec(tr_mjd), airmasses, sun_alts) else: return (None, None, None, None, -2)
def setup(run_num, ent_num, pol): #grab waveforms and time of event #Ben's Analysis Code: #dd= bt.DataDirectory() #r=dd.run(run_num) #e = r.get_entry(ent_num) #if(pol == 1): #Hpol # ADC0 = np.asarray(e.channel(0)) # ADC1 = np.asarray(e.channel(2)) # ADC2 = np.asarray(e.channel(4)) # ADC3 = np.asarray(e.channel(6)) #else: # ADC0 = np.asarray(e.channel(1)) # ADC1 = np.asarray(e.channel(3)) # ADC2 = np.asarray(e.channel(5)) # ADC3 = np.asarray(e.channel(7)) #volt0 = (ADC0-sum(ADC0)/len(ADC0)) #volt1 = (ADC1-sum(ADC1)/len(ADC1)) #volt2 = (ADC2-sum(ADC2)/len(ADC2)) #volt3 = (ADC3-sum(ADC3)/len(ADC3)) #times = r.get_entry(ent_num).times() lon = -118.238 lat = 37.589 d = beacon_data_reader.Reader("/project2/avieregg/beacon/telem/root", run_num) d.setEntry(ent_num) times = d.t() if (pol == 1): #Hpol volt0 = d.wf(0) - sum(d.wf(0)) / len(d.wf(0)) volt1 = d.wf(2) - sum(d.wf(2)) / len(d.wf(2)) volt2 = d.wf(4) - sum(d.wf(4)) / len(d.wf(4)) volt3 = d.wf(6) - sum(d.wf(6)) / len(d.wf(6)) else: #Vpol volt0 = d.wf(1) - sum(d.wf(1)) / len(d.wf(1)) volt1 = d.wf(3) - sum(d.wf(3)) / len(d.wf(3)) volt2 = d.wf(5) - sum(d.wf(5)) / len(d.wf(5)) volt3 = d.wf(7) - sum(d.wf(7)) / len(d.wf(7)) #filter events: volt0 = filter(volt0, times) volt1 = filter(volt1, times) volt2 = filter(volt2, times) volt3 = filter(volt3, times) #grab time stamp of event and format for later calculations h = d.header() event_time = datetime.datetime.utcfromtimestamp(h.readout_time) hour = event_time.hour + event_time.minute / 60.0 + event_time.second / 3600.0 loc = coord.EarthLocation(lon=lon * u.deg, lat=lat * u.deg) time = Time(event_time, location=loc) #-offset alt, az = 0, 0 return (volt0, volt1, volt2, volt3, times, alt, az, time, loc, hour)
def LSTScheduler(starttime, LSTbin_size, longitude=21.25): """ Round a time to the nearest LST bin for a given longitude on the globe. LSTbins run from 0 to 24 hours and step according to LSTbin_size. Parameters ---------- starttime : astropy.time.Time Target schedule time. LSTbin_size : float LST bin size in seconds. longitude : float Telescope longitude in degrees. Returns ------- schedule time : astropy.time.Time Time of next LST bin. schedule sidereal time : astropy.coord.Angle Sidereal time of next LST bin. """ sidesec = u.Quantity(1, 'sday').to('day').value # length of sidereal second in SI seconds. # HERA location, #XXX get the HERA location programmatically locate = coord.EarthLocation(lon=longitude * u.deg, lat=-30 * u.deg) if not isinstance(starttime, Time): raise TypeError("starttime is not a valid Astropy Time object") starttime.location = locate numChunks = (24 * 60 * 60) / LSTbin_size # seconds in a day lstGrid = np.linspace(0, int(numChunks), int(numChunks) + 1, dtype=int) * LSTbin_size hmsList = [None] * (int(numChunks + 1)) # convert the grid in seconds to HMS # make a grid of our evenly chunked LST times starting from 00h00m00s on the current day for i, sec in enumerate(lstGrid): hrs = int(lstGrid[i] / 3600) mins = int((lstGrid[i] % 3600) / 60) secs = int(lstGrid[i] - int(hrs * 3600) - int(mins * 60)) if hrs == 24: hrs = int(0) hms_str = '%02dh%02dm%02ds' % (hrs, mins, secs) hmsList[i] = hms_str lstAngleGrid = coord.Angle(hmsList) # turn LST grid into angle array for i, hour in enumerate(lstAngleGrid): # Find the timeslot our target is in if hour >= starttime.sidereal_time('apparent'): # get difference in sidereal diffSide = hour - starttime.sidereal_time('apparent') # convert difference to SI seconds diffSecs = diffSide.hms[2] * sidesec break dt = TimeDelta((diffSecs), format='sec') scheduleTime = starttime + dt # adjust target time by difference to get start time return scheduleTime, hour
def lookup(target: str) -> (str, str): """ Convert a target name 'M31', 'NGC6946', to a RA/Dec pair using the location of the observatory. Given a string representing a target ('M 31', 'NGC 4584', 'Horsehead Nebula') return an (RA, DEC) string tuple of the form ('hh:mm:sss', 'dd:mm:ss') Parameters ---------- target: str A string representing the target name Returns ------- ra: str String representation of right-ascension; 'hh:mm:ss' dec: str String representation of declination, 'dd:mm:ss' Notes ----- Author: rprechelt """ # location of observatory obs_location = coordinates.EarthLocation( lat=config.general.latitude * units.deg, lon=config.general.longitude * units.deg, height=config.general.altitude * units.m) obs_time = time.Time.now() frame = coordinates.AltAz(obstime=obs_time, location=obs_location) # planetary bodies - TODO: Add moons solar_system = [ 'mercury', 'venus', 'moon', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune', 'pluto' ] coordinates.solar_system_ephemeris.set('de432s') # convert it all to lowercase target = target.lower() # we have a planetary body if target in solar_system: celestial_body = coordinates.get_body(target, obs_time, obs_location) return (celestial_body.ra.to_string(unit=units.hour, sep=':'), celestial_body.dec.to_string(unit=units.degree, sep=':')) else: # stellar body try: target_coordinates = coordinates.SkyCoord.from_name(target) return (target_coordinates.ra.to_string(unit=units.hour, sep=':'), target_coordinates.dec.to_string(unit=units.degree, sep=':')) except Exception as e: return None, None
def get_coord_in_ecef(xyz): from astropy import coordinates as coord from astropy import units as u from astropy.time import Time now = Time(TIME) # position of satellite in GCRS or J20000 ECI: cartrep = coord.CartesianRepresentation(*xyz, unit=u.m) gcrs = coord.GCRS(cartrep, obstime=now) itrs = gcrs.transform_to(coord.ITRS(obstime=now)) loc = coord.EarthLocation(*itrs.cartesian.xyz) return [loc.lat, loc.lon, loc.height]
def solang(row): loc = coord.EarthLocation(lon=row['Longitude'] * u.deg, lat=row['Latitude'] * u.deg) #timy0 = timei.to_pydatetime() timy = Time(row['date_saved'], format='datetime') altaz = coord.AltAz(location=loc, obstime=timy) sun = coord.get_sun(timy) return sun.transform_to(altaz).zen.degree
def _perform(self): """ Returns an Argument() with the parameters that depend on this operation. """ self.log.info(f"Running {self.__class__.__name__} action") if self.action.args.imtype == 'OBJECT': if self.action.args.header_pointing is not None: self.log.info('Determine Moon info') site_lat = c.Latitude(self.cfg['Telescope'].getfloat('site_lat'), unit=u.degree) site_lon = c.Longitude(self.cfg['Telescope'].getfloat('site_lon'), unit=u.degree) site_elevation = self.cfg['Telescope'].getfloat('site_elevation') * u.meter loc = c.EarthLocation(site_lon, site_lat, site_elevation) pressure = self.cfg['Telescope'].getfloat('pressure', 700)*u.mbar obstime = Time(self.action.args.meta.get('date'), location=loc) altazframe = c.AltAz(location=loc, obstime=obstime, pressure=pressure) moon = c.get_moon(obstime) sun = c.get_sun(obstime) moon_alt = ((moon.transform_to(altazframe).alt).to(u.degree)).value moon_separation = (moon.separation(self.action.args.header_pointing).to(u.degree)).value\ if self.action.args.header_pointing is not None else None # Moon illumination formula from Meeus, ÒAstronomical # Algorithms". Formulae 46.1 and 46.2 in the 1991 edition, # using the approximation cos(psi) \approx -cos(i). Error # should be no more than 0.0014 (p. 316). moon_illum = 50*(1 - np.sin(sun.dec.radian)*np.sin(moon.dec.radian)\ - np.cos(sun.dec.radian)*np.cos(moon.dec.radian)\ * np.cos(sun.ra.radian-moon.ra.radian)) self.action.args.meta['moon_alt'] = moon_alt self.action.args.meta['moon_separation'] = moon_separation self.action.args.meta['moon_illum'] = moon_illum elif self.action.args.imtype == 'BIAS': self.log.info('Determine image stats') mean, med, std = stats.sigma_clipped_stats(self.action.args.ccddata.data) self.log.info(f" mean, med, std = {mean:.0f}, {med:.0f}, {std:.0f} (adu)") self.action.args.meta['mean adu'] = mean self.action.args.meta['median adu'] = med self.action.args.meta['std dev adu'] = std elif self.action.args.imtype == 'DARK': mean, med, std = stats.sigma_clipped_stats(self.action.args.ccddata.data) self.log.info(f" mean, med, std = {mean:.0f}, {med:.0f}, {std:.0f} (adu)") self.action.args.meta['mean adu'] = mean self.action.args.meta['median adu'] = med self.action.args.meta['std dev adu'] = std elif self.action.args.imtype in ['DOMEFLAT', 'TWIFLAT']: mean, med, std = stats.sigma_clipped_stats(self.action.args.ccddata.data) self.log.info(f" mean, med, std = {mean:.0f}, {med:.0f}, {std:.0f} (adu)") self.action.args.meta['mean adu'] = mean self.action.args.meta['median adu'] = med self.action.args.meta['std dev adu'] = std return self.action.args
def jdn_to_jyr_TCG(t): t = Time(t, format='jd', scale="tcb", location=coordinates.EarthLocation(x=0 * units.m, y=0 * units.m, z=0 * units.m)) # in newer astropy, use t.scale = 'tcg' t = t.tcg t = t + t.light_travel_time(SKY_LOCATION) t.format = "jyear" return t.value
def MJD_to_BJD(mjd_times, ra, dec, lat, lon, elevation, ra_unit='hourangle'): ''' Takes an array of times in MJD and converts to BJD, using observation and telescope data. Parameters ---------- mjd_times : array_like, shape (N, ) The times to be converted from MJD ra : tuple, length 3 The right ascension of the observation in either (d, m, s) or (h, m, s) depending on if unit is 'deg' or 'hourangle' dec : tuple, length 3 The declination of the observation in (d, m, s) lat : float or str The latitude of the observer in degrees or "dd:mm:ss" log : float or str The longitude of the observer in degrees or "dd:mm:ss" elevation : float The elevation of the observer in meters unit : str, optional The unit being used for ra. Either `'deg'` for degrees or `'hourangle'` for hour angle. Default is `'hourangle'`. Returns ------- bjd_times : array_like, shape (N, ) The times in Barycentric Julian Date ''' if ra_unit.lower() == 'deg': ra_unit = u.deg elif ra_unit.lower() == 'hourangle': ra_unit = u.hourangle else: raise ValueError('Unrecognised unit {}'.format(unit)) ra = coords.Angle(ra, unit=unit) dec = coords.Angle(dec, unit=u.deg) sky_coord = coords.SkyCoord(ra=ra, dec=dec, frame='icrs') obs_location = coords.EarthLocation(lat=lat, lon=lon, height=elevation) mjd_times = time.Time(mjd_times, format='mjd', location=obs_location, scale='utc') delta_time = mjd_times.light_travel_time(sky_coord) bjd_times = mjd_times.tdb + delta_time return bjd_times.value
def jdn_to_unix_TT(t): t = Time(t, format='jd', scale="tcb", location=coordinates.EarthLocation(x=0 * units.m, y=0 * units.m, z=0 * units.m)) t = t + t.light_travel_time(SKY_LOCATION) # in newer astropy, use t.scale = 'tt' t = t.tt # format=unix sets scale=utc, so we compute things by hand. return (t.value - 2440587.5) * 24 * 3600
def jdn_to_timestamp_UTC(t): t = Time(t, format='jd', scale="tcb", location=coordinates.EarthLocation(x=0 * units.m, y=0 * units.m, z=0 * units.m)) # in newer astropy, use t.scale = 'tt' t = t.utc t = t - (t.light_travel_time(SKY_LOCATION) - t.light_travel_time(SKY_LOCATION, kind='heliocentric')) t.format = "isot" return t.value
def getLoc(loc, unit='deg'): """ Get the a location Parameters ---------- * **loc** : tuple or str Location query (can be a tuple or a string). If tuple, expects (longitude, latitude). If string, expects an address, typically `'Paris, France'` and queries Google. * **unit** : str, optional If `loc` is a tuple of lon/lat, unit can be either `'deg'` or `'rad'` Returns ------- * **loc** : ``astropy.coord.EarthLocation`` EarthLocation object """ if isinstance(loc, str): if loc.lower() == 'nenufar': loc = coord.EarthLocation(lat=47.376511*u.deg, lon=2.1924002*u.deg) else: if not USE_GEOPY: loc = coord.EarthLocation.of_address(loc) else: geoloc = Nominatim(user_agent='my-application') gloc = geoloc.geocode(loc) loc = coord.EarthLocation(lat=gloc.latitude*u.deg, lon=gloc.longitude*u.deg) elif isinstance(loc, tuple): assert len(loc)==2, 'Only length 2 tuple is understood.' if not unit.lower() == 'deg': loc = np.degrees(loc) loc = coord.EarthLocation(lat=loc[0]*u.deg, lon=loc[1]*u.deg) elif isinstance(loc, coord.EarthLocation): pass else: raise ValueError('loc must be aither a tuple: (lon, lat) in degrees or a string adress.') return loc
def __init__ ( self, site='CTIO', timezone=None): if site=='CTIO': self.site = coordinates.EarthLocation ( lat='-30d10m10.78s', lon='-70d48m23.49s', height=2241.*u.m ) self.timezone= pytz.timezone ( 'America/Santiago' ) else: # // if not CTIO, trust the user to put in an EarthLocation # // and pytz.timezone () self.site = site if type(timezone) == str: self.timezone = pytz.timezone(timezone) else: self.timezone = timezone
def _get_observer_earth_location(frame, axis): earthlon = _get_observer_lat_or_lon_asfloat( frame.get('ObsLon({})'.format(axis))) * u.deg earthlat = _get_observer_lat_or_lon_asfloat( frame.get('ObsLat({})'.format(axis))) * u.deg earthheight = float(frame.get('ObsAlt({})'.format(axis))) * u.m earthlocation = coords.EarthLocation( lon=earthlon.value, lat=earthlat.value, height=earthheight.value, ) return earthlocation