Пример #1
0
def airmass_plots(KPNO=False,ING=False,MLO=False):

    observer_site = Observer.at_site("Kitt Peak", timezone="US/Mountain")

    if KPNO:
        print('plotting airmass curves for Kitt Peak')
        observing_location = EarthLocation.of_site('Kitt Peak')
        observer_site = Observer.at_site("Kitt Peak", timezone="US/Mountain")
        start_time = Time('2017-03-12 01:00:00') # UTC time, so 1:00 UTC = 6 pm AZ mountain time
        end_time = Time('2017-03-12 14:00:00')

    elif MLO:
        print('plotting airmass curves for MLO')
        observing_location = EarthLocation.of_site(u'Palomar')
        observer_site = Observer.at_site("Palomar", timezone="US/Pacific")
        # for run starting 2019-Apr-04 at MLO
        start_time = Time('2019-04-03 01:00:00') # need to enter UTC time, MLO UTC+6?
        end_time = Time('2019-04-03 14:00:00')
        
    elif ING:
        print('plotting airmass curves for INT')
        observing_location = EarthLocation.of_site(u'Roque de los Muchachos')
        observer_site = Observer.at_site("Roque de los Muchachos", timezone="GMT")
        # for run starting 2019-Feb-04 at INT
        start_time = Time('2019-02-04 19:00:00') # INT is on UTC
        end_time = Time('2019-02-05 07:00:00')

    #observing_time = Time('2017-05-19 07:00')  # 1am UTC=6pm AZ mountain time
    #observing_time = Time('2018-03-12 07:00')  # 1am UTC=6pm AZ mountain time
    #aa = AltAz(location=observing_location, obstime=observing_time)


    #for i in range(len(pointing_ra)):



    delta_t = end_time - start_time
    observing_time = start_time + delta_t*np.linspace(0, 1, 75)
    nplots = int(sum(obs_mass_flag)/8.)
    print(nplots)
    for j in range(nplots):
        plt.figure()
        legend_list = []
        for i in range(8):
            pointing_center = coords.SkyCoord(pointing_ra[8*j+i]*u.deg, pointing_dec[8*j+i]*u.deg, frame='icrs')
            if i == 3:
                plot_airmass(pointing_center,observer_site,observing_time,brightness_shading=True)
            else:
                plot_airmass(pointing_center,observer_site,observing_time)
            legend_list.append('Pointing %02d'%(8*j+i+1))
    
        plt.legend(legend_list)
        #plt.ylim(0.9,2.5)
        plt.gca().invert_yaxis()
        plt.subplots_adjust(bottom=.15)
        #plt.axvline(x=7*u.hour,ls='--',color='k')
        plt.axhline(y=2,ls='--',color='k')
        plt.savefig(outfile_prefix+'airmass-%02d.png'%(j+1))
Пример #2
0
def test_is_night():
    lco = Observer(location=EarthLocation.of_site('lco'))  # Las Campanas
    aao = Observer(location=EarthLocation.of_site('aao'))  # Sydney, Australia
    vbo = Observer(location=EarthLocation.of_site('vbo'))  # India

    time1 = Time('2015-07-28 17:00:00')
    nights1 = [observer.is_night(time1) for observer in [lco, aao, vbo]]
    assert np.all(nights1 == [False, True, True])

    time2 = Time('2015-07-28 02:00:00')
    nights2 = [observer.is_night(time2) for observer in [lco, aao, vbo]]
    assert np.all(nights2 == [True, False, False])
Пример #3
0
def test_is_night():
    lco = Observer(location=EarthLocation.of_site('lco'))  # Las Campanas
    aao = Observer(location=EarthLocation.of_site('aao'))  # Sydney, Australia
    vbo = Observer(location=EarthLocation.of_site('vbo'))  # India

    time1 = Time('2015-07-28 17:00:00')
    nights1 = [observer.is_night(time1) for observer in [lco, aao, vbo]]
    assert np.all(nights1 == [False, True, True])

    time2 = Time('2015-07-28 02:00:00')
    nights2 = [observer.is_night(time2) for observer in [lco, aao, vbo]]
    assert np.all(nights2 == [True, False, False])
Пример #4
0
def plot2D(df, threshold, ax=None):

    ax = ax or plt.gca()
    df_selected = df.query(f'gammaness > {threshold}')

    crab = SkyCoord.from_name('crab')
    altaz = AltAz(
        location = EarthLocation.of_site('Roque de los Muchachos'),
        obstime = Time(df_selected.dragon_time, format='unix')
    )
    telescope_pointing = SkyCoord(
        alt = u.Quantity(df_selected.alt_tel.to_numpy(), u.rad, copy=False),
        az = u.Quantity(df_selected.az_tel.to_numpy(), u.rad, copy=False),
        frame = altaz
    )
    camera_frame = CameraFrame(
        focal_length = u.Quantity(df_selected.focal_length.to_numpy(), u.m, copy=False),
        telescope_pointing = telescope_pointing,
        location = EarthLocation.of_site('Roque de los Muchachos'),
        obstime = Time(df_selected.dragon_time, format='unix')
    )
    crab_cf = crab.transform_to(camera_frame)

    #ax.hist2d(crab_cf.x.to_value(u.m), crab_cf.y.to_value(u.m), bins = 100)
    #ax.set_xlabel(r'$x \,/\, \mathrm{m}$')
    #ax.set_ylabel(r'$y \,/\, \mathrm{m}$')

    
    #crab_cf_1 = crab_cf.transform_to(altaz)
    #ax.hist2d(
    #    crab_cf_1.az.to_value(u.deg) - telescope_pointing.az.to_value(u.deg), 
    #    crab_cf_1.alt.to_value(u.deg) - telescope_pointing.alt.to_value(u.deg), 
    #    bins = 100,
    #    range = [[-0.5, 0.5], [-0.5, 0.5]]
    #)
    #ax.set_xlabel(r'$az \,/\, \mathrm{deg}$')
    #ax.set_ylabel(r'$alt \,/\, \mathrm{deg}$')

    crab_tf = crab_cf.transform_to(TelescopeFrame())
    ax.hist2d(
        crab_tf.fov_lon.to_value(u.deg),
        crab_tf.fov_lat.to_value(u.deg), 
        bins = 100,
        range = [[-0.3, 0.3], [-0.3, 0.3]]
    )
    ax.set_xlabel(r'fov_lon$ \,/\, \mathrm{deg}$')
    ax.set_ylabel(r'fov_lat$ \,/\, \mathrm{deg}$')

    return ax
