def generate_baseline_coordinates(layout, settings):
    """Generate baseline coordinates"""
    x, y = layout['x'], layout['y']
    wavelength_m = 299792458.0 / settings['freq_hz']
    mjd_start = settings['mjd_mid'] - (settings['obs_length_s'] / 2.0) / 86400.0
    x, y, z = np.array(x), np.array(y), np.zeros_like(x)
    x_ecef, y_ecef, z_ecef = convert_enu_to_ecef(x, y, z, settings['lon'],
                                                 settings['lat'])
    x_c, y_c, z_c = convert_enu_to_ecef([0.0], [0.0], [0.0], settings['lon'],
                                        settings['lat'])
    x_ecef -= x_c
    y_ecef -= y_c
    z_ecef -= z_c
    num_stations = x_ecef.shape[0]
    num_baselines = num_stations * (num_stations - 1) / 2
    num_coords = settings['num_times'] * num_baselines
    uu = np.zeros(num_coords, dtype='f4')
    vv, ww = np.zeros_like(uu), np.zeros_like(uu)
    u = np.zeros(num_stations, dtype='f4')
    v, w = np.zeros_like(u), np.zeros_like(u)
    for i in range(settings['num_times']):
        mjd = mjd_start + (i * settings['interval_s'] +
                           settings['interval_s'] / 2.0) / 86400.0
        uu_, vv_, ww_ = evaluate_baseline_uvw(x_ecef, y_ecef, z_ecef,
                                              settings['ra'], settings['dec'],
                                              mjd)
        u, v, w = evaluate_station_uvw(x_ecef, y_ecef, z_ecef, settings['ra'],
                                       settings['dec'], mjd)
        uu[i * num_baselines: (i + 1) * num_baselines] = uu_ / wavelength_m
        vv[i * num_baselines: (i + 1) * num_baselines] = vv_ / wavelength_m
        ww[i * num_baselines: (i + 1) * num_baselines] = ww_ / wavelength_m
    return uu, vv, ww, u, w, v
Example #2
0
def load_telescope(r_cut, station_d, lon, lat, plot_filename=None):
    # Load telescope model
    coords = np.loadtxt(join('v5.tm', 'layout.txt'))
    x, y, z = coords[:, 0], coords[:, 1], coords[:, 2]
    r = (x**2 + y**2)**0.5

    x = x[np.where(r < r_cut)]
    y = y[np.where(r < r_cut)]
    z = z[np.where(r < r_cut)]
    num_stations = x.shape[0]
    if plot_filename:
        plot_telescope(x, y, r_cut, station_d=station_d, filename=plot_filename)
    x, y, z = convert_enu_to_ecef(x, y, z, lon, lat)
    return x, y, z
Example #3
0
 def gen_uvw_coords(self):
     """Generate uvw coordinates"""
     x, y, z = self.get_coords_enu()
     x, y, z = convert_enu_to_ecef(x, y, z, radians(self.lon_deg),
                                   radians(self.lat_deg), self.alt_m)
     num_stations = x.shape[0]
     num_baselines = num_stations * (num_stations - 1) // 2
     n = num_baselines * self.num_times
     self.uu_m, self.vv_m, self.ww_m = np.zeros(n), np.zeros(n), np.zeros(n)
     ha_off = ((self.obs_length_h / 2) / 24) * (2 * pi)
     for i, ha in enumerate(np.linspace(-ha_off, ha_off, self.num_times)):
         uu_, vv_, ww_ = evaluate_baseline_uvw_ha_dec(
             x, y, z, ha - radians(self.lon_deg), radians(self.dec_deg))
         self.uu_m[i * num_baselines: (i + 1) * num_baselines] = uu_
         self.vv_m[i * num_baselines: (i + 1) * num_baselines] = vv_
         self.ww_m[i * num_baselines: (i + 1) * num_baselines] = ww_
     self.r_uv_m = (self.uu_m**2 + self.vv_m**2)**0.5
Example #4
0
 def gen_uvw_coords(self):
     """Generate uvw coordinates"""
     x, y, z = self.get_coords_enu()
     x, y, z = convert_enu_to_ecef(x, y, z, radians(self.lon_deg),
                                   radians(self.lat_deg), self.alt_m)
     num_stations = x.shape[0]
     num_baselines = num_stations * (num_stations - 1) // 2
     n = num_baselines * self.num_times
     self.uu_m, self.vv_m, self.ww_m = np.zeros(n), np.zeros(n), np.zeros(n)
     ha_off = ((self.obs_length_h / 2) / 24) * (2 * pi)
     for i, ha in enumerate(np.linspace(-ha_off, ha_off, self.num_times)):
         uu_, vv_, ww_ = evaluate_baseline_uvw_ha_dec(
             x, y, z, ha - radians(self.lon_deg), radians(self.dec_deg))
         self.uu_m[i * num_baselines:(i + 1) * num_baselines] = uu_
         self.vv_m[i * num_baselines:(i + 1) * num_baselines] = vv_
         self.ww_m[i * num_baselines:(i + 1) * num_baselines] = ww_
     self.r_uv_m = (self.uu_m**2 + self.vv_m**2)**0.5
Example #5
0
def load_telescope(r_cut, station_d, lon, lat, plot_filename=None):
    # Load telescope model
    coords = np.loadtxt(join('v5.tm', 'layout.txt'))
    x, y, z = coords[:, 0], coords[:, 1], coords[:, 2]
    r = (x**2 + y**2)**0.5

    x = x[np.where(r < r_cut)]
    y = y[np.where(r < r_cut)]
    z = z[np.where(r < r_cut)]
    num_stations = x.shape[0]
    if plot_filename:
        plot_telescope(x,
                       y,
                       r_cut,
                       station_d=station_d,
                       filename=plot_filename)
    x, y, z = convert_enu_to_ecef(x, y, z, lon, lat)
    return x, y, z
def generate_uv_coordinates(
    x, y, z, lon, lat, alt, ra, dec, num_times, num_baselines, mjd_start, dt_s, freq_hz, uv_cut_radius_wavelengths
):
    x, y, z = convert_enu_to_ecef(x, y, z, lon, lat, alt)
    uu, vv, ww = generate_baseline_uvw(x, y, z, ra, dec, num_times, num_baselines, mjd_start, dt_s)
    wave_length = 299792458.0 / freq_hz
    uu /= wave_length
    vv /= wave_length
    ww /= wave_length
    # uv_r_cut = uv_cut_radius_wavelengths
    # uv_r = (uu ** 2 + vv ** 2) ** 0.5
    # uv_sort_idx = numpy.argsort(uv_r)
    # uv_r = uv_r[uv_sort_idx]
    # uu = uu[uv_sort_idx]
    # vv = vv[uv_sort_idx]
    # ww = ww[uv_sort_idx]
    # i_uv_max = numpy.argmax(uv_r >= uv_r_cut)
    # uu = uu[:i_uv_max]
    # vv = vv[:i_uv_max]
    # ww = ww[:i_uv_max]
    uu = numpy.hstack((uu, -uu))
    vv = numpy.hstack((vv, -vv))
    ww = numpy.hstack((ww, -ww))
    return uu, vv, ww
