Пример #1
0
def test_single_zenith_source_uvdata():
    """Test single zenith source using test uvdata file."""
    hera_uv = UVData()
    hera_uv.read_uvfits(EW_uvfits_file)

    time = Time(hera_uv.time_array[0], scale='utc', format='jd')
    array_location = EarthLocation.from_geocentric(
        hera_uv.telescope_location[0],
        hera_uv.telescope_location[1],
        hera_uv.telescope_location[2],
        unit='m')
    freq = hera_uv.freq_array[0, 0] * units.Hz

    # get antennas positions into ENU
    antpos = hera_uv.antenna_positions[0:2, :] + hera_uv.telescope_location
    antpos = uvutils.ENU_from_ECEF(antpos.T,
                                   *hera_uv.telescope_location_lat_lon_alt).T

    antenna1 = pyuvsim.Antenna('ant1', 1, np.array(antpos[0, :]), 0)
    antenna2 = pyuvsim.Antenna('ant2', 2, np.array(antpos[1, :]), 0)

    # setup the things that don't come from pyuvdata:
    # make a source at zenith
    time.location = array_location
    source = create_zenith_source(time, 'zensrc')

    beam = UVBeam()
    beam.read_cst_beam(beam_files,
                       beam_type='efield',
                       frequency=[100e6, 123e6],
                       telescope_name='HERA',
                       feed_name='PAPER',
                       feed_version='0.1',
                       feed_pol=['x'],
                       model_name='E-field pattern - Rigging height 4.9m',
                       model_version='1.0')

    beam_list = [beam]

    baseline = pyuvsim.Baseline(antenna1, antenna2)
    array = pyuvsim.Telescope('telescope_name', array_location, beam_list)
    task = pyuvsim.UVTask(source, time, freq, baseline, array)
    engine = pyuvsim.UVEngine(task)

    visibility = engine.make_visibility()

    nt.assert_true(np.allclose(visibility, np.array([.5, .5, 0, 0]),
                               atol=5e-3))
Пример #2
0
    def test_add_obs(self):
        t1 = Time('2016-01-10 01:15:23', scale='utc')
        t2 = t1 + TimeDelta(120.0, format='sec')

        # t1.delta_ut1_utc = mc.iers_a.ut1_utc(t1)
        # t2.delta_ut1_utc = mc.iers_a.ut1_utc(t2)

        from math import floor
        obsid = floor(t1.gps)
        t1.location = EarthLocation.from_geodetic(observations.HERA_LON, observations.HERA_LAT)

        expected = [observations.Observation(obsid=obsid, start_time_jd=t1.jd,
                                             stop_time_jd=t2.jd,
                                             lst_start_hr=t1.sidereal_time('apparent').hour)]

        self.test_session.add(observations.Observation.new_with_astropy(t1, t2))
        result = self.test_session.get_obs()
        self.assertEqual(result, expected)
Пример #3
0
def height_time(coord, time, time_left=False, limalt=0.0*u.deg, site=EarthLocation(0.0, 0.0, 0.0), fuse=TimeDelta(0, format='sec', scale='tai')):
    """
    """
    coord = coord_pack(coord)
    timeut = time - fuse
    if len(time.shape) == 1:
        timeut = Time([[i] for i in timeut.jd], format='jd', scale='utc')
    timeut.location = site
    timeut.delta_ut1_utc = 0
    ra, ts = mesh_coord(coord, timeut)
    hourangle = Angle(ts-ra)
    distzen = np.arccos(np.sin(coord.dec)*np.sin(site.latitude) + np.cos(coord.dec)*np.cos(site.latitude)*np.cos(hourangle))
    altura = 90*u.deg - distzen
    if time_left == True:
        poente = sky_time(coord, time, rise_set=True, limalt=limalt, site=site, fuse=fuse)[2]
        time_rest = poente - time
        return altura, time_rest
    return altura