Пример #5
0
def get_telescope_coordinates(telescope):
    """Return the astropy.coordinates EarthLocation object associated
    with the position of the telescope.
    The input must be either a string with the name of a telescope listed in
    Astropy's sites list 
    (https://github.com/astropy/astropy-data/blob/gh-pages/coordinates/sites.json),
    an EarthLocation object (which is passed through unchanged),
    or a 3-component tuple with the latitude [deg], longitude [deg], 
    and height [m].
    
    Since ASKAP is not yet listed in the Astropy sites list, it's position is
    manually coded in as a temporary measure.
    
    """
    if type(
            telescope
    ) == EarthLocation:  #Pass EarthLocations through without processing
        return telescope
    elif type(telescope) == str:  #Hardcoded coordinates for some telescopes.
        if telescope == 'ASKAP':
            lat = -1 * 26 + 42 / 60 + 15 / 3600  #degree
            long = +1 * 116 + 39 / 60 + 32 / 3600  # degree
            height = 381.0  #
        else:
            return EarthLocation.of_site(telescope)
        return EarthLocation(lat=lat * u.deg,
                             lon=long * u.deg,
                             height=height * u.m)
    elif (type(telescope) == tuple) or (type(telescope) == list):
        return EarthLocation(lat=telescope[0] * u.deg,
                             lon=telescope[1] * u.deg,
                             height=telescope[2] * u.m)
Пример #6
0
def EarthVelocity(t, site, psr, rot):
    """Get the proper earth velocity in RA-DEC coordinates in the pulsar frame.

    For data taken from a given site, relative to the sun.

    Parameters
    ----------
    t : `~astropy.time.Time`
        Time of the observation.
    site : `~astropy.coordinates.EarthLocation` or string
        Location or name of the observatory where data was taken.
    psr : `~astropy.coordinates.SkyCoord`
        Position of the pulsar.
    rot : `~astropy.coordinates.Angle`
        Angle at which to set the offset frame.

    Returns
    -------
    v_earth : `~astropy.units.Quantity`
        Site XYZ velocities in units of km/s, with X and Y giving the
        velocities in the RA and DEC directions.
    """
    psr_frame = SkyOffsetFrame(origin=psr, rotation=rot)
    if not isinstance(site, EarthLocation):
        site = EarthLocation.of_site(site)
    pos = site.get_gcrs(t).transform_to(psr_frame).cartesian
    vel = pos.differentials['s']
    return vel.d_xyz.to(u.km / u.s)
Пример #7
0
def test_icrs_to_camera():
    from ctapipe.coordinates import CameraFrame

    obstime = Time("2013-11-01T03:00")
    location = EarthLocation.of_site("Roque de los Muchachos")
    horizon_frame = AltAz(location=location, obstime=obstime)

    # simulate crab "on" observations
    crab = SkyCoord(ra="05h34m31.94s", dec="22d00m52.2s")
    telescope_pointing = crab.transform_to(horizon_frame)

    camera_frame = CameraFrame(
        focal_length=28 * u.m,
        telescope_pointing=telescope_pointing,
        location=location,
        obstime=obstime,
    )

    ceta_tauri = SkyCoord(ra="5h37m38.6854231s", dec="21d08m33.158804s")
    ceta_tauri_camera = ceta_tauri.transform_to(camera_frame)

    camera_center = SkyCoord(0 * u.m, 0 * u.m, frame=camera_frame)
    crab_camera = crab.transform_to(camera_frame)

    assert crab_camera.x.to_value(u.m) == approx(0.0, abs=1e-10)
    assert crab_camera.y.to_value(u.m) == approx(0.0, abs=1e-10)

    # assert ceta tauri is in FoV
    assert camera_center.separation_3d(ceta_tauri_camera) < u.Quantity(0.6, u.m)
Пример #8
0
 def test_EarthLocation(self):
     lowell = EarthLocation.of_site('Lowell Observatory')
     eph1 = Ephem.from_miriade("Ceres",
                               location=lowell,
                               epochs=Time('2019-01-01'))
     eph2 = Ephem.from_miriade("Ceres", epochs=Time('2019-01-01'))
     assert abs(eph1['RA'][0] - eph2['RA'][0]) > 0.0001 * u.deg
Пример #9
0
def _get_obs_param(ra, dec, mjd):
    ''' get observing condition given tileid and time of observation 
    '''
    from astropy.time import Time
    from astropy.coordinates import EarthLocation, SkyCoord, AltAz, get_sun, get_moon
    kpno = EarthLocation.of_site('kitt peak')

    # get observing conditions
    coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg)
    utc_time = Time(mjd, format='mjd')  # observed time (UTC)

    kpno_altaz = AltAz(obstime=utc_time, location=kpno)
    coord_altaz = coord.transform_to(kpno_altaz)

    airmass = coord_altaz.secz

    # sun
    sun = get_sun(utc_time)
    sun_altaz = sun.transform_to(kpno_altaz)
    sun_alt = sun_altaz.alt.deg
    sun_sep = sun.separation(coord).deg  # sun separation
    # moon
    moon = get_moon(utc_time)
    moon_altaz = moon.transform_to(kpno_altaz)
    moon_alt = moon_altaz.alt.deg
    moon_sep = moon.separation(coord).deg  #coord.separation(self.moon).deg

    elongation = sun.separation(moon)
    phase = np.arctan2(sun.distance * np.sin(elongation),
                       moon.distance - sun.distance * np.cos(elongation))
    moon_phase = phase.value
    moon_ill = (1. + np.cos(phase)) / 2.
    return airmass, moon_ill.value, moon_alt, moon_sep, sun_alt, sun_sep
Пример #10
0
def test_EarthLocation_basic():
    greenwichel = EarthLocation.of_site('greenwich')
    lon, lat, el = greenwichel.to_geodetic()
    assert_quantity_allclose(lon, Longitude('0:0:0', unit=u.deg),
                             atol=10*u.arcsec)
    assert_quantity_allclose(lat, Latitude('51:28:40', unit=u.deg),
                             atol=1*u.arcsec)
    assert_quantity_allclose(el, 46*u.m, atol=1*u.m)

    names = EarthLocation.get_site_names()
    assert 'greenwich' in names
    assert 'example_site' in names

    with pytest.raises(KeyError) as exc:
        EarthLocation.of_site('nonexistent site')
    assert exc.value.args[0] == "Site 'nonexistent site' not in database. Use EarthLocation.get_site_names to see available sites."
Пример #11
0
    def visibility_altaz(self, source_radec, site, hardcoded=True):
        """
        To each time grid point associates AltAz coordinates.
        :param source_radec: source coordinates (astropy SkyCoord object)
        :param site: (str)
        :return:
        """
        if not hasattr(self, 'vis_points'):
            raise AttributeError(
                'Must invoke visibility_points() before using this method')
        if not hardcoded:
            site_coords = EarthLocation.of_site(site)
        else:
            if site.lower() in ('north', 'roque de los muchachos'):
                #site_coords = EarthLocation.from_geodetic('342.1184', '28.7606', 2326. * u.meter)
                site_coords = EarthLocation.from_geocentric(5327285.09211954,
                                                            -1718777.11250295,
                                                            3051786.7327476,
                                                            unit="m")

            elif site.lower() in ('south', 'paranal'):
                #site_coords = EarthLocation.from_geodetic('289.5972', '-24.6253', 2635. * u.meter)
                site_coords = EarthLocation.from_geocentric(1946635.7979987,
                                                            -5467633.94561753,
                                                            -2642498.5212285,
                                                            unit="m")
            else:
                raise Warning(f"{site} is not a valid site choice")
        self.altaz = source_radec.transform_to(
            AltAz(obstime=self.vis_points, location=site_coords))
        return self