def generate_baseline_coords(layout, settings):
    x, y = layout['x'], layout['y']
    z = numpy.zeros_like(x)
    wavelength_m = 299792458.0 / settings['freq_hz']
    mjd_start = settings['mjd_mid'] - (settings['obs_length_s'] / 2.0) / 86400.0
    x, y, z = numpy.array(x), numpy.array(y), numpy.zeros_like(x)
    x_ecef, y_ecef, z_ecef = pyuvwsim.convert_enu_to_ecef(x, y, z,
                                                          settings['lon'],
                                                          settings['lat'])
    num_stations = x_ecef.shape[0]
    num_baselines = num_stations * (num_stations - 1) / 2
    num_coords = settings['num_times'] * num_baselines
    uu = numpy.zeros(num_coords, dtype='f4')
    vv, ww = numpy.zeros_like(uu), numpy.zeros_like(uu)
    for i in range(settings['num_times']):
        mjd = mjd_start + (i * settings['interval_s'] +
                           settings['interval_s'] / 2.0) / 86400.0
        uu_, vv_, ww_ = pyuvwsim.evaluate_baseline_uvw(x_ecef, y_ecef, z_ecef,
                                                       settings['ra'],
                                                       settings['dec'], mjd)
        uu[i * num_baselines: (i + 1) * num_baselines] = uu_ / wavelength_m
        vv[i * num_baselines: (i + 1) * num_baselines] = vv_ / wavelength_m
        ww[i * num_baselines: (i + 1) * num_baselines] = ww_ / wavelength_m
    return uu, vv, ww
def main():
    out_dir = 'TEMP_0h'
    layouts = OrderedDict()
    layouts['v5'] = {'filename': join('v5.tm', 'layout.txt')}
    layouts['v5c'] = {'filename': join('v5c.tm', 'layout_enu_stations.txt')}
    station_radius_m = 40.0 / 2.0
    freq_hz = 100.0e6
    wave_length = 299792458.0 / freq_hz
    lon = radians(116.63128900)
    lat = radians(-26.69702400)
    ra = radians(68.698903779331502)
    dec = radians(-26.568851215532160)
    mjd_mid = 57443.4375000000
    snapshot = True
    if snapshot:
        mjd_start = mjd_mid
        obs_length = 0.0
        dt_s = 0.0
        num_times = 1
    else:
        obs_length = 4.0 * 3600.0  # seconds
        num_times = int(obs_length / (1 * 60.0))
        dt_s = obs_length / float(num_times)
        mjd_start = mjd_mid - (obs_length / 2.0) / (3600.0 * 24.0)

    # Create output directory and copy script =================================
    if os.path.exists(out_dir):
        shutil.rmtree(out_dir)
    os.makedirs(out_dir)
    shutil.copy(__file__, join(out_dir, 'copy_' + os.path.basename(__file__)))

    # Load station coordinates & generate baseline coordinates ================
    for name in layouts:
        coords = numpy.loadtxt(layouts[name]['filename'])
        layouts[name]['station_coords'] = coords
        x = coords[:, 0]
        y = coords[:, 1]
        z = coords[:, 2]
        # TODO(BM) remove stations > xx km
        r = (x**2 + y**2)**0.5
        sort_idx = numpy.argsort(r)
        r = r[sort_idx]
        x = x[sort_idx]
        y = y[sort_idx]
        z = z[sort_idx]
        x = x[r <= 5000.0]
        y = y[r <= 5000.0]
        z = z[r <= 5000.0]
        print(name, x.shape)
        x, y, z = pyuvwsim.convert_enu_to_ecef(x, y, z, lon, lat)
        uu, vv, ww = generate_baseline_uvw(x, y, z, ra, dec, num_times,
                                           mjd_start, dt_s)
        layouts[name]['uu'] = uu
        layouts[name]['vv'] = vv
        layouts[name]['ww'] = ww

    print('- UV coordinate generation complete.')
    print('- obs_length = %.2f s (%.2f h)' % (obs_length, obs_length / 3600.0))
    print('- num_times =', num_times)

    # Plotting ================================================================
    t0 = time.time()
    plot_layouts_2(layouts, station_radius_m, join(out_dir, 'layouts'))
    uv_plot_2(layouts, join(out_dir, 'uv_scatter'))
    plot_psf_2(layouts, freq_hz, 60.0, 4096, join(out_dir, 'psf'))
    plot_psf_2(layouts, freq_hz, 30.0, 4096, join(out_dir, 'psf'))
    plot_psf_2(layouts, freq_hz, 5.0, 4096, join(out_dir, 'psf'))
    plot_psf_2(layouts, freq_hz, 1.0, 4096, join(out_dir, 'psf'))
    # plot_uv_hist(uu_v4d, vv_v4d, uu_v4o1, vv_v4o1, wave_length,
    #              join(out_dir, 'uv_hist'))
    # plot_uv_images(uu_v4d, vv_v4d, uu_v4o1, vv_v4o1, wave_length,
    #                station_radius_m, join(out_dir, 'uv_images'))
    # plot_az_rms_2(uu_v4d, vv_v4d, uu_v4o1, vv_v4o1, wave_length,
    #               join(out_dir, 'uv_az'))
    print('- Plotting took %.2f s' % (time.time() - t0))
def main():
    # Load station positions
    t0 = time.time()
    v4d_file = join('v4d.tm', 'layout_enu_stations.txt')
    v4o1_file = join('v4o1.tm', 'layout_enu_stations.txt')
    v4d = numpy.loadtxt(v4d_file)
    v4o1 = numpy.loadtxt(v4o1_file)
    station_radius_m = 35.0 / 2.0
    num_stations = v4d.shape[0]
    assert(v4o1.shape[0] == v4d.shape[0])
    print('- loading coordinates took %.2f s' % (time.time() - t0))

    freq = 100.0e6
    wave_length = 299792458.0 / freq
    lon = radians(116.63128900)
    lat = radians(-26.69702400)
    alt = 0.0
    ra = radians(68.698903779331502)
    dec = radians(-26.568851215532160)
    mjd_mid = 57443.4375000000

    snapshot = True
    if snapshot:
        mjd_start = mjd_mid
        obs_length = 0.0
        dt_s = 0.0
        num_times = 1
    else:
        obs_length = 4.0 * 3600.0  # seconds
        num_times = int(obs_length / (3 * 60.0))
        dt_s = obs_length / float(num_times)
        mjd_start = mjd_mid - (obs_length / 2.0) / (3600.0 * 24.0)

    print('- obs_length = %.2f s (%.2f h)' % (obs_length, obs_length / 3600.0))
    print('- num_times =', num_times)

    num_baselines = num_stations * (num_stations - 1) / 2
    out_dir = 'uv_%3.1fh' % (obs_length / 3600.0)

    # UV coordinate generation ================================================
    t0 = time.time()
    x, y, z = convert_enu_to_ecef(v4d[:, 0], v4d[:, 1], v4d[:, 2],
                                  lon, lat, alt)
    uu_v4d, vv_v4d, ww_v4d = \
        generate_baseline_uvw(x, y, z, ra, dec, num_times, num_baselines,
                              mjd_start, dt_s)
    x, y, z = convert_enu_to_ecef(v4o1[:, 0], v4o1[:, 1], v4o1[:, 2],
                                  lon, lat, alt)
    uu_v4o1, vv_v4o1, ww_v4o1 = \
        generate_baseline_uvw(x, y, z, ra, dec, num_times, num_baselines,
                              mjd_start, dt_s)
    print('- coordinate generation took %.2f s' % (time.time() - t0))
    print('- num vis = %i' % uu_v4d.shape[0])

    # Plotting ===============================================================
    if os.path.exists(out_dir):
        shutil.rmtree(out_dir)
    # plot_layouts(v4d, v4o1, station_radius_m, join(out_dir, 'layouts'))
    # plot_psf(uu_v4d, vv_v4d, ww_v4d, uu_v4o1, vv_v4o1, ww_v4o1, freq,
    #          join(out_dir, 'psf'))
    # uv_plot(uu_v4d, vv_v4d, uu_v4o1, vv_v4o1, join(out_dir, 'uv_scatter'))
    plot_uv_hist(uu_v4d, vv_v4d, uu_v4o1, vv_v4o1, wave_length,
                 join(out_dir, 'uv_hist'))