Пример #4
0
def sky_time(coord, time, rise_set=False, limalt=0*u.deg, site=EarthLocation(0.0, 0.0, 0.0), fuse=TimeDelta(0, format='sec', scale='tai')):
    """
    """
    if type(limalt) != u.quantity.Quantity:
        limalt = limalt*u.deg
    if time.isscalar == True:
        time = Time([time.iso], format='iso', scale='utc')
    coord = coord_pack(coord)
    timeut = time - fuse
    if len(time.shape) == 1:
        timeut = Time([[i] for i in timeut.jd], format='jd', scale='utc')
    timeut.delta_ut1_utc = 0
    timeut.location = site
    ra, ts = mesh_coord(coord, timeut[:,0])
    dif_h_sid = Angle(ra-ts)
    dif_h_sid.wrap_at('180d', inplace=True)
    dif_h_sol = dif_h_sid * (23.0 + 56.0/60.0 + 4.0916/3600.0) / 24.0
    dif = TimeDelta(dif_h_sol.hour*u.h, scale='tai')
    culminacao = timeut + dif
    culminacao.delta_ut1_utc = 0
    culminacao.location = site
    if (site.latitude > 0*u.deg):
        alwaysup = np.where(coord.dec >= 90*u.deg - site.latitude + limalt)
        neverup = np.where(coord.dec <= -(90*u.deg - site.latitude - limalt))
    else:
        alwaysup = np.where(coord.dec <= -(90*u.deg + site.latitude + limalt))
        neverup = np.where(coord.dec >= 90*u.deg + site.latitude - limalt)
    if rise_set == True:
        hangle_lim = np.arccos((np.cos(90.0*u.deg-limalt) - np.sin(coord.dec)*np.sin(site.latitude)) / (np.cos(coord.dec)*np.cos(site.latitude)))
        tsg_lim = Angle(ra + hangle_lim)
        dtsg_lim = tsg_lim - culminacao.sidereal_time('mean')
        dtsg_lim.wrap_at(360 * u.deg, inplace=True)
        dtsg_lim_sol = dtsg_lim * (23.0 + 56.0/60.0 + 4.0916/3600.0) / 24.0
        a = np.where(np.isnan(dtsg_lim_sol))
        dtsg_lim_sol[a] = Angle([48.0]*len(a[0])*u.hour)
        dtsg_np = TimeDelta((dtsg_lim_sol.hour*u.h))
        sunrise = culminacao - dtsg_np
        sunset = culminacao + dtsg_np
        culminacao = culminacao + fuse
        sunrise = sunrise + fuse
        sunset = sunset + fuse
        return culminacao, sunrise, sunset, alwaysup, neverup
    culminacao = culminacao + fuse
    return culminacao, alwaysup, neverup
Пример #5
0
def sky_time(coord, time, rise_set=False, limalt=0*u.deg, site=EarthLocation(0.0, 0.0, 0.0), fuse=TimeDelta(0, format='sec', scale='tai')):
    """
    """
    if type(limalt) != u.quantity.Quantity:
        limalt = limalt*u.deg
    if time.isscalar == True:
        time = Time([time.iso], format='iso', scale='utc')
    coord = coord_pack(coord)
    timeut = time - fuse
    if len(time.shape) == 1:
        timeut = Time([[i] for i in timeut.jd], format='jd', scale='utc')
    timeut.delta_ut1_utc = 0
    timeut.location = site
    ra, ts = mesh_coord(coord, timeut)
    dif_h_sid = Angle(ra-ts)
    dif_h_sid.wrap_at('180d', inplace=True)
    dif_h_sol = dif_h_sid * (23.0 + 56.0/60.0 + 4.0916/3600.0) / 24.0
    dif = TimeDelta(dif_h_sol.hour*u.h, scale='tai')
    culminacao = timeut + dif
    culminacao.delta_ut1_utc = 0
    culminacao.location = site
    if rise_set == True:
        hangle_lim = np.arccos((np.cos(90.0*u.deg-limalt) - np.sin(coord.dec)*np.sin(site.latitude)) / (np.cos(coord.dec)*np.cos(site.latitude)))
        tsg_lim = Angle(ra + hangle_lim)
        dtsg_lim = tsg_lim - culminacao.sidereal_time('mean')
        dtsg_lim.wrap_at(360 * u.deg, inplace=True)
        dtsg_lim_sol = dtsg_lim * (23.0 + 56.0/60.0 + 4.0916/3600.0) / 24.0
        a = np.where(np.isnan(dtsg_lim_sol))
        dtsg_lim_sol[a] = Angle([48.0]*len(a[0])*u.hour)
        dtsg_np = TimeDelta((dtsg_lim_sol.hour*u.h))
        sunrise = culminacao - dtsg_np
        sunset = culminacao + dtsg_np
        if (site.latitude > 0*u.deg):
            alwaysup = np.where(coord.dec >= 90*u.deg - site.latitude + limalt)
            neverup = np.where(coord.dec <= -(90*u.deg - site.latitude - limalt))
        else:
            alwaysup = np.where(coord.dec <= -(90*u.deg + site.latitude + limalt))
            neverup = np.where(coord.dec >= 90*u.deg + site.latitude - limalt)
        culminacao = culminacao + fuse
        sunrise = sunrise + fuse
        sunset = sunset + fuse
        return culminacao, sunrise, sunset, alwaysup, neverup
    culminacao = culminacao + fuse
    return culminacao