Пример #12
0
def test_icrs_to_camera():
    from ctapipe.coordinates import CameraFrame

    obstime = Time('2013-11-01T03:00')
    location = EarthLocation.of_site('Roque de los Muchachos')
    horizon_frame = AltAz(location=location, obstime=obstime)

    # simulate crab "on" observations
    crab = SkyCoord(ra='05h34m31.94s', dec='22d00m52.2s')
    telescope_pointing = crab.transform_to(horizon_frame)

    camera_frame = CameraFrame(
        focal_length=28 * u.m,
        telescope_pointing=telescope_pointing,
        location=location, obstime=obstime,
    )

    ceta_tauri = SkyCoord(ra='5h37m38.6854231s', dec='21d08m33.158804s')
    ceta_tauri_camera = ceta_tauri.transform_to(camera_frame)

    camera_center = SkyCoord(0 * u.m, 0 * u.m, frame=camera_frame)
    crab_camera = crab.transform_to(camera_frame)

    assert crab_camera.x.to_value(u.m) == approx(0.0, abs=1e-10)
    assert crab_camera.y.to_value(u.m) == approx(0.0, abs=1e-10)

    # assert ceta tauri is in FoV
    assert camera_center.separation_3d(ceta_tauri_camera) < u.Quantity(0.6, u.m)
Пример #13
0
def check_moon(file, avoid=30.*u.degree):
    if not isinstance(avoid, u.Quantity):
        avoid = float(avoid)*u.degree
    else:
        avoid = avoid.to(u.degree)

    header = fits.getheader(file)

    mlo = EarthLocation.of_site('Keck Observatory') # Update later
    obstime = Time(header['DATE-OBS'], format='isot', scale='utc', location=mlo)
    moon = get_moon(obstime, mlo)

    if 'RA' in header.keys() and 'DEC' in header.keys():
        coord_string = '{} {}'.format(header['RA'], header['DEC'])
        target = SkyCoord(coord_string, unit=(u.hourangle, u.deg))
    else:
        ## Assume zenith
        target = SkyCoord(obstime.sidereal_time('apparent'), mlo.latitude)

    moon_alt = moon.transform_to(AltAz(obstime=obstime, location=mlo)).alt.to(u.deg)
    if moon_alt < 0*u.degree:
        print('Moon is down')
        return True
    else:
        sep = target.separation(moon)
        print('Moon is up. Separation = {:.1f} deg'.format(sep.to(u.degree).value))
        return (sep > avoid)
Пример #14
0
 def at_site(cls, site_name, **kwargs):
    
     name = kwargs.pop('name', site_name)
     if 'location' in kwargs:
         raise ValueError("Location kwarg should not be used if "
                          "initializing an Observer with Observer.at_site()")
     return cls(location=EarthLocation.of_site(site_name), name=name, **kwargs)
Пример #15
0
def mwa_alt_az_za(obsid, ra=None, dec=None, degrees=False):
    """
	Calculate the altitude, azumith and zenith for an obsid
	
	Args:
	obsid : The MWA observation id (GPS time)
	ra : The right acension in HH:MM:SS
	dec : The declintation in HH:MM:SS
	degrees: If true the ra and dec is given in degrees (Default:False)
	"""
    from astropy.time import Time
    from astropy.coordinates import SkyCoord, AltAz, EarthLocation
    from astropy import units as u

    obstime = Time(float(obsid), format='gps')

    if ra is None or dec is None:
        #if no ra and dec given use obsid ra and dec
        ra, dec = get_common_obs_metadata(obsid)[1:3]

    if degrees:
        sky_posn = SkyCoord(ra, dec, unit=(u.deg, u.deg))
    else:
        sky_posn = SkyCoord(ra, dec, unit=(u.hourangle, u.deg))
    earth_location = EarthLocation.of_site('Murchison Widefield Array')
    #earth_location = EarthLocation.from_geodetic(lon="116:40:14.93", lat="-26:42:11.95", height=377.8)
    altaz = sky_posn.transform_to(
        AltAz(obstime=obstime, location=earth_location))
    Alt = altaz.alt.deg
    Az = altaz.az.deg
    Za = 90. - Alt
    return Alt, Az, Za
Пример #16
0
        def jd2hjd(self, jd, ra, dec):
            obj = SkyCoord(ra, dec, unit=(U.hourangle, U.deg), frame='icrs')
            greenwich = EarthLocation.of_site('greenwich')
            jd = tm(jd, format="jd", location=greenwich)
            ltt_helio = jd.light_travel_time(obj, 'heliocentric')

            return jd + ltt_helio
Пример #17
0
    def __init__(self, setting="H/1/4", detector=1, orders=None):
        super().__init__()
        self.setting = setting
        self.detector = detector
        self.orders = orders
        self.pixels = 2048
        self.resolution = 100_000
        self.pixel_size = 18 * u.um
        self.collection_area = (8 * u.m)**2
        self.integration_time = 5 * u.min
        self.bad_pixel_ratio = 4e5 / (2048**2)
        self.spectral_broadening = 2.3
        self.observatory = EarthLocation.of_site("Cerro Paranal")

        # TODO: gain / readnoise for each detector / wavelength range
        self.gain = [2.15, 2.19, 2.00]
        self.readnoise = [11, 12, 12]
        self.efficiency = 0.5  # About 50 percent makes it though

        self.regions, self.norders = self.__class__.load_spectral_regions(
            setting, detector, orders)
        self.blaze = self.__class__.load_blaze_function(
            setting, detector, orders)

        assert (len(self.regions) == len(self.blaze) == sum(
            self.norders)), "Incompatible sizes, something went wrong"

        # Expand detector values to the wavelength regions
        self.gain = np.repeat(self.gain, self.norders)
        self.readnoise = np.repeat(self.readnoise, self.norders)
