def test_phasing_funcs(): # these tests are based on a notebook where I tested against the mwa_tools phasing code ra_hrs = 12.1 dec_degs = -42.3 mjd = 55780.1 array_center_xyz = np.array([-2559454.08, 5095372.14, -2849057.18]) lat_lon_alt = uvutils.LatLonAlt_from_XYZ(array_center_xyz) obs_time = Time(mjd, format='mjd', location=(lat_lon_alt[1], lat_lon_alt[0])) icrs_coord = SkyCoord(ra=Angle(ra_hrs, unit='hr'), dec=Angle(dec_degs, unit='deg'), obstime=obs_time) gcrs_coord = icrs_coord.transform_to('gcrs') # in east/north/up frame (relative to array center) in meters: (Nants, 3) ants_enu = np.array([-101.94, 0156.41, 0001.24]) ant_xyz_abs = uvutils.ECEF_from_ENU(ants_enu, lat_lon_alt[0], lat_lon_alt[1], lat_lon_alt[2]) ant_xyz_rel_itrs = ant_xyz_abs - array_center_xyz ant_xyz_rel_rot = uvutils.rotECEF_from_ECEF(ant_xyz_rel_itrs, lat_lon_alt[1]) array_center_coord = SkyCoord(x=array_center_xyz[0] * units.m, y=array_center_xyz[1] * units.m, z=array_center_xyz[2] * units.m, frame='itrs', obstime=obs_time) itrs_coord = SkyCoord(x=ant_xyz_abs[0] * units.m, y=ant_xyz_abs[1] * units.m, z=ant_xyz_abs[2] * units.m, frame='itrs', obstime=obs_time) gcrs_array_center = array_center_coord.transform_to('gcrs') gcrs_from_itrs_coord = itrs_coord.transform_to('gcrs') gcrs_rel = (gcrs_from_itrs_coord.cartesian - gcrs_array_center.cartesian).get_xyz().T gcrs_uvw = uvutils.phase_uvw(gcrs_coord.ra.rad, gcrs_coord.dec.rad, gcrs_rel.value) mwa_tools_calcuvw_u = -97.122828 mwa_tools_calcuvw_v = 50.388281 mwa_tools_calcuvw_w = -151.27976 assert np.allclose(gcrs_uvw[0, 0], mwa_tools_calcuvw_u, atol=1e-3) assert np.allclose(gcrs_uvw[0, 1], mwa_tools_calcuvw_v, atol=1e-3) assert np.allclose(gcrs_uvw[0, 2], mwa_tools_calcuvw_w, atol=1e-3) # also test unphasing temp2 = uvutils.unphase_uvw(gcrs_coord.ra.rad, gcrs_coord.dec.rad, np.squeeze(gcrs_uvw)) assert np.allclose(gcrs_rel.value, temp2)
def parse_telescope_params(tele_params): """ Parse the "telescope" section of a healvis obsparam. Args: tele_params: Dictionary of telescope parameters Returns: dict of array properties: | Nants_data: Number of antennas | Nants_telescope: Number of antennas | antenna_names: list of antenna names | antenna_numbers: corresponding list of antenna numbers | antenna_positions: Array of ECEF antenna positions | telescope_location: ECEF array center location | telescope_config_file: Path to configuration yaml file | antenna_location_file: Path to csv layout file | telescope_name: observatory name """ layout_csv = tele_params["array_layout"] if not os.path.exists(layout_csv): if not os.path.exists(layout_csv): raise ValueError( "layout_csv file from yaml does not exist: {}".format( layout_csv)) ant_layout = _parse_layout_csv(layout_csv) if isinstance(tele_params["telescope_location"], str): tloc = tele_params["telescope_location"][1:-1] # drop parens tloc = list(map(float, tloc.split(","))) else: tloc = list(tele_params["telescope_location"]) tloc[0] *= np.pi / 180.0 tloc[1] *= np.pi / 180.0 # Convert to radians tloc_xyz = uvutils.XYZ_from_LatLonAlt(*tloc) E, N, U = ant_layout["e"], ant_layout["n"], ant_layout["u"] antnames = ant_layout["name"] return_dict = {} return_dict["Nants_data"] = antnames.size return_dict["Nants_telescope"] = antnames.size return_dict["antenna_names"] = np.array(antnames.tolist()) return_dict["antenna_numbers"] = np.array(ant_layout["number"]) antpos_enu = np.vstack((E, N, U)).T return_dict["antenna_positions"] = ( uvutils.ECEF_from_ENU(antpos_enu, *tloc) - tloc_xyz) return_dict["array_layout"] = layout_csv return_dict["telescope_location"] = tloc_xyz return_dict["telescope_name"] = tele_params["telescope_name"] return return_dict
uv = UVData() uv.Nbls = 1 uv.Ntimes = Ntimes uv.spw_array = [0] uv.Nfreqs = Nfreqs uv.freq_array = freqs[np.newaxis, :] uv.Nblts = uv.Ntimes * uv.Nbls uv.ant_1_array = np.zeros(uv.Nblts, dtype=int) uv.ant_2_array = np.ones(uv.Nblts, dtype=int) uv.baseline_array = uv.antnums_to_baseline(uv.ant_1_array, uv.ant_2_array) uv.time_array = time_arr uv.Npols = 1 uv.polarization_array=np.array([1]) uv.Nants_telescope = 2 uv.Nants_data = 2 uv.antenna_positions = uvutils.ECEF_from_ENU(np.stack([ant1_enu, ant2_enu]), latitude, longitude, altitude) uv.Nspws = 1 uv.antenna_numbers = np.array([0,1]) uv.antenna_names = ['ant0', 'ant1'] #uv.channel_width = np.ones(uv.Nblts) * np.diff(freqs)[0] uv.channel_width = np.diff(freqs)[0] uv.integration_time = np.ones(uv.Nblts) * np.diff(time_arr)[0] * 24 * 3600. # Seconds uv.uvw_array = np.tile(ant1_enu - ant2_enu, uv.Nblts).reshape(uv.Nblts, 3) uv.history = 'Eorsky simulated' uv.set_drift() uv.telescope_name = 'Eorsky gaussian' uv.instrument = 'simulator' uv.object_name = 'zenith' uv.vis_units = 'Jy' uv.telescope_location_lat_lon_alt_degrees = (latitude, longitude, altitude) uv.set_lsts_from_time_array()
def initialize_uvdata(uvtask_list, source_list_name, uvdata_file=None, obs_param_file=None, telescope_config_file=None, antenna_location_file=None): """ Initialize an empty uvdata object to fill with simulation. Args: uvtask_list: List of uvtasks to simulate. source_list_name: Name of source list file or mock catalog. uvdata_file: Name of input UVData file or None if initializing from config files. obs_param_file: Name of observation parameter config file or None if initializing from a UVData file. telescope_config_file: Name of telescope config file or None if initializing from a UVData file. antenna_location_file: Name of antenna location file or None if initializing from a UVData file. """ if not isinstance(source_list_name, str): raise ValueError('source_list_name must be a string') if uvdata_file is not None: if not isinstance(uvdata_file, str): raise ValueError('uvdata_file must be a string') if (obs_param_file is not None or telescope_config_file is not None or antenna_location_file is not None): raise ValueError('If initializing from a uvdata_file, none of ' 'obs_param_file, telescope_config_file or ' 'antenna_location_file can be set.') elif (obs_param_file is None or telescope_config_file is None or antenna_location_file is None): if not isinstance(obs_param_file, str): raise ValueError('obs_param_file must be a string') if not isinstance(telescope_config_file, str): raise ValueError('telescope_config_file must be a string') if not isinstance(antenna_location_file, str): raise ValueError('antenna_location_file must be a string') raise ValueError('If not initializing from a uvdata_file, all of ' 'obs_param_file, telescope_config_file or ' 'antenna_location_file must be set.') # Version string to add to history history = get_version_string() history += ' Sources from source list: ' + source_list_name + '.' if uvdata_file is not None: history += ' Based on UVData file: ' + uvdata_file + '.' else: history += (' Based on config files: ' + obs_param_file + ', ' + telescope_config_file + ', ' + antenna_location_file) history += ' Npus = ' + str(Npus) + '.' task_freqs = [] task_bls = [] task_times = [] task_antnames = [] task_antnums = [] task_antpos = [] task_uvw = [] ant_1_array = [] ant_2_array = [] telescope_name = uvtask_list[0].telescope.telescope_name telescope_location = uvtask_list[0].telescope.telescope_location.geocentric source_0 = uvtask_list[0].source freq_0 = uvtask_list[0].freq for task in uvtask_list: if not task.source == source_0: continue task_freqs.append(task.freq) if task.freq == freq_0: task_bls.append(task.baseline) task_times.append(task.time) task_antnames.append(task.baseline.antenna1.name) task_antnames.append(task.baseline.antenna2.name) ant_1_array.append(task.baseline.antenna1.number) ant_2_array.append(task.baseline.antenna2.number) task_antnums.append(task.baseline.antenna1.number) task_antnums.append(task.baseline.antenna2.number) task_antpos.append(task.baseline.antenna1.pos_enu) task_antpos.append(task.baseline.antenna2.pos_enu) task_uvw.append(task.baseline.uvw) antnames, ant_indices = np.unique(task_antnames, return_index=True) task_antnums = np.array(task_antnums) task_antpos = np.array(task_antpos) antnums = task_antnums[ant_indices] antpos = task_antpos[ant_indices] freqs = np.unique(task_freqs) uv_obj = UVData() # add pyuvdata version info history += uv_obj.pyuvdata_version_str uv_obj.telescope_name = telescope_name uv_obj.telescope_location = np.array( [tl.to('m').value for tl in telescope_location]) uv_obj.instrument = telescope_name uv_obj.Nfreqs = freqs.size uv_obj.Ntimes = np.unique(task_times).size uv_obj.Nants_data = antnames.size uv_obj.Nants_telescope = uv_obj.Nants_data uv_obj.Nblts = len(ant_1_array) uv_obj.antenna_names = antnames.tolist() uv_obj.antenna_numbers = antnums antpos_ecef = uvutils.ECEF_from_ENU( antpos, * uv_obj.telescope_location_lat_lon_alt) - uv_obj.telescope_location uv_obj.antenna_positions = antpos_ecef uv_obj.ant_1_array = np.array(ant_1_array) uv_obj.ant_2_array = np.array(ant_2_array) uv_obj.time_array = np.array(task_times) uv_obj.uvw_array = np.array(task_uvw) uv_obj.baseline_array = uv_obj.antnums_to_baseline(ant_1_array, ant_2_array) uv_obj.Nbls = np.unique(uv_obj.baseline_array).size if uv_obj.Nfreqs == 1: uv_obj.channel_width = 1. # Hz else: uv_obj.channel_width = np.diff(freqs)[0] if uv_obj.Ntimes == 1: uv_obj.integration_time = np.ones_like(uv_obj.time_array, dtype=np.float64) # Second else: # Note: currently only support a constant spacing of times uv_obj.integration_time = ( np.ones_like(uv_obj.time_array, dtype=np.float64) * np.diff(np.unique(task_times))[0]) uv_obj.set_lsts_from_time_array() uv_obj.zenith_ra = uv_obj.lst_array uv_obj.zenith_dec = np.repeat(uv_obj.telescope_location_lat_lon_alt[0], uv_obj.Nblts) # Latitude uv_obj.object_name = 'zenith' uv_obj.set_drift() uv_obj.vis_units = 'Jy' uv_obj.polarization_array = np.array([-5, -6, -7, -8]) uv_obj.spw_array = np.array([0]) uv_obj.freq_array = np.array([freqs]) uv_obj.Nspws = uv_obj.spw_array.size uv_obj.Npols = uv_obj.polarization_array.size uv_obj.data_array = np.zeros( (uv_obj.Nblts, uv_obj.Nspws, uv_obj.Nfreqs, uv_obj.Npols), dtype=np.complex) uv_obj.flag_array = np.zeros( (uv_obj.Nblts, uv_obj.Nspws, uv_obj.Nfreqs, uv_obj.Npols), dtype=bool) uv_obj.nsample_array = np.ones_like(uv_obj.data_array, dtype=float) uv_obj.history = history uv_obj.check() return uv_obj
def apply_bda( uv, max_decorr, pre_fs_int_time, corr_fov_angle, max_time, corr_int_time=None ): """Apply baseline dependent averaging to a UVData object. For each baseline in the UVData object, the expected decorrelation from averaging in time is computed. Baselines are averaged together in powers- of-two until the specified level of decorrelation is reached (rounded down). Parameters ---------- uv : UVData object The UVData object to apply BDA to. No changes are made to this object, and instead a copy is returned. max_decorr : float The maximum decorrelation fraction desired in the output object. Must be between 0 and 1. pre_fs_int_time : astropy Quantity The pre-finge-stopping integration time inside of the correlator. The quantity should be compatible with units of time. corr_fov_angle : astropy Angle The opening angle at which the maximum decorrelation is to be calculated. Because a priori it is not known in which direction the decorrelation will be largest, the expected decorrelation is computed in all 4 cardinal directions at `corr_fov_angle` degrees off of zenith, and the largest one is used. This is a "worst case scenario" decorrelation. max_time : astropy Quantity The maximum amount of time that spectra from different times should be combined for. The ultimate integration time for a given baseline will be for max_time or the integration time that is smaller than the specified decorrelation level, whichever is smaller. The quantity should be compatible with units of time. corr_int_time : astropy Quantity, optional The output time of the correlator. If not specified, the smallest integration_time in the UVData object is used. If specified, the quantity should be compatible with units of time. Returns ------- uv2 : UVData object The UVData object with BDA applied. Raises ------ ValueError This is raised if the input parameters are not the appropriate type or in the appropriate range. It is also raised if the input UVData object is not in drift mode (the BDA code does rephasing within an averaged set of baselines). AssertionError This is raised if the baselines of the UVData object are not time- ordered. """ if not isinstance(uv, UVData): raise ValueError( "apply_bda must be passed a UVData object as its first argument" ) if not isinstance(corr_fov_angle, Angle): raise ValueError( "corr_fov_angle must be an Angle object from astropy.coordinates" ) if not isinstance(pre_fs_int_time, units.Quantity): raise ValueError("pre_fs_int_time must be an astropy.units.Quantity") try: pre_fs_int_time.to(units.s) except UnitConversionError: raise ValueError("pre_fs_int_time must be a Quantity with units of time") if ( corr_fov_angle.to(units.deg).value < 0 or corr_fov_angle.to(units.deg).value > 90 ): raise ValueError("corr_fov_angle must be between 0 and 90 degrees") if max_decorr < 0 or max_decorr > 1: raise ValueError("max_decorr must be between 0 and 1") if not isinstance(max_time, units.Quantity): raise ValueError("max_time must be an astropy.units.Quantity") try: max_time.to(units.s) except UnitConversionError: raise ValueError("max_time must be a Quantity with units of time") if corr_int_time is None: # assume the correlator integration time is the smallest int_time of the # UVData object corr_int_time = np.unique(uv.integration_time)[0] * units.s else: if not isinstance(corr_int_time, units.Quantity): raise ValueError("corr_int_time must be an astropy.units.Quantity") try: corr_int_time.to(units.s) except UnitConversionError: raise ValueError("corr_int_time must be a Quantity with units of time") if uv.phase_type != "drift": raise ValueError("UVData object must be in drift mode to apply BDA") # get relevant bits of metadata freq = np.amax(uv.freq_array[0, :]) * units.Hz chan_width = uv.channel_width * units.Hz antpos_enu, ants = uv.get_ENU_antpos() lat, lon, alt = uv.telescope_location_lat_lon_alt antpos_ecef = uvutils.ECEF_from_ENU(antpos_enu, lat, lon, alt) telescope_location = EarthLocation.from_geocentric( uv.telescope_location[0], uv.telescope_location[1], uv.telescope_location[2], unit="m", ) # make a new UVData object to put BDA baselines in uv2 = UVData() # copy over metadata uv2.Nbls = uv.Nbls uv2.Nfreqs = uv.Nfreqs uv2.Npols = uv.Npols uv2.vis_units = uv.vis_units uv2.Nspws = uv.Nspws uv2.spw_array = uv.spw_array uv2.freq_array = uv.freq_array uv2.polarization_array = uv.polarization_array uv2.channel_width = uv.channel_width uv2.object_name = uv.object_name uv2.telescope_name = uv.telescope_name uv2.instrument = uv.instrument uv2.telescope_location = uv.telescope_location history = uv.history + " Baseline dependent averaging applied." uv2.history = history uv2.Nants_data = uv.Nants_data uv2.Nants_telescope = uv.Nants_telescope uv2.antenna_names = uv.antenna_names uv2.antenna_numbers = uv.antenna_numbers uv2.x_orientation = uv.x_orientation uv2.extra_keywords = uv.extra_keywords uv2.antenna_positions = uv.antenna_positions uv2.antenna_diameters = uv.antenna_diameters uv2.gst0 = uv.gst0 uv2.rdate = uv.rdate uv2.earth_omega = uv.earth_omega uv2.dut1 = uv.dut1 uv2.timesys = uv.timesys uv2.uvplane_reference_time = uv.uvplane_reference_time # initialize place-keeping variables and Nblt-sized metadata start_index = 0 uv2.Nblts = 0 uv2.uvw_array = np.zeros_like(uv.uvw_array) uv2.time_array = np.zeros_like(uv.time_array) uv2.lst_array = np.zeros_like(uv.lst_array) uv2.ant_1_array = np.zeros_like(uv.ant_1_array) uv2.ant_2_array = np.zeros_like(uv.ant_2_array) uv2.baseline_array = np.zeros_like(uv.baseline_array) uv2.integration_time = np.zeros_like(uv.integration_time) uv2.data_array = np.zeros_like(uv.data_array) uv2.flag_array = np.zeros_like(uv.flag_array) uv2.nsample_array = np.zeros_like(uv.nsample_array) # iterate over baselines for key in uv.get_antpairs(): print("averaging baseline ", key) ind1, ind2, indp = uv._key2inds(key) if len(ind2) != 0: raise AssertionError( "ind2 from _key2inds() is not 0--exiting. This should not happen, " "please contact the package maintainers." ) data = uv._smart_slicing( uv.data_array, ind1, ind2, indp, squeeze="none", force_copy=True ) flags = uv._smart_slicing( uv.flag_array, ind1, ind2, indp, squeeze="none", force_copy=True ) nsamples = uv._smart_slicing( uv.nsample_array, ind1, ind2, indp, squeeze="none", force_copy=True ) # get lx and ly for baseline ant1 = np.where(ants == key[0])[0][0] ant2 = np.where(ants == key[1])[0][0] x1, y1, z1 = antpos_ecef[ant1, :] x2, y2, z2 = antpos_ecef[ant2, :] lx = np.abs(x2 - x1) * units.m ly = np.abs(y2 - y1) * units.m # figure out how many time samples we can combine together if key[0] == key[1]: # autocorrelation--don't average n_two_foldings = 0 else: n_two_foldings = dc.bda_compression_factor( max_decorr, freq, lx, ly, corr_fov_angle, chan_width, pre_fs_int_time, corr_int_time, ) # convert from max_time to max_samples max_samples = (max_time / corr_int_time).to(units.dimensionless_unscaled) max_two_foldings = int(np.floor(np.log2(max_samples))) n_two_foldings = min(n_two_foldings, max_two_foldings) n_int = 2 ** (n_two_foldings) print("averaging {:d} time samples...".format(n_int)) # figure out how many output samples we're going to have n_in = len(ind1) n_out = n_in // n_int + min(1, n_in % n_int) # get relevant metdata uvw_array = uv.uvw_array[ind1, :] times = uv.time_array[ind1] if not np.all(times == np.sort(times)): raise AssertionError( "times of uvdata object are not monotonically increasing; " "throwing our hands up" ) lsts = uv.lst_array[ind1] int_time = uv.integration_time[ind1] # do the averaging input_shape = data.shape assert input_shape == (n_in, 1, uv.Nfreqs, uv.Npols) output_shape = (n_out, 1, uv.Nfreqs, uv.Npols) data_out = np.empty(output_shape, dtype=np.complex128) flags_out = np.empty(output_shape, dtype=np.bool_) nsamples_out = np.empty(output_shape, dtype=np.float32) uvws_out = np.empty((n_out, 3), dtype=np.float64) times_out = np.empty((n_out,), dtype=np.float64) lst_out = np.empty((n_out,), dtype=np.float64) int_time_out = np.empty((n_out,), dtype=np.float64) if n_out == n_in: # we don't need to average current_index = start_index + n_out uv2.data_array[start_index:current_index, :, :, :] = data uv2.flag_array[start_index:current_index, :, :, :] = flags uv2.nsample_array[start_index:current_index, :, :, :] = nsamples uv2.uvw_array[start_index:current_index, :] = uvw_array uv2.time_array[start_index:current_index] = times uv2.lst_array[start_index:current_index] = lsts uv2.integration_time[start_index:current_index] = int_time uv2.ant_1_array[start_index:current_index] = key[0] uv2.ant_2_array[start_index:current_index] = key[1] uv2.baseline_array[start_index:current_index] = uvutils.antnums_to_baseline( ant1, ant2, None ) start_index = current_index else: # rats, we actually have to do work... # phase up the data along each chunk of times for i in range(n_out): # compute zenith of the desired output time i1 = i * n_int i2 = min((i + 1) * n_int, n_in) assert i2 - i1 > 0 t0 = Time((times[i1] + times[i2 - 1]) / 2, scale="utc", format="jd") zenith_coord = SkyCoord( alt=Angle(90 * units.deg), az=Angle(0 * units.deg), obstime=t0, frame="altaz", location=telescope_location, ) obs_zenith_coord = zenith_coord.transform_to("icrs") zenith_ra = obs_zenith_coord.ra zenith_dec = obs_zenith_coord.dec # get data, flags, and nsamples of slices data_chunk = data[i1:i2, :, :, :] flags_chunk = flags[i1:i2, :, :, :] nsamples_chunk = nsamples[i1:i2, :, :, :] # actually phase now # compute new uvw coordinates icrs_coord = SkyCoord( ra=zenith_ra, dec=zenith_dec, unit="radian", frame="icrs" ) uvws = np.float64(uvw_array[i1:i2, :]) itrs_telescope_location = SkyCoord( x=uv.telescope_location[0] * units.m, y=uv.telescope_location[1] * units.m, z=uv.telescope_location[2] * units.m, representation_type="cartesian", frame="itrs", obstime=t0, ) itrs_lat_lon_alt = uv.telescope_location_lat_lon_alt frame_telescope_location = itrs_telescope_location.transform_to("icrs") frame_telescope_location.representation_type = "cartesian" uvw_ecef = uvutils.ECEF_from_ENU(uvws, *itrs_lat_lon_alt) itrs_uvw_coord = SkyCoord( x=uvw_ecef[:, 0] * units.m, y=uvw_ecef[:, 1] * units.m, z=uvw_ecef[:, 2] * units.m, representation_type="cartesian", frame="itrs", obstime=t0, ) frame_uvw_coord = itrs_uvw_coord.transform_to("icrs") frame_rel_uvw = ( frame_uvw_coord.cartesian.get_xyz().value.T - frame_telescope_location.cartesian.get_xyz().value ) new_uvws = uvutils.phase_uvw( icrs_coord.ra.rad, icrs_coord.dec.rad, frame_rel_uvw ) # average these uvws together to get the "average" position in # the uv-plane avg_uvws = np.average(new_uvws, axis=0) # calculate and apply phasor w_lambda = ( new_uvws[:, 2].reshape((i2 - i1), 1) / const.c.to("m/s").value * uv.freq_array.reshape(1, uv.Nfreqs) ) phs = np.exp(-1j * 2 * np.pi * w_lambda[:, None, :, None]) data_chunk *= phs # sum data, propagate flag array, and adjusting nsample accordingly data_slice = np.sum(data_chunk, axis=0) flag_slice = np.sum(flags_chunk, axis=0) nsamples_slice = np.sum(nsamples_chunk, axis=0) / (i2 - i1) data_out[i, :, :, :] = data_slice flags_out[i, :, :, :] = flag_slice nsamples_out[i, :, :, :] = nsamples_slice # update metadata uvws_out[i, :] = avg_uvws times_out[i] = (times[i1] + times[i2 - 1]) / 2 lst_out[i] = (lsts[i1] + lsts[i2 - 1]) / 2 int_time_out[i] = np.average(int_time[i1:i2]) * (i2 - i1) # update data and metadata when we're done with this baseline current_index = start_index + n_out uv2.data_array[start_index:current_index, :, :, :] = data_out uv2.flag_array[start_index:current_index, :, :, :] = flags_out uv2.nsample_array[start_index:current_index, :, :, :] = nsamples_out uv2.uvw_array[start_index:current_index, :] = uvws_out uv2.time_array[start_index:current_index] = times_out uv2.lst_array[start_index:current_index] = lst_out uv2.integration_time[start_index:current_index] = int_time_out uv2.ant_1_array[start_index:current_index] = key[0] uv2.ant_2_array[start_index:current_index] = key[1] uv2.baseline_array[start_index:current_index] = uvutils.antnums_to_baseline( ant1, ant2, None ) start_index = current_index # clean up -- shorten all arrays to actually be size nblts nblts = start_index uv2.Nblts = nblts uv2.data_array = uv2.data_array[:nblts, :, :, :] uv2.flag_array = uv2.flag_array[:nblts, :, :, :] uv2.nsample_array = uv2.nsample_array[:nblts, :, :, :] uv2.uvw_array = uv2.uvw_array[:nblts, :] uv2.time_array = uv2.time_array[:nblts] uv2.lst_array = uv2.lst_array[:nblts] uv2.integration_time = uv2.integration_time[:nblts] uv2.ant_1_array = uv2.ant_1_array[:nblts] uv2.ant_2_array = uv2.ant_2_array[:nblts] uv2.baseline_array = uv2.baseline_array[:nblts] uv2.Ntimes = len(np.unique(uv2.time_array)) # set phasing info uv2.phase_type = "phased" uv2.phase_center_ra = zenith_ra.rad uv2.phase_center_dec = zenith_dec.rad uv2.phase_center_frame = 2000.0 # fix up to correct old phasing method uv2.phase(zenith_ra.rad, zenith_dec.rad, epoch="J2000", fix_old_proj=True) # run a check uv2.check() return uv2
def phase(jd, ra, dec, telescope_location, uvws0): """ Compute UVWs phased to a given RA/DEC at a particular epoch. This function was copied from the pyuvdata.UVData.phase method, and modified to be simpler. Parameters ---------- jd : float or array_like of float The Julian date of the observation. ra : float The ra to phase to in radians. dec : float The dec to phase to in radians. telescope_location : :class:`astropy.coordinates.EarthLocation` The location of the reference point of the telescope, in geodetic frame (i.e. it has lat, lon, height attributes). uvws0 : array The UVWs when phased to zenith. Returns ------- uvws : array Array of the same shape as `uvws0`, with entries modified to the new phase center. """ frame_phase_center = SkyCoord(ra=ra, dec=dec, unit="radian", frame="icrs") obs_time = Time(np.atleast_1d(jd), format="jd") itrs_telescope_location = telescope_location.get_itrs(obstime=obs_time) frame_telescope_location = itrs_telescope_location.transform_to(ICRS) frame_telescope_location.representation_type = "cartesian" uvw_ecef = uvutils.ECEF_from_ENU( uvws0, telescope_location.lat.rad, telescope_location.lon.rad, telescope_location.height, ) unique_times, r_inds = np.unique(obs_time, return_inverse=True) uvws = np.zeros((uvw_ecef.shape[0], unique_times.size, 3), dtype=np.float64) for ind, jd in tqdm.tqdm( enumerate(unique_times), desc="computing UVWs", total=len(unique_times), unit="times", disable=not config.PROGRESS or unique_times.size == 1, ): itrs_uvw_coord = SkyCoord( x=uvw_ecef[:, 0] * un.m, y=uvw_ecef[:, 1] * un.m, z=uvw_ecef[:, 2] * un.m, frame="itrs", obstime=jd, ) frame_uvw_coord = itrs_uvw_coord.transform_to("icrs") # this takes out the telescope location in the new frame, # so these are vectors again frame_rel_uvw = ( frame_uvw_coord.cartesian.get_xyz().value.T - frame_telescope_location[ind].cartesian.get_xyz().value) uvws[:, ind, :] = uvutils.phase_uvw(frame_phase_center.ra.rad, frame_phase_center.dec.rad, frame_rel_uvw) return uvws[:, r_inds, :]
def test_ENU_tofrom_ECEF(): center_lat = -30.7215261207 * np.pi / 180.0 center_lon = 21.4283038269 * np.pi / 180.0 center_alt = 1051.7 lats = np.array([ -30.72218216, -30.72138101, -30.7212785, -30.7210011, -30.72159853, -30.72206199, -30.72174614, -30.72188775, -30.72183915, -30.72100138 ]) * np.pi / 180.0 lons = np.array([ 21.42728211, 21.42811727, 21.42814544, 21.42795736, 21.42686739, 21.42918772, 21.42785662, 21.4286408, 21.42750933, 21.42896567 ]) * np.pi / 180.0 alts = np.array([ 1052.25, 1051.35, 1051.2, 1051., 1051.45, 1052.04, 1051.68, 1051.87, 1051.77, 1051.06 ]) # used pymap3d, which implements matlab code, as a reference. x = [ 5109327.46674067, 5109339.76407785, 5109344.06370947, 5109365.11297147, 5109372.115673, 5109266.94314734, 5109329.89620962, 5109295.13656657, 5109337.21810468, 5109329.85680612 ] y = [ 2005130.57953031, 2005221.35184577, 2005225.93775268, 2005214.8436201, 2005105.42364036, 2005302.93158317, 2005190.65566222, 2005257.71335575, 2005157.78980089, 2005304.7729239 ] z = [ -3239991.24516348, -3239914.4185286, -3239904.57048431, -3239878.02656316, -3239935.20415493, -3239979.68381865, -3239949.39266985, -3239962.98805772, -3239958.30386264, -3239878.08403833 ] east = [ -97.87631659, -17.87126443, -15.17316938, -33.19049252, -137.60520964, 84.67346748, -42.84049408, 32.28083937, -76.1094745, 63.40285935 ] north = [ -72.7437482, 16.09066646, 27.45724573, 58.21544651, -8.02964511, -59.41961437, -24.39698388, -40.09891961, -34.70965816, 58.18410876 ] up = [ 0.54883333, -0.35004539, -0.50007736, -0.70035299, -0.25148791, 0.33916067, -0.02019057, 0.16979185, 0.06945155, -0.64058124 ] xyz = uvutils.XYZ_from_LatLonAlt(lats, lons, alts) assert np.allclose(np.stack((x, y, z), axis=1), xyz, atol=1e-3) enu = uvutils.ENU_from_ECEF(xyz, center_lat, center_lon, center_alt) assert np.allclose(np.stack((east, north, up), axis=1), enu, atol=1e-3) # check warning if array transposed uvtest.checkWarnings(uvutils.ENU_from_ECEF, [xyz.T, center_lat, center_lon, center_alt], message='The expected shape of ECEF xyz array', category=DeprecationWarning) # check warning if 3 x 3 array uvtest.checkWarnings(uvutils.ENU_from_ECEF, [xyz[0:3], center_lat, center_lon, center_alt], message='The xyz array in ENU_from_ECEF is', category=DeprecationWarning) # check error if only 2 coordinates pytest.raises(ValueError, uvutils.ENU_from_ECEF, xyz[:, 0:2], center_lat, center_lon, center_alt) # check that a round trip gives the original value. xyz_from_enu = uvutils.ECEF_from_ENU(enu, center_lat, center_lon, center_alt) assert np.allclose(xyz, xyz_from_enu, atol=1e-3) # check warning if array transposed uvtest.checkWarnings(uvutils.ECEF_from_ENU, [enu.T, center_lat, center_lon, center_alt], message='The expected shape the ENU array', category=DeprecationWarning) # check warning if 3 x 3 array uvtest.checkWarnings(uvutils.ECEF_from_ENU, [enu[0:3], center_lat, center_lon, center_alt], message='The enu array in ECEF_from_ENU is', category=DeprecationWarning) # check error if only 2 coordinates pytest.raises(ValueError, uvutils.ENU_from_ECEF, enu[:, 0:2], center_lat, center_lon, center_alt) # check passing a single value enu_single = uvutils.ENU_from_ECEF(xyz[0, :], center_lat, center_lon, center_alt) assert np.allclose(np.array((east[0], north[0], up[0])), enu[0, :], atol=1e-3) xyz_from_enu = uvutils.ECEF_from_ENU(enu_single, center_lat, center_lon, center_alt) assert np.allclose(xyz[0, :], xyz_from_enu, atol=1e-3) # error checking pytest.raises(ValueError, uvutils.ENU_from_ECEF, xyz[:, 0:1], center_lat, center_lon, center_alt) pytest.raises(ValueError, uvutils.ECEF_from_ENU, enu[:, 0:1], center_lat, center_lon, center_alt) pytest.raises(ValueError, uvutils.ENU_from_ECEF, xyz / 2., center_lat, center_lon, center_alt)
def fake_data_generator(): """Generate a fake dataset as a module-level fixture.""" # generate a fake data file for testing BDA application uvd = UVData() t0 = 2459000.0 dt = (2 * units.s).to(units.day) t1 = t0 + dt.value t2 = t0 + 2 * dt.value # define baseline-time spacing uvd.ant_1_array = np.asarray([0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=np.int_) uvd.ant_2_array = np.asarray([0, 1, 2, 0, 1, 2, 0, 1, 2], dtype=np.int_) uvd.time_array = np.asarray([t0, t0, t0, t1, t1, t1, t2, t2, t2], dtype=np.float64) uvd.Ntimes = 3 uvd.Nbls = 3 uvd.Nblts = uvd.Ntimes * uvd.Nbls # define frequency array nfreqs = 1024 freq_array = np.linspace(50e6, 250e6, num=nfreqs) uvd.freq_array = freq_array[np.newaxis, :] uvd.spw_array = [0] uvd.Nfreqs = nfreqs uvd.Nspws = 1 # define polarization array uvd.polarization_array = [-5] uvd.Npols = 1 # make random data for data array data_shape = (uvd.Nblts, 1, uvd.Nfreqs, uvd.Npols) uvd.data_array = np.zeros(data_shape, dtype=np.complex128) rng = default_rng() uvd.data_array += rng.standard_normal(data_shape) uvd.data_array += 1j * rng.standard_normal(data_shape) uvd.flag_array = np.zeros_like(uvd.data_array, dtype=np.bool_) uvd.nsample_array = np.ones_like(uvd.data_array, dtype=np.float32) # set telescope and antenna positions hera_telescope = pyuvdata.telescopes.get_telescope("HERA") uvd.telescope_location_lat_lon_alt = hera_telescope.telescope_location_lat_lon_alt antpos0 = np.asarray([0, 0, 0], dtype=np.float64) antpos1 = np.asarray([14, 0, 0], dtype=np.float64) antpos2 = np.asarray([28, 0, 0], dtype=np.float64) antpos_enu = np.vstack((antpos0, antpos1, antpos2)) antpos_xyz = uvutils.ECEF_from_ENU(antpos_enu, *uvd.telescope_location_lat_lon_alt) uvd.antenna_positions = antpos_xyz - uvd.telescope_location uvw_array = np.zeros((uvd.Nblts, 3), dtype=np.float64) uvw_array[::3, :] = antpos0 - antpos0 uvw_array[1::3, :] = antpos1 - antpos0 uvw_array[2::3, :] = antpos2 - antpos0 uvd.uvw_array = uvw_array uvd.antenna_numbers = np.asarray([0, 1, 2], dtype=np.int_) uvd.antenna_names = np.asarray(["H0", "H1", "H2"], dtype=np.str_) uvd.Nants_data = 3 uvd.Nants_telescope = 3 # set other metadata uvd.vis_units = "uncalib" uvd.channel_width = 5e4 # 50 kHz uvd.phase_type = "drift" uvd.baseline_array = uvd.antnums_to_baseline(uvd.ant_1_array, uvd.ant_2_array) uvd.history = "BDA test file" uvd.instrument = "HERA" uvd.telescope_name = "HERA" uvd.object_name = "zenith" uvd.integration_time = 2 * np.ones_like(uvd.baseline_array, dtype=np.float64) uvd.set_lsts_from_time_array() # run a check uvd.check() yield uvd # clean up when done del uvd return
def write_vis(fname, data, lst_array, freq_array, antpos, time_array=None, flags=None, nsamples=None, filetype='miriad', write_file=True, outdir="./", overwrite=False, verbose=True, history=" ", return_uvd=False, longitude=21.42830, start_jd=None, instrument="HERA", telescope_name="HERA", object_name='EOR', vis_units='uncalib', dec=-30.72152, telescope_location=np.array( [5109325.85521063, 2005235.09142983, -3239928.42475395]), integration_time=None, **kwargs): """ Take DataContainer dictionary, export to UVData object and write to file. See pyuvdata.UVdata documentation for more info on these attributes. Parameters: ----------- fname : type=str, output filename of visibliity data data : type=DataContainer, holds complex visibility data. lst_array : type=float ndarray, contains unique LST time bins [radians] of data (center of integration). freq_array : type=ndarray, contains frequency bins of data [Hz]. antpos : type=dictionary, antenna position dictionary. keys are antenna integers and values are position vectors in meters in ENU (TOPO) frame. time_array : type=ndarray, contains unique Julian Date time bins of data (center of integration). flags : type=DataContainer, holds data flags, matching data in shape. nsamples : type=DataContainer, holds number of points averaged into each bin in data (if applicable). filetype : type=str, filetype to write-out, options=['miriad']. write_file : type=boolean, write UVData to file if True. outdir : type=str, output directory for output file. overwrite : type=boolean, if True, overwrite output files. verbose : type=boolean, if True, report feedback to stdout. history : type=str, history string for UVData object return_uvd : type=boolean, if True return UVData instance. longitude : type=float, longitude of observer in degrees East start_jd : type=float, starting integer Julian Date of time_array if time_array is None. instrument : type=str, instrument name. telescope_name : type=str, telescope name. object_name : type=str, observing object name. vis_unit : type=str, visibility units. dec : type=float, declination of observer in degrees North. telescope_location : type=ndarray, telescope location in xyz in ITRF (earth-centered frame). integration_time : type=float, integration duration in seconds for data_array. This does not necessarily have to be equal to the diff(time_array): for the case of LST-binning, this is not the duration of the LST-bin but the integration time of the pre-binned data. kwargs : type=dictionary, additional parameters to set in UVData object. Output: ------- if return_uvd: return UVData instance """ ## configure UVData parameters # get pols pols = np.unique(map(lambda k: k[-1], data.keys())) Npols = len(pols) polarization_array = np.array(map(lambda p: polstr2num[p], pols)) # get times if time_array is None: if start_jd is None: raise AttributeError( "if time_array is not fed, start_jd must be fed") time_array = hc.utils.LST2JD(lst_array, start_jd, longitude=longitude) Ntimes = len(time_array) if integration_time is None: integration_time = np.median(np.diff(time_array)) * 24 * 3600. # get freqs Nfreqs = len(freq_array) channel_width = np.median(np.diff(freq_array)) freq_array = freq_array.reshape(1, -1) spw_array = np.array([0]) Nspws = 1 # get baselines keys bls = sorted(data.bls()) Nbls = len(bls) Nblts = Nbls * Ntimes # reconfigure time_array and lst_array time_array = np.repeat(time_array[np.newaxis], Nbls, axis=0).ravel() lst_array = np.repeat(lst_array[np.newaxis], Nbls, axis=0).ravel() # get data array data_array = np.moveaxis( map(lambda p: map(lambda bl: data[str(p)][bl], bls), pols), 0, -1) # resort time and baseline axes data_array = data_array.reshape(Nblts, 1, Nfreqs, Npols) if nsamples is None: nsample_array = np.ones_like(data_array, np.float) else: nsample_array = np.moveaxis( map(lambda p: map(lambda bl: nsamples[str(p)][bl], bls), pols), 0, -1) nsample_array = nsample_array.reshape(Nblts, 1, Nfreqs, Npols) # flags if flags is None: flag_array = np.zeros_like(data_array, np.float).astype(np.bool) else: flag_array = np.moveaxis( map( lambda p: map(lambda bl: flags[str(p)][bl].astype(np.bool), bls ), pols), 0, -1) flag_array = flag_array.reshape(Nblts, 1, Nfreqs, Npols) # configure baselines bls = np.repeat(np.array(bls), Ntimes, axis=0) # get ant_1_array, ant_2_array ant_1_array = bls[:, 0] ant_2_array = bls[:, 1] # get baseline array baseline_array = 2048 * (ant_1_array + 1) + (ant_2_array + 1) + 2**16 # get antennas in data data_ants = np.unique(np.concatenate([ant_1_array, ant_2_array])) Nants_data = len(data_ants) # get telescope ants antenna_numbers = np.unique(antpos.keys()) Nants_telescope = len(antenna_numbers) antenna_names = map(lambda a: "HH{}".format(a), antenna_numbers) # set uvw assuming drift phase i.e. phase center is zenith uvw_array = np.array( [antpos[k[1]] - antpos[k[0]] for k in zip(ant_1_array, ant_2_array)]) # get antenna positions in ITRF frame tel_lat_lon_alt = uvutils.LatLonAlt_from_XYZ(telescope_location) antenna_positions = np.array(map(lambda k: antpos[k], antenna_numbers)) antenna_positions = uvutils.ECEF_from_ENU( antenna_positions.T, *tel_lat_lon_alt).T - telescope_location # get zenith location: can only write drift phase phase_type = 'drift' zenith_dec_degrees = np.ones_like(baseline_array) * dec zenith_ra_degrees = hc.utils.JD2RA(time_array, longitude) zenith_dec = zenith_dec_degrees * np.pi / 180 zenith_ra = zenith_ra_degrees * np.pi / 180 # instantiate object uvd = UVData() # assign parameters params = [ 'Nants_data', 'Nants_telescope', 'Nbls', 'Nblts', 'Nfreqs', 'Npols', 'Nspws', 'Ntimes', 'ant_1_array', 'ant_2_array', 'antenna_names', 'antenna_numbers', 'baseline_array', 'channel_width', 'data_array', 'flag_array', 'freq_array', 'history', 'instrument', 'integration_time', 'lst_array', 'nsample_array', 'object_name', 'phase_type', 'polarization_array', 'spw_array', 'telescope_location', 'telescope_name', 'time_array', 'uvw_array', 'vis_units', 'antenna_positions', 'zenith_dec', 'zenith_ra' ] local_params = locals() # overwrite paramters by kwargs local_params.update(kwargs) # set parameters in uvd for p in params: uvd.__setattr__(p, local_params[p]) # write to file if write_file: if filetype == 'miriad': # check output fname = os.path.join(outdir, fname) if os.path.exists(fname) and overwrite is False: if verbose: print("{} exists, not overwriting".format(fname)) else: if verbose: print("saving {}".format(fname)) uvd.write_miriad(fname, clobber=True) else: raise AttributeError( "didn't recognize filetype: {}".format(filetype)) if return_uvd: return uvd