Пример #6
0
def test_add_obs(mcsession):
    test_session = mcsession
    t1 = Time('2016-01-10 01:15:23', scale='utc')
    t2 = t1 + TimeDelta(120.0, format='sec')

    # generated test hera_lat, hera_lon using the output of geo.py -c
    # with this website:
    # http://www.uwgb.edu/dutchs/usefuldata/ConvertUTMNoOZ.HTM

    obsid_calc = int(floor(t1.gps))
    obsid = utils.calculate_obsid(t1)
    assert obsid_calc == obsid
    t1.location = EarthLocation.from_geodetic(21.4283038269, -30.7215261207)

    expected = Observation(obsid=obsid,
                           starttime=t1.gps,
                           stoptime=t2.gps,
                           jd_start=t1.jd,
                           lst_start_hr=t1.sidereal_time('apparent').hour)

    test_session.add_obs(t1, t2, obsid)
    result = test_session.get_obs()
    assert len(result) == 1
    result = result[0]
    assert result.length == 120.0
    assert result.isclose(expected)

    t3 = t1 + TimeDelta(10 * 60., format='sec')
    t4 = t2 + TimeDelta(10 * 60., format='sec')
    test_session.add_obs(t3, t4, utils.calculate_obsid(t3))

    result_mult = test_session.get_obs_by_time(starttime=t1, stoptime=t4)
    assert len(result_mult) == 2

    result_most_recent = test_session.get_obs_by_time(most_recent=True)
    assert result_most_recent[0] == result_mult[1]

    result_orig = test_session.get_obs(obsid=obsid)
    assert len(result_orig) == 1
    result_orig = result_orig[0]
    assert result_orig.isclose(expected)
Пример #7
0
def test_single_zenith_source():
    """Test single zenith source."""
    time = Time('2018-03-01 00:00:00', scale='utc')

    array_location = EarthLocation(lat='-30d43m17.5s',
                                   lon='21d25m41.9s',
                                   height=1073.)
    time.location = array_location

    freq = (150e6 * units.Hz)
    source = create_zenith_source(time, 'zensrc')

    antenna1 = pyuvsim.Antenna('ant1', 1, np.array([0, 0, 0]), 0)
    antenna2 = pyuvsim.Antenna('ant2', 2, np.array([107, 0, 0]), 0)

    baseline = pyuvsim.Baseline(antenna1, antenna2)

    beam = UVBeam()
    beam.read_cst_beam(beam_files,
                       beam_type='efield',
                       frequency=[150e6, 123e6],
                       telescope_name='HERA',
                       feed_name='PAPER',
                       feed_version='0.1',
                       feed_pol=['x'],
                       model_name='E-field pattern - Rigging height 4.9m',
                       model_version='1.0')

    beam_list = [beam]
    array = pyuvsim.Telescope('telescope_name', array_location, beam_list)

    task = pyuvsim.UVTask(source, time, freq, baseline, array)

    engine = pyuvsim.UVEngine(task)

    visibility = engine.make_visibility()

    nt.assert_true(np.allclose(visibility, np.array([.5, .5, 0, 0]),
                               atol=5e-3))
Пример #8
0
    def test_add_obs(self):
        t1 = Time('2016-01-10 01:15:23', scale='utc')
        t2 = t1 + TimeDelta(120.0, format='sec')

        # t1.delta_ut1_utc = mc.iers_a.ut1_utc(t1)
        # t2.delta_ut1_utc = mc.iers_a.ut1_utc(t2)

        from math import floor
        obsid = floor(t1.gps)
        t1.location = EarthLocation.from_geodetic(observations.HERA_LON,
                                                  observations.HERA_LAT)

        expected = [
            observations.Observation(
                obsid=obsid,
                start_time_jd=t1.jd,
                stop_time_jd=t2.jd,
                lst_start_hr=t1.sidereal_time('apparent').hour)
        ]

        self.test_session.add(observations.Observation.new_with_astropy(
            t1, t2))
        result = self.test_session.get_obs()
        self.assertEqual(result, expected)