Пример #18
0
    def __init__(self):
        self.config = yaml.safe_load(open('solar_config.yml', 'r'))
        self.nohardware = self.config['no-hardware']
        self.site = EarthLocation.of_site('lowell')
        self.tz = pytz.timezone('US/Arizona')
        if self.nohardware:
            self.guider = FakeGuider()
            self.camera = FakeCamera()
            self.telescope = FakeTelescope()
        else:
            self.guider = Guider()
            self.camera = Camera()
            self.telescope = Telescope()
        self.planner = expres_solar_planner()
        self.sio = socketio.Client()
        self.sio.connect('http://localhost:8081')
        self.scheduler = BackgroundScheduler()
        self.scheduler.start()
        self.scheduler.add_job(self.getDayPlan,
                               'cron',
                               hour=1,
                               minute=0,
                               replace_existing=True)

        self.getDayPlan()  # Also need to run this on the first run through
        t = Time(datetime.now())
        if (t < Time(self.planner.sun_up)):
            return
        elif (t < Time(self.planner.meridian_flip)):
            self.morning()
        elif (t < Time(self.planner.sun_down)):
            self.afternoon()
        else:
            return
Пример #19
0
def check_moon(file, avoid=30. * u.degree):
    if not isinstance(avoid, u.Quantity):
        avoid = float(avoid) * u.degree
    else:
        avoid = avoid.to(u.degree)

    header = fits.getheader(file)

    mlo = EarthLocation.of_site('Keck Observatory')  # Update later
    obstime = Time(header['DATE-OBS'],
                   format='isot',
                   scale='utc',
                   location=mlo)
    moon = get_moon(obstime, mlo)

    if 'RA' in header.keys() and 'DEC' in header.keys():
        coord_string = '{} {}'.format(header['RA'], header['DEC'])
        target = SkyCoord(coord_string, unit=(u.hourangle, u.deg))
    else:
        ## Assume zenith
        target = SkyCoord(obstime.sidereal_time('apparent'), mlo.latitude)

    moon_alt = moon.transform_to(AltAz(obstime=obstime,
                                       location=mlo)).alt.to(u.deg)
    if moon_alt < 0 * u.degree:
        print('Moon is down')
        return True
    else:
        sep = target.separation(moon)
        print('Moon is up. Separation = {:.1f} deg'.format(
            sep.to(u.degree).value))
        return (sep > avoid)
Пример #20
0
        def jd2bjd(self, jd, ra, dec):
            obj = SkyCoord(ra, dec, unit=(U.hourangle, U.deg), frame='icrs')
            greenwich = EarthLocation.of_site('greenwich')
            self.logger.warning("JD: {}".format(jd))
            jd = tm(jd, format="jd", location=greenwich)
            ltt_bary = jd.light_travel_time(obj)

            return jd + ltt_bary
Пример #21
0
def MMT_barycentric_correction(sp, header_MMT) :  # Applying barycentric correction to wavelengths
    thistime =  Time('2014-05-05T09:21:00', format='isot', scale='utc')
    thisradec = SkyCoord("17:23:37.23", "+34:11:59.07", unit=(u.hourangle, u.deg), frame='icrs')
    mmt= EarthLocation.of_site('mmt') # Needs internet connection 
    barycor_vel = jrr.barycen.compute_barycentric_correction(thistime, thisradec, location=mmt)
    header_MMT += ("# The barycentric correction factor for s1723 was" + str(barycor_vel))
    jrr.barycen.apply_barycentric_correction(sp, barycor_vel, colwav='oldwave', colwavnew='wave') 
    return(0)
Пример #22
0
def heliocorrection(ra, dec, ot):
    location = 'gemini_north'
    uh88 = EarthLocation.of_site(location)
    sc = SkyCoord(ra=ra * u.deg, dec=dec * u.deg)
    heliocorr = sc.radial_velocity_correction('heliocentric',
                                              obstime=ot,
                                              location=uh88)
    return (heliocorr.to(u.km / u.s))
Пример #23
0
def dct_loc():
    location_name = 'Discovery Channel Telescope'
    try:
        dct_loc_dict = pickle.load(open(settings.DCT_LOC_PICKLE, 'rb'))
    except FileNotFoundError:
        dct_loc_dict = {'archive_time': dt.utcnow(), 'location': EarthLocation.of_site(location_name)}
        file = open(settings.DCT_LOC_PICKLE, 'wb')
        pickle.dump(dct_loc_dict, file)
        file.close()
    archive_time = dct_loc_dict['archive_time']
    dct_loc_obj = dct_loc_dict['location']
    if (dt.utcnow()-archive_time) > td(days=2):
        dct_loc_dict = {'archive_time': dt.utcnow(), 'location': EarthLocation.of_site(location_name)}
        file = open(settings.DCT_LOC_PICKLE, 'wb')
        pickle.dump(dct_loc_dict, file)
        file.close()
    return dct_loc_obj
Пример #24
0
def main():

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--ra', type=float, default=25.0,
        help='Right Ascension (degrees)')
    parser.add_argument('--dec', type=float, default=12.0,
        help='Declination (degrees)')
    parser.add_argument('--mjd', type=float, default=55000.0,
        help='Modified Julien Date (days)')
    parser.add_argument('--scan-offset', type=float, default=15.0,
        help='Scan offset (hours)')
    parser.add_argument('--scan-width', type=float, default=4.0,
        help='Scan width (hours)')
    parser.add_argument('--scan-steps', type=int, default=100,
        help='Number of sampling points')
    parser.add_argument('--astropy-apo', action='store_true',
        help='User apo observatory from astropy')
    args = parser.parse_args()

    if args.astropy_apo:
        sdss = EarthLocation.of_site('apo')
    else:
        sdss = EarthLocation(lat=32.7797556*u.deg, lon=-(105+49./60.+13/3600.)*u.deg, height=2797*u.m)

    coord = SkyCoord(ra=args.ra*u.degree, dec=args.dec*u.degree, frame='icrs')

    # scan of time
    hours = args.scan_offset + np.linspace(-0.5*args.scan_width, 0.5*args.scan_width, args.scan_steps)
    my_alt = np.zeros((hours.size))
    py_alt = np.zeros((hours.size))
    py_ha = np.zeros((hours.size))

    for i in range(hours.size):
        mjd_value = args.mjd*u.day + hours[i]*u.hour
        time = Time(val=mjd_value, scale='tai', format='mjd', location=sdss)
        # altitude from astropy
        py_alt[i] = coord.transform_to(AltAz(obstime=time, location=sdss)).alt.to(u.deg).value
        # this is supposed to be the hour angle from astropy
        py_ha[i] = time.sidereal_time('apparent').to(u.deg).value - args.ra 
        # simple rotation to get alt,az based on ha
        my_alt[i], az = hadec2altaz(py_ha[i], args.dec, sdss.latitude.to(u.deg).value) 
        print hours[i], py_ha[i], py_alt[i], my_alt[i]

    py_ha = np.array(map(normalize_angle, py_ha.tolist()))
    ii = np.argsort(py_ha)
    py_ha=py_ha[ii]
    py_alt=py_alt[ii]
    my_alt=my_alt[ii]

    fig = plt.figure(figsize=(8,6))
    plt.plot(py_ha, py_alt - my_alt, 'o', c='b')
    plt.title('Compare hadec2altaz')
    # plt.title('(ra,dec) = (%.2f,%.2f)' % (args.ra, args.dec))
    plt.xlabel('Hour Angle [deg]')
    plt.ylabel('astropy_alt - rotation_alt [deg]')
    plt.grid(True)
    plt.show()
