Пример #1
0
def test_itrs_vals_5133():
    time = Time('2010-1-1')
    el = EarthLocation.from_geodetic(lon=20*u.deg, lat=45*u.deg, height=0*u.km)

    lons = [20, 30, 20]*u.deg
    lats = [44, 45, 45]*u.deg
    alts = [0, 0, 10]*u.km
    coos = [EarthLocation.from_geodetic(lon, lat, height=alt).get_itrs(time)
            for lon, lat, alt in zip(lons, lats, alts)]

    aaf = AltAz(obstime=time, location=el)
    aacs = [coo.transform_to(aaf) for coo in coos]

    assert all([coo.isscalar for coo in aacs])

    # the ~1 arcsec tolerance is b/c aberration makes it not exact
    assert_quantity_allclose(aacs[0].az, 180*u.deg, atol=1*u.arcsec)
    assert aacs[0].alt < 0*u.deg
    assert aacs[0].distance > 50*u.km

    # it should *not* actually be 90 degrees, b/c constant latitude is not
    # straight east anywhere except the equator... but should be close-ish
    assert_quantity_allclose(aacs[1].az, 90*u.deg, atol=5*u.deg)
    assert aacs[1].alt < 0*u.deg
    assert aacs[1].distance > 50*u.km

    assert_quantity_allclose(aacs[2].alt, 90*u.deg, atol=1*u.arcsec)
    assert_quantity_allclose(aacs[2].distance, 10*u.km)
Пример #2
0
def check_builtin_matches_remote(download_url=True):
    """
    This function checks that the builtin sites registry is consistent with the
    remote registry (or a registry at some other location).

    Note that current this is *not* run by the testing suite (because it
    doesn't start with "test", and is instead meant to be used as a check
    before merging changes in astropy-data)
    """
    builtin_registry = EarthLocation._get_site_registry(force_builtin=True)
    dl_registry = EarthLocation._get_site_registry(force_download=download_url)

    in_dl = {}
    matches = {}
    for name in builtin_registry.names:
        in_dl[name] = name in dl_registry
        if in_dl[name]:
            matches[name] = quantity_allclose(builtin_registry[name], dl_registry[name])
        else:
            matches[name] = False

    if not all(matches.values()):
        # this makes sure we actually see which don't match
        print("In builtin registry but not in download:")
        for name in in_dl:
            if not in_dl[name]:
                print('    ', name)
        print("In both but not the same value:")
        for name in matches:
            if not matches[name] and in_dl[name]:
                print('    ', name, 'builtin:', builtin_registry[name], 'download:', dl_registry[name])
        assert False, "Builtin and download registry aren't consistent - failures printed to stdout"
Пример #3
0
def compute_sun_time_offset(LONG,LAT):
    EL = el.from_geodetic( LONG , LAT )
    sidingSpringEL = el.from_geodetic(149.071111, -31.273333)

    ### calculate time offset:
    time_offsets = np.linspace(0, 24, num=24 * 6)
    full_night_times = time.Time.now() + time_offsets * u.hour
    full_night_aa_frames = AltAz(location=EL, obstime=full_night_times)

    sun = ((coor.get_sun(full_night_times).transform_to(full_night_aa_frames)).alt.deg)

    s = 0
    if sun[0] < -18:
        start = 0
    else:
        while sun[s] > -18:
            s = s + 1
        start = time_offsets[s]

    e = s + 1
    while sun[e] < -18:
        e = e + 1
    end = time_offsets[e]
    mid = time_offsets[s + (e - s) // 2]


    return [start, mid, end]
Пример #4
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))
Пример #5
0
def test_regression_simple_5133():
    t = Time('J2010')
    obj = EarthLocation(-1*u.deg, 52*u.deg, height=[100., 0.]*u.km)
    home = EarthLocation(-1*u.deg, 52*u.deg, height=10.*u.km)
    aa = obj.get_itrs(t).transform_to(AltAz(obstime=t, location=home))

    # az is more-or-less undefined for straight up or down
    assert_quantity_allclose(aa.alt, [90, -90]*u.deg, rtol=1e-5)
    assert_quantity_allclose(aa.distance, [90, 10]*u.km)
Пример #6
0
def test_EarthLocation_state_online():
    EarthLocation._site_registry = None
    EarthLocation._get_site_registry(force_download=True)
    assert EarthLocation._site_registry is not None

    oldreg = EarthLocation._site_registry
    newreg = EarthLocation._get_site_registry()
    assert oldreg is newreg
    newreg = EarthLocation._get_site_registry(force_download=True)
    assert oldreg is not newreg
Пример #7
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])
Пример #8
0
    def find_parallax(self, date):
        '''Find the maximum parallax of self.planet on the given date
           from self.observer's location -- in other words, the difference
           in Mars' position between the observer's position and an
           observer at the same latitude but opposite longitude:
           this tells you you how much difference you would see from
           your position if Mars didn't move between your sunrise and sunset.
        '''
        # To calculate from a point on the equator, set lat to 0.
        observer_loc = EarthLocation.from_geodetic(self.location.lon,
                                                   self.location.lat,
                                                   self.location.height)

        # Specify the anti-point.
        # This isn't really an antipode unless lat == 0.
        antipode_loc = EarthLocation.from_geodetic(-observer.lon,
                                                   observer.lat,
                                                   observer.height)

        # XXX Oops, astropy doesn't offer next_rising etc.
        # so we'll need a function to find that before this
        # function can be implemented since it only works
        # when the planet is on the horizon so both the observer
        # and the anti-observer can see it.
        risetime = find_next_rising(planetname, date)

        obs_planet = get_body(planetname, risetime, observer_loc)
        ant_planet = get_body(planetname, risetime, antipode_loc)

        # First, calculate it the straightforward way using the arctan:
        print()
        mars_dist_miles = mars.distance.km / 1.609344
        print("Miles to Mars:", mars_dist_miles)
        earth_mean_radius = 3958.8    # in miles
        half_dist = earth_mean_radius * math.cos(observer_loc.lat)
        print("Distance between observers:", 2. * half_dist)
        par = 2. * math.atan(half_dist / mars_dist_miles) \
              * 180. / math.pi * 3600.
        print("Calculated parallax (arcsec):", par)

        # See what astropy calculates as the difference between observations:
        print()
        print("parallax on %s: RA %f, dec %f" % (antipode.date,
                                                 obs_planet.ra - ant_planet.ra,
                                             obs_planet.dec - ant_planet.dec))
        total_par = (math.sqrt((obs_planet.ra.radians
                                - ant_planet.ra.radians)**2
                               + (obs_planet.dec.radians
                                - ant_planet.dec.radians)**2)
                     * 180. * 3600. / math.pi)
        print("Total parallax (sum of squares): %f arcseconds" % total_par)
        print()
Пример #9
0
def test_regression_6697():
    """
    Test for regression of a bug in get_gcrs_posvel that introduced errors at the 1m/s level.

    Comparison data is derived from calculation in PINT
    https://github.com/nanograv/PINT/blob/master/pint/erfautils.py
    """
    pint_vels = CartesianRepresentation(*(348.63632871, -212.31704928, -0.60154936), unit=u.m/u.s)
    location = EarthLocation(*(5327448.9957829, -1718665.73869569,  3051566.90295403), unit=u.m)
    t = Time(2458036.161966612, format='jd', scale='utc')
    obsgeopos, obsgeovel = location.get_gcrs_posvel(t)
    delta = (obsgeovel-pint_vels).norm()
    assert delta < 1*u.cm/u.s
Пример #10
0
    def new_with_astropy(cls, starttime, stoptime, obsid=None):
        """
        Add an observation to the M&C database, using Astropy to compute
        the LST.

        Parameters:
        ------------
        starttime: astropy time object
            observation starttime
        stoptime: astropy time object
            observation stoptime
        obsid: long integer
            observation identification number. If not provided, will be set
            to the gps second corresponding to the starttime using floor.
        """
        t_start = starttime.utc
        t_stop = stoptime.utc

        # t_start.delta_ut1_utc = iers_a.ut1_utc(t_start)
        # t_stop.delta_ut1_utc = iers_a.ut1_utc(t_stop)

        if obsid is None:
            from math import floor
            obsid = floor(t_start.gps)

        t_start.location = EarthLocation.from_geodetic(HERA_LON, HERA_LAT)
        return cls(obsid=obsid, start_time_jd=t_start.jd,
                   stop_time_jd=t_stop.jd,
                   lst_start_hr=t_start.sidereal_time('apparent').hour)
Пример #11
0
def eci2el(x,y,z,dt):
    """
    Convert Earth-Centered Inertial (ECI) cartesian coordinates to ITRS for astropy EarthLocation object.

    Inputs :
    x = ECI X-coordinate 
    y = ECI Y-coordinate 
    z = ECI Z-coordinate 
    dt = UTC time (datetime object)
    """

    from astropy.coordinates import GCRS, ITRS, EarthLocation, CartesianRepresentation
    import astropy.units as u
    
    # convert datetime object to astropy time object
    tt=Time(dt,format='datetime')

    # Read the coordinates in the Geocentric Celestial Reference System
    gcrs = GCRS(CartesianRepresentation(x=x, y=y,z=z), obstime=tt)

    # Convert it to an Earth-fixed frame
    itrs = gcrs.transform_to(ITRS(obstime=tt))

    el = EarthLocation.from_geocentric(itrs.x, itrs.y, itrs.z) 

    return el
Пример #12
0
def test_Observer_constructor_location():
    """
    Show that location defined by latitude/longitude/elevation is parsed
    identically to passing in an `~astropy.coordinates.EarthLocation` directly.
    """

    lat = '+19:00:00'
    lon = '-155:00:00'
    elevation = 0.0 * u.m
    location = EarthLocation.from_geodetic(lon, lat, elevation)

    environment_kwargs = dict(pressure=1*u.bar, relative_humidity=0.1,
                              temperature=10*u.deg_C)

    obs1 = Observer(name='Observatory',
                    latitude=lat,
                    longitude=lon,
                    elevation=elevation,
                    **environment_kwargs)

    obs2 = Observer(name='Observatory',
                    location=location,
                    **environment_kwargs)

    assert obs1.location == obs2.location, ('using latitude/longitude/'
                                            'elevation keywords gave a '
                                            'different answer from passing in '
                                            'an EarthLocation directly')