Пример #9
0
def test_redundant_baselines():
    """Check that two perfectly redundant baselines are truly redundant. """

    hera_uv = UVData()
    hera_uv.read_uvfits(EW_uvfits_file, ant_str='cross')
    hera_uv.unphase_to_drift()

    src_az = Angle('90.0d')
    src_alt = Angle('85.0d')
    src_za = Angle('90.0d') - src_alt

    src_l = np.sin(src_az.rad) * np.sin(src_za.rad)
    src_m = np.cos(src_az.rad) * np.sin(src_za.rad)
    src_n = np.cos(src_za.rad)

    time = Time(hera_uv.time_array[0], scale='utc', format='jd')
    array_location = EarthLocation.from_geocentric(
        hera_uv.telescope_location[0],
        hera_uv.telescope_location[1],
        hera_uv.telescope_location[2],
        unit='m')
    freq = hera_uv.freq_array[0, 0] * units.Hz

    # get antennas positions into ENU
    antpos, _ = hera_uv.get_ENU_antpos()

    en_shift = [5., 5., 0]
    antenna1 = pyuvsim.Antenna('ant1', 1, np.array(antpos[0, :]), 0)
    antenna2 = pyuvsim.Antenna('ant2', 2, np.array(antpos[1, :]), 0)
    antenna3 = pyuvsim.Antenna('ant3', 3, np.array(antpos[0, :]) + en_shift, 0)
    antenna4 = pyuvsim.Antenna('ant4', 4, np.array(antpos[1, :]) + en_shift, 0)

    # setup the things that don't come from pyuvdata:
    # make a source off zenith
    time.location = array_location
    source = create_offzenith_source(time, 'offzensrc', az=src_az, alt=src_alt)

    beam = UVBeam()
    beam.read_cst_beam(beam_files,
                       beam_type='efield',
                       frequency=[100e6, 123e6],
                       telescope_name='HERA',
                       feed_name='PAPER',
                       feed_version='0.1',
                       feed_pol=['x'],
                       model_name='E-field pattern - Rigging height 4.9m',
                       model_version='1.0')

    beam_list = [beam]

    baseline1 = pyuvsim.Baseline(antenna1, antenna2)
    baseline2 = pyuvsim.Baseline(antenna3, antenna4)

    print('Baseline1 uvw: ', baseline1.uvw)
    print('Baseline2 uvw: ', baseline2.uvw)
    print('Baseline1 enus: ', baseline1.antenna1.pos_enu,
          baseline1.antenna2.pos_enu)
    print('Baseline2 enus: ', baseline2.antenna1.pos_enu,
          baseline2.antenna2.pos_enu)

    array = pyuvsim.Telescope('telescope_name', array_location, beam_list)

    task1 = pyuvsim.UVTask(source, time, freq, baseline1, array)
    engine = pyuvsim.UVEngine(task1)

    visibility1 = engine.make_visibility()

    task2 = pyuvsim.UVTask(source, time, freq, baseline2, array)
    engine = pyuvsim.UVEngine(task2)

    visibility2 = engine.make_visibility()

    nt.assert_true(np.allclose(visibility1, visibility2))