Пример #25
0
def to_location_via_telescope_name(self):
    """Calculate the observatory location via the telescope name.

    Returns
    -------
    loc : `astropy.coordinates.EarthLocation`
        Location of the observatory.
    """
    return EarthLocation.of_site(self.to_telescope())
Пример #26
0
 def test_to_skycoord(self):
     t = Time('2001-01-01 12:00:00', scale='utc')
     g = EarthLocation.of_site('greenwich')
     a = grand_tools.astro.AstroConversion(longitude=g.lon,
                                           latitude=g.lat,
                                           altitude=g.height)
     c = a.to_skycoord(theta='0d', phi='0d', time=t)
     self.assertAlmostEqual(c.ra.value, 281.20741528)
     self.assertAlmostEqual(c.dec.value, 51.47647952)
Пример #27
0
    def __init__(self):
        super().__init__()

        # TODO :: Might need to change the tolerance of disperser angle in
        # pypeit setup (two BH2 nights where sufficiently different that this
        # was important).

        # TODO :: Might consider changing TelescopePar to use the astropy
        # EarthLocation. KBW: Fine with me!
        self.location = EarthLocation.of_site('Keck Observatory')
Пример #28
0
def test_EarthLocation_basic():
    greenwichel = EarthLocation.of_site('greenwich')
    lon, lat, el = greenwichel.to_geodetic()
    assert_quantity_allclose(lon,
                             Longitude('0:0:0', unit=u.deg),
                             atol=10 * u.arcsec)
    assert_quantity_allclose(lat,
                             Latitude('51:28:40', unit=u.deg),
                             atol=1 * u.arcsec)
    assert_quantity_allclose(el, 46 * u.m, atol=1 * u.m)

    names = EarthLocation.get_site_names()
    assert 'greenwich' in names
    assert 'example_site' in names

    with pytest.raises(KeyError) as exc:
        EarthLocation.of_site('nonexistent site')
    assert exc.value.args[
        0] == "Site 'nonexistent site' not in database. Use EarthLocation.get_site_names to see available sites."
Пример #29
0
def test_detector_frame():
    site_1 = EarthLocation.of_site('H1')
    site_2 = EarthLocation.of_site('L1')
    t = Time(1e9, format='gps')

    detector_frame = DetectorFrame(site_1=site_1, site_2=site_2, obstime=t)
    itrs_frame = ITRS(obstime=t)

    itrs_coord = SkyCoord(*(u.Quantity(site_1.geocentric) -
                            u.Quantity(site_2.geocentric)).value,
                          frame=itrs_frame)
    assert itrs_coord.transform_to(detector_frame).lat.deg == 90

    detector_coord = SkyCoord(lon=0 * u.deg,
                              lat=90 * u.deg,
                              frame=detector_frame)
    converted = detector_coord.transform_to(itrs_frame)
    assert converted.spherical.lon.deg == approx(itrs_coord.spherical.lon.deg)
    assert converted.spherical.lat.deg == approx(itrs_coord.spherical.lat.deg)
Пример #30
0
def altitude(time, ra, dec):
    """
    This returns altitude with respect to GBT given right ascension, declination, and time
    """
    s = SkyCoord(ra=time * u.rad, dec=dec * u.rad, frame="icrs")
    time = Time(time, format="mjd", scale="utc")
    loc = EarthLocation.of_site("Green Bank Telescope")
    attribute = AltAz(obstime=time, location=loc)
    altaz = s.transform_to(attribute)
    alt = altaz.alt.value
    return alt
Пример #31
0
 def __init__(self, filename, location):
     self.hdu_list = fits.open(filename)
     self.hdr = self.hdu_list[0].header
     self.ra = self.hdr['RA']
     self.dec = self.hdr['DEC']
     try:
         self.location = EarthLocation.of_site(location)
     except errors.UnknownSiteException:
         print('Unknown site, use one of these sites:')
         print(EarthLocation.get_site_names())
         sys.exit(1)
Пример #32
0
def get_earth_location_coordinates(location):
    """
    Gets the Lat and Long on earth from a location (Site)
    """
    real_location = EarthLocation.of_site(location)

    long_lat_repr = real_location.to_geodetic()
    longi = long_lat_repr.lon.deg
    lat = long_lat_repr.lat.deg

    return lat, longi
Пример #33
0
 def create(self, name=None):
     """Create site"""
     try:
         if name is None:
             return EarthLocation(lat=self._lati_,
                                  lon=self._long_,
                                  height=self._alti_ * units.m)
         else:
             return EarthLocation.of_site(name)
     except Exception as e:
         self.logger.error(e)
Пример #34
0
def BJDConvert(mjd, RA, Dec):
    times = mjd
    t = Time(times, format='mjd', scale='utc')
    t2 = t.tdb
    c = SkyCoord(RA, Dec, unit="deg")
    d = c.transform_to(BarycentricTrueEcliptic)
    Palomar = EarthLocation.of_site('Palomar')
    delta = t2.light_travel_time(c, kind='barycentric', location=Palomar)
    BJD_TDB = t2 + delta

    return BJD_TDB
Пример #35
0
    def to_location(self):
        """Calculate the observatory location.
        Returns
        -------
        location : `astropy.coordinates.EarthLocation`
            An object representing the location of the telescope.
        """

        # Look up the value since files do not have location
        value = EarthLocation.of_site("paranal")

        return value
Пример #36
0
    def __init__(self, date=None, site='sutherland', targets=None, tz=2*u.h, **options): #res
        
        self.sitename = site.title()
        self.siteloc = EarthLocation.of_site(self.sitename)
        #TODO from time import timezone
        self.tz = tz                         #can you get this from the site location??
        #obs = Observer(self.siteloc)
        self.targets = {}
        self.trajectories = {}
        self.plots = OrderedDict()
        
        if not date:
            now = datetime.now()        #current local time
            #default behaviour of this function changes depending on the time of day.
            #if calling during early morning hours (at telescope) - let midnight refer to previous midnight
            #if calling during afternoon hours - let midnight refer to coming midnight
            d = now.day# + (now.hour > 7)    #FIXME =32??
            date = datetime(now.year, now.month, d, 0, 0, 0)
        else:
            raise NotImplementedError
        self.date = date
        
        self.midnight = midnight = Time(date) - tz    #midnight UTC in local time
        #TODO: efficiency here.  Dont need to plot everything over 
        self.hours = h = np.linspace(-12, 12, 250) * u.h      #variable time 
        self.t = t = midnight + h
        self.tp = t.plot_date
        self.frames = AltAz(obstime=t, location=self.siteloc)
        #self.tmoon
        
        #collect name, coordinates in dict

        if not targets is None:
            self.add_coordinates(targets)
        
        #Get sun, moon coordinates
        sun = get_sun(t)
        self.sun = sun.transform_to(self.frames)    #WARNING: slow!!!!
        #TODO: other bright stars / planets
        
        #get dawn / dusk times
        self.dusk, self.dawn = self.get_daylight()
        self.sunset, self.sunrise = self.dusk['sunset'], self.dawn['sunrise']
        
        #get moon rise/set times, phase, illumination etc...
        self.moon = get_moon(t).transform_to(self.frames)
        self.mooning = self.get_moonlight()
        self.moon_phase, self.moon_ill  = self.get_moon_phase()
        
        self.setup_figure()
        #HACK
        self.cid = self.figure.canvas.mpl_connect('draw_event', self._on_first_draw)