def main():
    # Load station positions
    t0 = time.time()
    v4d_file = join('v4d.tm', 'layout_enu_stations.txt')
    v4o1_file = join('v4o1.tm', 'layout_enu_stations.txt')
    v4d = numpy.loadtxt(v4d_file)
    v4o1 = numpy.loadtxt(v4o1_file)
    station_radius_m = 35.0 / 2.0
    num_stations = v4d.shape[0]
    assert(v4o1.shape[0] == v4d.shape[0])
    print('- loading coordinates took %.2f s' % (time.time() - t0))

    freq = 120.0e6
    wave_length = 299792458.0 / freq
    lon = radians(116.63128900)
    lat = radians(-26.69702400)
    alt = 0.0
    ra = radians(68.698903779331502)
    dec = radians(-26.568851215532160)
    mjd_mid = 57443.4375000000

    snapshot = True
    if snapshot:
        mjd_start = mjd_mid
        obs_length = 0.0
        dt_s = 0.0
        num_times = 1
    else:
        obs_length = 4.0 * 3600.0  # seconds
        num_times = int(obs_length / (3 * 60.0))
        dt_s = obs_length / float(num_times)
        mjd_start = mjd_mid - (obs_length / 2.0) / (3600.0 * 24.0)

    print('- obs_length = %.2f s (%.2f h)' % (obs_length, obs_length / 3600.0))
    print('- num_times =', num_times)

    num_baselines = num_stations * (num_stations - 1) / 2
    out_dir = 'uv_%3.1fh' % (obs_length / 3600.0)

    if os.path.exists(out_dir):
        shutil.rmtree(out_dir)
    os.makedirs(out_dir)

    # UV coordinate generation ===============================================
    t0 = time.time()
    x, y, z = convert_enu_to_ecef(v4d[:, 0], v4d[:, 1], v4d[:, 2],
                                  lon, lat, alt)
    uu_v4d, vv_v4d, ww_v4d = \
        generate_baseline_uvw(x, y, z, ra, dec, num_times, num_baselines,
                              mjd_start, dt_s)
    print('- Coordinate generation took %.2f s' % (time.time() - t0))
    print('- Num vis = %i' % uu_v4d.shape[0])

    fov = 180.0  # deg
    im_size = 8192
    n = im_size
    c = n / 2
    z = 128

    cell_size_lm_arcsec = fov_to_cell_size(fov, im_size)
    cell_size_uv = grid_cell_size(cell_size_lm_arcsec, im_size)
    uv_max = ((im_size / 2) - 5) * cell_size_uv

    uv_r_cut = uv_max * wave_length
    uv_r = (uu_v4d**2 + vv_v4d**2)**0.5
    uv_sort_idx = numpy.argsort(uv_r)
    uv_r = uv_r[uv_sort_idx]
    uu_v4d = uu_v4d[uv_sort_idx]
    vv_v4d = vv_v4d[uv_sort_idx]
    ww_v4d = ww_v4d[uv_sort_idx]

    i_uv_max = numpy.argmax(uv_r >= uv_r_cut)
    uu_v4d = uu_v4d[:i_uv_max]
    vv_v4d = vv_v4d[:i_uv_max]
    ww_v4d = ww_v4d[:i_uv_max]
    print('- No. uv points after radial cut = %i' % uu_v4d.shape[0])

    fig = pyplot.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, aspect='equal')
    ax.plot(uu_v4d, vv_v4d, '.', ms=2.0, alpha=0.2)
    ax.set_xlim(-uv_max * wave_length, uv_max * wave_length)
    ax.set_ylim(-uv_max * wave_length, uv_max * wave_length)
    fig.savefig(join(out_dir, 'uv_scatter.png'))
    pyplot.close(fig)

    psf_v4d = make_psf(uu_v4d, vv_v4d, ww_v4d, freq, fov, im_size)
    lm_max = psf_v4d['lm_max']
    lm_inc = psf_v4d['lm_inc']
    off = lm_inc / 2.0
    extent = [-lm_max - off, lm_max - off, -lm_max - off, lm_max - off]
    plot_image_log(psf_v4d['image'], extent, fov, join(out_dir, 'psf'))

    print('- Loading beam image.')
    prefix = 'b_TIME_AVG_CHAN_AVG_CROSS_POWER'
    beam_amp = pyfits.getdata(join('beams_180.0_120.0MHz',
                                   prefix + '_AMP_I_I.fits'))
    beam_phase = pyfits.getdata(join('beams_180.0_120.0MHz',
                                     prefix + '_PHASE_I_I.fits'))
    beam_amp = numpy.squeeze(beam_amp)
    beam_phase = numpy.squeeze(beam_phase)
    beam_amp[numpy.isnan(beam_amp)] = 0.0
    beam_phase[numpy.isnan(beam_phase)] = 0.0
    beam = beam_amp * numpy.exp(1.0j * beam_phase)
    # beam /= numpy.sum(beam)
    print('- beam sum = %f %f' % (numpy.sum(beam.real), numpy.sum(beam_amp)))

    beam_amp = beam_amp / numpy.nanmax(beam_amp)
    plot_image_lin(beam_amp, extent, fov, join(out_dir, 'beam_amp'))
    plot_image_lin(beam_phase, extent, fov, join(out_dir, 'beam_phase'))
    plot_image_lin(beam_amp[c - z:c + z, c - z:c + z],
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5],
                   0, join(out_dir, 'beam_amp_zoom'))
    plot_image_lin(numpy.real(beam[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'beam_re_zoom'))
    plot_image_lin(numpy.imag(beam[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'beam_im_zoom'))

    # Beam uv plane response
    uv_beam = numpy.fft.fftshift(numpy.fft.ifft2(numpy.fft.fftshift(beam)))
    plot_image_lin(numpy.real(uv_beam), extent, 0, join(out_dir, 'uv_beam_re'))
    plot_image_lin(numpy.imag(uv_beam), extent, 0, join(out_dir, 'uv_beam_im'))
    plot_image_lin(numpy.real(uv_beam[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'uv_beam_re_zoom'))
    plot_image_lin(numpy.imag(uv_beam[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'uv_beam_im_zoom'))

    print('- Beam x PSF.')
    beam_psf = beam * psf_v4d['image']
    plot_image_log(numpy.real(beam_psf), extent, fov,
                   join(out_dir, 'psf_beam_re'))
    plot_image_log(numpy.imag(beam_psf), extent, fov,
                   join(out_dir, 'psf_beam_im'))

    print('- UV image (beam convolved).')
    uv_psf_beam = numpy.fft.fftshift(numpy.fft.ifft2(numpy.fft.fftshift(beam_psf)))
    plot_image_lin(numpy.real(uv_psf_beam), [-1, 1, -1, 1], 0,
                   join(out_dir, 'uv_psf_beam_re'))
    plot_image_lin(numpy.imag(uv_psf_beam), [-1, 1, -1, 1], 0,
                   join(out_dir, 'uv_psf_beam_im'))

    print('- UV image (PSF only).')
    uv_psf = numpy.fft.fftshift(
        numpy.fft.ifft2(numpy.fft.fftshift(psf_v4d['image'])))
    print('- uv_psf grid sum = %f %f' % (numpy.sum(uv_psf.real),
                                         numpy.sum(uv_psf.real)))
    print('- uv_psf_beam grid sum = %f %f' % (numpy.sum(uv_psf_beam.real),
                                              numpy.sum(uv_psf_beam.real)))
    uv_psf /= numpy.sum(uv_psf)
    uv_psf_beam /= numpy.sum(uv_psf_beam)
    uv_psf *= uu_v4d.shape[0]
    uv_psf_beam *= uu_v4d.shape[0]

    plot_image_lin(numpy.real(uv_psf), [-1, 1, -1, 1], 0,
                   join(out_dir, 'uv_psf_re'))
    plot_image_lin(numpy.imag(uv_psf), [-1, 1, -1, 1], 0,
                   join(out_dir, 'uv_psf_im'))
    plot_image_lin(numpy.real(uv_psf[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'uv_psf_re_zoom'))
    plot_image_lin(numpy.imag(uv_psf[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'uv_psf_im_zoom'))
    plot_image_lin(numpy.real(uv_psf_beam[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'uv_psf_beam_re_zoom'))
    plot_image_lin(numpy.imag(uv_psf_beam[c - z: c + z, c - z: c + z]),
                   [-z - 0.5, z - 0.5, -z + 0.5, z + 0.5], 0,
                   join(out_dir, 'uv_psf_beam_im_zoom'))

    # # Grid uv data to compare with FT(psf) wrt normalisation
    # uv_grid = numpy.zeros((im_size, im_size))
    # for i in range(uu_v4d.shape[0]):
    #     gx = round(uu_v4d[i] / cell_size_uv) + (im_size / 2)
    #     gy = round(vv_v4d[i] / cell_size_uv) + (im_size / 2)
    #     uv_grid[gy, gx] += 1

    # print('- uv_grid sum = %f' % numpy.sum(uv_grid))
    print('- uv_psf sum = %f' % numpy.sum(uv_psf.real))
    plot_uv_image(uu_v4d, vv_v4d, cell_size_uv, 250 * cell_size_uv,
                  station_radius_m, join(out_dir, 'uv_image'))

    print('- Producing Azimuthal averaged plots')
    # Azimuthal average and plot vs radius
    _, _, r = image_coords(im_size, lm_inc)
    x = r.flatten()
    sort_idx = numpy.argsort(x)
    x = x[sort_idx]
    y1 = numpy.real(uv_psf).flatten()
    y1 = y1[sort_idx]
    y2 = numpy.real(uv_psf_beam).flatten()
    y2 = y2[sort_idx]

    fig = pyplot.figure(figsize=(8, 8))
    ax = fig.add_subplot(111)
    ax.plot(x, y1, 'b.', ms=3.0, alpha=0.1, label='uv')
    ax.plot(x, y2, 'r.', ms=3.0, alpha=0.1, label='uv convolved with PB')
    ax.legend()
    ax.set_xlim(0, 0.1)
    fig.savefig(join(out_dir, 'az_uv_r.png'))
    pyplot.close(fig)
# ---------------------------------------------------------
filename   = '@PROJECT_BINARY_DIR@/test/VLA_A_hor_xyz.txt'
lon        = 0.0  * (np.pi/180.)
lat        = 90.0 * (np.pi/180.)
alt        = 0.0
ra0        = 0.0  * (np.pi/180.)
dec0       = 90.0 * (np.pi/180.)
ntimes     = 10
obs_length = 0.2 # days
# ---------------------------------------------------------

# Generate coordinates.
mjd_start  = uvw.datetime_to_mjd(2014, 7, 28, 14, 26, 1.321);
(x,y,z) = uvw.load_station_coords(filename)
(x,y,z) = uvw.convert_enu_to_ecef(x, y, z, lon, lat, alt)
t0 = time.time()
for i in range(0, ntimes):
    mjd = mjd_start
    (uu_m,vv_m,ww_m) = uvw.evaluate_baseline_uvw(x,y,z, ra0, dec0, mjd)
print '- Time taken to evaluate uww coordinates = %.3f ms' % ((time.time()-t0)*1.e3)

# Scatter plot of baseline coordinates.
plt.ioff()
plt_filename = 'test.png'
fig = plt.figure(figsize=(6,6))
matplotlib.rcParams.update({'font.size': 10})
scatter_size = 3
fig.add_subplot(1,1,1, aspect='equal')
plt.scatter(uu_m, vv_m, c='b', lw = 0, s=scatter_size);
plt.scatter(-uu_m, -vv_m, c='r', lw = 0, s=scatter_size);
Example #12
0
def simulate(config):
    telescope = config['sim']['telescope']
    obs = config['sim']['observation']
    freq_hz = obs['freq_hz']
    lon = math.radians(telescope['lon_deg'])
    lat = math.radians(telescope['lat_deg'])
    alt = telescope['alt_m']
    vis_ra = math.radians(obs['ra_deg'])
    vis_dec = math.radians(obs['dec_deg'])
    mjd_start = obs['start_time_mjd']
    num_dumps = obs['num_times']
    dump_time_s = obs['dump_time_s']
    over_sample = obs['over_sample']
    dt_s = dump_time_s / over_sample
    num_times = num_dumps * over_sample
    telescope_model = telescope['path']
    x, y, z = load_station_coords(join(telescope_model, 'layout.txt'))
    x, y, z = convert_enu_to_ecef(x, y, z, lon, lat, alt)
    num_antennas = x.shape[0]
    num_baselines = num_antennas * (num_antennas - 1) / 2
    num_vis = num_times * num_baselines
    sky_model = config['sim']['sky_file']
    sky = numpy.loadtxt(sky_model, delimiter=',')
    sky = sky.reshape((-1, 3))
    l, m, n = convert_ra_dec_to_relative_directions(sky[:, 0], sky[:, 1],
                                                    vis_ra, vis_dec)
    amp = numpy.zeros(num_vis, dtype='c16')
    weight = numpy.ones(num_vis, dtype='f8')

    print('- Simulating data...')
    print('  - No. antennas  :', num_antennas)
    print('  - No. baselines :', num_baselines)
    print('  - Obs. length   : %.1f s' % (num_dumps * dump_time_s))
    print('  - No. times     : %i (no. dumps: %i, over-sample: %i)' %
          (num_times, num_dumps, over_sample))
    print('  - No. vis       :', num_vis)
    print('  - No. sources   :', sky.shape[0])

    num_bytes = num_vis * 7 * 8
    mem = virtual_memory()
    print('  - Mem. required : %.1f / %.1f MB' %
          (num_bytes / 1024.0**2, mem.total / 1024.0**2))
    if num_bytes >= mem.total:
        raise RuntimeError('Not enough system memory for requested '
                           'simulation.')

    # Generate UVW coordinates.
    t0 = time.time()
    uu, vv, ww = generate_baseline_uvw(x, y, z, vis_ra, vis_dec, num_times,
                                       num_baselines, mjd_start, dt_s)
    t_coords = time.time() - t0

    # Generate amplitudes.
    t1 = time.time()
    wavelength = 299792458.0 / freq_hz
    for i in range(len(l)):
        phase = (2.0 * math.pi / wavelength) * \
                (uu * l[i] + vv * m[i] + ww * (n[i] - 1.0))
        amp += numpy.exp(1.0j * phase)
    t_amp = time.time() - t1
    print('  - Total simulation time = %.2f s (coords: %.2f s, amp: %.2f s)'
          % (time.time() - t0, t_coords, t_amp))

    return {'model': amp, 'uu': uu, 'vv': vv, 'ww': ww, 'weight': weight}
Example #13
0
def simulate_2(config):
    """Simulate with and without corruptions followed by averaging.
    Simulation to be performed in blocks due to memory constraints.
    """
    telescope = config['sim']['telescope']
    obs = config['sim']['observation']
    corrupt = config['corrupt']
    freq_hz = obs['freq_hz']
    wavelength = 299792458.0 / freq_hz
    lon = math.radians(telescope['lon_deg'])
    lat = math.radians(telescope['lat_deg'])
    alt = telescope['alt_m']
    ra = math.radians(obs['ra_deg'])
    dec = math.radians(obs['dec_deg'])
    mjd_start = obs['start_time_mjd']
    num_dumps = obs['num_times']
    dump_time_s = obs['dump_time_s']
    over_sample = obs['over_sample']
    dt_s = dump_time_s / over_sample
    num_times = num_dumps * over_sample
    telescope_model = telescope['path']
    x, y, z = load_station_coords(join(telescope_model, 'layout.txt'))
    x, y, z = convert_enu_to_ecef(x, y, z, lon, lat, alt)
    num_antennas = x.shape[0]
    num_baselines = num_antennas * (num_antennas - 1) / 2
    num_vis = num_dumps * num_baselines
    sky_model = config['sim']['sky_file']
    sky = numpy.loadtxt(sky_model, delimiter=',')
    sky = sky.reshape((-1, 3))
    num_sources = sky.shape[0]
    source_ra = numpy.radians(sky[:, 0])
    source_dec = numpy.radians(sky[:, 1])

    l, m, n = convert_ra_dec_to_relative_directions(
        source_ra, source_dec, ra, dec)
    tau = corrupt['tau_s']
    hurst_amp = corrupt['amplitude']['hurst']
    adev_amp = corrupt['amplitude']['allan_dev']
    std_t_mid_amp = corrupt['amplitude']['std_t_mid']
    hurst_phase = corrupt['phase']['hurst']
    adev_phase = corrupt['phase']['allan_dev']
    std_t_mid_phase = corrupt['phase']['std_t_mid']
    smoothing_length = corrupt['smoothing_length']

    print('- Simulating data...')
    print('  - No. antennas  :', num_antennas)
    print('  - No. baselines :', num_baselines)
    print('  - Obs. length   : %.1f s' % (num_dumps * dump_time_s))
    print('  - No. times     : %i (no. dumps: %i, over-sample: %i)' %
          (num_times, num_dumps, over_sample))
    print('  - No. vis       :', num_vis)
    print('  - No. sources   :', num_sources)
    print('  - Corruptions:')
    print('    -  Hurst amp %.1f, phase %.1f' % (hurst_amp, hurst_phase))
    print('    -  A. dev amp %.1e, phase %.1e' % (adev_amp, adev_phase))

    num_bytes = num_vis * 8 * 8 + (num_antennas * num_times) * 16
    mem = virtual_memory()
    print('  - Mem. required : %.1f / %.1f MB' %
          (num_bytes / 1024.0**2, mem.total / 1024.0**2))
    if num_bytes >= mem.total:
        raise RuntimeError('Not enough system memory for requested '
                           'simulation.')

    # Generate corruptions
    gains = numpy.empty((num_antennas, num_times), dtype='c16')
    t0 = time.time()
    for i in range(num_antennas):
        gains[i, :] = eval_complex_gains(num_times, dt_s, hurst_amp, adev_amp,
                                         std_t_mid_amp, hurst_phase, adev_phase,
                                         std_t_mid_phase, smoothing_length,
                                         tau)
    conj_gains = numpy.conj(gains)
    print('  - Gains generated in %.1f s' % (time.time() - t0))

    # TODO-BM plot the gains ...

    # Simulation
    phase0 = 2.0 * math.pi / wavelength
    model = numpy.empty(num_vis, dtype='c16')
    data = numpy.empty(num_vis, dtype='c16')
    weight = numpy.ones(num_vis, dtype='f8')
    block_model = numpy.empty((over_sample, num_baselines), dtype='c16')
    block_data = numpy.empty((over_sample, num_baselines), dtype='c16')
    t1 = time.time()
    # Loop over correlator dumps
    for i in range(num_dumps):
        block_model.fill(0.0 + 0.0j)
        block_data.fill(0.0 + 0.0j)
        # Loop over times in a dump.
        for t in range(over_sample):
            delta_t = (i * dump_time_s) + (t * dt_s) + (dt_s / 2.0)
            mjd = mjd_start + (delta_t / 86400.0)
            uu_, vv_, ww_ = evaluate_baseline_uvw(x, y, z, ra, dec, mjd)
            for s in range(num_sources):
                phase = phase0 * (uu_ * l[s] + vv_ * m[s] + ww_ * (n[s] - 1.0))
                block_model[t, :] += numpy.exp(1.0j * phase)
            ig = i * over_sample + t
            block_data[t, :] = apply_gains(block_model[t, :], gains[:, ig])
            # data_ = apply_gains(block_model[t, :], gains[:, ig])
            # idx = 0
            # for p in range(num_antennas):
            #     for q in range(p + 1, num_antennas):
            #         gp = gains[p, ig]
            #         gq = conj_gains[q, ig]
            #         block_data[t, idx] = gp * block_model[t, idx] * gq
            #         idx += 1
            # if i < 3:
            #     print('t[%02i]' % t)
            #     print(' C:', data_[0])
            #     print(' P:', block_data[t, 0])
            #     print(' D:', numpy.max(numpy.abs(data_[:] - block_data[t, :])))
            # assert numpy.max(numpy.abs(data_[:] - block_data[t, :])) == 0.0

        # Average the block to get visibility data amplitudes for the dump.
        b0 = i * num_baselines
        b1 = b0 + num_baselines
        model[b0:b1] = numpy.mean(block_model, axis=0)
        data[b0:b1] = numpy.mean(block_data, axis=0)

    uu, vv, ww = generate_baseline_uvw(x, y, z, ra, dec, num_dumps,
                                       num_baselines, mjd_start, dump_time_s)

    print('  - Visibilities simulated in %.2f s' % (time.time() - t1))

    return {'model': model, 'data': data, 'uu': uu, 'vv': vv, 'ww': ww,
            'weight': weight, 'num_baselines': num_baselines,
            'num_times': num_dumps, 'num_antennas': num_antennas}
def main():
    """
    1. Generate a large-ish core of stations using random generator.
         a. overlap some stations in the core to have a very dense station
            region
    2. After core area start using arms but generate some randomness in the arms
       by placing antennas randomly near the outer stations keeping them along
       the spiral
    3. Remove radius redundancy in the spiral arms
    """

    # =========================================================================

    # ====== Core
    seed = 1
    num_tries = 10
    num_core_stations = (1 + 5 + 11 + 17) * 6 + (3 * 6)
    core_radius_m = 480.0
    inner_core_radius_m = 280.0
    station_radius_m = 35.0 / 2.0
    sll = -28
    # ====== Core arms
    num_arms = 3
    core_arm_count = 4
    stations_per_arm_cluster = 6
    arm_cluster_radius = 75.0
    # a = 300.0
    # b = 0.513
    a = 300.0
    b = 0.513
    delta_theta = math.radians(37.0)
    arm_offsets = numpy.radians([35.0, 155.0, 270.0])
    num_core_arm_stations = num_arms * core_arm_count * stations_per_arm_cluster
    # ====== Outer arms
    outer_arm_count = 12
    stations_per_outer_cluster = 6
    num_clusters_outer = outer_arm_count * num_arms
    v4a_ss_enu_file = 'v7ska1lowN1v2rev3R.enu.94x4.fixed.txt'
    outer_arm_cluster_radius = 80.0

    # ===== uvw coordinate generation.
    lon = radians(116.63128900)
    lat = radians(-26.69702400)
    alt = 0.0
    ra = radians(68.698903779331502)
    dec = radians(-26.568851215532160)
    mjd_mid = 57443.4375000000

    obs_length = 0.0
    mjd_start = mjd_mid
    dt_s = 0.0
    num_times = 1

    obs_length = 2.0 * 3600.0  # seconds
    num_times = int(obs_length / (3.0 * 60.0))
    dt_s = obs_length / float(num_times)
    mjd_start = mjd_mid - ((obs_length / 2.0) / 3600.0 * 24.0)
    print('num times = %i' % num_times)

    out_dir = 'v5c-2h'
    # =========================================================================
    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)

    # Generate core stations
    x_core, y_core, weights, r_weights = \
        generate_random_core(num_core_stations, core_radius_m,
                             inner_core_radius_m, sll, station_radius_m,
                             num_tries, seed)

    # Core arms
    x_arm, y_arm, cx_arm, cy_arm = \
        generate_core_arms(num_arms, core_arm_count, stations_per_arm_cluster,
                           arm_cluster_radius, station_radius_m,
                           a, b, delta_theta, arm_offsets, num_tries)

    # Outer stations.
    x_arm_outer, y_arm_outer, cx_outer, cy_outer = \
        generate_outer_arms(v4a_ss_enu_file, num_clusters_outer,
                            stations_per_outer_cluster,
                            outer_arm_cluster_radius, station_radius_m,
                            num_tries)

    # Plotting
    plot_layout(x_core, y_core, x_arm, y_arm, x_arm_outer, y_arm_outer,
                cx_arm, cy_arm, cx_outer, cy_outer, station_radius_m,
                inner_core_radius_m, core_radius_m, arm_cluster_radius,
                outer_arm_cluster_radius, out_dir)
    plot_core_thinning_profile(r_weights, weights, core_radius_m,
                               inner_core_radius_m, out_dir)

    if uvwsim_found:
        x = numpy.hstack((x_core, x_arm, x_arm_outer))
        y = numpy.hstack((y_core, y_arm, y_arm_outer))
        print('total stations = %i' % x.shape[0])
        num_stations = x.shape[0]
        z = numpy.zeros_like(x)

        num_baselines = num_stations * (num_stations - 1) / 2
        x, y, z = convert_enu_to_ecef(x, y, z, lon, lat, alt)
        uu, vv, ww = generate_baseline_uvw(x, y, z, ra, dec, num_times,
                                           num_baselines, mjd_start,
                                           dt_s)
        plot_hist(uu, vv, join(out_dir, 'uv_hist_%.2fh.png'
                               % (obs_length/3600.0)),
                  'v5c %.2f h' % (obs_length/3600.0))
        plot_uv_dist(uu, vv, station_radius_m, join(out_dir, 'uv_%.2fh'
                                                    % (obs_length/3600.0)))
        # TODO-BM see ALMA memo for plots?
        # TODO-BM Plot of azimuthal variation
        # TODO-BM movie of uv coverage histogram improvement with time?
        # TODO-BM convolve uv response with station beam?!

    print('making image...')
    imager = Imager('single')
    fov = 1.0
    im_size = 2048
    freq = 150.0e6
    wavelength = 299792458.0 / freq
    uu /= wavelength
    vv /= wavelength
    ww /= wavelength
    amp = numpy.ones(uu.shape, dtype='c16')
    weight = numpy.ones(uu.shape, dtype='f8')
    image = imager.make_image(uu, vv, ww, amp, weight, fov, im_size)
    fig = pyplot.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, aspect='equal')
    ax.imshow(image, interpolation='nearest')
    pyplot.show()

    cell = math.degrees(imager.fov_to_cellsize(math.radians(fov), im_size))
    save_fits_image_2(join(out_dir, 'psf.fits'), image, cell, math.degrees(ra),
                      math.degrees(dec), freq)
def main():
    print("*" * 80)
    print("*" * 80)
    print("THIS SCRIPT IS DEPRECATED IN FAVOUR OF: generate_uv_coverage_2.py")
    print("*" * 80)
    print("*" * 80)
    return

    # Load station positions
    t0 = time.time()
    v4d_file = join("v4d.tm", "layout_enu_stations.txt")
    v4o1_file = join("v4o1.tm", "layout_enu_stations.txt")
    v4d = numpy.loadtxt(v4d_file)
    v4o1 = numpy.loadtxt(v4o1_file)
    station_radius_m = 35.0 / 2.0
    num_stations = v4d.shape[0]
    assert v4o1.shape[0] == v4d.shape[0]
    print("- loading coordinates took %.2f s" % (time.time() - t0))

    freq = 100.0e6
    wave_length = 299792458.0 / freq
    lon = radians(116.63128900)
    lat = radians(-26.69702400)
    alt = 0.0
    ra = radians(68.698903779331502)
    dec = radians(-26.568851215532160)
    mjd_mid = 57443.4375000000

    snapshot = True
    if snapshot:
        mjd_start = mjd_mid
        obs_length = 0.0
        dt_s = 0.0
        num_times = 1
    else:
        obs_length = 4.0 * 3600.0  # seconds
        num_times = int(obs_length / (3 * 60.0))
        dt_s = obs_length / float(num_times)
        mjd_start = mjd_mid - (obs_length / 2.0) / (3600.0 * 24.0)

    print("- obs_length = %.2f s (%.2f h)" % (obs_length, obs_length / 3600.0))
    print("- num_times =", num_times)

    num_baselines = num_stations * (num_stations - 1) / 2
    out_dir = "uv_%3.1fh" % (obs_length / 3600.0)
    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)

    # plot_layouts(v4d, v4o1, station_radius_m, out_dir)
    #
    t0 = time.time()
    x, y, z = convert_enu_to_ecef(v4d[:, 0], v4d[:, 1], v4d[:, 2], lon, lat, alt)
    uu_v4d, vv_v4d, ww_v4d = generate_baseline_uvw(x, y, z, ra, dec, num_times, num_baselines, mjd_start, dt_s)
    x, y, z = convert_enu_to_ecef(v4o1[:, 0], v4o1[:, 1], v4o1[:, 2], lon, lat, alt)
    uu_v4o1, vv_v4o1, ww_v4o1 = generate_baseline_uvw(x, y, z, ra, dec, num_times, num_baselines, mjd_start, dt_s)
    print("- coordinate generation took %.2f s" % (time.time() - t0))
    print("- num vis = %i" % uu_v4d.shape[0])

    # t0 = time.time()
    # uv_plot(uu_v4d, vv_v4d, uu_v4o1, vv_v4o1, out_dir)
    # print('- uv scatter plot took %.2f s' % (time.time() - t0))

    # t0 = time.time()
    # v4d_uv_dist = (uu_v4d**2 + vv_v4d**2)**0.5
    # v4d_uv_dist.sort()
    # v4o1_uv_dist = (uu_v4o1**2 + vv_v4o1**2)**0.5
    # v4o1_uv_dist.sort()
    # hist_plot_1(v4d_uv_dist, v4o1_uv_dist, wave_length, 300.0, out_dir)
    # hist_plot_1(v4d_uv_dist, v4o1_uv_dist, wave_length * 5.0, 1500.0, out_dir)
    # hist_plot_1(v4d_uv_dist, v4o1_uv_dist, wave_length, 1500.0, out_dir)
    # hist_plot_1(v4d_uv_dist, v4o1_uv_dist, wave_length * 10.0, 3000.0, out_dir)
    # print('- histograms took %.2f s' % (time.time() - t0))
    #
    # hist_plot_2(v4d_uv_dist, v4o1_uv_dist, wave_length, out_dir)
    # hist_plot_3(v4d_uv_dist, v4o1_uv_dist, wave_length, out_dir)
    #
    plot_uv_images(uu_v4d, vv_v4d, uu_v4o1, vv_v4o1, wave_length, station_radius_m, out_dir)

    make_psf_images(uu_v4d, vv_v4d, ww_v4d, uu_v4o1, vv_v4o1, ww_v4o1, ra, dec, freq, out_dir)
def main():
    # ==========================================================================
    # Telescope element radii
    st_radius = 35.0 / 2.0  # Station-radius
    ss_radius = st_radius * 3.0  # Super-station radius

    # Core ring super-stations
    num_rings = 4
    ring_counts = [1, 5, 11, 17]
    ring_radii = [0.0, 100.0, 190.0, 290.0]  # metres
    num_super_stations_rings = numpy.array(ring_counts).sum()
    ring_start_angle = -360.0 * random(num_rings) + 360.0
    ss_ring_petal_angle = -360.0 * random(num_super_stations_rings) + 360.0

    # Core arms
    num_arms = 3
    core_arm_count = 5  # Number of super-stations per core arm
    a = 300.0
    b = 0.513
    delta_theta = 37.0
    arm_offsets = [35.0, 155.0, 275.0]
    num_super_stations_arms = num_arms * core_arm_count
    ss_arm_petal_angle = -360.0 * random(num_super_stations_arms) + 360.0

    # Outer arms (same outer 3 * 12 = 36 stations as v4a)
    outer_arm_count = 12  # Number of super-stations per outer arm
    num_super_stations_outer = num_arms * outer_arm_count
    v4a_ss_enu_file = 'v7ska1lowN1v2rev3R.enu.94x4.fixed.txt'
    ss_petal_angle_outer = -360.0 * random(num_super_stations_outer) + 360.0

    # Stations
    num_stations_per_ss = 6

    out_dir = 'v4d_layout'
    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)
    # ==========================================================================

    # == Super-stations

    # Generate core ring super-stations
    v4d_ss_x_rings = numpy.zeros(num_super_stations_rings)
    v4d_ss_y_rings = numpy.zeros(num_super_stations_rings)
    idx = 0
    for i, hist in enumerate(ring_counts):
        angles = numpy.arange(hist) * (360.0 / hist)
        angles += ring_start_angle[i]
        x = ring_radii[i] * numpy.cos(numpy.radians(angles))
        y = ring_radii[i] * numpy.sin(numpy.radians(angles))
        v4d_ss_x_rings[idx:idx+hist] = x
        v4d_ss_y_rings[idx:idx+hist] = y
        idx += hist

    # Generate core spiral arm super-stations
    v4d_ss_x_arms = numpy.zeros(num_super_stations_arms)
    v4d_ss_y_arms = numpy.zeros(num_super_stations_arms)
    for i in range(num_arms):
        t = numpy.arange(1, core_arm_count + 1) * delta_theta
        t = numpy.radians(t)
        x = a * numpy.exp(b * t) * numpy.cos(t + numpy.radians(arm_offsets[i]))
        y = a * numpy.exp(b * t) * numpy.sin(t + numpy.radians(arm_offsets[i]))
        i0 = i * core_arm_count
        i1 = i0 + core_arm_count
        v4d_ss_x_arms[i0:i1] = x
        v4d_ss_y_arms[i0:i1] = y

    # Load super-station outer spiral arms from the v4a config
    v4a_ss_enu = numpy.loadtxt(v4a_ss_enu_file)
    v4a_ss_enu = v4a_ss_enu[:, 1:]
    v4a_ss_r = (v4a_ss_enu[:, 0]**2 + v4a_ss_enu[:, 1]**2)**0.5
    sort_idx = numpy.argsort(v4a_ss_r)
    v4a_ss_enu = v4a_ss_enu[sort_idx[::-1], :]
    v4d_ss_x_outer = v4a_ss_enu[:num_super_stations_outer, 0]
    v4d_ss_y_outer = v4a_ss_enu[:num_super_stations_outer, 1]

    # == Stations

    # Generate core ring stations
    v4d_st_x_rings = numpy.zeros((num_super_stations_rings,
                                  num_stations_per_ss))
    v4d_st_y_rings = numpy.zeros_like(v4d_st_x_rings)
    for i in range(num_super_stations_rings):
        angles = 360.0 / (num_stations_per_ss - 1) * \
                 numpy.arange(num_stations_per_ss - 1)
        x = (st_radius * 2.0) * numpy.cos(numpy.radians(angles))
        y = (st_radius * 2.0) * numpy.sin(numpy.radians(angles))
        x, y = rotate_coords(x, y, ss_ring_petal_angle[i])
        v4d_st_x_rings[i, 1:] = x
        v4d_st_y_rings[i, 1:] = y
        v4d_st_x_rings[i, :] += v4d_ss_x_rings[i]
        v4d_st_y_rings[i, :] += v4d_ss_y_rings[i]
    v4d_st_x_rings = v4d_st_x_rings.flatten()
    v4d_st_y_rings = v4d_st_y_rings.flatten()

    # Generate core spiral arm stations
    v4d_st_x_arms = numpy.zeros((num_super_stations_arms,
                                 num_stations_per_ss))
    v4d_st_y_arms = numpy.zeros_like(v4d_st_x_arms)
    for i in range(num_super_stations_arms):
        angles = 360.0 / (num_stations_per_ss - 1) * \
                 numpy.arange(num_stations_per_ss - 1)
        x = (st_radius * 2.0) * numpy.cos(numpy.radians(angles))
        y = (st_radius * 2.0) * numpy.sin(numpy.radians(angles))
        x, y = rotate_coords(x, y, ss_arm_petal_angle[i])
        v4d_st_x_arms[i, 1:] = x
        v4d_st_y_arms[i, 1:] = y
        v4d_st_x_arms[i, :] += v4d_ss_x_arms[i]
        v4d_st_y_arms[i, :] += v4d_ss_y_arms[i]
    v4d_st_x_arms = v4d_st_x_arms.flatten()
    v4d_st_y_arms = v4d_st_y_arms.flatten()

    # Generate outer arm stations
    v4d_st_x_outer = numpy.zeros((num_super_stations_outer, num_stations_per_ss))
    v4d_st_y_outer = numpy.zeros((num_super_stations_outer, num_stations_per_ss))
    for i in range(num_super_stations_outer):
        angles = 360.0 / (num_stations_per_ss - 1) * \
                 numpy.arange(num_stations_per_ss - 1)
        x = (st_radius * 2.0) * numpy.cos(numpy.radians(angles))
        y = (st_radius * 2.0) * numpy.sin(numpy.radians(angles))
        x, y = rotate_coords(x, y, ss_petal_angle_outer[i])
        v4d_st_x_outer[i, 1:] = x
        v4d_st_y_outer[i, 1:] = y
        v4d_st_x_outer[i, :] += v4d_ss_x_outer[i]
        v4d_st_y_outer[i, :] += v4d_ss_y_outer[i]
    v4d_st_x_outer = v4d_st_x_outer.flatten()
    v4d_st_y_outer = v4d_st_y_outer.flatten()

    # Concatenate coords.
    v4d_ss_x = numpy.hstack((v4d_ss_x_rings, v4d_ss_x_arms, v4d_ss_x_outer))
    v4d_ss_y = numpy.hstack((v4d_ss_y_rings, v4d_ss_y_arms, v4d_ss_y_outer))
    v4d_st_x = numpy.hstack((v4d_st_x_rings, v4d_st_x_arms, v4d_st_x_outer))
    v4d_st_y = numpy.hstack((v4d_st_y_rings, v4d_st_y_arms, v4d_st_y_outer))

    # === Generate layouts ==============================
    num_stations = v4d_st_x.shape[0]
    v4d_st_enu = numpy.zeros((num_stations, 3))
    v4d_st_enu[:, 0] = v4d_st_x
    v4d_st_enu[:, 1] = v4d_st_y
    numpy.savetxt(join(out_dir, 'v4d_stations_enu.txt'), v4d_st_enu,
                  fmt='% -16.12f % -16.12f % -16.12f')

    num_super_stations = v4d_ss_x.shape[0]
    v4d_ss_enu = numpy.zeros((num_super_stations, 3))
    v4d_ss_enu[:, 0] = v4d_ss_x
    v4d_ss_enu[:, 1] = v4d_ss_y
    numpy.savetxt(join(out_dir, 'v4d_super_stations_enu.txt'), v4d_ss_enu,
                  fmt='% -16.12f % -16.12f % -16.12f')

    # ==== Plotting ===========================================================
    fig = pyplot.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, aspect='equal')
    for i in range(num_super_stations_rings):
        circle = pyplot.Circle((v4d_ss_x_rings[i], v4d_ss_y_rings[i]),
                               ss_radius, color='b', fill=True, alpha=0.5,
                               linewidth=0.0)
        ax.add_artist(circle)

    arm_colors = ['y', 'g', 'r']
    for i in range(num_super_stations_arms):
        q = int(i / core_arm_count)
        circle = pyplot.Circle((v4d_ss_x_arms[i], v4d_ss_y_arms[i]),
                               ss_radius, color=arm_colors[q],
                               fill=True, alpha=0.5, linewidth=0.0)
        ax.add_artist(circle)

    for q in range(num_arms):
        i0 = q * outer_arm_count
        i1 = i0 + outer_arm_count
        for i in range(i0, i1):
            circle = pyplot.Circle((v4d_ss_x_outer[i], v4d_ss_y_outer[i]),
                                   ss_radius, color='c', fill=True, alpha=0.5)
            ax.add_artist(circle)

    # Plot station positions
    for i in range(v4d_st_x.shape[0]):
        circle = pyplot.Circle((v4d_st_x[i], v4d_st_y[i]),
                               st_radius, color='k', linewidth=1.0,
                               fill=True, alpha=0.2)
        ax.add_artist(circle)

    # circle = pyplot.Circle((0.0, 0.0), 1700.0, color='r', linestyle='--',
    #                        linewidth=1.0, fill=False, alpha=0.5)
    # ax.add_artist(circle)

    ax.grid(which='both')
    ax.grid(which='minor', alpha=0.5)
    ax.grid(which='major', alpha=1.0)
    ax.set_ylabel('North [m]')
    ax.set_xlabel('East [m]')
    ax.set_xlim(-1500, 1500)
    ax.set_ylim(-1500, 1500)
    pyplot.savefig(join(out_dir, 'v4d_station_layout_zoom_1.5km.png'))
    ax.set_xlim(-3000, 3000)
    ax.set_ylim(-3000, 3000)
    pyplot.savefig(join(out_dir, 'v4d_station_layout_zoom_3.0km.png'))
    ax.set_xlim(-5000, 5000)
    ax.set_ylim(-5000, 5000)
    pyplot.savefig(join(out_dir, 'v4d_station_layout_zoom_5.0km.png'))
    ax.set_xlim(-50000, 50000)
    ax.set_ylim(-50000, 50000)
    pyplot.savefig(join(out_dir, 'v4d_station_layout_50.0km.png'))
    pyplot.close(fig)

    if uvwsim_found:
        # TODO-BM make this a function in layout_utils.py
        print('generating uv coords...')
        x = v4d_st_x
        y = v4d_st_y
        num_stations = x.shape[0]
        z = numpy.zeros_like(x)
        lon = radians(116.63128900)
        lat = radians(-26.69702400)
        alt = 0.0
        ra = radians(68.698903779331502)
        dec = radians(-26.568851215532160)
        mjd_mid = 57443.4375000000
        obs_length = 4.0 * 3600.0  # seconds
        num_times = int(obs_length / (3 * 60.0))
        # print('num_times =', num_times)
        dt_s = obs_length / float(num_times)
        mjd_start = mjd_mid - (obs_length / 2.0) / (3600.0 * 24.0)
        mjd_start = mjd_mid
        obs_length = 0.0
        dt_s = 0.0
        num_times = 1
        num_baselines = num_stations * (num_stations - 1) / 2
        x, y, z = convert_enu_to_ecef(x, y, z, lon, lat, alt)
        uu, vv, ww = generate_baseline_uvw(x, y, z, ra, dec, num_times,
                                           num_baselines, mjd_start,
                                           dt_s)
        layout_utils.plot_hist(uu, vv, join(out_dir, 'v4d_hist.png'),
                               'v4d snapshot-uv')
        layout_utils.plot_uv_dist(uu, vv, st_radius,
                                  join(out_dir, 'v4d_snapshot_uv_zenith'))
        layout_utils.plot_uv_grid_image(uu, vv, 5.0,
                                        join(out_dir, 'uv_image'))
Example #17
0
# ---------------------------------------------------------
filename = '@PROJECT_BINARY_DIR@/test/VLA_A_hor_xyz.txt'
lon = 0.0 * (np.pi / 180.)
lat = 90.0 * (np.pi / 180.)
alt = 0.0
ra0 = 0.0 * (np.pi / 180.)
dec0 = 90.0 * (np.pi / 180.)
ntimes = 10
obs_length = 0.2  # days
# ---------------------------------------------------------

# Generate coordinates.
mjd_start = uvw.datetime_to_mjd(2014, 7, 28, 14, 26, 1.321)
(x, y, z) = uvw.load_station_coords(filename)
(x, y, z) = uvw.convert_enu_to_ecef(x, y, z, lon, lat, alt)
t0 = time.time()
for i in range(0, ntimes):
    mjd = mjd_start
    (uu_m, vv_m, ww_m) = uvw.evaluate_baseline_uvw(x, y, z, ra0, dec0, mjd)
print '- Time taken to evaluate uww coordinates = %.3f ms' % (
    (time.time() - t0) * 1.e3)

# Scatter plot of baseline coordinates.
plt.ioff()
plt_filename = 'test.png'
fig = plt.figure(figsize=(6, 6))
matplotlib.rcParams.update({'font.size': 10})
scatter_size = 3
fig.add_subplot(1, 1, 1, aspect='equal')
plt.scatter(uu_m, vv_m, c='b', lw=0, s=scatter_size)