Пример #10
0
def test_source_below_horizon():
    time = Time('2018-03-01 00:00:00', scale='utc')

    array_location = EarthLocation(lat='-30d43m17.5s',
                                   lon='21d25m41.9s',
                                   height=1073.)
    time.location = array_location

    freq = (150e6 * units.Hz)

    source = create_offzenith_source(time,
                                     'src_down',
                                     az=Angle('0d'),
                                     alt=Angle('-40d'))

    antenna1 = pyuvsim.Antenna('ant1', 1, np.array([0, 0, 0]), 0)
    antenna2 = pyuvsim.Antenna('ant2', 2, np.array([107, 0, 0]), 0)

    baseline = pyuvsim.Baseline(antenna1, antenna2)

    beam = UVBeam()
    beam.read_cst_beam(beam_files,
                       beam_type='efield',
                       frequency=[150e6, 123e6],
                       telescope_name='HERA',
                       feed_name='PAPER',
                       feed_version='0.1',
                       feed_pol=['x'],
                       model_name='E-field pattern - Rigging height 4.9m',
                       model_version='1.0')

    beam_list = [beam]
    array = pyuvsim.Telescope('telescope_name', array_location, beam_list)

    task = pyuvsim.UVTask(source, time, freq, baseline, array)

    engine = pyuvsim.UVEngine(task)

    visibility = engine.make_visibility()

    nt.assert_true(np.allclose(visibility, np.array([0, 0, 0, 0])))

    # redo with RA/Dec defined source
    time = Time(2458098.27471265, format='jd')
    time.location = array_location

    source_coord = SkyCoord(ra=Angle('13h20m'),
                            dec=Angle('-30d43m17.5s'),
                            obstime=time,
                            frame='icrs',
                            location=array_location)

    source = pyuvsim.Source('src_down', source_coord.ra, source_coord.dec,
                            freq, [1.0, 0, 0, 0])

    task = pyuvsim.UVTask(source, time, freq, baseline, array)

    engine = pyuvsim.UVEngine(task)

    visibility = engine.make_visibility()

    nt.assert_true(np.allclose(visibility, np.array([0, 0, 0, 0])))
Пример #11
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
Пример #12
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='Time Column "b" has no '
                          '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='Time Column "b" has no '
                          'specified location, but global Time Position is present'):
            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()
        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
Пример #13
0
        tracklist = get_best_gridpoints(
            gps_start=start_time.gps + 16,  # Add 16 to allow for mode change
            obs_source_ra_deg=options.obs_source_ra_deg,
            obs_source_dec_deg=options.obs_source_dec_deg,
            avoid_source_ra_deg=options.avoid_source_ra_deg,
            avoid_source_dec_deg=options.avoid_source_dec_deg,
            model=options.model,
            min_gain=options.min_gain,
            max_beam_distance_deg=options.max_beam_distance_deg,
            channel=options.channel,
            verb_level=1,
            duration=options.duration,
            step=step,
            min_elevation=options.min_elevation)

    start_time.location = config.MWAPOS

    if options.outfile is None:
        # 20170216_cmdfile_J112537_LST9.91.txt
        outfile_name = ("%s_cmdfile_%s_LST%.4f_BeamModel-%s_mingain%.2f.txt" %
                        (start_time.datetime.strftime("%Y%m%d"), options.obj,
                         start_time.sidereal_time('mean').hour, options.model,
                         options.min_gain))
    else:
        outfile_name = options.outfile

    creator = getpass.getuser()

    outfile = open(outfile_name, 'a+')
    outfile.write("# setting correlator mode :\n")