Пример #37
0
def calc_dist(df, coord, n_offs, OFF=False):
    if coord is not None:
        crab = SkyCoord.from_name(coord)
        altaz = AltAz(
            location = EarthLocation.of_site('Roque de los Muchachos'),
            obstime = Time(df.dragon_time, format='unix')
        )
        telescope_pointing = SkyCoord(
            alt = u.Quantity(df.alt_tel.to_numpy(), u.rad, copy=False),
            az = u.Quantity(df.az_tel.to_numpy(), u.rad, copy=False),
            frame = altaz
        )
        camera_frame = CameraFrame(
            focal_length = u.Quantity(df.focal_length.to_numpy(), u.m, copy=False),
            telescope_pointing = telescope_pointing,
            location = EarthLocation.of_site('Roque de los Muchachos'),
            obstime = Time(df.dragon_time, format='unix')
        )
        crab_cf = crab.transform_to(camera_frame)

        if OFF == False:
            dist = (df.source_x_prediction - crab_cf.x.to_value(u.m))**2 + (df.source_y_prediction - crab_cf.y.to_value(u.m))**2
        elif OFF == True and n_offs != 1:
            r = np.sqrt(crab_cf.x.to_value(u.m)**2 + crab_cf.y.to_value(u.m)**2)
            phi = np.arctan2(crab_cf.y.to_value(u.m), crab_cf.x.to_value(u.m))

            dist = pd.Series()
            for i in range(1, n_offs + 1):
                x_off = r * np.cos(phi + i * 2 * np.pi / (n_offs + 1)) 
                y_off = r * np.sin(phi + i * 2 * np.pi / (n_offs + 1))
                dist = dist.append(
                    (df.source_x_prediction - x_off)**2 + (df.source_y_prediction - y_off)**2
                )
        else:
            dist = df.source_x_prediction**2 + df.source_y_prediction**2
    else:
        dist = df.source_x_prediction**2 + df.source_y_prediction**2
    
    return dist
Пример #38
0
def get_coordinates_from_observer(righta, dec, location, obstime):
    """
    Gets the Alt and Az of an Ra and Dec from a location and time 
    """
    real_time = Time(obstime)
    real_location = EarthLocation.of_site(location)

    real_coordinates = SkyCoord(righta, dec, unit=("hour", "deg"))

    alt_az = real_coordinates.transform_to(
        AltAz(obstime=real_time, location=real_location))

    return alt_az.az.deg, alt_az.alt.deg
Пример #39
0
def get_the_spectra(filenames, obslog, colwave='obswave') :
    df = {}
    for thisfile in filenames :
        print("loading file ", thisfile)
        df[thisfile] = pandas.read_table(thisfile, delim_whitespace=True, comment="#")
        # Apply the Barycentric correction
        thisobs = obslog.loc[thisfile]
        keck = EarthLocation.of_site('keck')
        my_target = SkyCoord(thisobs['RA'], thisobs['DEC'], unit=(units.hourangle, units.deg), frame='icrs')
        my_start_time = Time( thisobs['DATE-OBS'] + "T" + thisobs['UT_START'] , format='isot', scale='utc')
        midpt = TimeDelta(thisobs['EXPTIME'] / 2.0, format='sec')
        my_time = my_start_time + midpt  # time at middle of observation
        barycor_vel = jrr.barycen.compute_barycentric_correction(my_time, my_target, location=keck)
        #print "DEBUGGING", my_target, thisobs, my_target, my_start_time
        print("FYI, the barycentric correction factor for", thisfile,  "was", barycor_vel)
        jrr.barycen.apply_barycentric_correction(df[thisfile], barycor_vel, colwav='obswave', colwavnew='wave') #   
        df[thisfile]['Nfiles'] = 1 # N of exposures that went into this spectrum
    return(df)  # return a dictionary of dataframes of spectra
Пример #40
0
def getMonths(ra, dec):
    from astropy import units as u
    from astropy.time import Time
    from astropy.coordinates import SkyCoord, EarthLocation, AltAz, get_sun, FK5
    from datetime import datetime
    fk5 = SkyCoord(ra, dec, frame='fk5')
    # fk5c = SkyCoord(ra, dec, frame='fk5')
    # print fk5c
     # same as SkyCoord.from_name('M33'): use the explicit coordinates to allow building doc plots w/o internet
    kpno = EarthLocation.of_site('kpno')
    utcoffset = -7*u.hour  # Mountain Standard Time

    delta_midnight = np.linspace(-5, 5,11)*u.hour

    months = np.array([1,2,3,4,5,6,7,8,9,10,11,12])
    days = np.array([7, 14, 21, 28])
    monthDict = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
    monthBool = []
    for m in months:
        upMonth = [False, False, False, False]
        for j,day in enumerate(days):
            t = datetime(2017, m, day, 00, 00, 00)
            midnight = Time(t) - utcoffset
            times = midnight + delta_midnight
            # print times
            altazframe = AltAz(obstime=times, location=kpno)
            # sunaltazs = get_sun(times).transform_to(altazframe)
            fk5altazs = fk5.transform_to(altazframe)
            am = fk5altazs.secz
            # print am
            up = np.where((am < 1.5) & (am > 1.0))
            # print len(up[0])
            if len(up[0]) >= 3:
                upMonth[j] = True
        # print upMonth
        if any(upMonth):
            monthBool.append(True)
        else:
            monthBool.append(False)
    monthBool = np.array(monthBool)
    obsmonths = months[monthBool]
    return obsmonths
Пример #41
0
def test_separation_is_the_same():
    from ctapipe.coordinates import TelescopeFrame

    obstime = Time('2013-11-01T03:00')
    location = EarthLocation.of_site('Roque de los Muchachos')
    horizon_frame = AltAz(location=location, obstime=obstime)

    crab = SkyCoord(ra='05h34m31.94s', dec='22d00m52.2s')
    ceta_tauri = SkyCoord(ra='5h37m38.6854231s', dec='21d08m33.158804s')

    # simulate crab "on" observations
    telescope_pointing = crab.transform_to(horizon_frame)

    telescope_frame = TelescopeFrame(
        telescope_pointing=telescope_pointing,
        location=location,
        obstime=obstime,
    )

    ceta_tauri_telescope = ceta_tauri.transform_to(telescope_frame)
    crab_telescope = crab.transform_to(telescope_frame)

    sep = ceta_tauri_telescope.separation(crab_telescope).to_value(u.deg)
    assert ceta_tauri.separation(crab).to_value(u.deg) == approx(sep, rel=1e-4)