Пример #13
0
def test_solar_transit_convenience_methods():
    """
    Test that astroplan's noon and midnight convenience methods agree with
    PyEphem's solar transit/antitransit time.
    """
    lat = '00:00:00'
    lon = '00:00:00'
    elevation = 0.0 * u.m
    pressure = 0 * u.bar
    location = EarthLocation.from_geodetic(lon, lat, elevation)
    time = Time('2000-01-01 12:00:00')
    from astropy.coordinates import get_sun
    obs = Observer(location=location, pressure=pressure)

    # Compute next/previous noon/midnight using generic calc_transit methods
    astroplan_next_noon = obs.noon(time, which='next').datetime
    astroplan_next_midnight = obs.midnight(time, which='next').datetime
    astroplan_prev_noon = obs.noon(time, which='previous').datetime
    astroplan_prev_midnight = obs.midnight(time, which='previous').datetime

    # Computed in print_pyephem_solar_transit_noon()
    pyephem_next_transit = datetime.datetime(2000, 1, 1, 12, 3, 17, 207300)
    pyephem_next_antitransit = datetime.datetime(2000, 1, 2, 0, 3, 31, 423333)
    pyephem_prev_transit = datetime.datetime(1999, 12, 31, 12, 2, 48, 562755)
    pyephem_prev_antitransit = datetime.datetime(2000, 1, 1, 0, 3, 2, 918943)

    threshold_minutes = 8
    assert (abs(astroplan_next_noon - pyephem_next_transit) <
            datetime.timedelta(minutes=threshold_minutes))
    assert (abs(astroplan_next_midnight - pyephem_next_antitransit) <
            datetime.timedelta(minutes=threshold_minutes))
    assert (abs(astroplan_prev_noon - pyephem_prev_transit) <
            datetime.timedelta(minutes=threshold_minutes))
    assert (abs(astroplan_prev_midnight - pyephem_prev_antitransit) <
            datetime.timedelta(minutes=threshold_minutes))
Пример #14
0
    def earth_location_itrf(self, time=None):
        '''Return Fermi spacecraft location in ITRF coordinates'''

        if self.tt2tdb_mode.lower().startswith('none'):
            log.warning('Using location=None for TT to TDB conversion')
            return None
        elif self.tt2tdb_mode.lower().startswith('geo'):
            log.warning('Using location geocenter for TT to TDB conversion')
            return EarthLocation.from_geocentric(0.0*u.m,0.0*u.m,0.0*u.m)
        elif self.tt2tdb_mode.lower().startswith('spacecraft'):
            # First, interpolate Earth-Centered Inertial (ECI) geocentric
            # location from orbit file.
            # These are inertial coordinates aligned with ICRS, called GCRS
            # <http://docs.astropy.org/en/stable/api/astropy.coordinates.GCRS.html>
            pos_gcrs =  GCRS(CartesianRepresentation(self.X(time.tt.mjd)*u.m,
                                                     self.Y(time.tt.mjd)*u.m,
                                                     self.Z(time.tt.mjd)*u.m),
                             obstime=time)

            # Now transform ECI (GCRS) to ECEF (ITRS)
            # By default, this uses the WGS84 ellipsoid
            pos_ITRS = pos_gcrs.transform_to(ITRS(obstime=time))

            # Return geocentric ITRS coordinates as an EarthLocation object
            return pos_ITRS.earth_location
        else:
            log.error('Unknown tt2tdb_mode %s, using None', self.tt2tdb_mode)
            return None
Пример #15
0
def test_new_site_info_to_json():
    lon_str = "-155d28m34s"
    lat_str = "+19d49m32s"
    elevation = 4139*u.m
    location = EarthLocation.from_geodetic(lon_str, lat_str, elevation)
    short_name = "New telescope (subaru)"
    aliases = ["example new telescope with subaru's coordinates"]
    source = "the tests module"
    new_site_json = new_site_info_to_json(short_name, location, aliases, source)
    new_site = json.loads(new_site_json)

    ns = new_site[short_name]
    assert_quantity_allclose(Longitude(lon_str),
                             Longitude(ns["longitude"]*u.Unit(ns["longitude_unit"])),
                             atol=0.001*u.deg)
    assert_quantity_allclose(Latitude(lat_str),
                             Latitude(ns["latitude"]*u.Unit(ns["latitude_unit"])),
                             atol=0.001*u.deg)
    assert_quantity_allclose(elevation,
                             new_site[short_name]["elevation"]*u.Unit(ns["elevation_unit"]),
                             atol=1*u.m)
    assert short_name == new_site[short_name]['name']
    assert aliases == new_site[short_name]['aliases']

    with pytest.raises(ValueError):
        # This name already exists
        new_site_info_to_json("Keck", location, aliases, source)
Пример #16
0
def test_exceptions():
    lat = '00:00:00'
    lon = '00:00:00'
    elevation = 0.0 * u.m
    location = EarthLocation.from_geodetic(lon, lat, elevation)
    time = Time('2000-01-01 12:00:00')
    vega_coords = SkyCoord('18h36m56.33635s', '+38d47m01.2802s')

    obs = Observer(location=location)

    with pytest.raises(ValueError):
        obs.target_rise_time(time, vega_coords, which='oops').datetime

    with pytest.raises(ValueError):
        obs.target_set_time(time, vega_coords, which='oops').datetime

    with pytest.raises(ValueError):
        obs.target_meridian_transit_time(time, vega_coords,
                                         which='oops').datetime

    with pytest.raises(ValueError):
        obs.target_meridian_antitransit_time(time, vega_coords,
                                             which='oops').datetime

    with pytest.raises(TypeError):
        FixedTarget(['00:00:00', '00:00:00'], name='VE')

    with pytest.raises(TypeError):
        Observer(location='Greenwich')

    with pytest.raises(TypeError):
        Observer(location=EarthLocation(0, 0, 0), timezone=-6)
Пример #17
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)
Пример #18
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)
    def from_itrf(ant_itrf_xyz, ant_labels):
        """
        Instantiate telescope model from ITRF co-ordinates of antennae

        (aka ECEF-coords, i.e. Earth-Centered-Earth-Fixed reference frame.)

        Takes care of calculating central Latitude and Longitude from the mean
        antenna position, and converts the antenna positions into local-XYZ
        frame.

        Args:
            ant_itrf_xyz (numpy.ndarray): Array co-ordinatates in the ITRF frame
            ant_labels (list[str]): Antennae labels
        Returns:
            Telescope: A telescope class with the given array co-ords.
        """
        mean_posn = np.mean(ant_itrf_xyz, axis=0)
        centre = EarthLocation.from_geocentric(mean_posn[0],
                                               mean_posn[1],
                                               mean_posn[2],
                                               unit=u.m,
                                               )
        lon, lat, height = centre.to_geodetic()

        mean_subbed_itrf = ant_itrf_xyz - mean_posn

        rotation = z_rotation_matrix(lon)
        ant_local_xyz = np.dot(rotation, mean_subbed_itrf.T).T

        return Telescope(
            centre=centre,
            ant_labels=ant_labels,
            ant_itrf_xyz=ant_itrf_xyz,
            ant_local_xyz=ant_local_xyz,
        )
Пример #20
0
def test_moon_rise_set():
    pyephem_next_rise = datetime.datetime(2017, 10, 7, 23, 50, 24, 407018)
    pyephem_next_set = datetime.datetime(2017, 10, 7, 12, 30, 30, 787116)
    pyephem_prev_rise = datetime.datetime(2017, 10, 6, 23, 13, 43, 644455)
    pyephem_prev_set = datetime.datetime(2017, 10, 6, 11, 20, 9, 340009)

    time = Time('2017-10-07 12:00:00')
    lat = '42:00:00'
    lon = '-70:00:00'
    elevation = 0.0 * u.m
    pressure = 0 * u.bar
    location = EarthLocation.from_geodetic(lon, lat, elevation)

    obs = Observer(location=location)

    astroplan_next_rise = obs.moon_rise_time(time, which='next')
    astroplan_next_set = obs.moon_set_time(time, which='next')
    astroplan_prev_rise = obs.moon_rise_time(time, which='previous')
    astroplan_prev_set = obs.moon_set_time(time, which='previous')

    threshold_minutes = 2
    assert (abs(pyephem_next_rise - astroplan_next_rise.datetime) <
            datetime.timedelta(minutes=threshold_minutes))
    assert (abs(pyephem_next_set - astroplan_next_set.datetime) <
            datetime.timedelta(minutes=threshold_minutes))
    assert (abs(pyephem_prev_rise - astroplan_prev_rise.datetime) <
            datetime.timedelta(minutes=threshold_minutes))
    assert (abs(pyephem_prev_set - astroplan_prev_set.datetime) <
            datetime.timedelta(minutes=threshold_minutes))
Пример #21
0
def test_sunrise_sunset_equator():
    """
    Check that time of sunrise/set for an observer on the equator is
    consistent with PyEphem results (for no atmosphere/pressure=0)
    """
    lat = "00:00:00"
    lon = "00:00:00"
    elevation = 0.0 * u.m
    pressure = 0 * u.bar
    location = EarthLocation.from_geodetic(lon, lat, elevation)
    time = Time("2000-01-01 12:00:00")
    obs = Observer(location=location, pressure=pressure)
    astroplan_next_sunrise = obs.sun_rise_time(time, which="next").datetime
    astroplan_next_sunset = obs.sun_set_time(time, which="next").datetime

    astroplan_prev_sunrise = obs.sun_rise_time(time, which="previous").datetime
    astroplan_prev_sunset = obs.sun_set_time(time, which="previous").datetime

    # Run print_pyephem_sunrise_sunset() to compute analogous
    # result from PyEphem:
    pyephem_next_sunrise = datetime.datetime(2000, 1, 2, 6, 3, 39, 150790)
    pyephem_next_sunset = datetime.datetime(2000, 1, 1, 18, 3, 23, 676686)
    pyephem_prev_sunrise = datetime.datetime(2000, 1, 1, 6, 3, 10, 720052)
    pyephem_prev_sunset = datetime.datetime(1999, 12, 31, 18, 2, 55, 100786)

    # Typical difference in this example between PyEphem and astroplan
    # with an atmosphere is <2 min
    threshold_minutes = 8
    assert abs(pyephem_next_sunrise - astroplan_next_sunrise) < datetime.timedelta(minutes=threshold_minutes)
    assert abs(pyephem_next_sunset - astroplan_next_sunset) < datetime.timedelta(minutes=threshold_minutes)
    assert abs(pyephem_prev_sunrise - astroplan_prev_sunrise) < datetime.timedelta(minutes=threshold_minutes)
    assert abs(pyephem_prev_sunset - astroplan_prev_sunset) < datetime.timedelta(minutes=threshold_minutes)