Пример #14
0
def get_skytemp(datetimestring, delays, frequency, alpha=-2.6, verbose=True):
    """
    Tx,Ty=get_skytemp(datetimestring, delays, frequency, alpha=-2.6, verbose=True)
    not completely sure about the normalization, since the Haslam FITS image is not specific

    """
    su.init_data()

    if not os.path.exists(config.RADIO_IMAGE_FILE):
        logger.error("Could not find 408 MHz image: %s\n" %
                     (config.RADIO_IMAGE_FILE))
        return None
    try:
        if (verbose):
            print("Loading 408 MHz map from %s..." % config.RADIO_IMAGE_FILE)
        f = pyfits.open(config.RADIO_IMAGE_FILE)
    except Exception as e:
        logger.error("Error opening 408 MHz image: %s\nError: %s\n" %
                     (config.RADIO_IMAGE_FILE, e))
        return None
    skymap = f[0].data[0]

    ra = (f[0].header.get('CRVAL1') +
          (numpy.arange(1, skymap.shape[1] + 1) - f[0].header.get('CRPIX1')) *
          f[0].header.get('CDELT1')) / 15.0
    dec = (f[0].header.get('CRVAL2') +
           (numpy.arange(1, skymap.shape[0] + 1) - f[0].header.get('CRPIX2')) *
           f[0].header.get('CDELT2'))

    # parse the datetimestring
    try:
        yr = int(datetimestring[:4])
        mn = int(datetimestring[4:6])
        dy = int(datetimestring[6:8])
        hour = int(datetimestring[8:10])
        minute = int(datetimestring[10:12])
        second = int(datetimestring[12:14])
    except ValueError:
        logger.error('Could not parse datetimestring %s\n' % datetimestring)
        return None
    # UT = hour + minute / 60.0 + second / 3600.0
    UTs = '%02d:%02d:%02d' % (hour, minute, second)
    a_obstime = Time('%d-%d-%d %s' % (yr, mn, dy, UTs), scale='utc')
    a_obstime.delta_ut1_utc = 0
    a_obstime.location = config.MWAPOS
    if (verbose):
        print("For %02d-%02d-%02d %s UT, LST=%6.3f" %
              (yr, mn, dy, UTs, a_obstime.sidereal_time(kind='mean').hour))

    RA, Dec = numpy.meshgrid(ra * 15, dec)
    coords = SkyCoord(ra=RA,
                      dec=Dec,
                      equinox='J2000',
                      unit=(astropy.units.deg, astropy.units.deg))
    coords.location = config.MWAPOS
    coords.obstime = a_obstime
    coords_prec = coords.transform_to('altaz')
    Az, Alt = coords_prec.az.deg, coords_prec.alt.deg

    if (verbose):
        print("Creating primary beam response for frequency %.2f MHz..." %
              (frequency))
        print("Beamformer delays are %s" % delays)
    # get the beam response
    # first go from altitude to zenith angle
    theta = (90 - Alt) * math.pi / 180
    phi = Az * math.pi / 180

    # this is the response for XX and YY
    try:
        respX, respY = primary_beam.MWA_Tile_analytic(
            theta, phi, freq=frequency * 1e6, delays=numpy.array(delays))
    except Exception as e:
        logger.error('Error creating primary beams: %s\n' % e)
        return None
    rX = numpy.real(numpy.conj(respX) * respX)
    rY = numpy.real(numpy.conj(respY) * respY)

    maskedskymap = numpy.ma.array(skymap, mask=Alt <= 0)
    maskedskymap *= (frequency / 408.0)**alpha
    rX /= rX.sum()
    rY /= rY.sum()
    return ((rX * maskedskymap).sum()) / 10.0, (
        (rY * maskedskymap).sum()) / 10.0