Пример #42
0
def plot_moon(ra, dec, year, months, outfile='plot_moon.png'):
    """
    This will plot distance/illumination of moon
    for one specified month
    """
    # Setup local time.
    utc_offset = 10 * u.hour   # Hawaii Standard Time
        
    month_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

    # Observatory (for symbol)
    keck_loc = EarthLocation.of_site('keck')
    keck = ephem.Observer()
    keck.long = keck_loc.longitude.value
    keck.lat = keck_loc.latitude.value
    
    # Setup Object
    obj = ephem.FixedBody()
    obj._ra = ephem.hours(ra)
    obj._dec = ephem.degrees(dec)
    obj._epoch = 2000
    obj.compute()
    
    month_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

    # Labels and colors for different months.
    labels = []
    label_fmt = '{0:s} {1:d}'
    for ii in range(len(months)):
        label = label_fmt.format(month_labels[months[ii]-1], year)
        labels.append(label)

    sym = ['rD', 'bD', 'gD', 'cD', 'mD', 'yD']
    colors = ['r', 'b', 'g', 'c', 'm', 'y']

    daysInMonth = np.arange(1, 31)

    moondist = np.zeros(len(daysInMonth), dtype=float)
    moonillum = np.zeros(len(daysInMonth), dtype=float)

    moon = ephem.Moon()

    py.close(3)
    py.figure(3, figsize=(7, 7))
    py.clf()
    py.subplots_adjust(left=0.1)

    for mm in range(len(months)):
        for dd in range(len(daysInMonth)):
            # Set the date and time to midnight
            keck.date = '%d/%d/%d %d' % (year, months[mm],
                                         daysInMonth[dd],
                                         utc_offset.value)

            moon.compute(keck)
            obj.compute(keck)
            sep = ephem.separation((obj.ra, obj.dec), (moon.ra, moon.dec))
            sep *= 180.0 / math.pi

            moondist[dd] = sep
            moonillum[dd] = moon.phase

            print( 'Day: %2d   Moon Illum: %4.1f   Moon Dist: %4.1f' % \
                  (daysInMonth[dd], moonillum[dd], moondist[dd]))

        py.plot(daysInMonth, moondist, sym[mm],label=labels[mm])

        for dd in range(len(daysInMonth)):
            py.text(daysInMonth[dd] + 0.45, moondist[dd]-2, '%2d' % moonillum[dd], 
                    color=colors[mm])

    py.plot([0,31], [30,30], 'k')
    py.legend(loc=2, numpoints=1)
    py.title('Moon distance and %% Illumination (RA = %s, DEC = %s)' % (ra, dec), fontsize=14)
    py.xlabel('Day of Month (UT)', fontsize = 16)
    py.ylabel('Moon Distance (degrees)', fontsize = 16)
    py.axis([0, 31, 0, 200])

    py.savefig(outfile)
Пример #43
0
    if os.path.exists(bis_g2_path):
        with fits.open(bis_g2_path) as image:
            for h in cal_header_keys:
                harps_results[trim_eso_header(h)][i] = image[0].header.get(h, np.nan)
                print(h, image[0].header.get(h, np.nan))

    else:
        logger.warning(f"Could not find calibration file ({bis_g2_path}) for {dataset_identifier}")


# Step 6: Add an astropy-calculated barycentric velocity correction to each
#         header.

logger.info("Calculating barycentric velocity corrections")

observatory = EarthLocation.of_site("lasilla")
gaia_coord = SkyCoord(ra=gaia_result["ra"] * u.degree,
                      dec=gaia_result["dec"] * u.degree,
                      pm_ra_cosdec=gaia_result["pmra"] * u.mas/u.yr,
                      pm_dec=gaia_result["pmdec"] * u.mas/u.yr,
                      obstime=Time(2015.5, format="decimalyear"),
                      frame="icrs")

def apply_space_motion(coord, time):
    return SkyCoord(ra=coord.ra + coord.pm_ra_cosdec/np.cos(coord.dec.radian) * (time - coord.obstime),
                    dec=coord.dec + coord.pm_dec * (time - coord.obstime),
                    obstime=time, frame="icrs")


berv_key = "ASTROPY BERV"
harps_results[berv_key] = np.nan * np.ones(len(harps_results))
def main():

    ##-------------------------------------------------------------------------
    ## Parse Command Line Arguments
    ##-------------------------------------------------------------------------
    ## create a parser object for understanding command-line arguments
    parser = argparse.ArgumentParser(
             description="Program description.")
    ## add flags
    ## add arguments
    parser.add_argument("-y", "--year",
        type=int, dest="year",
        default=-1,
        help="The calendar year to analyze")
    parser.add_argument("-s", "--site",
        type=str, dest="site",
        default='Keck Observatory',
        help="Site name to use")
    parser.add_argument("-z", "--timezone",
        type=str, dest="timezone",
        default='US/Hawaii',
        help='pytz timezone name')
    parser.add_argument("-d", "--dark_time",
        type=float, dest="dark_time",
        default=2,
        help='Minimum dark time required (hours)')
    parser.add_argument("-w", "--wait_time",
        type=float, dest="wait_time",
        default=2.5,
        help='Maximum time after dusk to wait for moon set (hours)')

    args = parser.parse_args()

    if args.year == -1:
        args.year = dt.now().year

    ##-------------------------------------------------------------------------
    ## 
    ##-------------------------------------------------------------------------
    loc = EarthLocation.of_site(args.site)
    obs = Observer.at_site(args.site)
    utc = pytz.timezone('UTC')
    localtz = pytz.timezone(args.timezone)
#     hour = tdelta(seconds=60.*60.*1.)

#     pyephem_site = ephem.Observer()
#     pyephem_site.lat = str(loc.lat.to(u.degree).value)
#     pyephem_site.lon = str(loc.lon.to(u.deg).value)
#     pyephem_site.elevation = loc.height.to(u.m).value
#     pyephem_moon = ephem.Moon()

    oneday = TimeDelta(60.*60.*24., format='sec')
    date_iso_string = '{:4d}-01-01T00:00:00'.format(args.year)
    start_date = Time(date_iso_string, format='isot', scale='utc', location=loc)
    sunset = obs.sun_set_time(start_date, which='next')

    ical_file = 'DarkMoonCalendar_{:4d}.ics'.format(args.year)
    if os.path.exists(ical_file): os.remove(ical_file)
    with open(ical_file, 'w') as FO:
        FO.write('BEGIN:VCALENDAR\n'.format())
        FO.write('PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'.format())

        while sunset < start_date + 365*oneday:
            search_around = sunset + oneday
            sunset = analyze_day(search_around, obs, FO, localtz, args,
                                 verbose=True)
        FO.write('END:VCALENDAR\n')