Пример #22
0
def test_exceptions():
    lat = "00:00:00"
    lon = "00:00:00"
    elevation = 0.0 * u.m
    location = EarthLocation.from_geodetic(lon, lat, elevation)
    time = Time("2000-01-01 12:00:00")
    vega_coords = SkyCoord("18h36m56.33635s", "+38d47m01.2802s")

    obs = Observer(location=location)

    with pytest.raises(ValueError):
        obs.target_rise_time(time, vega_coords, which="oops").datetime

    with pytest.raises(ValueError):
        obs.target_set_time(time, vega_coords, which="oops").datetime

    with pytest.raises(ValueError):
        obs.target_meridian_transit_time(time, vega_coords, which="oops").datetime

    with pytest.raises(ValueError):
        obs.target_meridian_antitransit_time(time, vega_coords, which="oops").datetime

    with pytest.raises(TypeError):
        FixedTarget(["00:00:00", "00:00:00"], name="VE")

    with pytest.raises(TypeError):
        Observer(location="Greenwich")

    with pytest.raises(TypeError):
        Observer(location=EarthLocation(0, 0, 0), timezone=-6)
Пример #23
0
def test_sunrise_sunset_equator_civil_twilight():
    """
    Check that time of sunrise/set for an observer on the equator is
    consistent with PyEphem results (for no atmosphere/pressure=0)
    """
    lat = "00:00:00"
    lon = "00:00:00"
    elevation = 0.0 * u.m
    pressure = 0 * u.bar
    location = EarthLocation.from_geodetic(lon, lat, elevation)
    time = Time("2000-01-01 12:00:00")
    obs = Observer(location=location, pressure=pressure)
    # Manually impose horizon equivalent to civil twilight
    horizon = -6 * u.degree
    astroplan_next_sunrise = obs.sun_rise_time(time, which="next", horizon=horizon).datetime
    astroplan_next_sunset = obs.sun_set_time(time, which="next", horizon=horizon).datetime

    astroplan_prev_sunrise = obs.sun_rise_time(time, which="previous", horizon=horizon).datetime
    astroplan_prev_sunset = obs.sun_set_time(time, which="previous", horizon=horizon).datetime

    # Run print_pyephem_sunrise_sunset_equator_civil_twilight() to compute
    # analogous result from PyEphem:
    pyephem_next_rise = datetime.datetime(2000, 1, 2, 5, 37, 34, 83328)
    pyephem_next_set = datetime.datetime(2000, 1, 1, 18, 29, 29, 195908)
    pyephem_prev_rise = datetime.datetime(2000, 1, 1, 5, 37, 4, 701708)
    pyephem_prev_set = datetime.datetime(1999, 12, 31, 18, 29, 1, 530987)

    threshold_minutes = 8
    assert abs(pyephem_next_rise - astroplan_next_sunrise) < datetime.timedelta(minutes=threshold_minutes)
    assert abs(pyephem_next_set - astroplan_next_sunset) < datetime.timedelta(minutes=threshold_minutes)
    assert abs(pyephem_prev_rise - astroplan_prev_sunrise) < datetime.timedelta(minutes=threshold_minutes)
    assert abs(pyephem_prev_set - astroplan_prev_sunset) < datetime.timedelta(minutes=threshold_minutes)
Пример #24
0
def test_vega_sirius_transit_seattle():
    """
    Check that time of transit of Vega for an observer in Seattle is
    consistent with PyEphem results (for no atmosphere/pressure=0)
    """
    lat = "47d36m34.92s"
    lon = "122d19m59.16s"
    elevation = 0.0 * u.m
    pressure = 0 * u.bar
    location = EarthLocation.from_geodetic(lon, lat, elevation)
    time = Time("1990-01-01 12:00:00")
    vega = SkyCoord(279.23473479 * u.degree, 38.78368896 * u.degree)
    sirius = SkyCoord(101.28715533 * u.degree, -16.71611586 * u.degree)

    obs = Observer(location=location, pressure=pressure)
    astroplan_vega_transit = obs.target_meridian_transit_time(time, vega, which="next").datetime
    astroplan_sirius_transit = obs.target_meridian_transit_time(time, sirius, which="next").datetime

    astroplan_vector_transit = obs.target_meridian_transit_time(time, [vega, sirius], which="next").datetime

    # Run print_pyephem_vega_sirius_transit() to compute analogous
    # result from PyEphem:
    pyephem_vega_transit = datetime.datetime(1990, 1, 2, 3, 41, 9, 244067)
    pyephem_sirius_transit = datetime.datetime(1990, 1, 1, 15, 51, 15, 135167)

    # Typical difference in this example between PyEphem and astroplan
    # with an atmosphere is <2 min
    threshold_minutes = 8
    assert abs(pyephem_vega_transit - astroplan_vega_transit) < datetime.timedelta(minutes=threshold_minutes)
    assert abs(pyephem_sirius_transit - astroplan_sirius_transit) < datetime.timedelta(minutes=threshold_minutes)

    # Now check vectorized solutions against scalar:
    assert astroplan_vector_transit[0] == astroplan_vega_transit
    assert astroplan_vector_transit[1] == astroplan_sirius_transit
Пример #25
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."
Пример #26
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)
Пример #27
0
def test_hour_angle():
    # TODO: Add tests for different targets/times with tools other than PyEphem
    time = Time('2005-02-03 00:00:00')
    location = EarthLocation.from_geodetic(10*u.deg, 40*u.deg, 0*u.m)
    obs = Observer(location=location)
    vernal_eq = FixedTarget(SkyCoord(ra=0*u.deg, dec=0*u.deg))
    hour_angle = obs.target_hour_angle(time, vernal_eq)
    lst = obs.local_sidereal_time(time)
    assert_quantity_allclose(hour_angle, lst, atol=0.001*u.deg)
Пример #28
0
def test_moon_altaz():
    time = Time('2012-06-21 03:00:00')
    location = EarthLocation.from_geodetic(-155*u.deg, 19*u.deg, 0*u.m)
    obs = Observer(location=location, pressure=0*u.bar)
    altaz = obs.moon_altaz(time)
    astroplan_altaz = [altaz.alt.radian, altaz.az.radian]
    # Get this from print_pyephem_moon_altaz():
    pyephem_altaz = [0.7092548608779907, 4.865438938140869]
    assert_allclose(astroplan_altaz, pyephem_altaz, atol=0.1)
Пример #29
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()
Пример #30
0
def test_local_sidereal_time():
    time = Time('2005-02-03 00:00:00')
    location = EarthLocation.from_geodetic(10*u.deg, 40*u.deg, 0*u.m)
    obs = Observer(location=location)
    # test sidereal time
    astroplan_lst = obs.local_sidereal_time(time)
    # Compute this with print_pyephem_lst()
    pyephem_lst = 2.5005375428099104*u.rad
    assert_quantity_allclose(astroplan_lst, pyephem_lst, atol=0.01*u.deg)
Пример #31
0
    #now get az/el
    uv = UVData()
    uv.read(filename + "/" + filename + "_b.uvh5", read_data=False)

    ra = uv.phase_center_ra_degrees
    dec = uv.phase_center_dec_degrees

    lst_array = uv.lst_array  #this is an entire array for every time integration in my file
    lst = lst_array.mean()

    jd_array = uv.time_array
    jd = jd_array.mean()

    ata_location = EarthLocation(lat="40:49:03.0",
                                 lon="-121:28:24.0",
                                 height=1008)
    observing_time = Time(jd, format='jd')

    aa = AltAz(location=ata_location, obstime=observing_time)
    coord = SkyCoord(ra * u.degree, dec * u.degree)
    coords_alt_az = coord.transform_to(aa)

    az, el = coords_alt_az.az.value, coords_alt_az.alt.value

    azm.append(az)
    elev.append(el)

#az, el = np.loadtxt("/home/sonata/corr_data/az_el_multiobs.txt").T
fig = plt.figure(0)
#.title(str(ant_name) + "x-pol")
Пример #32
0
# don't worry about iers
#from astropy.utils import iers
#iers.conf.auto_download = False
#iers.conf.auto_max_age = None

# Location, never changes
apl = Location()
apl.name = 'Apache Point Observatory'
apl.region = 'NM'
apl.latitude = 32.780208
apl.longitude = -105.819749
apl.timezone = 'US/Mountain'
apl.elevation = 2790

aplEL = EarthLocation(lon=apl.longitude * u.deg,
                      lat=apl.latitude * u.deg,
                      height=apl.elevation * u.m)