Пример #15
0
def test_offzenith_source_multibl_uvfits():
    """Test single off-zenith source using test uvdata file.
        Calculate visibilities for a baseline triangle.
    """
    hera_uv = UVData()
    hera_uv.read_uvfits(
        longbl_uvfits_file, ant_str='cross'
    )  # consists of a right triangle of baselines with w term
    hera_uv.unphase_to_drift()

    src_az = Angle('90.0d')
    src_alt = Angle('85.0d')
    src_za = Angle('90.0d') - src_alt

    src_l = np.sin(src_az.rad) * np.sin(src_za.rad)
    src_m = np.cos(src_az.rad) * np.sin(src_za.rad)
    src_n = np.cos(src_za.rad)

    time = Time(hera_uv.time_array[0], scale='utc', format='jd')
    array_location = EarthLocation.from_geocentric(
        hera_uv.telescope_location[0],
        hera_uv.telescope_location[1],
        hera_uv.telescope_location[2],
        unit='m')
    freq = hera_uv.freq_array[0, 0] * units.Hz

    # get antennas positions into ENU
    antpos, ants = hera_uv.get_ENU_antpos()
    antenna1 = pyuvsim.Antenna('ant1', ants[0], np.array(antpos[0, :]), 0)
    antenna2 = pyuvsim.Antenna('ant2', ants[1], np.array(antpos[1, :]), 0)
    antenna3 = pyuvsim.Antenna('ant3', ants[2], np.array(antpos[2, :]), 0)

    # setup the things that don't come from pyuvdata:
    # make a source off zenith
    time.location = array_location
    source = create_offzenith_source(time, 'offzensrc', az=src_az, alt=src_alt)

    # beam = UVBeam()
    # beam.read_cst_beam(beam_files, beam_type='efield', frequency=[100e6, 123e6],
    #                    telescope_name='HERA',
    #                    feed_name='PAPER', feed_version='0.1', feed_pol=['x'],
    #                    model_name='E-field pattern - Rigging height 4.9m',
    #                    model_version='1.0')

    beam = pyuvsim.AnalyticBeam('tophat')

    beam_list = [beam]

    baselines = [
        pyuvsim.Baseline(antenna2, antenna1),
        pyuvsim.Baseline(antenna3, antenna1),
        pyuvsim.Baseline(antenna3, antenna2)
    ]
    array = pyuvsim.Telescope('telescope_name', array_location, beam_list)
    tasks = [pyuvsim.UVTask(source, time, freq, bl, array) for bl in baselines]
    visibilities = []
    uvws = []
    for t in tasks:
        engine = pyuvsim.UVEngine(t)
        visibilities.append(engine.make_visibility())
        uvws.append(t.baseline.uvw)

    uvws = np.array(uvws)
    # analytically calculate visibilities

    beam.peak_normalize()
    beam.interpolation_function = 'az_za_simple'
    interpolated_beam, interp_basis_vector = beam.interp(
        az_array=np.array([src_az.rad]),
        za_array=np.array([src_za.rad]),
        freq_array=np.array([freq.to('Hz').value]))
    jones = np.zeros((2, 2), dtype=np.complex64)
    jones[0, 0] = interpolated_beam[1, 0, 0, 0, 0]
    jones[1, 1] = interpolated_beam[0, 0, 1, 0, 0]
    jones[1, 0] = interpolated_beam[1, 0, 1, 0, 0]
    jones[0, 1] = interpolated_beam[0, 0, 0, 0, 0]

    uvw_wavelength_array = hera_uv.uvw_array[
        0:hera_uv.Nbls] * units.m / const.c * freq.to('1/s')

    visibilities_analytic = []
    for u, v, w in uvw_wavelength_array:
        vis = 0.5 * np.dot(
            jones,
            np.conj(jones).T) * np.exp(2j * np.pi *
                                       (u * src_l + v * src_m + w * src_n))
        visibilities_analytic.append(
            np.array([vis[0, 0], vis[1, 1], vis[1, 0], vis[0, 1]]))

    print('pyuvsim uvws: ', np.around(uvws))
    print('file uvws: ', np.around(hera_uv.uvw_array[0:hera_uv.Nbls]))
    print('Difference: ', uvws - hera_uv.uvw_array[0:hera_uv.Nbls])

    # the file used different phasing code than the test uses -- increase the tolerance
    nt.assert_true(
        np.allclose(uvws, hera_uv.uvw_array[0:hera_uv.Nbls], atol=1e-4))

    print('Analytic visibility', visibilities_analytic)
    print('Calculated visibility', visibilities)
    print(np.array(visibilities) - np.array(visibilities_analytic))

    # the file used different phasing code than the test uses -- increase the tolerance
    nt.assert_true(np.allclose(visibilities, visibilities_analytic, atol=1e-4))