Пример #45
0
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
from astropy.time import Time
from pytest import approx

location = EarthLocation.of_site('Roque de los Muchachos')


def test_cam_to_nominal():
    from ctapipe.coordinates import CameraFrame, NominalFrame

    telescope_pointing = SkyCoord(alt=70 * u.deg, az=0 * u.deg, frame=AltAz())
    array_pointing = SkyCoord(alt=72 * u.deg, az=0 * u.deg, frame=AltAz())

    cam_frame = CameraFrame(focal_length=28 * u.m, telescope_pointing=telescope_pointing)
    cam = SkyCoord(x=0.5 * u.m, y=0.1 * u.m, frame=cam_frame)

    nom_frame = NominalFrame(origin=array_pointing)
    cam.transform_to(nom_frame)


def test_icrs_to_camera():
    from ctapipe.coordinates import CameraFrame

    obstime = Time('2013-11-01T03:00')
    location = EarthLocation.of_site('Roque de los Muchachos')
    horizon_frame = AltAz(location=location, obstime=obstime)

    # simulate crab "on" observations
    crab = SkyCoord(ra='05h34m31.94s', dec='22d00m52.2s')
Пример #46
0
def plot_airmass(ra, dec, year, months, days, observatory, outfile='plot_airmass.png', date_idx = 0):
    """
    ra =  R.A. value of target (e.g. '17:45:40.04')
    dec = Dec. value of target (e.g. '-29:00:28.12')
    year = int value of year you want to observe
    months = array of months (integers) where each month will have a curve.
    days = array of days (integers), of same length as months.
    observatory = Either 'keck1' or 'keck2'
    date_idx = Index of day to use for twilight dashed lines.  Defaults to first day.

    Notes:
    Months are 1-based (i.e. 1 = January). Same for days.
    """
    # Setup the target
    target = SkyCoord(ra, dec, unit=(u.hour, u.deg), frame='icrs')

    # Setup local time.
    utc_offset = -10 * u.hour   # Hawaii Standard Time
        
    month_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

    # Observatory (for symbol)
    obs = 'keck'
    keck = EarthLocation.of_site('keck')

    # Labels and colors for different months.
    labels = []
    label_fmt = '{0:s} {1:d}, {2:d} (HST)'
    for ii in range(len(months)):
        label = label_fmt.format(month_labels[months[ii]-1],
                                 days[ii], year)
        labels.append(label)

    colors = ['r', 'b', 'g', 'c', 'm', 'y']

    # Get sunset and sunrise times on the first specified day
    midnight = Time('{0:d}-{1:d}-{2:d} 00:00:00'.format(year, months[date_idx], days[date_idx])) - utc_offset
    delta_midnight = np.arange(-12, 12, 0.01) * u.hour
    times = midnight + delta_midnight
    altaz_frame = AltAz(obstime=times, location=keck)
    sun_altaz = get_sun(times).transform_to(altaz_frame)

    sun_down = np.where(sun_altaz.alt < -0*u.deg)[0]
    twilite = np.where(sun_altaz.alt < -12*u.deg)[0]
    sunset = delta_midnight[sun_down[0]].value
    sunrise = delta_midnight[sun_down[-1]].value
    twilite1 = delta_midnight[twilite[0]].value
    twilite2 = delta_midnight[twilite[-1]].value

    # Get the half-night split times
    splittime = twilite1 + ((twilite2 - twilite1) / 2.0)

    print( 'Sunrise %4.1f   Sunset %4.1f  (hours around midnight HST)' % (sunrise, sunset))
    print( '12-degr %4.1f  12-degr %4.1f  (hours around midnight HST)' % (twilite1, twilite2))

    py.close(3)
    py.figure(3, figsize=(7, 7))
    py.clf()
    py.subplots_adjust(left=0.1)
    for ii in range(len(days)):
        midnight = Time('{0:d}-{1:d}-{2:d} 00:00:00'.format(year, months[ii], days[ii])) - utc_offset
        delta_midnight = np.arange(-7, 7, 0.2) * u.hour
        times = delta_midnight.value

        target_altaz = target.transform_to(AltAz(obstime=midnight + delta_midnight,
                                                 location=keck))
        
        airmass = target_altaz.secz

        # Trim out junk where target is at "negative airmass"
        good = np.where(airmass > 0)[0]
        times = times[good]
        airmass = airmass[good]

        # Find the points beyond the Nasmyth deck. Also don't bother with anything above sec(z) = 3
        transitTime = times[airmass.argmin()]

        if observatory == 'keck2':
            belowDeck = (np.where((times >= transitTime) & (airmass >= 1.8)))[0]
            aboveDeck = (np.where(((times >= transitTime) & (airmass < 1.8)) |
                            (times < transitTime)))[0]
        else:
            belowDeck = (np.where((times <= transitTime) & (airmass >= 1.8)))[0]
            aboveDeck = (np.where(((times <= transitTime) & (airmass < 1.8)) |
                            (times > transitTime)))[0]
            
        py.plot(times[belowDeck], airmass[belowDeck], colors[ii] + 'o', mfc='w', mec=colors[ii], ms=12)
        py.plot(times[aboveDeck], airmass[aboveDeck], colors[ii] + 'o', mec=colors[ii], ms=12)
        py.plot(times, airmass, colors[ii] + '-')

        py.text(-3.5,
                airmass[15] + (ii*0.1) - 0.65,
                labels[ii], color=colors[ii])

    # Make observatory name nice for title
    if observatory == "keck1":
        observatory = 'Keck I'
    if observatory == "keck2":
        observatory = 'Keck II'
        
    py.title('Obs. RA = 18:00, DEC = -30:00 from %s' %observatory, fontsize = 18)
#    py.title('Observing RA = %s, DEC = %s from %s' % (ra, dec, observatory), fontsize=14)
    py.xlabel('Local Time in Hours (0 = midnight)', fontsize=16)
    py.ylabel('Air Mass', fontsize=16)

    loAirmass = 1
    hiAirmass = 2.2

    # Draw on the 12-degree twilight limits
    py.axvline(splittime, color='k', linestyle='--')
    py.axvline(twilite1 + 0.5, color='k', linestyle='--')
    py.axvline(twilite2, color='k', linestyle='--')

    py.axis([sunset, sunrise, loAirmass, hiAirmass])
    py.savefig(outfile)
Пример #47
0
def demo_site_chooser() :
    EarthLocation.get_site_names()  # Print names of all sites astropy knows about. May need internet connection
    keck = EarthLocation.of_site('keck')  
    lco  = EarthLocation.of_site('Las Campanas Observatory') 
    return(0)