def moon_angle_var(fobj, ext):
    #getting RA and DEC
    sampling = fobj[0].header

    #FINDING INTERPLATE SKY TIME
    fin_mean = [
    ]  #time for each moon sky observation interplate, used for moon angle
    h_beg = []
    h_end = []
    mean_per = []  #time for each moon sky observation intraplate
    h = ext.header
    h_beg.append(
Пример #33
0
       <https://doi.org/10.3847/2041-8205/826/1/L13>.
"""  # noqa: E501

from astropy.coordinates import (CartesianRepresentation,
                                 DynamicMatrixTransform, EarthLocation,
                                 EarthLocationAttribute, frame_transform_graph,
                                 ITRS, SphericalRepresentation)
from astropy.coordinates.matrix_utilities import matrix_transpose
from astropy import units as u
import lal
import numpy as np

__all__ = ('DetectorFrame', )

# Add gravitational-wave detectors to site registry
registry = EarthLocation._get_site_registry()
for detector in lal.CachedDetectors:
    names = [detector.frDetector.name, detector.frDetector.prefix]
    location = EarthLocation(*detector.location, unit=u.m)
    registry.add_site(names, location)
    del names, detector
del lal, registry


class DetectorFrame(ITRS):
    """A coordinate frames to visualize triangulation rings from pairs of
    gravitational-wave detectors."""

    site_1 = EarthLocationAttribute()
    site_2 = EarthLocationAttribute()
Пример #34
0
from sunpy.coordinates import frames, sun
import astropy.units as u

######################################################################################
# We use `~astropy.coordinates.SkyCoord` to define the center of the Sun
obstime = "2013-09-21 16:00:00"
c = SkyCoord(0 * u.arcsec,
             0 * u.arcsec,
             obstime=obstime,
             frame=frames.Helioprojective)

######################################################################################
# Now we establish our location on the Earth, in this case let's consider a high altitude
# balloon launched from Fort Sumner, NM.
Fort_Sumner = EarthLocation(lat=34.4900 * u.deg,
                            lon=-104.221800 * u.deg,
                            height=40 * u.km)

######################################################################################
# Now lets convert this to a local measurement of Altitude and Azimuth.
frame_altaz = AltAz(obstime=Time(obstime), location=Fort_Sumner)
sun_altaz = c.transform_to(frame_altaz)
print('Altitude is {0} and Azimuth is {1}'.format(sun_altaz.T.alt,
                                                  sun_altaz.T.az))

######################################################################################
# Next let's check this calculation by converting it back to helioprojective.
# We should get our original input which was the center of the Sun.
# To go from Altitude/Azimuth to Helioprojective, you will need the distance to the Sun.
# solar distance. Define distance with SunPy's almanac.
distance = sun.earth_distance(obstime)
Пример #35
0
def get_closest_obs(pointings_arr, band_pointings_arr, KN, obs_times, t1,
                    max_extra_slew):
    #Are we scheduled to observe this event anyway? If not find the closest observation in the next 24 hours

    #get pointings in the next week
    pointings_later = band_pointings_arr[KN[0] < band_pointings_arr[:, 3], :]
    pointings_nextday_possible = pointings_later[pointings_later[:, 3] < (
        KN[0] + t1)]

    #only consider pointings in next day when KN is observable
    if len(
            obs_times
    ) == 0:  #if there are no observable times then we still need to create variable pointings_nextday
        pointings_nextday = []
        closest_obs, original_overhead_time, slew_to_KN = 0, 3, np.nan
    else:
        for i, time in enumerate(obs_times):
            add = pointings_nextday_possible[pointings_nextday_possible[:, 3] <
                                             (time + 1 / 48.)]
            add = add[add[:, 3] > time]
            if i == 0:
                pointings_nextday = np.copy(add)
            else:
                pointings_nextday = np.vstack((pointings_nextday, add))

        #pointings_not_observable = [pointing for pointing in pointings_nextday_possible if pointing not in pointings_nextday]
        #print len(pointings_nextday_possible), len(pointings_not_observable), len(pointings_nextday)
    if len(pointings_nextday_possible) != 0:  #for checking
        pointings_lcs = SkyCoord(
            ra=pointings_nextday_possible[:, 1] * u.degree,
            dec=pointings_nextday_possible[:, 2] * u.degree)
        KN_loc = SkyCoord(ra=KN[1] * u.degree, dec=KN[2] * u.degree)
        ags = KN_loc.separation(pointings_lcs).deg

    if len(pointings_nextday) == 0:
        if len(obs_times
               ) != 0:  #if no pointings in the next 24hrs, due to no pointings
            closest_obs, original_overhead_time, slew_to_KN = 0, 0, np.nan
    else:
        #get angles between all of pointings and KN
        pointings_locs = SkyCoord(ra=pointings_nextday[:, 1] * u.degree,
                                  dec=pointings_nextday[:, 2] * u.degree)
        KN_loc = SkyCoord(ra=KN[1] * u.degree, dec=KN[2] * u.degree)
        angsep = KN_loc.separation(pointings_locs).deg

        #find closest pointing within 24hours for swap
        closest_obs = pointings_nextday[np.argmin(angsep), :]
        slew_to_KN = np.min(angsep)

        row_of_pointingsarr = np.argwhere(
            pointings_arr[:, 4] == closest_obs[4])[0][0]
        original_overhead_time = pointings_arr[
            row_of_pointingsarr, 3] - pointings_arr[row_of_pointingsarr - 1, 3]

        #check if we are scheduled to observe this event anyway
        #observations_arg = np.argwhere(angsep < np.sqrt(9.6/np.pi))
        #KN_observations = pointings_nextday[observations_arg,:] #observations made of KN, if any
        if slew_to_KN < np.sqrt(9.6 / np.pi):
            original_overhead_time = 1  #no swap because observation already exists
        if slew_to_KN > max_extra_slew:
            original_overhead_time = 2  #no swap because smallest slew angle was too large

    if len(pointings_nextday_possible) != 0:
        if np.min(ags) < np.sqrt(9.6 / np.pi) and np.min(ags) != slew_to_KN:
            print 'Problem', np.min(ags), slew_to_KN
            mjd = pointings_nextday_possible[np.argmin(ags), 3]
            print mjd, obs_times
            lsst_location = EarthLocation(lat=-32.344633333333334 * u.deg,
                                          lon=-77.34941666666666 * u.deg,
                                          height=2652 * u.m)
            times = np.arange(KN[0], KN[0] + t1,
                              1 / 48.)  #30 minute intervals in next 24 hours
            time = Time(mjd, format='mjd')
            KN_loc = SkyCoord(ra=KN[1] * u.degree, dec=KN[2] * u.degree)
            KNaltaz = KN_loc.transform_to(
                AltAz(obstime=time, location=lsst_location))
            altitude = KNaltaz.alt.deg

            #put limit on airmass, Could be below ~2
            zenith_ang = 90 - altitude  #in deg
            zenith_ang_rad = zenith_ang * np.pi / 180
            airmass = 1 / np.cos(zenith_ang_rad)
            print 'airmass is ', airmass

    return closest_obs, slew_to_KN, original_overhead_time
Пример #36
0
def reframe(
    ixds,
    outframe=None,
    reference_time=None,
    observer_location=None,
    target_location=None,
    reference_frequency=None,
    # velocity=None,
):
    """
    Change the velocity system of an image

    .. warn::
        This function is stil being implemented

    .. todo:
        Use refpix attribute (if present) to improve accuracy of target_location assignment

    .. todo:
        Account for epoch, distance, and velocity (if present in input attributes) in target_location and observer_location

    .. todo:
        decide whether to drop velocity coordinate (if assigned)

    Parameters
    ----------
    xds : xarray.core.dataset.Dataset
        input Image
    outframe : str
        reference frame to which the input will be converted
    reference_time : numpy.datetime64 or datetime, optional
        any valid initializer of astropy.time.TimeBase should work
    observer_location : astropy.cordinates.SkyCoord, optional
        position and velocity of observer for frame transformation
    target_location : astropy.cordinates.SkyCoord, optional
        position and velocity of source for frame transformation
    reference_frequency : astropy.units.Quantity, optional
        value and unit to use when expressing the spectral value as a velocity, input to SpectralCoord doppler_rest parameter

    Returns
    -------
    xarray.core.dataset.Dataset
        output Image
    """
    from astropy import units
    from astropy.coordinates import EarthLocation, SkyCoord, SpectralCoord
    from astropy.time import Time
    from datetime import datetime
    import xarray as xr
    import numpy as np

    # create a working object
    _ixds = ixds

    # it would be better if the axis attributes were a single dict
    _ixds.attrs["units_map"] = dict(
        zip(_ixds.attrs["axisnames"], _ixds.attrs["axisunits"]))

    # Assigning reference_time
    if reference_time is None:
        try:
            reference_time = _ixds["time"].values[0]
        except:
            reference_time = datetime.now()
        finally:
            print(f"Adopted reference time: {reference_time}")

    # Assigning observer_location
    if observer_location is None:
        try:
            telpos = [
                xx.strip(",[]()")
                for xx in _ixds.attrs["telescope_position"].split(" ")
            ]
            telcoord = [float(xyz.strip("m")) for xyz in telpos[:-1]]
            if telpos[-1].lower() == "itrf":
                observer_location = SkyCoord(
                    x=telcoord[0],
                    y=telcoord[1],
                    z=telcoord[2],
                    unit=units.Unit("m"),
                    frame="itrs",
                    obstime=_ixds["time"].values[0],
                )
            else:
                raise NotImplementedError(
                    "Unsupported frame accompanying telescope_position attribute of input dataset"
                )
        except ValueError:
            print(
                "Failed to find valid telescope postition from dataset attributes"
            )
            print("Defaulting to astropy-data telescope location")
            observer_location = EarthLocation.of_site(
                _ixds.attrs["telescope"]).get_itrs(
                    obstime=Time(_ixds["time"].values[0]))
        finally:
            print(f"Adopted reference postion: {observer_location}")

    # Assigning reference_frequency
    if reference_frequency is None:
        try:
            reference_frequency = units.Quantity(_ixds.attrs["rest_frequency"])
        except ValueError:
            print(
                "Failed to assign valid rest frequency from dataset attributes"
            )
            print("Attempting to parse and convert")
            try:
                malformed_quantity = _ixds.attrs["rest_frequency"].split(" ")
                if isinstance(malformed_quantity[0], str):
                    value = float(malformed_quantity[0])
                # this is where pint-xarray would be useful
                # note that we'll have to extend this logic to handle a variety of inputs, e.g., km/s
                if malformed_quantity[1].lower() == "hz":
                    unit = "Hz"
                    reference_frequency = units.Quantity(value, unit)
            except (AttributeError, ValueError):
                # AttributeError: seems like the attribute is not a string
                # ValueError: seems like attribute can't be converted to float
                print(
                    "Failed to convert dataset attributes to valid rest frequency"
                )
                print("Assuming 100 GHz, this may not be desired")
                value, unit = 100, "GHz"
                reference_frequency = units.Quantity(value, unit)
        finally:
            print(f"Adopted reference frequency: {reference_frequency}")

    # Assigning target_location
    if target_location is None:
        try:
            target_location = SkyCoord.from_name(
                _ixds.attrs["object_name"],
                frame=_ixds.attrs["spectral__reference"])
        except:  # NameResolveError
            # Here is where we could add another try block to check for velocity attributes in the ixds
            # Also check for refpix attribute in the input instead of having to calculate it
            # If not available and we couldn't get pointing center in terms of coordinates...
            print(
                f"Direction reference '{_ixds.attrs['pointing_center']}' is not a valid SkyCoord initializer"
            )
            target_location = SkyCoord(
                _ixds["right_ascension"][_ixds.l.size // 2][_ixds.m.size //
                                                            2].values *
                units.Unit(ixds.attrs["units_map"]["Right Ascension"]),
                _ixds["declination"][_ixds.l.size // 2][_ixds.m.size //
                                                        2].values *
                units.Unit(_ixds.attrs["units_map"]["Declination"]),
                frame=_ixds.attrs["spectral__reference"],
                # if target frame velocity reference is available, it would be easiest to assign it here
            )
            # note that we could include telescope dependent conditionals (e.g., FK5 vs ICRS)
            # these could likely be based on ixds.attrs["direction_reference"]
        finally:
            print(f"Adopted target location: {target_location}")
            if target_location.is_transformable_to(outframe):
                pass
            else:
                print(
                    "Input to outframe argument incompatible with target position"
                )
                print(
                    "Adding velocity coordinate for per-channel assignment to target_location"
                )
                # if velocity information isn't present in the input
                # (and it won't be because that logic hasn't been encoded due to available test data)
                # then calculate a velocity for each channel and assign as dataset coordinate,
                # for selection inside the mapped function (_change_frame)
                measured_frequencies = _ixds.chan.values * units.Unit(
                    _ixds.attrs["units_map"]["Frequency"])
                radio_equiv = units.doppler_radio(reference_frequency)
                measured_velocities = measured_frequencies.to(
                    units.km / units.s, equivalencies=radio_equiv)
                _ixds = _ixds.assign_coords(
                    velocity=("chan", measured_velocities.value))
                _ixds.attrs["units_map"][
                    "Velocity"] = measured_velocities.unit.to_string()

    # Defining a function to apply the transformation across the chan axis
    def _change_frame(ixds_block, observer, target, frequency, frame):
        """
        This function will be called using xr.map_blocks

        reference
        http://xarray.pydata.org/en/stable/generated/xarray.map_blocks.html
        and
        https://xarray-contrib.github.io/xarray-tutorial/scipy-tutorial/06_xarray_and_dask.html#map_blocks
        """

        if ("velocity"
                in ixds_block.coords) and ("Velocity"
                                           in ixds_block.attrs["units_map"]):
            # update target to use velo coordinate value for this block
            # since this is inside map_blocks, the only velo/chan available is the one we want to use
            chan_vel = ixds_block.velocity.values * units.Unit(
                ixds_block.attrs["units_map"]["Velocity"])
            # assignment via `SkyCoord(target, radial_velocity=chan_vel)` doesn't seem to work
            # see
            # https://docs.astropy.org/en/stable/coordinates/velocities.html#adding-velocities-to-existing-frame-objects
            # https://docs.astropy.org/en/stable/coordinates/representations.html#attaching-differential-objects-to-representation-objects
            target = target.data.with_differentials(
                {'s': RadialDifferential(chan_vel)})

        for xda in ixds_block.data_vars:
            # we don't want to transform boolean data arrays
            # we also don't want to if there is no chan dimension
            if ixds_block[xda].dtype != bool and "chan" in ixds_block[xda].dims:
                # ixds_block[xda].values is the computed ndarray for this block
                sc = SpectralCoord(
                    ixds_block[xda].values,
                    unit=ixds_block.attrs["units_map"]["Frequency"],
                    observer=observer,
                    target=target,
                    doppler_rest=frequency,
                    doppler_convention=ixds_block.attrs["velocity__type"],
                )
                # see https://docs.astropy.org/en/stable/coordinates/spectralcoord.html#specifying-an-observer-and-a-target-explicitly
                new_sc = sc.with_observer_stationary_relative_to(frame)
                ixds_block[xda] = new_sc.values

        return ixds_block

    # Apply the function to the data
    # The parallelism happens inside this function
    try:
        output_ixds = xr.map_blocks(
            obj=_ixds,
            func=_change_frame,
            args=[],  # no positional args
            kwargs={
                "observer": observer_location,
                "target": target_location,
                "frequency": reference_frequency,
                "frame": outframe,
            },
            template=_ixds,
        )
    except:
        print("Failed to change frame. Returning original dataset.")
        output_ixds = _ixds

    # ouptut_ixds.compute()
    return output_ixds
Пример #37
0
    def test_time_to_fits_loc(self, table_types):
        """
        Test all the unusual conditions for locations of ``Time``
        columns in a ``Table``.
        """
        t = table_types()
        t['a'] = Time(self.time, format='isot', scale='utc')
        t['b'] = Time(self.time, format='isot', scale='tt')

        # Check that vectorized location is stored using Green Bank convention
        t['a'].location = EarthLocation([1., 2.], [2., 3.], [3., 4.],
                                        unit='Mm')

        with pytest.warns(
                AstropyUserWarning,
                match=r'Time Column "b" has no '
                r'specified location, but global Time Position is present'):
            table, hdr = time_to_fits(t)
        assert (table['OBSGEO-X'] == t['a'].location.x.to_value(
            unit='m')).all()
        assert (table['OBSGEO-Y'] == t['a'].location.y.to_value(
            unit='m')).all()
        assert (table['OBSGEO-Z'] == t['a'].location.z.to_value(
            unit='m')).all()

        with pytest.warns(
                AstropyUserWarning,
                match=r'Time Column "b" has no '
                r'specified location, but global Time Position is present'):
            t.write(self.temp('time.fits'), format='fits', overwrite=True)

        # Check that a blank value for the "TRPOSn" keyword is not generated
        hdr = fits.getheader(self.temp('time.fits'), 1)
        assert hdr.get('TRPOS2', None) is None

        with pytest.warns(
                AstropyUserWarning,
                match=r'Time column reference position '
                r'"TRPOSn" is not specified. The default value for it is '
                r'"TOPOCENTER", and the observatory position has been specified.'
        ):
            tm = table_types.read(self.temp('time.fits'),
                                  format='fits',
                                  astropy_native=True)

        assert (tm['a'].location == t['a'].location).all()
        assert tm['b'].location == t['b'].location

        # Check that multiple Time columns with different locations raise an exception
        t['a'].location = EarthLocation(1, 2, 3)
        t['b'].location = EarthLocation(2, 3, 4)

        with pytest.raises(ValueError) as err:
            table, hdr = time_to_fits(t)
            assert 'Multiple Time Columns with different geocentric' in str(
                err.value)

        # Check that Time column with no location specified will assume global location
        t['b'].location = None

        with catch_warnings() as w:
            table, hdr = time_to_fits(t)
            assert len(w) == 1
            assert str(w[0].message).startswith(
                'Time Column "b" has no specified '
                'location, but global Time Position '
                'is present')

        # Check that multiple Time columns with same location can be written
        t['b'].location = EarthLocation(1, 2, 3)

        with catch_warnings() as w:
            table, hdr = time_to_fits(t)
            assert len(w) == 0

        # Check compatibility of Time Scales and Reference Positions

        for scale in BARYCENTRIC_SCALES:
            t.replace_column('a', getattr(t['a'], scale))
            with catch_warnings() as w:
                table, hdr = time_to_fits(t)
                assert len(w) == 1
                assert str(w[0].message).startswith(
                    'Earth Location "TOPOCENTER" '
                    'for Time Column')

        # Check that multidimensional vectorized location (ndim=3) is stored
        # using Green Bank convention.
        t = table_types()
        location = EarthLocation([[[1., 2.], [1., 3.], [3., 4.]]],
                                 [[[1., 2.], [1., 3.], [3., 4.]]],
                                 [[[1., 2.], [1., 3.], [3., 4.]]],
                                 unit='Mm')
        t['a'] = Time(self.time_3d, format='jd', location=location)

        table, hdr = time_to_fits(t)
        assert (table['OBSGEO-X'] == t['a'].location.x.to_value(
            unit='m')).all()
        assert (table['OBSGEO-Y'] == t['a'].location.y.to_value(
            unit='m')).all()
        assert (table['OBSGEO-Z'] == t['a'].location.z.to_value(
            unit='m')).all()

        t.write(self.temp('time.fits'), format='fits', overwrite=True)
        tm = table_types.read(self.temp('time.fits'),
                              format='fits',
                              astropy_native=True)

        assert (tm['a'].location == t['a'].location).all()

        # Check that singular location with ndim>1 can be written
        t['a'] = Time(self.time,
                      location=EarthLocation([[[1.]]], [[[2.]]], [[[3.]]],
                                             unit='Mm'))

        table, hdr = time_to_fits(t)
        assert hdr['OBSGEO-X'] == t['a'].location.x.to_value(unit='m')
        assert hdr['OBSGEO-Y'] == t['a'].location.y.to_value(unit='m')
        assert hdr['OBSGEO-Z'] == t['a'].location.z.to_value(unit='m')

        t.write(self.temp('time.fits'), format='fits', overwrite=True)
        tm = table_types.read(self.temp('time.fits'),
                              format='fits',
                              astropy_native=True)

        assert tm['a'].location == t['a'].location
from astropy.time import Time
from astropy.coordinates import get_sun, SkyCoord, EarthLocation, AltAz

# input data
file_data = '/Users/chervias/Documents/Postdoc_FSU/Pointing_correction/fits_s19.txt'
file_name = 'pointing_corr_arr4_f150_snr0_FullSeason19.csv'
df_tot = pd.read_csv(file_data, sep='\s+\|*\s*', header=None)
df_tot = df_tot.drop_duplicates(subset=0, keep='first')
isSNR = df_tot[15] >= 0.0
df_tot = df_tot[isSNR]
df_tot.reset_index(drop=True, inplace=True)
N = len(df_tot)

act_pos = (-22.9586, -67.7875, 5190.0)
ACT = EarthLocation(lat=act_pos[0] * u.deg,
                    lon=act_pos[1] * u.deg,
                    height=act_pos[2] * u.m)

# define a new data frame with the selected data
df = pd.DataFrame(columns=['ctime', 'ctime 2 hr ago', 'freq', 'array'])
c = 0
for n in range(N):
    first = df_tot[0][n]
    array = first.split('.')
    array2 = array[2].split(':')
    freq = int(array2[1].replace('f', ''))
    arr_det = array2[0]
    ctime = float(array[0])
    ctime_2hrago = ctime - 7200.0
    df.loc[c] = [ctime, ctime_2hrago, freq, arr_det]
    c += 1
Пример #39
0
def predict(lat,
            lon,
            height=0,
            source='',
            date='',
            plot_sun=True,
            plot_file=''):
    from astropy.time import Time
    from astropy.visualization import astropy_mpl_style, quantity_support
    from astropy.coordinates import SkyCoord, EarthLocation, AltAz, get_sun
    import astropy.units as u
    import matplotlib
    import matplotlib.pyplot as plt

    plt.style.use(astropy_mpl_style)
    plt.rcParams['figure.constrained_layout.use'] = True
    plt.rcParams['figure.figsize'] = (18, 10)
    plt.rcParams['legend.fontsize'] = 20
    plt.rcParams['axes.labelsize'] = 22
    plt.rcParams['axes.titlesize'] = 26
    plt.rcParams['xtick.labelsize'] = 18
    plt.rcParams['ytick.labelsize'] = 18

    quantity_support()

    # Define source
    if source != '':
        obj = SkyCoord.from_name(source)

    # Set observer location
    loc = EarthLocation(lat=lat * u.deg, lon=lon * u.deg, height=height * u.m)

    # Get system timezone and set UTC offset
    try:
        offset = time.timezone if (time.localtime().tm_isdst
                                   == 0) else time.altzone
        utcoffset = (offset / 60 / 60 * -1) * u.hour
    except:
        utcoffset = 0

    # Fetch toady's system date if not specified
    if date == '':
        date = datetime.datetime.today().strftime('%Y-%m-%d')

    midnight = Time(date + ' 00:00:00') - utcoffset
    delta_midnight = np.linspace(0, 24, 1000) * u.hour
    full_day = midnight + delta_midnight
    frame = AltAz(obstime=full_day, location=loc)
    sun_altaz = get_sun(full_day).transform_to(frame)

    if source != '':
        obj_altaz = obj.transform_to(frame)

    # Note source altitude peak
    if source != '':
        seconds = float(delta_midnight[np.argmax(obj_altaz.alt * u.deg)] *
                        3600 / u.hour)
        max = seconds / 3600

        plt.axvline(x=max,
                    color='brown',
                    linestyle='--',
                    linewidth=2,
                    zorder=2)

        # Plot source
        plt.scatter(delta_midnight,
                    obj_altaz.alt,
                    c=obj_altaz.az,
                    label=source,
                    lw=0,
                    s=8,
                    cmap='viridis')

    # Plot Sun
    if plot_sun:
        plt.scatter(delta_midnight,
                    sun_altaz.alt,
                    c=sun_altaz.az,
                    label='Sun',
                    lw=0,
                    s=8,
                    cmap='viridis')

    # Plot properties
    plt.colorbar(aspect=40).set_label('Azimuth (deg)', labelpad=13)
    plt.legend(loc='best')

    plt.xlim(0 * u.hour, 24 * u.hour)
    plt.xticks((np.arange(24)) * u.hour)
    plt.ylim(0 * u.deg, 90 * u.deg)

    if source != '':
        plt.title(source + ' | ' + date, y=1.01)
    else:
        plt.title('Sun | ' + date, y=1.01)

    offset = ["", "+"][int(utcoffset / u.hour) > 0] + str(
        int(utcoffset / u.hour))
    if utcoffset / u.hour != 0:
        plt.xlabel('Time (UTC' + str(offset) + ')')
    else:
        plt.xlabel('Time (UTC)')
    plt.ylabel('Altitude')

    if plot_file != '':
        plt.savefig(plot_file, bbox_inches='tight', pad_inches=0.2)
    else:
        plt.show()
    plt.clf()
Пример #40
0
gps = MirrorGPS.getGPSinfo()
print(gps)
date = gps[0]
time = gps[1]
suntime = Time(date + " " + time)
lon = float(gps[2]) / 100
lat = float(gps[4]) / 100
print("lon: %f" % lon)
print("lat: %f" % lat)
print("suntime: %s" % suntime)
sunPos = get_sun(suntime)
print("sunra: %s" % sunPos.ra)
magDecl = wmm.wmm(lat, lon, 0, 2019)
print("magDecl: %s" % (magDecl.decl.item(), ))

location = EarthLocation.from_geodetic(lat=lat, lon=lon, height=0)
altaz = sunPos.transform_to(AltAz(obstime=suntime, location=location))
sunalt = altaz.alt.deg
sunaz = altaz.az.deg
sunaltZero = sunalt
sunazZero = sunaz

print(sunalt, sunaz)

if (argHeading == None):
    import berryIMU
    orientation = berryIMU.getValues()
    print("pitch: %s , roll: %s , heading: %s" % orientation)
    heading = orientation[2] - magDecl.decl.item()
    print("corrected heading %f" % heading)
else:
Пример #41
0
    session = aoSession(input_src_file, input_cat_file, input_date, input_time,
                        input_obs_len_hr)

    session.create_plan(verbose=args.verbose, make_plot=args.make_plot,\
      use_srcfile_order=args.force_order)

    session.make_cmd_file(args.out_file)


# Some things that are useful
za_min = 1.1  # deg
za_max = 19.7  # deg
slew_speed_az = 25.  # deg/min
slew_speed_za = 2.5  # deg/min
ao = EarthLocation(x=2390490.0, y=-5564764.0, z=1994727.0, unit='meter')
cal_times = {"search": 5, "fold": 60}


class aoSource:
    def __init__(self,
                 name,
                 ra_str,
                 dec_str,
                 nsec,
                 mode,
                 receiver,
                 altaz_frame,
                 parfile_path=None,
                 stepsize_sec=None):
        self.name = name
Пример #42
0
    async def _set_tag_values(self):
        """Convenience coroutine to provide values for all the tags in the FITS
        header."""
        # ---- Date, night and basic image information ----
        now_string = datetime.datetime.now(tz=datetime.timezone.utc).strftime(
            utils.DATETIME_FORMAT)
        date_obs = self.datetime_start.strftime(utils.DATE_FORMAT)
        date_beg = self.datetime_start.strftime(utils.DATETIME_FORMAT)
        date_end = self.datetime_end.strftime(utils.DATETIME_FORMAT)
        self.get_tag(name="DATE").value = now_string
        self.get_tag(name="DATE-OBS").value = date_obs
        self.get_tag(name="DATE-BEG").value = date_beg
        self.get_tag(name="DATE-END").value = date_end
        self.get_tag(name="MJD").value = Time(now_string, format="mjd").value
        self.get_tag(name="MJD-OBS").value = Time(date_obs, format="mjd").value
        self.get_tag(name="MJD-BEG").value = Time(date_beg, format="mjd").value
        self.get_tag(name="MJD-END").value = Time(date_end, format="mjd").value
        # TODO Not sure what value to set here.
        self.get_tag(name="OBSID").value = ""
        self.get_tag(name="IMGTYPE").value = "OBJECT"

        # ---- Pointing info, etc. ----
        # Always pointing at the zenith.
        elevation = 90.0
        # Minor axis always points south
        azimuth = 0.0

        # Retrieve observing location info
        lon = next((tag for tag in self.tags if tag.name == "OBS-LONG")).value
        lat = next((tag for tag in self.tags if tag.name == "OBS-LAT")).value
        height = next(
            (tag for tag in self.tags if tag.name == "OBS-ELEV")).value
        # Create EarthLocation instance for Rubin Observatory
        rubin = EarthLocation.from_geodetic(lon=lon, lat=lat, height=height)

        radec_start = self.__get_radec_from_altaz_location_time(
            alt=elevation, az=azimuth, obs_time=date_beg, location=rubin)
        radec_end = self.__get_radec_from_altaz_location_time(
            alt=elevation, az=azimuth, obs_time=date_end, location=rubin)
        self.get_tag(name="RASTART").value = radec_start.ra.value
        self.get_tag(name="DECSTART").value = radec_start.dec.value
        self.get_tag(name="RAEND").value = radec_end.ra.value
        self.get_tag(name="DECEND").value = radec_end.dec.value
        # Rotation for AllsSky camera is assumed to always be zero.
        self.get_tag(name="ROTPA").value = 0
        # Can be the same as azimuth since only the unit differs.
        self.get_tag(name="HASTART").value = azimuth
        self.get_tag(name="EL").value = elevation
        self.get_tag(name="AZ").value = azimuth
        # Can be the same as azimuth since only the unit differs.
        self.get_tag(name="HAEND").value = azimuth
        self.get_tag(name="RADESYS").value = "ICRS"
        # This value was measured.
        self.get_tag(name="CUBE-MNT").value = self.cube_mnt
        # This value was measured.
        self.get_tag(name="QUAD-MNT").value = self.quad_mnt

        # ---- Image-identifying used to build OBS-ID ----
        self.get_tag(
            name="CAMCODE").value = f"AllSkyCam_{self.name()}_{self.id}"
        # TODO Not sure what value to set here.
        self.get_tag(name="DAYOBS").value = ""
        # TODO Not sure what value to set here.
        self.get_tag(name="SEQNUM").value = ""
        self.get_tag(name="IMGTYPE").value = "OBS"

        # ---- Information from Camera ----
        self.get_tag(name="APERTURE").value = "F/4"
        self.get_tag(name="FLEN").value = 8.0

        # ---- Geometry from Camera ----
        self.get_tag(name="DETSIZE").value = "36 x 24"
        # Pixel size = 5.36 micrometer, focal length = 8.0 mm
        self.get_tag(name="SECPIX").value = (5.36 / 8.0) * 206.265

        # ---- Exposure-related information ----
        self.get_tag(name="EXPTIME").value = self.exposure_time
        self.get_tag(name="ISO").value = self.iso
Пример #43
0
#        with fits.open(path) as f:
#            img = f[0].data
#            img /= 2**16
#            h = f[0].header
#            timestamp = Time(h['DATE-OBS'] + 'T' + h['TIME-OBS'])

#        if self.rotate_image:
#            img = self.rotate(img)

#        return Image(img, timestamp)
#

cta_la_palma = CTA(
    location=EarthLocation(
        lat='28.761870°',
        lon='-17.890777°',
        height=2200 * u.m
    ),
    zenith_row=1699 / 2,
    zenith_col=1699 / 2 - 2,
    rotation=2.75 * u.deg,
)

#magic_2018 = MAGIC2018(
#    location=EarthLocation(
#        lat='28.761870°',
#        lon='-17.890777°',
#        height=2200 * u.m
#    ),
#    zenith_row=MAGIC2018.sensor.resolution_row / 2 + 7,
#    zenith_col=MAGIC2018.sensor.resolution_col / 2 + 33,
Пример #44
0
def _earth_location_from_dict(meta):
    lon = Angle(meta['GEOLON'], 'deg')
    lat = Angle(meta['GEOLAT'], 'deg')
    height = Quantity(meta['ALTITUDE'], 'meter')
    return EarthLocation(lon=lon, lat=lat, height=height)
Пример #45
0
    elif args.instrument == 'europa':
        from speculoos_europa import *
    elif args.instrument == 'ganymede':
        from speculoos_ganymede import *
    elif args.instrument == 'saintex':
        from saintex import *
    elif args.instrument == 'artemis':
        from speculoos_artemis import *
    elif args.instrument == 'rcos20':
        from rcos20 import *
    else:
        sys.exit(1)

    # set up observatory location from coords in telescope file
    observatory = EarthLocation(lat=OLAT * u.deg,
                                lon=OLON * u.deg,
                                height=ELEV * u.m)

    # dictionaries to hold reference images for different fields/filters
    ref_track = defaultdict(dict)

    # outer loop to loop over field and night changes etc
    while 1:
        # initialise the PID controllers for X and Y
        PIDx = PID(PID_COEFFS['x']['p'], PID_COEFFS['x']['i'],
                   PID_COEFFS['x']['d'])
        PIDy = PID(PID_COEFFS['y']['p'], PID_COEFFS['y']['i'],
                   PID_COEFFS['y']['d'])
        PIDx.setPoint(PID_COEFFS['set_x'])
        PIDy.setPoint(PID_COEFFS['set_y'])
Пример #46
0
def get_site():
    from astropy.coordinates import EarthLocation
    from astropy.units import m
    from astropy.utils import iers
    iers.conf.auto_download = False
    return EarthLocation(-1994503. * m, -5037539. * m, 3358105. * m)
Пример #47
0
WORKERS = [
    "arts001", "arts002", "arts003", "arts004", "arts005", "arts006",
    "arts007", "arts008", "arts009", "arts010", "arts011", "arts012",
    "arts013", "arts014", "arts015", "arts016", "arts017", "arts018",
    "arts019", "arts020", "arts021", "arts022", "arts023", "arts024",
    "arts025", "arts026", "arts027", "arts028", "arts029", "arts030",
    "arts031", "arts032", "arts033", "arts034", "arts035", "arts036",
    "arts037", "arts038", "arts039", "arts040"
]

#: ITRF WSRT reference position
ARRAY_ITRF = np.array([
    3828630.63486200943589211, 443593.39226634375518188,
    5064922.99755000043660402
]) * u.m
WSRT_LOC = EarthLocation.from_geocentric(*ARRAY_ITRF)

#: WSRT dish diameter
DISH_DIAM = 25 * u.m

#: Apertif/ARTS number of channels
NCHAN = 1536

#: Apertif/ARTS bandwidth
BANDWIDTH = 300. * u.MHz

#: Apertif/ARTS sampling time
TSAMP = 81.92E-6 * u.s

#: Apertif/ARTS number of compound beams
NUMCB = 40
Пример #48
0
        a2 = obj2
        for subattr in attr.split('.'):
            try:
                a1 = getattr(a1, subattr)
                a2 = getattr(a2, subattr)
            except AttributeError:
                a1 = a1[subattr]
                a2 = a2[subattr]

        if isinstance(a1, np.ndarray) and a1.dtype.kind == 'f':
            assert quantity_allclose(a1, a2, rtol=1e-10)
        else:
            assert np.all(a1 == a2)


el = EarthLocation(x=[1, 2] * u.km, y=[3, 4] * u.km, z=[5, 6] * u.km)
sc = SkyCoord([1, 2], [3, 4], unit='deg,deg', frame='fk4', obstime='J1990.5')
scc = sc.copy()
scc.representation_type = 'cartesian'
tm = Time([51000.5, 51001.5],
          format='mjd',
          scale='tai',
          precision=5,
          location=el[0])
tm2 = Time(tm, format='iso')
tm3 = Time(tm, location=el)
tm3.info.serialize_method['ecsv'] = 'jd1_jd2'

mixin_cols = {
    'tm':
    tm,
Пример #49
0
    filename = os.path.join(args.base_path, '{}.log'.format(
        fn.replace('.py', '')))  # ToDo datetime, name of the script
    logformat = '%(asctime)s:%(name)s:%(levelname)s:%(message)s'
    logging.basicConfig(filename=filename,
                        level=args.level.upper(),
                        format=logformat)
    logger = logging.getLogger()

    if args.toconsole:
        # http://www.mglerner.com/blog/?p=8
        soh = logging.StreamHandler(sys.stdout)
        soh.setLevel(args.level)
        logger.addHandler(soh)

    obs = EarthLocation(lon=float(args.obs_lng) * u.degree,
                        lat=float(args.obs_lat) * u.degree,
                        height=float(args.obs_height) * u.m)
    dt_utc = Time(args.utc, format='iso', scale='utc', location=obs)
    sigma = args.sigma / 3600. / 180. * np.pi
    simulation_data = os.path.join(args.base_path, args.simulation_data)
    wfl = open(simulation_data, 'w')
    vn_lon = 0.
    vn_lat = 0.

    #rf_m=None
    #ri_m=None
    #if 'built_in' not in args.refraction_method:
    #  if 'ciddor' in  args.refractive_index_method or 'edlen' in  args.refractive_index_method:
    #    if import_message is not None:
    #      self.lg.error('u_analyze: {}'.format(import_message))
    #      sys.exit(1)
Пример #50
0
resp_ip = requests.get('http://ipinfo.io/')
loc_json = resp_ip.json()
loc_data = loc_json['loc'].split(",")
lat = float(loc_data[0])
lon = float(loc_data[1])

#user elevation infromation based on IP address

API_KEY = "AIzaSyDwg1l0kMyhYagjdIikdTF57J5p_YVOsDE"
ELEVATION_URL = "https://maps.googleapis.com/maps/api/elevation/json?locations={},\
   {}&key={}".format(lat, lon, API_KEY)
resp_elevation = requests.get(ELEVATION_URL)
elev_json = resp_elevation.json()
elevation = elev_json["results"][0]["elevation"]
location = EarthLocation(lat=lat*u.deg, lon=lon*u.deg, height=elevation*u.m)

#RA/DEC coordinate calculation for all objects in csv file "astro data"

star_coords = set()
messier_coords = set()
ss_coords = set()
for index, row in astrodata.iterrows():
    star_coords.add(SkyCoord.from_name(row[0]))
    messier_coords.add(SkyCoord.from_name(row[1]))
    #ss_coords.add(SkyCoord.from_name(row[2].lower()))
    #messier_coords += SkyCoord.from_name(row[1])
    #ss_coords += SkyCoord.from_name(row[2])

#alt/az coordinate conversions
Пример #51
0
    SkyCoord,
    Longitude,
    Latitude,
    EarthLocation,
    AltAz,
)

TS = load.timescale()  # save repeated use in iterative loops
LE_FORMAT = '3le'  # catalog storage is set up to use 3le format

# location of RASA, La Palma
SITE_LATITUDE = 28.7603135
SITE_LONGITUDE = -17.8796168
SITE_ELEVATION = 2387
SITE_LOCATION = EarthLocation(lat=SITE_LATITUDE * u.deg,
                              lon=SITE_LONGITUDE * u.deg,
                              height=SITE_ELEVATION * u.m)

# topocentric location of RASA, La Palma
TOPOS_LOCATION = Topos(SITE_LATITUDE,
                       SITE_LONGITUDE,
                       elevation_m=SITE_ELEVATION)

# checks for orbital type requests
GEO_CHECK = ['g', 'geo']
LEO_CHECK = ['l', 'leo']
MEO_CHECK = ['m', 'meo']
HEO_CHECK = ['h', 'heo']
ALL_CHECK = ['a', 'all']

Пример #52
0
def t120_insert_radec(work_dir,
                      ahead_file=t120.t120_scamp_ahead,
                      reduc_root='-c.fits'):
    """Put object RA,DEC in fits header
    
    Parameters
    ----------
    work_dir : string
        directory name root where original fits image files are to be found.
    ahead_file : string
        Scamp ahead file to consider to put basic astrometry info.
    reduc_root : string
        Reduced file name suffix. Default is '-c.fit'.
    
    Returns
    -------
    None.
    
    
    """
    redu_dir = work_dir + t120.t120_redu_dir
    t120.log.info('redu_dir ' + redu_dir)

    comm = {
        'OBJCTRA': 'Nominal Right Ascension of center of image',
        'OBJCTDEC': 'Nominal Declination of center of image'
    }

    for fit_file in glob.glob(redu_dir + '*-c.fits'):
        t120.log.info('*** Now opening image ' + fit_file)
        hdulist = fits.open(fit_file)
        hdu = hdulist[0]
        hdr = hdu.header
        data = hdu.data
        target_name = hdr['OBJECT'].strip()
        hdr['OBJECT'] = (target_name.upper().replace(' ', ''), 'Target name')
        skycoo = SkyCoord(hdr['OBJCTRA'],
                          hdr['OBJCTDEC'],
                          unit=(u.hourangle, u.deg))
        time = Time(hdr['DATE-OBS'])
        site = EarthLocation(lat=hdr['SITELAT'], lon=hdr['SITELONG'])
        hdr['CRVAL1'] = (skycoo.ra.to('deg').value,
                         'Reference Right ascencion in decimal deg')
        hdr['CRVAL2'] = (skycoo.dec.to('deg').value,
                         'Reference Declination in decimal deg')
        # now put astrometry info from ahead_file
        aheader = fits.Header.fromfile(ahead_file,
                                       sep='\n',
                                       endcard=False,
                                       padding=False)
        for ahdr in aheader:
            #nhdr=len(hdr)
            t120.log.debug('Setting: ' + ahdr + ' with value: ' +
                           str(aheader.cards[ahdr].value))
            hdr.set(ahdr,
                    value=aheader.cards[ahdr].value,
                    comment=aheader.cards[ahdr].comment)
        hdr.add_history('BASIC ASTROMETRY WAS TAKEN FROM FILE ' + ahead_file)
        hdu.writeto(fit_file, overwrite=True)
        t120.log.info('Image saved in ' + fit_file)
    return
Пример #53
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)
Пример #54
0
    # check if files exist
    if not os.path.isfile(args.filterbank):
        print "Cannot find filterbank file {}".format(args.filterbank)
        sys.exit(1)
    if not os.path.isfile(args.triggers):
        print "Cannot find trigger file {}".format(args.trigger)
        sys.exit(1)

    # get header info
    hdr = FilReader(args.filterbank).header
    radec = SkyCoord(hdr.ra, hdr.dec, unit=(u.hourangle, u.deg))
    starttime = Time(hdr.tstart, format='mjd', scale='utc')

    # define coordinates
    wsrt = EarthLocation(lat=52.915184*u.deg, lon=6.60387*u.deg, height=0*u.m)
    altazstart = radec.transform_to(AltAz(obstime=starttime, location=wsrt))

    # check alt az start
    #assert np.abs(hdr.az_start - altazstart.az.deg) < 1E-4 and \
    #       np.abs(hdr.za_start - (90 - altazstart.alt.deg)) < 1E-4

    # load triggers
    triggers = np.loadtxt(args.triggers, unpack=True)
    if args.triggers.endswith('.trigger'):
        try:
            dm, sigma, t0, downs = triggers[6], triggers[8], triggers[5], triggers[3]
        except:
            dm, sigma, t0, downs = triggers[-2], triggers[-1], triggers[-3], triggers[3]
    elif args.triggers.endswith('.singlepulse'):
        try:
Пример #55
0
 def setup_method(self):
     self.DAP_location = EarthLocation(lon=-76.877, lat=39.1495, height=42)
     self.merra2_ascii = os.path.join(
         'pwv', 'tests', 'data', 'M2T1NXSLV_tqv_20090101-20090104.asc')
     self.aqua_ascii = os.path.join('pwv', 'tests', 'data',
                                    'Aqua_TotO3_D_TotH2OVap_D_test.asc')
Пример #56
0
 def setup_method(self):
     self.FTN = EarthLocation(lon=-156.257029,
                              lat=20.706657,
                              height=3046.52)
     self.GES_example = EarthLocation(lon=-75.625, lat=37.375, height=0)
Пример #57
0
def geramapa(star,
             data,
             title,
             labelx,
             nameimg,
             mapstyle='1',
             resolution='l',
             centermap=None,
             lats=None,
             erro=None,
             ring=None,
             atm=None,
             clat=None,
             sitearq=None,
             fmt='png',
             dpi=100,
             mapsize=None,
             cpoints=60,
             off=0):
    lon = star.ra - data.sidereal_time('mean', 'greenwich')
    center_map = EarthLocation(lon.value, star.dec.value)
    if not centermap == None:
        center_map = EarthLocation(centermap[0], centermap[1])
    m = Basemap(projection='ortho',
                lat_0=center_map.latitude.value,
                lon_0=center_map.longitude.value,
                resolution=resolution)
    #    m = Basemap(projection='ortho',lat_0=center_map.latitude.value,lon_0=center_map.longitude.value,resolution=resolution,llcrnrx=-2000000.,llcrnry=-1500000.,urcrnrx=2000000.,urcrnry=1500000.)
    #    kx = fig.add_axes([-0.003,-0.001,1.006,1.002])
    #    kx.set_rasterization_zorder(1)
    m.nightshade(data.datetime, alpha=0.3,
                 zorder=0.5)  ## desenha a sombra da noite
    m.drawcoastlines(linewidth=0.5)  ## desenha as linhas da costa
    m.drawcountries(linewidth=0.5)  ## desenha os paises
    m.drawstates(linewidth=0.5)  ## Desenha os estados
    m.drawmeridians(np.arange(0, 360, 30))  ## desenha os meridianos
    m.drawparallels(np.arange(-90, 90, 30))  ## desenha os paralelos
    m.drawmapboundary()  ## desenha o contorno do mapa
    style = {
        '1': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'blue',
            'rncolor': 'blue',
            'atcolor': 'blue',
            'outcolor': 'red'
        },
        '2': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '3': {
            'ptcolor': 'red',
            'lncolor': 'blue',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '4': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        },
        '5': {
            'ptcolor': 'red',
            'lncolor': 'red',
            'ercolor': 'red',
            'rncolor': 'black',
            'atcolor': 'black',
            'outcolor': 'red'
        }
    }
    if mapstyle == '2':
        m.drawmapboundary(fill_color='aqua')
        m.fillcontinents(color='coral', lake_color='aqua')
    elif mapstyle == '3':
        m.shadedrelief()
    elif mapstyle == '4':
        m.bluemarble()
    elif mapstyle == '5':
        m.etopo()
    if not lats == None:
        xs, ys = m(lats[0], lats[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['lncolor'])
        xt, yt = m(lats[2], lats[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['lncolor'])
        m.plot(lats[4],
               lats[5],
               color=style[mapstyle]['outcolor'],
               clip_on=False,
               zorder=-0.2)
        m.plot(lats[6],
               lats[7],
               color=style[mapstyle]['outcolor'],
               clip_on=False,
               zorder=-0.2)
#    else:
#        m.plot(lats[4], lats[5], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
#        m.plot(lats[6], lats[7], color=style[mapstyle]['outcolor'], clip_on=False, zorder=0.2)
    if not erro == None:
        xs, ys = m(erro[0], erro[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['ercolor'])
        xt, yt = m(erro[2], erro[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['ercolor'])
    if not ring == None:
        xs, ys = m(ring[0], ring[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, '--', color=style[mapstyle]['rncolor'])
        xt, yt = m(ring[2], ring[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, '--', color=style[mapstyle]['rncolor'])
    if not atm == None:
        xs, ys = m(atm[0], atm[1])
        xs = [i for i in xs if i < 1e+30]
        ys = [i for i in ys if i < 1e+30]
        m.plot(xs, ys, color=style[mapstyle]['atcolor'])
        xt, yt = m(atm[2], atm[3])
        xt = [i for i in xt if i < 1e+30]
        yt = [i for i in yt if i < 1e+30]
        m.plot(xt, yt, color=style[mapstyle]['atcolor'])
    if not clat == None:
        xc, yc, lab = [], [], []
        cp = Time(clat[5], format='iso')
        vec = np.arange(0, (cp[-1] - data).sec, cpoints)
        vec = np.sort(np.concatenate((vec, -vec[1:]), axis=0)) * u.s
        for i in vec:
            g = data + TimeDelta(i) + TimeDelta(off * u.s)
            if g.iso in clat[2]:
                a = np.where(np.array(clat[2]) == g.iso)
                x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                xc.append(x)
                yc.append(y)
                lab.append(g.iso.split()[1][0:8])
            elif g.iso in clat[5]:
                a = np.where(np.array(clat[5]) == g.iso)
                xc.append(np.array(clat[3])[a])
                yc.append(np.array(clat[4])[a])
                lab.append(g.iso.split()[1][0:8])
            else:
                a = np.argsort(np.absolute(cp - g))[0:2]
                if not 0 in a or not len(cp) - 1 in a:
                    b = np.absolute((cp[a] - g).sec)
                    x, y = m(np.array(clat[0])[a], np.array(clat[1])[a])
                    xc.append(np.mean(x * (1 / b)) / np.sum(b))
                    yc.append(np.mean(y * (1 / b)) / np.sum(b))
                    lab.append(g.iso.split()[1][0:8])
                else:
                    co = Time(clat[5], format='iso')
                    a = np.argsort(np.absolute(co - g))[0:2]
                    b = np.absolute((co[a] - g).sec)
                    xc.append(
                        np.mean(np.array(clat[3])[a] * (1 / b)) / np.sum(b))
                    yc.append(
                        np.mean(np.array(clat[4])[a] * (1 / b)) / np.sum(b))
                    lab.append(g.iso.split()[1][0:8])
        m.plot(xc, yc, 'o', color=style[mapstyle]['ptcolor'], clip_on=False)


#    for label, axpt, bypt in zip(lab, xc, yc):
#        plt.text(axpt + 0, bypt + 350000, label, rotation=60, weight='bold')

#    m.plot(ax,by, 'o', color=ptcolor, markersize=int(mapsize[0].value*20/46))
#    m.plot(ax2.to(u.m),by2.to(u.m), 'o', color=ptcolor, markersize=int(mapsize[0].value*12/46))
#    m.plot(ax3.to(u.m), by3.to(u.m), color='red')
#    m.plot(ax4.to(u.m), by4.to(u.m), color='red')
#    m.quiver(a-0*u.m,b-600000*u.m, 20, 0, width=0.005)

#    ax2 = a + dista*np.sin(pa) + [(i - datas).sec for i in temposplot]*u.s*vel*np.cos(paplus)
#    by2 = b + dista*np.cos(pa) - [(i - datas).sec for i in temposplot]*u.s*vel*np.sin(paplus)
#
#    labels = [i.iso.split()[1][0:8] for i in temposplot]
#    m.plot(ax2, by2, 'ro')

#    if os.path.isfile(sitearq) == True:
#        xpt,ypt = m(sites['lon'],sites['lat'])
#        m.plot(xpt,ypt,'bo')
#        offset = [[xpt[0] + 100000,xpt[0] + 100000,xpt[0] + 100000,xpt[3] + 400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000,xpt[3] +400000],[10000,-30000,-60000,70000,30000,-20000,-70000,-30000,-70000]]
#        for i in np.arange(len(xpt)):
#            ax.text(offset[0][i],ypt[i]+offset[1][i],sites['nome'][i], weight='bold')

#    m.plot(ax5.to(u.m), by5.to(u.m), '--', color=dscolor, label='+-{} error'.format(erro))
#    m.plot(ax6.to(u.m), by6.to(u.m), '--', color=dscolor)
#    plt.legend(fontsize=mapsize[0].value*21/46)

    fig = plt.gcf()
    fig.set_size_inches(mapsize[0].to(u.imperial.inch).value,
                        mapsize[1].to(u.imperial.inch).value)
    plt.title(title,
              fontsize=mapsize[0].value * 25 / 46,
              fontproperties='FreeMono',
              weight='bold')
    plt.xlabel(labelx,
               fontsize=mapsize[0].value * 21 / 46,
               fontproperties='FreeMono',
               weight='bold')
    plt.savefig('{}.{}'.format(nameimg, fmt), format=fmt, dpi=dpi)
    print 'Gerado: {}.{}'.format(nameimg, fmt)
    plt.clf()
Пример #58
0
#Obj=SkyCoord.from_name('3c138')

#Obj=SkyCoord.from_name('J071338.1+434917')

#print Phase_cal

#Phase_cal_ra='23:55:09.458169'
#Phase_cal_dec='+49:50:08.34001'

#Sun_ra='22:13:30.0'
#Sun_dec='-10:59:42.0'

VLA_longitude=-107.61777778*u.deg

VLA=EarthLocation(lat=34.07874917*u.deg,lon=VLA_longitude,height=2124*u.m)

#print VLA

#Test_longitude=0*u.deg

#Time at VLA = UTC - 7

utcoffset=-7*u.hour ######Check UTC and sidereal time difference

date='2019-02-20'

midnight=Time(date+' 00:00:00', scale='utc')

#midnight=0*u.hour+0*u.minute+0*u.second
Пример #59
0
from __future__ import print_function, division

from astropy.coordinates import AltAz, SkyCoord, EarthLocation
from astropy.io.fits import getheader
from astropy.time import Time
import astropy.units as u
import numpy as np
import os

MWAPOS = EarthLocation.from_geodetic(lon="116:40:14.93",
                                     lat="-26:42:11.95",
                                     height=377.8)


def get_time(metafits, pos):
    """Grab time and lst from a metafits file of an observation

    Parameters
    ----------
    metafits : [type]
        [description]
    pos : Astropy location object
        Geographic location of the array

    Returns
    -------
    tuple(time object, LST)
        time object and LST of the observation
    """
    metafits = getheader(metafits)
    time = Time(metafits["DATE-OBS"], location=pos)
Пример #60
0
    "get_event_pos_in_camera",
    "get_geomagnetic_delta",
    "impute_pointing",
    "linear_imputer",
    "polar_to_cartesian",
    "predict_source_position_in_camera",
    "radec_to_camera",
    "reco_source_position_sky",
    "rotate",
    "sky_to_camera",
    "source_dx_dy",
    "source_side",
]

# position of the LST1
location = EarthLocation.from_geodetic(-17.89139 * u.deg, 28.76139 * u.deg, 2184 * u.m)
obstime = Time("2018-11-01T02:00")
horizon_frame = AltAz(location=location, obstime=obstime)

# Geomagnetic parameters for the LST1 as per
# https://www.ngdc.noaa.gov/geomag/calculators/magcalc.shtml?#igrfwmm and
# using IGRF model on date  TIME_MC = 2020-06-29
GEOM_MAG_REFERENCE_TIME = Time("2020-06-29", format="iso")
GEOMAG_DEC = (-5.0674 * u.deg).to(u.rad)
GEOMAG_INC = (37.4531 * u.deg).to(u.rad)
GEOMAG_TOTAL = 38.7305 * u.uT

DELTA_DEC = (0.1656 * u.deg / u.yr).to(u.rad / u.year)
DELTA_INC = (-0.0698 * u.deg / u.yr).to(u.rad / u.year)
DELTA_TOTAL = 0.009 * u.uT / u.yr