Пример #16
0
def test_single_offzenith_source_miriad():
    """Test single off-zenith source using test uvdata file."""
    miriad_uv = UVData()
    miriad_uv.read_miriad(os.path.join(DATA_PATH, 'hera_testfile'),
                          ant_str='9_10')
    miriad_uv.select(times=miriad_uv.time_array[0])

    src_az = Angle('90.0d')
    src_alt = Angle('85.0d')
    src_za = Angle('90.0d') - src_alt

    src_l = np.sin(src_az.rad) * np.sin(src_za.rad)
    src_m = np.cos(src_az.rad) * np.sin(src_za.rad)
    src_n = np.cos(src_za.rad)

    time = Time(miriad_uv.time_array[0], scale='utc', format='jd')
    array_location = EarthLocation.from_geocentric(
        miriad_uv.telescope_location[0],
        miriad_uv.telescope_location[1],
        miriad_uv.telescope_location[2],
        unit='m')
    freq = miriad_uv.freq_array[0, 0] * units.Hz

    # get antennas positions into ENU
    antpos = miriad_uv.antenna_positions[0:2, :] + miriad_uv.telescope_location
    antpos = uvutils.ENU_from_ECEF(antpos.T,
                                   *miriad_uv.telescope_location_lat_lon_alt).T

    antenna1 = pyuvsim.Antenna('ant1', 1, np.array(antpos[0, :]), 0)
    antenna2 = pyuvsim.Antenna('ant2', 2, np.array(antpos[1, :]), 0)

    # setup the things that don't come from pyuvdata:
    # make a source off zenith
    time.location = array_location
    source = create_offzenith_source(time, 'offzensrc', az=src_az, alt=src_alt)

    beam = UVBeam()
    beam.read_cst_beam(beam_files,
                       beam_type='efield',
                       frequency=[100e6, 123e6],
                       telescope_name='HERA',
                       feed_name='PAPER',
                       feed_version='0.1',
                       feed_pol=['x'],
                       model_name='E-field pattern - Rigging height 4.9m',
                       model_version='1.0')

    beam_list = [beam]

    baseline = pyuvsim.Baseline(antenna1, antenna2)
    array = pyuvsim.Telescope('telescope_name', array_location, beam_list)
    task = pyuvsim.UVTask(source, time, freq, baseline, array)
    engine = pyuvsim.UVEngine(task)

    visibility = engine.make_visibility()

    # analytically calculate visibility

    beam.peak_normalize()
    beam.interpolation_function = 'az_za_simple'
    interpolated_beam, interp_basis_vector = beam.interp(
        az_array=np.array([src_az.rad]),
        za_array=np.array([src_za.rad]),
        freq_array=np.array([freq.to('Hz').value]))
    jones = np.zeros((2, 2), dtype=np.complex64)
    jones[0, 0] = interpolated_beam[1, 0, 0, 0, 0]
    jones[1, 1] = interpolated_beam[0, 0, 1, 0, 0]
    jones[1, 0] = interpolated_beam[1, 0, 1, 0, 0]
    jones[0, 1] = interpolated_beam[0, 0, 0, 0, 0]

    uvw_wavelength_array = hera_uv.uvw_array * units.m / const.c * freq.to(
        '1/s')

    vis_analytic = 0.5 * np.dot(
        jones,
        np.conj(jones).T) * np.exp(
            -2j * np.pi *
            (uvw_wavelength_array[0, 0] * src_l + uvw_wavelength_array[0, 1] *
             src_m + uvw_wavelength_array[0, 2] * src_n))
    vis_analytic = np.array([
        vis_analytic[0, 0], vis_analytic[1, 1], vis_analytic[1, 0],
        vis_analytic[0, 1]
    ])

    print('Analytic visibility', vis_analytic)
    print('Calculated visibility', visibility)

    nt.assert_true(np.allclose(visibility, vis_analytic, atol=5e-3))
Пример #17
0
    def skycoord(self):
        '''
        Manage and fix sky coordinates
        '''
        head = self.head.copy()

        # time
        if self.obstime not in head:
            head['JD'] = Time.now().jd

        # earthlocation
        location = EarthLocation(lon=self.lon, lat=self.lat, height=self.alt)

        timekey = head[self.obstime]
        # log.warning(timekey)
        if 'MJD' in self.obstime:
            obstime = Time(timekey, format='mjd')
        elif self.obstime == 'JD':
            obstime = Time(timekey, format='jd')
        # elif isinstance(self.obstime, list):
        #     obstime = Time(Time(timekey[0]).unix+timekey[1])
        elif 'DATE' in self.obstime:
            obstime = Time(timekey)
        else:
            obstime = Time(timekey)

        obstime.location = location

        # skycoord
        if self.ra in head and self.dec in head:
            coord = SkyCoord(
                ra=head[self.ra],
                dec=head[self.dec],
                location=location,
                obstime=obstime,
                equinox=obstime.jyear_str[:-2],
                # frame='icrs',
                frame='fk5',
                unit=self.unit)

        elif self.obj in head:
            coord = SkyCoord.from_name(
                head[self.obj],
                #location=location,
                #obstime=obstime,
                # frame='icrs',
                #equinox=obstime.jyear_str[:-2]
                frame='fk5')

        else:
            log.error("No (RA DEC) and no OBJECT in header")
            return

        coord = coord.transform_to(FK5(equinox='J2000'))

        # Meteo
        if self.temperature and self.temperature in head:
            coord.temperature = head[self.temperature] * u.deg_C
        if self.pressure and self.pressure in head:
            coord.pressure = head[self.pressure] * u.hPa
        if self.humidity and self.humidity in head:
            coord.relative_humidity = head[self.humidity] / 100

        # coord.obstime=obstime

        self.coord = coord
        return coord