Utility Functions
Some of our utility functions are widely used and so are available to be imported from the pyuvdata.utils namespace. These are shown here, for the full list of all utility functions see: Utils subpackage.
- pyuvdata.utils.uvcalibrate(uvdata, uvcal, *, inplace: bool = True, prop_flags: bool = True, d_term_cal: bool = False, flip_gain_conj: bool = False, delay_convention: Literal['minus', 'plus'] = 'minus', undo: bool = False, time_check: bool = True, ant_check: bool = True, freq_range_check: bool = True, uvc_pol_convention: Literal['sum', 'avg'] | None = None, uvd_pol_convention: Literal['sum', 'avg'] | None = None)[source]
Calibrate a UVData object with a UVCal object.
- Parameters:
uvdata (UVData object) – UVData object to calibrate.
uvcal (UVCal object) – UVCal object containing the calibration.
inplace (bool, optional) – if True edit uvdata in place, else return a calibrated copy
prop_flags (bool, optional) – if True, propagate calibration flags to data flags and doesn’t use flagged gains. Otherwise, uses flagged gains and does not propagate calibration flags to data flags.
Dterm_cal (bool, optional) – Calibrate the off-diagonal terms in the Jones matrix if present in uvcal. Default is False. Currently not implemented.
flip_gain_conj (bool, optional) – This function uses the UVData ant_1_array and ant_2_array to specify the antennas in the UVCal object. By default, the conjugation convention, which follows the UVData convention (i.e. ant2 - ant1), is that the applied gain = ant1_gain * conjugate(ant2_gain). If the other convention is required, set flip_gain_conj=True.
delay_convention (str, optional) – Exponent sign to use in conversion of ‘delay’ to ‘gain’ cal_type if the input uvcal is not inherently ‘gain’ cal_type. Default to ‘minus’.
undo (bool, optional) – If True, undo the provided calibration. i.e. apply the calibration with flipped gain_convention. Flag propagation rules apply the same.
time_check (bool) – Option to check that times match between the UVCal and UVData objects if UVCal has a single time or time range. Times are always checked if UVCal has multiple times.
ant_check (bool) – Option to check that all antennas with data on the UVData object have calibration solutions in the UVCal object. If this option is set to False, uvcalibrate will proceed without erroring and data for antennas without calibrations will be flagged.
freq_range_check (bool) – Option to check that frequency ranges on the UVCal object matches the channel frequencies given in the UVData object for a given spectral window. Only applicable for wide-band UVCal objects, default is True.
uvc_pol_convention (str, {“sum”, “avg”}, optional) – The convention for how instrumental polarizations (e.g. XX and YY) are assumed to have been converted to Stokes parameters in
uvcal. Options are ‘sum’ and ‘avg’, corresponding to I=XX+YY and I=(XX+YY)/2 (for linear instrumental polarizations) respectively. Only required ifpol_conventionis not set onuvcalitself. If it is not specified and is not set on the UVCal object, a deprecation warning is raised (will be an error in the future).uvd_pol_convention (str, {“sum”, “avg”}, optional) – The same polarization convention as
uvc_pol_convention, except that this represents either the convention that has been adopted inuvdata(in the case thatundo=True), or the convention that is desired for the resultingUVDataobject (ifundo=False).
- Returns:
UVData, optional – Returns if not inplace
- pyuvdata.utils.apply_uvflag(uvd, uvf, *, inplace=True, unflag_first=False, flag_missing=True, force_pol=True)[source]
Apply flags from a UVFlag to a UVData instantiation.
Note that if uvf.Nfreqs or uvf.Ntimes is 1, it will broadcast flags across that axis.
- Parameters:
uvd (UVData object) – UVData object to add flags to.
uvf (UVFlag object) – A UVFlag object in flag mode.
inplace (bool) – If True overwrite flags in uvd, otherwise return new object
unflag_first (bool) – If True, completely unflag the UVData before applying flags. Else, OR the inherent uvd flags with uvf flags.
flag_missing (bool) – If input uvf is a baseline type and antpairs in uvd do not exist in uvf, flag them in uvd. Otherwise leave them untouched.
force_pol (bool) – If True, broadcast flags to all polarizations if they do not match. Only works if uvf.Npols == 1.
- Returns:
UVData – If not inplace, returns new UVData object with flags applied
- pyuvdata.utils.baseline_to_antnums(baseline, *, Nants_telescope: int, use_miriad_convention: bool = False)[source]
Get the antenna numbers corresponding to a given baseline number.
- Parameters:
baseline (int or array_like of ints) – baseline number
Nants_telescope (int) – number of antennas
use_miriad_convention (bool) – Option to use the MIRIAD convention where BASELINE id is bl = 256 * ant1 + ant2 if ant2 < 256, otherwise bl = 2048 * ant1 + ant2 + 2**16. Note antennas should be 1-indexed (start at 1, not 0)
- Returns:
int or array_like of int – first antenna number(s)
int or array_like of int – second antenna number(s)
- pyuvdata.utils.antnums_to_baseline(ant1, ant2, *, Nants_telescope, attempt256=False, use_miriad_convention=False)[source]
Get the baseline number corresponding to two given antenna numbers.
- Parameters:
ant1 (int or array_like of int) – first antenna number
ant2 (int or array_like of int) – second antenna number
Nants_telescope (int) – number of antennas
attempt256 (bool) – Option to try to use the older 256 standard used in many uvfits files. If there are antenna numbers >= 256, the 2048 standard will be used unless there are antenna numbers >= 2048 or Nants_telescope > 2048. In that case, the 2147483648 standard will be used. Default is False.
use_miriad_convention (bool) – Option to use the MIRIAD convention where BASELINE id is bl = 256 * ant1 + ant2 if ant2 < 256, otherwise bl = 2048 * ant1 + ant2 + 2**16. Note antennas should be 1-indexed (start at 1, not 0)
- Returns:
int or array of int – baseline number corresponding to the two antenna numbers.
- pyuvdata.utils.LatLonAlt_from_XYZ(xyz, *, frame='ITRS', ellipsoid=None, check_acceptability=True)[source]
Calculate lat/lon/alt from ECEF x,y,z.
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
frame (str) – Coordinate frame of xyz. Valid options are ITRS (default) or MCMF.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF.
check_acceptability (bool) – Flag to check XYZ coordinates are reasonable.
- Returns:
latitude (ndarray or float) – latitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
longitude (ndarray or float) – longitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
altitude (ndarray or float) – altitude, numpy array (if Npts > 1) or value (if Npts = 1) in meters
- pyuvdata.utils.XYZ_from_LatLonAlt(latitude, longitude, altitude, *, frame='ITRS', ellipsoid=None)[source]
Calculate ECEF x,y,z from lat/lon/alt values.
- Parameters:
latitude (ndarray or float) – latitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
longitude (ndarray or float) – longitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
altitude (ndarray or float) – altitude, numpy array (if Npts > 1) or value (if Npts = 1) in meters
frame (str) – Coordinate frame of xyz. Valid options are ITRS (default) or MCMF.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF.
- Returns:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
- pyuvdata.utils.rotECEF_from_ECEF(xyz, longitude)[source]
Get rotated ECEF positions such that the x-axis goes through the longitude.
Miriad and uvfits expect antenna positions in this frame (with longitude of the array center/telescope location)
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
longitude (float) – longitude in radians to rotate coordinates to (usually the array center/telescope location).
- Returns:
ndarray of float – Rotated ECEF coordinates, shape (Npts, 3).
- pyuvdata.utils.ECEF_from_rotECEF(xyz, longitude)[source]
Calculate ECEF from a rotated ECEF (Inverse of rotECEF_from_ECEF).
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with rotated ECEF x,y,z coordinates.
longitude (float) – longitude in radians giving the x direction of the rotated coordinates (usually the array center/telescope location).
- Returns:
ndarray of float – ECEF coordinates, shape (Npts, 3).
- pyuvdata.utils.ENU_from_ECEF(xyz, *, center_loc=None, latitude=None, longitude=None, altitude=None, frame='ITRS', ellipsoid=None)[source]
Calculate local ENU (east, north, up) coordinates from ECEF coordinates.
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
center_loc (EarthLocation or MoonLocation object) – An EarthLocation or MoonLocation object giving the center of the ENU coordinates. Either center_loc or all of latitude, longitude, altitude must be passed.
latitude (float) – Latitude of center of ENU coordinates in radians. Not used if center_loc is passed.
longitude (float) – Longitude of center of ENU coordinates in radians. Not used if center_loc is passed.
altitude (float) – Altitude of center of ENU coordinates in radians. Not used if center_loc is passed.
frame (str) – Coordinate frame of xyz and center of ENU coordinates. Valid options are ITRS (default) or MCMF. Not used if center_loc is passed.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF. Not used if center_loc is passed.
- Returns:
ndarray of float – numpy array, shape (Npts, 3), with local ENU coordinates
- pyuvdata.utils.ECEF_from_ENU(enu, center_loc=None, latitude=None, longitude=None, altitude=None, frame='ITRS', ellipsoid=None)[source]
Calculate ECEF coordinates from local ENU (east, north, up) coordinates.
- Parameters:
enu (ndarray of float) – numpy array, shape (Npts, 3), with local ENU coordinates.
center_loc (EarthLocation or MoonLocation object) – An EarthLocation or MoonLocation object giving the center of the ENU coordinates. Either center_loc or all of latitude, longitude, altitude must be passed.
latitude (float) – Latitude of center of ENU coordinates in radians. Not used if center_loc is passed.
longitude (float) – Longitude of center of ENU coordinates in radians. Not used if center_loc is passed.
altitude (float) – Altitude of center of ENU coordinates in radians. Not used if center_loc is passed.
frame (str) – Coordinate frame of xyz and center of ENU coordinates. Valid options are ITRS (default) or MCMF. Not used if center_loc is passed.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF. Not used if center_loc is passed.
- Returns:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
- pyuvdata.utils.polstr2num(pol: str | Iterable[str], *, x_orientation: str | None = None)[source]
Convert polarization str to number according to AIPS Memo 117.
Prefer ‘pI’, ‘pQ’, ‘pU’ and ‘pV’ to make it clear that these are pseudo-Stokes, not true Stokes, but also supports ‘I’, ‘Q’, ‘U’, ‘V’.
- Parameters:
pol (str) – polarization string
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings. See corresonding parameter on UVData for more details.
- Returns:
int – Number corresponding to string
- Raises:
ValueError – If the pol string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.polnum2str(num, *, x_orientation=None)[source]
Convert polarization number to str according to AIPS Memo 117.
Uses ‘pI’, ‘pQ’, ‘pU’ and ‘pV’ to make it clear that these are pseudo-Stokes, not true Stokes
- Parameters:
num (int) – polarization number
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to convert to E/N strings. See corresonding parameter on UVData for more details.
- Returns:
str – String corresponding to polarization number
- Raises:
ValueError – If the polarization number cannot be converted to a polarization string.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.jstr2num(jstr, *, x_orientation=None)[source]
Convert jones polarization str to number according to calfits memo.
- Parameters:
jstr (str or array_like of str) – antenna (jones) polarization string(s) to convert.
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings. See corresonding parameter on UVData for more details.
- Returns:
int or list of int – antenna (jones) polarization number(s) corresponding to the input string(s)
- Raises:
ValueError – If the jones string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.jnum2str(jnum, *, x_orientation=None)[source]
Convert jones polarization number to str according to calfits memo.
- Parameters:
num (int or array_like of int) – antenna (jones) polarization number(s) to convert to strings
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to convert to E/N strings. See corresonding parameter on UVData for more details.
- Returns:
str or list of str – antenna (jones) polarization string(s) corresponding to number
- Raises:
ValueError – If the jones polarization number cannot be converted to a jones polarization string.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.conj_pol(pol)[source]
Return the polarization for the conjugate baseline.
For example, (1, 2, ‘xy’) = conj(2, 1, ‘yx’). The returned polarization is determined by assuming the antenna pair is reversed in the data, and finding the correct polarization correlation which will yield the requested baseline when conjugated. Note this means changing the polarization for linear cross-pols, but keeping auto-pol (e.g. xx) and Stokes the same.
- Parameters:
pol (str or int) – Polarization string or integer.
- Returns:
cpol (str or int) – Polarization as if antennas are swapped (type matches input)
- pyuvdata.utils.x_orientation_pol_map(x_orientation: str) dict[source]
Return map from “x” and “y” pols to “e” and “n” based on x_orientation.
- Parameters:
x_orientation (str) – String giving the x_orientation, one of “east” or “north”.
- Returns:
dict – Dictionary mapping “x” and “y” pols to “e” and “n” based on x_orientation.
- pyuvdata.utils.parse_polstr(polstr, *, x_orientation=None)[source]
Parse a polarization string and return pyuvdata standard polarization string.
See utils.POL_STR2NUM_DICT for options.
- Parameters:
polstr (str) – polarization string
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings. See corresonding parameter on UVData for more details.
- Returns:
str – AIPS Memo 117 standard string
- Raises:
ValueError – If the pol string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.parse_jpolstr(jpolstr, *, x_orientation=None)[source]
Parse a Jones polarization string and return pyuvdata standard jones string.
See utils.JONES_STR2NUM_DICT for options.
- Parameters:
jpolstr (str) – Jones polarization string
- Returns:
str – calfits memo standard string
- Raises:
ValueError – If the jones string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.get_lst_for_time(jd_array=None, *, telescope_loc=None, latitude=None, longitude=None, altitude=None, astrometry_library=None, frame='itrs', ellipsoid=None)[source]
Get the local apparent sidereal time for a set of jd times at an earth location.
This function calculates the local apparent sidereal time (LAST), given a UTC time and a position on the Earth, using either the astropy or NOVAS libraries. It is important to note that there is an apporoximate 20 microsecond difference between the two methods, presumably due to small differences in the apparent reference frame. These differences will cancel out when calculating coordinates in the TOPO frame, so long as apparent coordinates are calculated using the same library (i.e., astropy or NOVAS). Failing to do so can introduce errors up to ~1 mas in the horizontal coordinate system (i.e., AltAz).
- Parameters:
jd_array (ndarray of float) – JD times to get lsts for.
telescope_loc (tuple or EarthLocation or MoonLocation) – Alternative way of specifying telescope lat/lon/alt, either as a 3-element tuple with latitude and longitude in degrees, or as an astropy EarthLocation (or lunarsky MoonLocation). Cannot supply both telescope_loc and latitute, longitude, or altitude.
latitude (float) – Latitude of location to get lst for in degrees. Cannot specify both latitute and telescope_loc.
longitude (float) – Longitude of location to get lst for in degrees. Cannot specify both longitude and telescope_loc.
altitude (float) – Altitude of location to get lst for in meters. Cannot specify both altitude and telescope_loc.
astrometry_library (str) – Library used for running the LST calculations. Allowed options are ‘erfa’ (which uses the pyERFA), ‘novas’ (which uses the python-novas library), and ‘astropy’ (which uses the astropy utilities). Default is erfa unless the telescope_location is a MoonLocation object, in which case the default is astropy.
frame (str) – Reference frame for latitude/longitude/altitude. Options are itrs (default) or mcmf. Not used if telescope_loc is an EarthLocation or MoonLocation object.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf. Not used if telescope_loc is an EarthLocation or MoonLocation object.
- Returns:
ndarray of float – LASTs in radians corresponding to the jd_array.
- pyuvdata.utils.uvw_track_generator(*, lon_coord=None, lat_coord=None, coord_frame='icrs', coord_epoch=None, coord_type='sidereal', time_array=None, telescope_loc=None, telescope_frame='itrs', ellipsoid=None, antenna_positions=None, antenna_numbers=None, ant_1_array=None, ant_2_array=None, uvw_array=None, force_postive_u=False)[source]
Calculate uvw coordinates (among other values) for a given position on the sky.
This function is meant to be a user-friendly wrapper around several pieces of code for effectively simulating a track.
- Parameters:
lon_coord (float or ndarray of float) – Longitudinal (e.g., RA) coordinates, units of radians. Must match the same shape as lat_coord.
lat_coord (float or ndarray of float) – Latitudinal (e.g., Dec) coordinates, units of radians. Must match the same shape as lon_coord.
coord_frame (string) – The requested reference frame for the output coordinates, can be any frame that is presently supported by astropy.
coord_epoch (float or str or Time object, optional) – Epoch for ref_frame, nominally only used if converting to either the FK4 or FK5 frames, in units of fractional years. If provided as a float and the ref_frame is an FK4-variant, value will assumed to be given in Besselian years (i.e., 1950 would be ‘B1950’), otherwise the year is assumed to be in Julian years.
coord_type (str) –
- Type of source to calculate coordinates for. Must be one of:
“sidereal” (fixed RA/Dec), “ephem” (RA/Dec that moves with time), “driftscan” (fixed az/el position), “unprojected” (alias for “driftscan” with (Az, Alt) = (0 deg, 90 deg)).
time_array (ndarray of float or Time object) – Times for which the apparent coordinates were calculated, in UTC JD. Must match the shape of lon_coord and lat_coord.
telescope_loc (array-like of floats or EarthLocation or MoonLocation) – ITRF latitude, longitude, and altitude (rel to sea-level) of the phase center of the array. Can either be provided as an astropy EarthLocation, a lunarsky Moonlocation, or a tuple of shape (3,) containing (in order) the latitude, longitude, and altitude for a position on Earth in units of degrees, degrees, and meters, respectively.
telescope_frame (str, optional) – Reference frame for latitude/longitude/altitude. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
antenna_positions (ndarray of float) – List of antenna positions relative to array center in ECEF coordinates, required if not providing uvw_array. Shape is (Nants, 3).
antenna_numbers (ndarray of int, optional) – List of antenna numbers, ordered in the same way as antenna_positions (e.g., antenna_numbers[0] should given the number of antenna that resides at ECEF position given by antenna_positions[0]). Shape is (Nants,), requred if supplying ant_1_array and ant_2_array.
ant_1_array (ndarray of int, optional) – Antenna number of the first antenna in the baseline pair, for all baselines Required if not providing uvw_array, shape is (Nblts,). If not supplied, then the method will automatically fill in ant_1_array with all unique antenna pairings for each time/position.
ant_2_array (ndarray of int, optional) – Antenna number of the second antenna in the baseline pair, for all baselines Required if not providing uvw_array, shape is (Nblts,). If not supplied, then the method will automatically fill in ant_2_array with all unique antenna pairings for each time/position.
uvw_array (ndarray of float, optional) – Array of baseline coordinates (in ENU), required if not deriving new coordinates from antenna positions. Setting this value will will cause antenna positions to be ignored. Shape is (Nblts, 3).
force_positive_u (bool, optional) – If set to true, then forces the conjugation of each individual baseline to be set such that the uvw coordinates land on the positive-u side of the uv-plane. Default is False.
- Returns:
obs_dict (dict) –
- Dictionary containing the results of the simulation, which includes:
”uvw” the uvw-coordinates (meters), “app_ra” apparent RA of the sources (radians), “app_dec” apparent Dec of the sources (radians), “frame_pa” ngle between apparent north and coord_frame north (radians), “lst” local apparent sidereal time (radians), “site_loc” EarthLocation or MoonLocation for the telescope site.
- pyuvdata.utils.collapse(arr, alg, *, weights=None, axis=None, return_weights=False, return_weights_square=False)[source]
Parent function to collapse an array with a given algorithm.
- Parameters:
arr (array) – Input array to process.
alg (str) – Algorithm to use. Must be defined in this function with corresponding subfunction above.
weights (ndarray, optional) – weights for collapse operation (e.g. weighted mean). NOTE: Some subfunctions do not use the weights. See corresponding doc strings.
axis (int or tuple, optional) – Axis or axes to collapse. Default is all.
return_weights (bool) – Whether to return sum of weights.
return_weights_square (bool) – Whether to return the sum of the squares of the weights. Default is False.
Polarization Dictionaries
We also define some useful dictionaries for mapping polarizations:
pyuvdata.utils.POL_STR2NUM_DICT: maps visibility polarization strings to polarization integers
pyuvdata.utils.POL_NUM2STR_DICT: maps visibility polarization integers to polarization strings
pyuvdata.utils.JONES_STR2NUM_DICT: maps calibration polarization strings to polarization integers
pyuvdata.utils.JONES_NUM2STR_DICT: maps calibration polarization strings to polarization integers
pyuvdata.utils.CONJ_POL_DICT: maps how visibility polarizations change when antennas are swapped (visibilities are conjugated)
pyuvdata.utils.XORIENTMAP: maps x_orientation strings to cannonical names
Utils subpackage
This gives the full documentation of all functions inside the utils subpackage. Unless they are also listed above, these functions must be imported using their full subpackage/submodule path.
Note that we are also listing private functions here (functions that start with an underscore). While they are listed here, they are not considered part of the public API, so they can change without notice. If you find that you need to rely one of them let us know in a github issue and we can consider making it part of the public API.
File I/O Utility Functions
Antenna position files
Read antenna position files.
- pyuvdata.utils.io.antpos.read_antpos_csv(antenna_positions_file)[source]
Interpret an antenna positions file.
- Parameters:
antenna_positions_file (str) – Name of the antenna_positions_file, which is assumed to be in DATA_PATH. Should be a csv file with the following columns:
“name”: antenna names
“number”: antenna numbers
“x”: x ECEF coordinate relative to the telescope location.
“y”: y ECEF coordinate relative to the telescope location.
“z”: z ECEF coordinate relative to the telescope location.
- Returns:
antenna_names (array of str) – Antenna names.
antenna_names (array of int) – Antenna numbers.
antenna_positions (array of float) – Antenna positions in ECEF relative to the telescope location.
FHD files
Utilities for working with FHD files.
- pyuvdata.utils.io.fhd.fhd_filenames(*, vis_files: list[str] | ndarray | str | None = None, params_file: str | None = None, obs_file: str | None = None, flags_file: str | None = None, layout_file: str | None = None, settings_file: str | None = None, cal_file: str | None = None)[source]
Check the FHD input files for matching prefixes and folders.
- Parameters:
vis_files (str or array-like of str, optional) – FHD visibility save file names, can be data or model visibilities.
params_file (str) – FHD params save file name.
obs_file (str) – FHD obs save file name.
flags_file (str) – FHD flag save file name.
layout_file (str) – FHD layout save file name.
layout_file (str) – FHD layout save file name.
settings_file (str) – FHD settings text file name.
cal_file (str) – FHD cal save file name.
- Returns:
A list of file basenames to be used in the object filename attribute.
- pyuvdata.utils.io.fhd.get_fhd_history(settings_file, *, return_user=False)[source]
Small function to get the important history from an FHD settings text file.
Includes information about the command line call, the user, machine name and date
- Parameters:
settings_file (str) – FHD settings file name
return_user (bool) – optionally return the username who ran FHD
- Returns:
history (str) – string of history extracted from the settings file
user (str) – Only returned if return_user is True
- pyuvdata.utils.io.fhd.get_fhd_layout_info(*, layout_file, telescope_name, latitude, longitude, altitude, obs_tile_names, run_check_acceptability=True)[source]
Get the telescope and antenna positions from an FHD layout file.
- Parameters:
layout_file (str) – FHD layout file name
telescope_name (str) – Telescope name
latitude (float) – telescope latitude in radians
longitude (float) – telescope longitude in radians
altitude (float) – telescope altitude in meters
obs_tile_names (array-like of str) – Tile names from the bl_info structure inside the obs structure. Only used if telescope_name is “mwa”.
run_check_acceptability (bool) – Option to check acceptable range of the telescope locations.
- Returns:
dict – A dictionary of parameters from the layout file to assign to the object. The keys are:
telescope_xyz : Telescope location in ECEF, shape (3,) (float)
Nants_telescope : Number of antennas in the telescope (int)
- antenna_postionsAntenna positions in relative ECEF,
shape (Nants_telescope, 3) (float)
antenna_names : Antenna names, length Nants_telescope (list of str)
antenna_numbers : Antenna numbers, shape (Nants_telescope,) (array of int)
gst0 : Greenwich sidereal time at midnight on reference date. (float)
earth_omega : Earth’s rotation rate in degrees per day. (float)
dut1 : DUT1 (google it) AIPS 117 calls it UT1UTC. (float)
timesys : Time system (should only ever be UTC). (str)
diameters : Antenna diameters in meters. shape (Nants_telescope,) (float)
extra_keywords : Dictionary of extra keywords to preserve on the object.
FITS files
Utilities for working with FITS files.
- pyuvdata.utils.io.fits._gethduaxis(hdu, axis)[source]
Make axis arrays for fits files.
- Parameters:
hdu (astropy.io.fits HDU object) – The HDU to make an axis array for.
axis (int) – The axis number of interest (1-based).
- Returns:
ndarray of float – Array of values for the specified axis.
- pyuvdata.utils.io.fits._indexhdus(hdulist)[source]
Get a dict of table names and HDU numbers from a FITS HDU list.
- Parameters:
hdulist (list of astropy.io.fits HDU objects) – List of HDUs to get names for
- Returns:
dict – dictionary with table names as keys and HDU number as values.
- pyuvdata.utils.io.fits._get_extra_keywords(header, *, keywords_to_skip=None)[source]
Get any extra keywords and return as dict.
- Parameters:
header (FITS header object) – header object to get extra_keywords from.
keywords_to_skip (list of str) – list of keywords to not include in extra keywords in addition to standard FITS keywords.
- Returns:
dict – dict of extra keywords.
HDF5 files
Utilities for working with HDF5 files.
- pyuvdata.utils.io.hdf5._check_complex_dtype(dtype)[source]
Check that a specified custom datatype conforms to UVH5 standards.
According to the UVH5 spec, the data type for the data array must be a compound datatype with an “r” field and an “i” field. Additionally, both datatypes must be the same (e.g., “<i4”, “<r8”, etc.).
- Parameters:
dtype (numpy dtype) – A numpy dtype object with an “r” field and an “i” field.
- Returns:
None
- Raises:
ValueError – This is raised if dtype is not a numpy dtype, if the dtype does not have an “r” field and an “i” field, or if the “r” field and “i” fields have different types.
- pyuvdata.utils.io.hdf5._get_slice_len(s, axlen)[source]
Get length of a slice s into array of len axlen.
- Parameters:
s (slice object) – Slice object to index with
axlen (int) – Length of axis s slices into
- Returns:
int – Length of slice object
- pyuvdata.utils.io.hdf5._get_dset_shape(dset, indices)[source]
Given a tuple of indices, determine the indexed array shape.
- Parameters:
dset (numpy array or h5py dataset) – A numpy array or a reference to an HDF5 dataset on disk. Requires the dset.shape attribute exists and returns a tuple.
indices (tuple) – A tuple with the indices to extract along each dimension of dset. Each element should contain a list of indices, a slice element, or a list of slice elements that will be concatenated after slicing. For data arrays with 4 dimensions, the second dimension (the old spw axis) should not be included because it can only be length one.
- Returns:
tuple – a tuple with the shape of the indexed array
tuple – a tuple with indices used (will be different than input if dset has 4 dimensions and indices has 3 dimensions)
- pyuvdata.utils.io.hdf5._index_dset(dset, indices, *, input_array=None)[source]
Index a UVH5 data, flags or nsamples h5py dataset to get data or overwrite data.
If no input_array is passed, this function extracts the data at the indices and returns it. If input_array is passed, this function replaced the data at the indices with the input array.
- Parameters:
dset (h5py dataset) – A reference to an HDF5 dataset on disk.
indices (tuple) – A tuple with the indices to extract along each dimension of dset. Each element should contain a list of indices, a slice element, or a list of slice elements that will be concatenated after slicing. Indices must be provided such that all dimensions can be indexed simultaneously. This should have a length equal to the length of the dset, with an exception to support the old array shape for uvdata arrays (in that case the dset is length 4 but the second dimension is shallow, so only three indices need to be passed).
input_array (ndarray, optional) – Array to be copied into the dset at the indices. If not provided, the data in the dset is indexed and returned.
- Returns:
ndarray or None – The indexed dset if the input_array parameter is not used.
Notes
This makes and fills an empty array with dset indices. For trivial indexing, (e.g. a trivial slice), constructing a new array and filling it is suboptimal over direct indexing, e.g. dset[indices]. This function specializes in repeated slices over the same axis, e.g. if indices is [[slice(0, 5), slice(10, 15), …], …, ]
- pyuvdata.utils.io.hdf5._read_complex_astype(dset, indices, dtype_out=<class 'numpy.complex64'>)[source]
Read the given data set of a specified type to floating point complex data.
- Parameters:
dset (h5py dataset) – A reference to an HDF5 dataset on disk.
indices (tuple) – The indices to extract. Should be either lists of indices or numpy slice objects.
dtype_out (str or numpy dtype) – The datatype of the output array. One of (complex, np.complex64, np.complex128). Default is np.complex64 (single-precision real and imaginary floats).
- Returns:
output_array (ndarray) – The array referenced in the dataset cast to complex values.
- Raises:
ValueError – This is raised if dtype_out is not an acceptable value.
- pyuvdata.utils.io.hdf5._write_complex_astype(data, dset, indices)[source]
Write floating point complex data as a specified type.
- Parameters:
data (ndarray) – The data array to write out. Should be a complex-valued array that supports the .real and .imag attributes for accessing real and imaginary components.
dset (h5py dataset) – A reference to an HDF5 dataset on disk.
indices (tuple) – A 3-tuple representing indices to write data to. Should be either lists of indices or numpy slice objects. For data arrays with 4 dimensions, the second dimension (the old spw axis) should not be included because it can only be length one.
- Returns:
None
- pyuvdata.utils.io.hdf5._get_compression(compression)[source]
Get the HDF5 compression and compression options to use.
- Parameters:
compression (str) – HDF5 compression specification or “bitshuffle”.
- Returns:
compression_use (str) – HDF5 compression specification
compression_opts (tuple) – HDF5 compression options
- class pyuvdata.utils.io.hdf5.HDF5Meta(path: str | Path | File | Group)[source]
A base class for fast read-only interface to our HDF5 file metadata.
This class is just a really thin wrapper over our HDF5 files that makes it easier to read in parts of the metadata at a time. This makes it much faster to perform small tasks where simple metadata is required, rather than reading in the whole header.
All metadata is available as attributes, through
__getattr__magic. Thus, accessing eg.obj.freq_arraywill go and get the frequencies directly from the file, and store them in memory.Anything that is read in is stored in memory so the second access is much faster. However, the memory can be released simply by deleting the attribute (it can be accessed again, and the data will be re-read).
- Parameters:
path (str or Path) – The filename to read from.
Notes
To check if a particular attribute is available, use
hasattr(obj, attr). Many attributes will not show up dynamically in an interpreter, because they are gotten dynamically from the file.- _defaults = {}
- _string_attrs = frozenset({'instrument', 'telescope_name', 'x_orientation'})
- _int_attrs = frozenset({'Nants_telescope'})
- _float_attrs = frozenset({})
- _bool_attrs = frozenset({})
- property header: Group
Get the header group.
- property datagrp: Group
Get the header group.
- get_transactional(item: str, cache: bool = True) Any[source]
Get an attribute from the metadata but close the file object afterwards.
Using this method is safer than direct attribute access when dealing with many files.
- Parameters:
item – The attribute to get.
cache – Whether to cache the attribute in the object so that the next access is faster.
- property telescope_location_lat_lon_alt: tuple[float, float, float]
The telescope location in latitude, longitude, and altitude, in degrees.
- property telescope_location_lat_lon_alt_degrees: tuple[float, float, float]
The telescope location in latitude, longitude, and altitude, in degrees.
- property antpos_enu: ndarray
The antenna positions in ENU coordinates, in meters.
- property telescope_frame: str
The telescope frame.
- property ellipsoid: str
The reference ellipsoid to use for lunar coordinates.
- property telescope_location_obj
The telescope location object.
- property telescope_location
The telescope location in ECEF coordinates, in meters.
- property antenna_names: list[str]
The antenna names in the file.
- property mount_type: list[str]
The antenna names in the file.
- property feed_array: ndarray[str]
The antenna names in the file.
- property feed_angle: ndarray[float]
The antenna names in the file.
- property x_orientation: str
The x_orientation in the file.
- property extra_keywords: dict
The extra_keywords from the file.
- property phase_center_catalog: dict | None
Dictionary of phase centers.
- property telescope
A Telescope object created from the data.
Measurement Set files
Utilities for working with MeasurementSet files.
- pyuvdata.utils.io.ms._parse_pyuvdata_frame_ref(frame_name, epoch_val, *, raise_error=True)[source]
Interpret a UVData pair of frame + epoch into a CASA frame name.
- Parameters:
frame_name (str) – Name of the frame. Typically matched to the UVData attribute phase_center_frame.
epoch_val (float) – Epoch value for the given frame, in Julian years unless frame_name=”FK4”, in which case the value is in Besselian years. Typically matched to the UVData attribute phase_center_epoch.
raise_error (bool) – Whether to raise an error if the name has no match. Default is True, if set to false will raise a warning instead.
- Returns:
ref_name (str) – Name of the CASA-based spatial coordinate reference frame.
- Raises:
ValueError – If the provided coordinate frame and/or epoch value has no matching counterpart to those supported in CASA.
- pyuvdata.utils.io.ms._get_time_scale(ms_table, *, raise_error=False)[source]
Read time scale from TIME column in an MS table.
- Parameters:
ms_table (table) – Handle for the MeasurementSet table that contains a “TIME” column.
raise_error (bool) – Whether to raise an error if the name has no match. Default is True, if set to false will raise a warning instead.
- Returns:
time_scale_name (str) – Name of the time scale.
- Raises:
ValueError – If the CASA time scale frame does not match the known supported list of time scales for astropy.
- pyuvdata.utils.io.ms._parse_casa_frame_ref(ref_name, *, raise_error=True)[source]
Interpret a CASA frame into an astropy-friendly frame and epoch.
- Parameters:
ref_name (str) – Name of the CASA-based spatial coordinate reference frame.
raise_error (bool) – Whether to raise an error if the name has no match. Default is True, if set to false will raise a warning instead.
- Returns:
frame_name (str) – Name of the frame. Typically matched to the UVData attribute phase_center_frame.
epoch_val (float) – Epoch value for the given frame, in Julian years unless frame_name=”FK4”, in which case the value is in Besselian years. Typically matched to the UVData attribute phase_center_epoch.
- Raises:
ValueError – If the CASA coordinate frame does not match the known supported list of frames for CASA.
NotImplementedError – If using a CASA coordinate frame that does not yet have a corresponding astropy frame that is supported by pyuvdata.
- pyuvdata.utils.io.ms.read_ms_antenna(filepath, check_frame=True)[source]
Read Measurement Set ANTENNA table.
- Parameters:
filepath (str) – path to MS (without ANTENNA suffix)
check_frame (bool) – If set to True and the “telescope_frame” keyword is found within the Measurement Set, check that the frame is one supported by pyuvdata (and if not, an error is raised). Currently supported frames include ITRS/ITRF and MCMF.
- Returns:
ant_dict (dict) – A dictionary with keys that map to columns of the MS, including “antenna_names” (list of type string, shape (Nants_telescope,)), “station_names” (list of type string, shape (Nants_telescope,)), “antenna_numbers” (ndarray of type int, shape (Nants_telescope,)), “antenna_diameters” (ndarray of type float, shape (Nants_telescope,)), “telescope_frame” (str), “telescope_ellipsoid” (str), and “antenna_positions” (ndarray of type float, shape (Nants_telescope, 3)).
- Raises:
ValueError – If check_frame=True and “telescope_frame” does not match to a supported type.
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_antenna(filepath, uvobj=None, *, antenna_numbers=None, antenna_names=None, antenna_positions=None, antenna_diameters=None, antenna_mount=None, telescope_location=None, telescope_frame=None, telescope_ellipsoid=None)[source]
Write out the antenna information into a CASA table.
- Parameters:
filepath (str) – Path to MS (without ANTENNA suffix).
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have a telescope parameter with parameters that match by name to the other keywords required here (with the exception of telescope_frame and telescope_ellipsoid, which are derived from the telescope.location UVParameter).
antenna_numbers (ndarray) – Required if uvobj not provided, antenna numbers for all antennas of the telescope, dtype int and shape (Nants_telescope,).
antenna_names (list) – Required if uvobj not provided, antenna names for all antennas of the telescope. List should be length Nants_telescope, and contain elements of type str.
antenna_positions (ndarray) – Required if uvobj not provided, ITRF/MCMF 3D position (in meters) of antennas relative to the array center, of dtype float with shape (Nants_telescope, 3).
antenna_diameters (ndarray) – Required if uvobj not provided, diameter (in meters) of each antenna, dtype float with shape (Nants_telescope,).
telescope_location (ndarray) – Required if uvobj not provided, ITRF/MCMF 3D location of the array center (in meters), dtype float with shape (3,).
telescope_frame (str) – Required if uvobj not provided, name of the frame in which the telescope positions are provided (typically “MCMF”, “ITRS”, or “ITRF”).
telescope_ellipsoid (str) – Required if uvobj not provided and telescope frame is “MCMF”, ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details).
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_data_description(filepath)[source]
Read Measurement Set DATA_DESCRIPTION table.
- Parameters:
filepath (str) – path to MS (without DATA_DESCRIPTION suffix)
- Returns:
data_desc_dict (dict) – A dictionary with keys that map to columns of the MS, used to index against other tables. These include “SPECTRAL_WINDOW_ID”, which match to given rows from the SPECTRAL_WINDOW table, “POLARIZATION_ID”, which match to given rows in the POLARIZATION table, and “FLAG_ROW”, which denotes of the ID in question has been flagged.
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_data_description(filepath, uvobj=None, nspws=None, flex_spw_polarization_array=None)[source]
Write out the data description information into a CASA table.
- Parameters:
filepath (str) – Path to MS (without DATA_DESCRIPTION suffix).
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here.
nspws (int) – Required if uvobj is not supplied, the total number of spectral windows to be recorded.
flex_spw_polarization_array (list of int) – Optional argument, required if trying to record a flex-pol data set, which denotes the polarization per spectral window, with length equal to nspws.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_field(filepath, return_phase_center_catalog=False)[source]
Read Measurement Set FIELD table.
- Parameters:
filepath (str) – path to MS (without FIELD suffix)
return_phase_center_catalog (bool) – Nominally this function will return a dict containing the columns of the table, but if set to True, instead a catalog will be supplied in the style of the UVData/UVCal phase_center_catalog parameters (further description of this parameter can be found in the class documentation).
- Returns:
field_dict (dict) – A dictionary with keys that map to columns of the MS, including “name” (field names, list of len Nfield with elements of type str), “ra” (RA in radians, ndarray of floats with shape (Nfield,)), “dec” (Dec in radians, ndarray of floats with shape (Nfield,)), “source_id” (row number in MS file, ndarray of ints with shape (Nfield,)), and “alt_id” (matching source ID number, ndarray of ints with shape (Nfield,)). Only given if return_phase_center_catalog=False.
phase_center_catalog (dict) – A catalog stylized like the UVData/UVCal phase_center_catalog parameters, with keys matching to the “alt_id”/source ID entries. Useful for plugging directly into the phase_center_catalog attribute of a UVBase object. Only supplied if return_phase_center_catalog=True.
field_map (dict) – A dict between row number (keys) and the source ID (values), which can be used to map the phase center ID array from the main MS table. Only supplied if return_phase_center_catalog=True.
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_field(filepath, uvobj=None, phase_center_catalog=None, time_val=None)[source]
Write out the field information into a CASA table.
- Parameters:
filepath (str) – path to MS (without FIELD suffix)
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here (with the exception of time_val, which is calculated from the time_array UVParameter).
phase_center_catalog (dict) – A catalog stylized like the UVData/UVCal phase_center_catalog parameters (see documentation of those classes for more details on expected structure). Required if uvobj is not supplied.
time_val (float) – Required if uvobj is not supplied, representative JD date for the catalog to be recorded into the MS file.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_history(filepath, pyuvdata_version_str, check_origin=False, raise_err=True)[source]
Read a CASA history table into a string for the uvdata history parameter.
Also stores messages column as a list for consistency with other uvdata types
- Parameters:
filepath (str) – Path to CASA table with history information.
pyuvdata_version_str (str) – String containing the version of pyuvdata used to read in the MS file, which is appended to the history if not previously encoded into the history table.
check_origin (bool) – If set to True, check whether the MS in question was created by pyuvdata, as determined by the history table. Default is False.
raise_err (bool) – Normally an error is raised if a HISTORY table cannot be found. However, if set to False, the history string containing just the pyuvdata version will be returned instead.
- Returns:
str – string encoding complete casa history table converted with a new line denoting rows and a ‘;’ denoting column breaks.
pyuvdata_written (bool) – boolean indicating whether or not this MS was written by pyuvdata. Only returned of check_origin=True.
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_history(filepath, history=None, uvobj=None)[source]
Parse the history into an MS history table.
If the history string contains output from _ms_hist_to_string, parse that back into the MS history table.
- Parameters:
filepath (str) – path to MS (without HISTORY suffix)
history (str) – Required if uvobj is not given, a string containing the history to be written.
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the history string.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_observation(filepath)[source]
Read Measurement Set OBSERVATION table.
- Parameters:
filepath (str) – path to MS (without OBSERVATION suffix)
- Returns:
obs_dict (dict) – A dictionary containing observation information, including “telescope_name” (str with the name of the telescope), “observer” (str of observer name), and if present, “telescope_location” (ndarray of floats and shape (3,) describing the ITRF/MCMF 3D location in meters of the array center).
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_observation(filepath, uvobj=None, *, telescope_name=None, telescope_location=None, observer=None)[source]
Write out the observation information into a CASA table.
- Parameters:
filepath (str) – path to MS (without OBSERVATION suffix)
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here (with the exception of telescope_frame, which is pulled from the telescope_location UVParameter).
telescope_name (str) – Required if uvobj not provided, name of the telescope.
telescope_location (ndarray) – Required if uvobj not provided, 3D location (in ITRF/MCMF coordinates in meters) of the array center.
observer (str) – Required if uvobj not provided, name of the observer.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_spectral_window(filepath)[source]
Read Measurement Set SPECTRAL_WINDOW table.
- Parameters:
filepath (str) – path to MS (without SPECTRAL_WINDOW suffix)
- Returns:
spw_dict (dict) – Dictionary containing spectral window information, including “chan_freq” (ndarray of float and shape (Nspws,), center frequencies of the channels), “chan_width” (ndarray of float and shape (Nspws,), channel bandwidths), “num_chan” (ndarray of int and shape (Nspws,), number of channels per window), and “row_idx” (list of length Nspws with int elements, containing the table row number for each window).
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_spectral_window(filepath=None, uvobj=None, *, freq_array=None, channel_width=None, spw_array=None, id_array=None)[source]
Write out the spectral information into a CASA table.
- Parameters:
filepath (str) – path to MS (without SPECTRAL_WINDOW suffix)
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here (with the exception of id_array, which is pulled from spw_array or flex_spw_id_array depending on the context).
freq_array (ndarray) – Required if uvobj not provided, frequency centers for each channel. Expected shape is (Nfreqs,), type float.
channel_width (ndarray or float) – Required if uvobj not provided, frequency centers for each channel. Expected to be of shape (Nfreqs,), type float.
spw_array (ndarray) – Required if uvobj not provided, ID numbers for spectral windows.
id_array (ndarray) – Map of how each entry in freq_array matches to the spectral windows in spw_array. Required if uvobj not provided.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_feed(filepath, select_ants=None)[source]
Read Measurement Set FEED table.
Note that this method is not yet implemented, and is a placeholder for future development.
- Parameters:
filepath (str) – path to MS (without FEED suffix)
- Returns:
feed_dict (dict) – Dictionary containing feed information.
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_feed(filepath, uvobj=None, nfeeds=None, nspws=None, feed_array=None, feed_angle=None, antenna_numbers=None, time_val=None)[source]
Write out the feed information into a CASA table.
- Parameters:
filepath (str) – path to MS (without FEED suffix)
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here.
nfeeds (int) – Required if uvobj not provided, number of feeds in the telescope for the object.
feed_array (ndarray of str) – Required if uvobj not provided, describes the polarization of each receiver, should be one of “X”, “Y”, “L”, or “R”. Shape (nants, nfeeds).
feed_angle (ndarray of float) – Required if uvobj not provided, orientation of the receiver with respect to the great circle at fixed azimuth, shape (nants, nfeeds).
antenna_numbers (array-like of int) – Required if uvobj not provided, antenna numbers for all antennas of the telescope, dtype int and shape (nants,).
time_val (float) – Required if uvobj is not supplied, representative JD date for the catalog to be recorded into the MS file.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_source(filepath)[source]
Read Measurement Set SOURCE table.
- Parameters:
filepath (str) – path to MS (without SOURCE suffix)
- Returns:
source_dict (dict) – A dictionary with keys matched to the source ID, and up to six values which map to specific keys in entries of the phase_center_catalog parameter found in UVData/UVCal objects. They are “cat_lon” (longitudinal position in radians), “cat_lat” (latitudinal position in radians), “cat_times” (JD dates of ephemeris entries), “cat_type” (type of catalog entry), “cat_pm_ra” (proper motion in RA), and “cat_pm_dec” (proper motion in Dec). These entries can be used to update keys in phase_center_catalog as derived from the FIELD table, which only has space to record a single RA/Dec coordinate plus reference frame information.
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_source(filepath, uvobj=None, time_default=None, phase_center_catalog=None)[source]
Write out the source information into a CASA table.
- Parameters:
filepath (str) – path to MS (without SOURCE suffix)
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here (with the exception of time_default, which is derived from the time_array UVParameter).
time_default (float) – Default time (in MJD seconds) to use for the catalog entries.
phase_center_catalog (dict) – A catalog stylized like the UVData/UVCal phase_center_catalog parameters (see documentation of those classes for more details on expected structure). Required if uvobj is not supplied.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_pointing(filepath)[source]
Read Measurement Set POINTING table.
Note that this method is not yet implemented, and is a placeholder for future development.
- Parameters:
filepath (str) – path to MS (without POINTING suffix)
- Returns:
pointing_dict (dict) – Dictionary containing pointing information.
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_pointing(filepath, uvobj=None, max_ant=None, integration_time=None, time_array=None)[source]
Write out the pointing information into a CASA table.
- Parameters:
filepath (str) – path to MS (without POINTING suffix)
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here (with the exception of max_ant, which is derived from from the antenna_numbers UVParameter).
max_ant (int) – Required if uvobj not provided, the highest-number antenna for the telescope.
integration_time (ndarray) – Required if uvobj not provided, integration time per entry. Ndarray of float, should match in shape to time_array.
time_array (ndarray) – Required if uvobj not provided, JD date of each entry. Ndarray of float, should match in shape to integration_time.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.read_ms_polarization(filepath)[source]
Read Measurement Set POLARIZATION table.
- Parameters:
filepath (str) – path to MS (without POLARIZATION suffix)
- Returns:
pol_dict (dict) – A dictionary with keys matched to the polarization ID, with values “corr_type” (ndarray of int, shape (Npols,), matched to polarization code) and “num_corr” (ndarray of int, shape (Npols,), tallying the total number of polarization entries per record).
- Raises:
FileNotFoundError – If no MS file is found with the provided name.
- pyuvdata.utils.io.ms.write_ms_polarization(filepath, *, pol_order=Ellipsis, uvobj=None, polarization_array=None, flex_pol=False)[source]
Write out the polarization information into a CASA table.
- Parameters:
filepath (str) – path to MS (without POLARIZATION suffix)
pol_order (slice or list of int) – Ordering of the polarization axis on write, only used if not writing a flex-pol dataset.
uvobj (UVBase (with matching parameters)) – Optional parameter, can be used to automatically fill the other required keywords for this function. Note that the UVBase object must have parameters that match by name to the other keywords required here (with the exception of flex_pol, which is derived from the presence of the flex_spw_polarization array UVParameter).
polarization_array (ndarray) – Required if uvobj not provided, array containing polarization ID codes (ndarray of dtype int and shape (Npols,) if flex_pol=False, otherwise shape (Nspws,)).
flex_pol (bool) – Required if uvobj not provided, whether or not the supplied polarization_array is derived for a flex-pol object (can contain duplicate entries of codes, with positions indexed against entries in the spectral window table). Default is False.
- Raises:
FileNotFoundError – If no main MS table is found when looking at filepath.
- pyuvdata.utils.io.ms.init_ms_file(filepath, make_model_col=False, make_corr_col=False)[source]
Create a skeleton MS dataset to fill.
- Parameters:
filepath (str) – Path to MS to be created.
make_model_col (bool) – If set to True, will construct a measurement set that contains a MODEL_DATA column in addition to the DATA column. Default is False.
make_model_col (bool) – If set to True, will construct a measurement set that contains a CORRECTED_DATA column in addition to the DATA column. Default is False.
- Returns:
ms_table (casacore Table) – Table object linked to the newly created MS file.
- pyuvdata.utils.io.ms.init_ms_cal_file(filename, delay_table=False)[source]
Create a skeleton MS calibration table to fill.
- Parameters:
filepath (str) – Path to MS table to be created.
delay_table (bool) – Set to False by default, which will create a MS table capable of storing complex gains. However, if set to True, the method will instead construct a table which can store delay information.
Applying UVFlags to other objects
Apply flags from a UVFlag to a UVData instantiation.
Note that if uvf.Nfreqs or uvf.Ntimes is 1, it will broadcast flags across that axis.
- Parameters:
uvd (UVData object) – UVData object to add flags to.
uvf (UVFlag object) – A UVFlag object in flag mode.
inplace (bool) – If True overwrite flags in uvd, otherwise return new object
unflag_first (bool) – If True, completely unflag the UVData before applying flags. Else, OR the inherent uvd flags with uvf flags.
flag_missing (bool) – If input uvf is a baseline type and antpairs in uvd do not exist in uvf, flag them in uvd. Otherwise leave them untouched.
force_pol (bool) – If True, broadcast flags to all polarizations if they do not match. Only works if uvf.Npols == 1.
- returns:
UVData – If not inplace, returns new UVData object with flags applied
Array collapse functions for flags
Utilities for collapsing arrays.
- pyuvdata.utils.array_collapse.mean_collapse(arr, *, weights=None, axis=None, return_weights=False, return_weights_square=False)[source]
Collapse by averaging data.
Bools are cast to integers prior to calculations.
This is similar to np.average, except it handles infs (by giving them zero weight) and zero weight axes (by forcing result to be inf with zero output weight).
- Parameters:
arr (array) – Input array to process.
weights (ndarray, optional) – weights for average. If none, will default to equal weight for all non-infinite data.
axis (int or tuple, optional) – Axis or axes to collapse (passed to np.sum). Default is all.
return_weights (bool) – Whether to return sum of weights.
return_weights_square (bool) – Whether to return the sum of the square of the weights. Default is False.
- pyuvdata.utils.array_collapse.absmean_collapse(arr, *, weights=None, axis=None, return_weights=False, return_weights_square=False)[source]
Collapse by averaging absolute value of data.
Bools are cast to integers prior to calculations.
- Parameters:
arr (array) – Input array to process.
weights (ndarray, optional) – weights for average. If none, will default to equal weight for all non-infinite data.
axis (int or tuple, optional) – Axis or axes to collapse (passed to np.sum). Default is all.
return_weights (bool) – Whether to return sum of weights.
return_weights_square (bool) – whether to return the sum of the squares of the weights. Default is False.
- pyuvdata.utils.array_collapse.quadmean_collapse(arr, *, weights=None, axis=None, return_weights=False, return_weights_square=False)[source]
Collapse by averaging in quadrature.
Bools are cast to integers prior to calculations.
- Parameters:
arr (array) – Input array to process.
weights (ndarray, optional) – weights for average. If none, will default to equal weight for all non-infinite data.
axis (int or tuple, optional) – Axis or axes to collapse (passed to np.sum). Default is all.
return_weights (bool) – Whether to return sum of weights.
return_weights_square (bool) – whether to return the sum of the squares of the weights. Default is False.
- pyuvdata.utils.array_collapse.or_collapse(arr, *, weights=None, axis=None, return_weights=False, return_weights_square=False)[source]
Collapse using OR operation.
- Parameters:
arr (array) – Input array to process.
weights (ndarray, optional) – NOT USED, but kept for symmetry with other collapsing functions.
axis (int or tuple, optional) – Axis or axes to collapse (take OR over). Default is all.
return_weights (bool) – Whether to return dummy weights array. NOTE: the dummy weights will simply be an array of ones
return_weights_square (bool) – NOT USED, but kept for symmetry with other collapsing functions.
- pyuvdata.utils.array_collapse.and_collapse(arr, *, weights=None, axis=None, return_weights=False, return_weights_square=False)[source]
Collapse using AND operation.
- Parameters:
arr (array) – Input array to process.
weights (ndarray, optional) – NOT USED, but kept for symmetry with other collapsing functions.
axis (int or tuple, optional) – Axis or axes to collapse (take AND over). Default is all.
return_weights (bool) – Whether to return dummy weights array. NOTE: the dummy weights will simply be an array of ones
return_weights_square (bool) – NOT USED, but kept for symmetry with other collapsing functions.
- pyuvdata.utils.array_collapse.collapse(arr, alg, *, weights=None, axis=None, return_weights=False, return_weights_square=False)[source]
Parent function to collapse an array with a given algorithm.
- Parameters:
arr (array) – Input array to process.
alg (str) – Algorithm to use. Must be defined in this function with corresponding subfunction above.
weights (ndarray, optional) – weights for collapse operation (e.g. weighted mean). NOTE: Some subfunctions do not use the weights. See corresponding doc strings.
axis (int or tuple, optional) – Axis or axes to collapse. Default is all.
return_weights (bool) – Whether to return sum of weights.
return_weights_square (bool) – Whether to return the sum of the squares of the weights. Default is False.
Functions for working with baseline numbers
Utilities for baseline numbers.
- pyuvdata.utils.bls.baseline_to_antnums(baseline, *, Nants_telescope: int, use_miriad_convention: bool = False)[source]
Get the antenna numbers corresponding to a given baseline number.
- Parameters:
baseline (int or array_like of ints) – baseline number
Nants_telescope (int) – number of antennas
use_miriad_convention (bool) – Option to use the MIRIAD convention where BASELINE id is bl = 256 * ant1 + ant2 if ant2 < 256, otherwise bl = 2048 * ant1 + ant2 + 2**16. Note antennas should be 1-indexed (start at 1, not 0)
- Returns:
int or array_like of int – first antenna number(s)
int or array_like of int – second antenna number(s)
- pyuvdata.utils.bls.antnums_to_baseline(ant1, ant2, *, Nants_telescope, attempt256=False, use_miriad_convention=False)[source]
Get the baseline number corresponding to two given antenna numbers.
- Parameters:
ant1 (int or array_like of int) – first antenna number
ant2 (int or array_like of int) – second antenna number
Nants_telescope (int) – number of antennas
attempt256 (bool) – Option to try to use the older 256 standard used in many uvfits files. If there are antenna numbers >= 256, the 2048 standard will be used unless there are antenna numbers >= 2048 or Nants_telescope > 2048. In that case, the 2147483648 standard will be used. Default is False.
use_miriad_convention (bool) – Option to use the MIRIAD convention where BASELINE id is bl = 256 * ant1 + ant2 if ant2 < 256, otherwise bl = 2048 * ant1 + ant2 + 2**16. Note antennas should be 1-indexed (start at 1, not 0)
- Returns:
int or array of int – baseline number corresponding to the two antenna numbers.
- pyuvdata.utils.bls.baseline_index_flip(baseline, *, Nants_telescope)[source]
Change baseline number to reverse antenna order.
- pyuvdata.utils.bls.parse_ants(uv, ant_str, *, print_toggle=False, x_orientation=None)[source]
Get antpair and polarization from parsing an aipy-style ant string.
Used to support the select function. Generates two lists of antenna pair tuples and polarization indices based on parsing of the string ant_str. If no valid polarizations (pseudo-Stokes params, or combinations of [lr] or [xy]) or antenna numbers are found in ant_str, ant_pairs_nums and polarizations are returned as None.
- Parameters:
uv (UVBase Object) – A UVBased object that supports the following functions and parameters: - get_ants - get_antpairs - get_pols These are used to construct the baseline ant_pair_nums and polarizations returned.
ant_str (str) – String containing antenna information to parse. Can be ‘all’, ‘auto’, ‘cross’, or combinations of antenna numbers and polarization indicators ‘l’ and ‘r’ or ‘x’ and ‘y’. Minus signs can also be used in front of an antenna number or baseline to exclude it from being output in ant_pairs_nums. If ant_str has a minus sign as the first character, ‘all,’ will be appended to the beginning of the string. See the tutorial for examples of valid strings and their behavior.
print_toggle (bool) – Boolean for printing parsed baselines for a visual user check.
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings. If input uv object has an x_orientation parameter and the input to this function is None, the value from the object will be used. Any input given to this function will override the value on the uv object. See corresponding parameter on UVData for more details.
- Returns:
ant_pairs_nums (list of tuples of int or None) – List of tuples containing the parsed pairs of antenna numbers, or None if ant_str is ‘all’ or a pseudo-Stokes polarizations.
polarizations (list of int or None) – List of desired polarizations or None if ant_str does not contain a polarization specification.
- pyuvdata.utils.bls._extract_bls_pol(*, bls, polarizations, baseline_array, ant_1_array, ant_2_array, nants_telescope, invert=False, strict=True)[source]
Decompose a list of ant-tuples or baseline numbers into ant-pairs and polarizations.
This is a helper function that takes the bls parameter from the select function of several different classes (which can accept multiple different input types) and generates a consistent output, namely antenna pairs and a list of polarizations to select upon.
- Parameters:
bls (list of tuple or int) – List containing the baselines being selected, either based on baseline number (in which case, the list should contain only ints), antenna-pairs (the list should contain 2-tuples), or antenna-polarization pairs (the list should contain 3-tules, with the third element being a string denoting the polarization).
polarizations (str or array-like of str) – List of polarizations that are being selected. If provided and bls contains 3-tuples, an error is thrown.
baseline_array (array-like of int) – Array of baseline numbers for the object.
ant_1_array (array-like of int) – Array of first antenna numbers for the object.
ant_2_array (array-like of int) – Array of second antenna numbers for the object.
nants_telescope (int) – Number of antennas within a given telescope. Used to translate between baseline number and antenna pairs.
invert (bool) – Option to specify whether a select operation is trying to perform an inverse selection (matching everything but what is listed). If set to True and bls contains 3-tuples, an error is thrown.
strict (bool or None) – Normally, select will warn when an element of the selection criteria does not match any element for the parameter, as long as the selection criteria results in at least one element being selected. However, if set to True, an error is thrown if any selection criteria does not match what is given for the object parameters element. If set to None, then neither errors nor warnings are raised, unless no records are selected. Default is False.
- Returns:
bls (list of tuples) – List containing all matching antenna-pairs (in the form of 2-tuples).
polarizations (list of str) – List specifying which polarizations are being selected.
Functions for working with the baseline-time axis
Utilities for the baseline-time axis.
- pyuvdata.utils.bltaxis.determine_blt_order(*, time_array, ant_1_array, ant_2_array, baseline_array, Nbls, Ntimes) tuple[str] | None[source]
Get the blt order from analysing metadata.
- pyuvdata.utils.bltaxis.determine_rectangularity(*, time_array: ndarray, baseline_array: ndarray, nbls: int, ntimes: int, blt_order: str | tuple[str] | None = None)[source]
Determine if the data is rectangular or not.
- Parameters:
time_array (array_like) – Array of times in JD.
baseline_array (array_like) – Array of baseline integers.
nbls (int) – Number of baselines.
ntimes (int) – Number of times.
blt_order (str or tuple of str, optional) – If known, pass the blt_order, which can short-circuit the determination of rectangularity.
- Returns:
is_rect (bool) – True if the data is rectangular, False otherwise.
time_axis_faster_than_bls (bool) – True if the data is rectangular and the time axis is the last axis (i.e. times change first, then bls). False either if baselines change first, OR if it is not rectangular.
Notes
Rectangular data is defined as data for which using regular slicing of size Ntimes or Nbls will give you either all the same time and all different baselines, or vice versa. This does NOT require that the baselines and times are sorted within that structure.
Note that blt_order being (time, baseline) does not guarantee rectangularity, even when Nblts == Nbls * Ntimes, since if autos_first = True is set on reorder_blts, then it will still set the blt_order attribute to (time, baseline), but they will not strictly be in that order (since it will actually be in autos-first order).
- pyuvdata.utils.bltaxis._select_blt_preprocess(*, select_antenna_nums, select_antenna_names, bls, times, time_range, lsts, lst_range, blt_inds, phase_center_ids, antenna_names, antenna_numbers, ant_1_array, ant_2_array, baseline_array, time_array, time_tols, lst_array, lst_tols, phase_center_id_array, invert=False, strict=False)[source]
Build up blt_inds and selections list for _select_preprocess.
- Parameters:
select_antenna_nums (array_like of int, optional) – The antennas numbers to keep in the object (antenna positions and names for the removed antennas will be retained unless keep_all_metadata is False). This cannot be provided if select_antenna_names is also provided.
select_antenna_names (array_like of str, optional) – The antennas names to keep in the object (antenna positions and names for the removed antennas will be retained unless keep_all_metadata is False). This cannot be provided if select_antenna_nums is also provided.
bls (list of 2-tuples, optional) – A list of antenna number tuples (e.g. [(0, 1), (3, 2)]) specifying baselines to keep in the object. The ordering of the numbers within the tuple does not matter. Note that this is different than what can be passed to the parameter of the same name on select – this parameter does not accept 3-tuples or baseline numbers.
times (array_like of float, optional) – The times to keep in the object, each value passed here should exist in the time_array. Cannot be used with time_range, lsts, or lst_array.
time_range (array_like of float, optional) – The time range in Julian Date to keep in the object, must be length 2. Some of the times in the object should fall between the first and last elements. Cannot be used with times, lsts, or lst_array.
lsts (array_like of float, optional) – The local sidereal times (LSTs) to keep in the object, each value passed here should exist in the lst_array. Cannot be used with times, time_range, or lst_range.
lst_range (array_like of float, optional) – The local sidereal time (LST) range in radians to keep in the object, must be of length 2. Some of the LSTs in the object should fall between the first and last elements. If the second value is smaller than the first, the LSTs are treated as having phase-wrapped around LST = 2*pi = 0, and the LSTs kept on the object will run from the larger value, through 0, and end at the smaller value.
phase_center_ids (array_like of int, optional) – Phase center IDs to keep on the object (effectively a selection on baseline-times).
blt_inds (array_like of int, optional) – The baseline-time indices to keep in the object. This is not commonly used.
ant_1_array (array_like of int) – Array of first antenna numbers to select on.
ant_2_array (array_like of int) – Array of second antenna numbers to select on.
baseline_array (array_like of int) – Array of baseline numbers to select on.
time_array (array_like of float) – Array of times in JD to select on.
lst_array (array_like of float) – Array of lsts in radians to select on.
phase_center_id_array (array_like of int) – Array of phase center IDs to select on.
invert (bool) – Normally indices matching given criteria are what are included in the subsequent list. However, if set to True, these indices are excluded instead. Default is False.
strict (bool or None) – Normally, select will warn when an element of the selection criteria does not match any element for the parameter, as long as the selection criteria results in at least one element being selected. However, if set to True, an error is thrown if any selection criteria does not match what is given for the object parameters element. If set to None, then neither errors nor warnings are raised, unless no records are selected. Default is False.
- Returns:
blt_inds (list of int) – list of baseline-time indices to keep. Can be None (to keep everything).
selections (list of str) – list of selections done.
Functions for working with telescope coordinates
Utilities for coordinate transforms.
- pyuvdata.utils.coordinates.get_loc_obj(telescope_loc, telescope_frame='itrs', ellipsoid=None, angle_units=Unit('rad'), return_moon=False)[source]
Check if telescope is on the moon.
- Parameters:
telescope_loc (array-like of floats or EarthLocation or MoonLocation) – ITRS latitude, longitude, and altitude (rel to sea-level) of the phase center of the array. Can either be provided as an astropy EarthLocation, or a tuple of shape (3,) containing (in order) the latitude, longitude, and altitude, in units of radians, radians, and meters, respectively.
telescope_frame (str, optional) – Reference frame for telescope location. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
- pyuvdata.utils.coordinates.LatLonAlt_from_XYZ(xyz, *, frame='ITRS', ellipsoid=None, check_acceptability=True)[source]
Calculate lat/lon/alt from ECEF x,y,z.
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
frame (str) – Coordinate frame of xyz. Valid options are ITRS (default) or MCMF.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF.
check_acceptability (bool) – Flag to check XYZ coordinates are reasonable.
- Returns:
latitude (ndarray or float) – latitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
longitude (ndarray or float) – longitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
altitude (ndarray or float) – altitude, numpy array (if Npts > 1) or value (if Npts = 1) in meters
- pyuvdata.utils.coordinates.XYZ_from_LatLonAlt(latitude, longitude, altitude, *, frame='ITRS', ellipsoid=None)[source]
Calculate ECEF x,y,z from lat/lon/alt values.
- Parameters:
latitude (ndarray or float) – latitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
longitude (ndarray or float) – longitude, numpy array (if Npts > 1) or value (if Npts = 1) in radians
altitude (ndarray or float) – altitude, numpy array (if Npts > 1) or value (if Npts = 1) in meters
frame (str) – Coordinate frame of xyz. Valid options are ITRS (default) or MCMF.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF.
- Returns:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
- pyuvdata.utils.coordinates.rotECEF_from_ECEF(xyz, longitude)[source]
Get rotated ECEF positions such that the x-axis goes through the longitude.
Miriad and uvfits expect antenna positions in this frame (with longitude of the array center/telescope location)
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
longitude (float) – longitude in radians to rotate coordinates to (usually the array center/telescope location).
- Returns:
ndarray of float – Rotated ECEF coordinates, shape (Npts, 3).
- pyuvdata.utils.coordinates.ECEF_from_rotECEF(xyz, longitude)[source]
Calculate ECEF from a rotated ECEF (Inverse of rotECEF_from_ECEF).
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with rotated ECEF x,y,z coordinates.
longitude (float) – longitude in radians giving the x direction of the rotated coordinates (usually the array center/telescope location).
- Returns:
ndarray of float – ECEF coordinates, shape (Npts, 3).
- pyuvdata.utils.coordinates.ENU_from_ECEF(xyz, *, center_loc=None, latitude=None, longitude=None, altitude=None, frame='ITRS', ellipsoid=None)[source]
Calculate local ENU (east, north, up) coordinates from ECEF coordinates.
- Parameters:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
center_loc (EarthLocation or MoonLocation object) – An EarthLocation or MoonLocation object giving the center of the ENU coordinates. Either center_loc or all of latitude, longitude, altitude must be passed.
latitude (float) – Latitude of center of ENU coordinates in radians. Not used if center_loc is passed.
longitude (float) – Longitude of center of ENU coordinates in radians. Not used if center_loc is passed.
altitude (float) – Altitude of center of ENU coordinates in radians. Not used if center_loc is passed.
frame (str) – Coordinate frame of xyz and center of ENU coordinates. Valid options are ITRS (default) or MCMF. Not used if center_loc is passed.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF. Not used if center_loc is passed.
- Returns:
ndarray of float – numpy array, shape (Npts, 3), with local ENU coordinates
- pyuvdata.utils.coordinates.ECEF_from_ENU(enu, center_loc=None, latitude=None, longitude=None, altitude=None, frame='ITRS', ellipsoid=None)[source]
Calculate ECEF coordinates from local ENU (east, north, up) coordinates.
- Parameters:
enu (ndarray of float) – numpy array, shape (Npts, 3), with local ENU coordinates.
center_loc (EarthLocation or MoonLocation object) – An EarthLocation or MoonLocation object giving the center of the ENU coordinates. Either center_loc or all of latitude, longitude, altitude must be passed.
latitude (float) – Latitude of center of ENU coordinates in radians. Not used if center_loc is passed.
longitude (float) – Longitude of center of ENU coordinates in radians. Not used if center_loc is passed.
altitude (float) – Altitude of center of ENU coordinates in radians. Not used if center_loc is passed.
frame (str) – Coordinate frame of xyz and center of ENU coordinates. Valid options are ITRS (default) or MCMF. Not used if center_loc is passed.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is MCMF. Not used if center_loc is passed.
- Returns:
xyz (ndarray of float) – numpy array, shape (Npts, 3), with ECEF x,y,z coordinates.
- pyuvdata.utils.coordinates.hpx_latlon_to_zenithangle_azimuth(hpx_lat, hpx_lon)[source]
Convert from healpix lat/lon to UVBeam za/az convention.
Note that this is different (unfortunately) from the conversion between the UVBeam Zenith Angle, Azimuth coordinate system and the astropy Alt/Az coordinate system. The astropy Azimuth runs the opposite direction and has a different starting angle than UVBeam’s Azimuth because they are both right handed coordinate systems but Altitude moves the opposite direction than Zenith Angle does.
The conversion used in this code sets the Healpix latitude to 90-zenith angle but it does not change the origin or direction for the azimuthal angle. This convention was set early in the development of UVBeam and we preserve it to preserve backwards compatibility.
- Parameters:
hpx_lat (float or array of float) – Healpix latiudinal coordinate in radians.
hpx_lon (float or array of float) – Healpix longitudinal coordinate in radians.
- Returns:
zenith_angle (float or array of float) – In radians
azimuth (float or array of float) – In radians in uvbeam convention: North of East(East=0, North=pi/2)
- pyuvdata.utils.coordinates.zenithangle_azimuth_to_hpx_latlon(zenith_angle, azimuth)[source]
Convert from UVBeam az/za convention to healpix lat/lon.
Note that this is different (unfortunately) from the conversion between the UVBeam Zenith Angle, Azimuth coordinate system and the astropy Alt/Az coordinate system. The astropy Azimuth runs the opposite direction and has a different starting angle than UVBeam’s Azimuth because they are both right handed coordinate systems but Altitude moves the opposite direction than Zenith Angle does.
The conversion used in this code sets the Healpix latitude to 90-zenith angle but it does not change the origin or direction for the azimuthal angle. This convention was set early in the development of UVBeam and we preserve it to preserve backwards compatibility.
- Parameters:
zenith_angle (float, array_like of float) – Zenith angle in radians
azimuth (float, array_like of float) – Azimuth in radians in uvbeam convention: North of East(East=0, North=pi/2)
- Returns:
hpx_lat (float or array of float) – Healpix latiudinal coordinate in radians.
hpx_lon (float or array of float) – Healpix longitudinal coordinate in radians.
- pyuvdata.utils.coordinates.check_surface_based_positions(*, telescope_loc=None, telescope_frame='itrs', antenna_positions=None, raise_error=True, raise_warning=True)[source]
Check that antenna positions are consistent with ground-based values.
Check that the antenna position, telescope location, or combination of both produces locations that are consistent with surface-based positions. If supplying both antenna position and telescope location, the check will be run against the sum total of both. For the Earth, the permitted range of values is betwen 6350 and 6390 km, whereas for theMoon the range is 1717.1 to 1757.1 km.
- telescope_locarray-like of float or EarthLocation or MoonLocation
Telescope location, specified as a 3-element tuple (specifying geo/selenocentric position in meters) or as an astropy EarthLocation (or lunarsky MoonLocation).
- telescope_framestr, optional
Reference frame for latitude/longitude/altitude. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
- antenna_positionsndarray of float
List of antenna positions relative to array center in ECEF coordinates, required if not providing uvw_array. Shape is (Nants, 3). If no telescope_loc is specified, these values will be assumed to be relative to geocenter.
- raise_errorbool
If True, an error is raised if telescope_loc and/or telescope_loc do not conform to expectations for a surface-based telescope. Default is True.
- raise_warningbool
If True, a warning is raised if telescope_loc and/or telescope_loc do not conform to expectations for a surface-based telescope. Default is True, only used if raise_error is set to False.
- Returns:
valid (bool) – If True, the antenna_positions and/or telescope_loc conform to expectations for a surface-based telescope. Otherwise returns false.
Functions for working with the frequency axis
Frequency related utilities.
- pyuvdata.utils.frequency._check_flex_spw_contiguous(*, spw_array, flex_spw_id_array, strict=True)[source]
Check if the spectral windows are contiguous for multi-spw datasets.
This checks the flex_spw_id_array to make sure that all channels for each spectral window are together in one block, versus being interspersed (e.g., channel #1 and #3 is in spw #1, channels #2 and #4 are in spw #2). In theory, UVH5 and UVData objects can handle this, but MIRIAD, MIR, UVFITS, and MS file formats cannot, so we just consider it forbidden.
- Parameters:
spw_array (array of integers) – Array of spectral window numbers, shape (Nspws,).
flex_spw_id_array (array of integers) – Array of spectral window numbers per frequency channel, shape (Nfreqs,).
strict (bool) – If set to True, then the function will raise an error if checks are failed. If set to False, then a warning is raised instead. If set to None, then no errors or warnings are raised.
- pyuvdata.utils.frequency._check_freq_spacing(*, freq_array, freq_tols=None, channel_width=None, channel_width_tols=None, spw_array=None, flex_spw_id_array=None, strict=True, ignore_chanwidth_error=False)[source]
Check if frequencies are evenly spaced and separated by their channel width.
This is a requirement for writing uvfits & miriad files.
- Parameters:
freq_array (array of float or UVParameter) – Array of frequencies, shape (Nfreqs,).
freq_tols (tuple of float) – freq_array tolerances (from uvobj._freq_array.tols).
channel_width (array of float or UVParameter) – Channel widths, either a scalar or an array of shape (Nfreqs,).
channel_width_tols (tuple of float) – channel_width tolerances (from uvobj._channel_width.tols).
spw_array (array of integers or None) – Array of spectral window numbers, shape (Nspws,).
flex_spw_id_array (array of integers or None) – Array of spectral window numbers per frequency channel, shape (Nfreqs,).
strict (bool) – If set to True, then the function will raise an error if checks are failed. If set to False, then a warning is raised instead. If set to None, then no errors or warnings are raised.
ignore_chanwidth_error (bool) – If set to True, when no errors or warnings are raised if the channel spacing does not match the channel width. Default is False. Note: this does not affect what is returned by the function (e.g., chanwidth_error is correctly returned regardless of what is set here).
- Returns:
spacing_error (bool) – Flag that channel spacings or channel widths are not equal.
chanwidth_error (bool) – Flag that channel spacing does not match channel width.
- pyuvdata.utils.frequency._sort_freq_helper(*, Nfreqs, freq_array, Nspws, spw_array, flex_spw_id_array, spw_order, channel_order, select_spw)[source]
Figure out the frequency sorting order for object based frequency sorting.
- Parameters:
Nfreqs (int) – Number of frequencies, taken directly from the object parameter.
freq_array (array_like of float) – Frequency array, taken directly from the object parameter.
Nfreqs (int) – Number of spectral windows, taken directly from the object parameter.
spw_array (array_like of int) – Spectral window array, taken directly from the object parameter.
flex_spw_id_array (array_like of int) – Array of SPW IDs for each channel, taken directly from the object parameter.
spw_order (str or array_like of int) – A string describing the desired order of spectral windows along the frequency axis. Allowed strings include number (sort on spectral window number) and freq (sort on median frequency). A ‘-’ can be prepended to signify descending order instead of the default ascending order, e.g., if you have SPW #1 and 2, and wanted them ordered as [2, 1], you would specify -number. Alternatively, one can supply an index array of length Nspws that specifies how to shuffle the spws (this is not the desired final spw order). Default is to apply no sorting of spectral windows.
channel_order (str or array_like of int) – A string describing the desired order of frequency channels within a spectral window. Allowed strings include freq, which will sort channels within a spectral window by frequency. A ‘-’ can be optionally prepended to signify descending order instead of the default ascending order. Alternatively, one can supply an index array of length Nfreqs that specifies the new order. Default is to apply no sorting of channels within a single spectral window. Note that proving an array_like of ints will cause the values given to spw_order and select_spw to be ignored.
select_spw (int or array_like of int) – An int or array_like of ints which specifies which spectral windows to apply sorting. Note that setting this argument will cause the value given to spw_order to be ignored.
- Returns:
index_array (ndarray of int) – Array giving the desired order of the channels to be used for sorting along the frequency axis
- Raises:
UserWarning – Raised if providing arguments to select_spw and channel_order (the latter overrides the former).
ValueError – Raised if select_spw contains values not in spw_array, or if channel_order is not the same length as freq_array.
- pyuvdata.utils.frequency._select_freq_helper(*, frequencies, freq_chans, obj_freq_array, freq_tols, obj_channel_width=None, channel_width_tols=None, spws=None, obj_spw_array=None, obj_spw_id_array=None, polarizations=None, obj_flex_spw_pol_array=None, jones=None, obj_flex_jones_array=None, obj_x_orientation=None, warn_spacing=False, invert=False, strict=False)[source]
Get time indices in a select.
- Parameters:
frequencies (array_like of float) – The frequencies to keep in the object, each value passed here should exist in the freq_array.
freq_chans (array_like of float) – The frequency channel numbers to keep in the object.
obj_freq_array (array_like of float) – Frequency array on object.
freq_tols (tuple of float) – Length 2 tuple giving (rtol, atol) to use for freq matching.
obj_channel_width (array_like of float or None) – Channel width array on object, used for checking for FITs issues.
channel_width_tols (tuple of float or None) – Length 2 tuple giving (rtol, atol) to use for channel_width vs freq separation checking. Can be None if obj_channel_width is None.
obj_spw_id_array (array_like of int) – flex_spw_id_array on object.
warn_spacing (bool) – Whether or not to warn about frequency/polarization spacing. Default is False.
invert (bool) – Normally indices matching given criteria are what are included in the subsequent list. However, if set to True, these indices are excluded instead. Default is False.
strict (bool or None) – Normally, select will warn when an element of the selection criteria does not match any element for the parameter, as long as the selection criteria results in at least one element being selected. However, if set to True, an error is thrown if any selection criteria does not match what is given for the object parameters element. If set to None, then neither errors nor warnings are raised, unless no records are selected. Default is False.
- Returns:
freq_inds (np.ndarray of int) – Indices of frequencies to keep on the object.
selections (list of str) – list of selections done.
Functions for working with history
History management utilities.
- pyuvdata.utils.history._check_history_version(history, version_string)[source]
Check if version_string is present in history string.
Functions for working with phase center catalogs
Utilities for working with phase center catalogs.
- pyuvdata.utils.phase_center_catalog.look_in_catalog(phase_center_catalog, *, cat_name=None, cat_type=None, cat_lon=None, cat_lat=None, cat_frame=None, cat_epoch=None, cat_times=None, cat_pm_ra=None, cat_pm_dec=None, cat_dist=None, cat_vrad=None, ignore_name=False, target_cat_id=None, phase_dict=None)[source]
Check the catalog to see if an existing entry matches provided data.
This is a helper function for verifying if an entry already exists within the catalog, contained within the supplied phase center catalog.
- Parameters:
phase_center_catalog (dict) – Dictionary containing the entries to check.
cat_name (str) – Name of the phase center, which should match a the value of “cat_name” inside an entry of phase_center_catalog.
cat_type (str) –
- Type of phase center of the entry. Must be one of:
“sidereal” (fixed RA/Dec), “ephem” (RA/Dec that moves with time), “driftscan” (fixed az/el position), “unprojected” (no w-projection, equivalent to the old phase_type == “drift”).
cat_lon (float or ndarray) – Value of the longitudinal coordinate (e.g., RA, Az, l) in radians of the phase center. No default unless cat_type=”unprojected”, in which case the default is zero. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
cat_lat (float or ndarray) – Value of the latitudinal coordinate (e.g., Dec, El, b) in radians of the phase center. No default unless cat_type=”unprojected”, in which case the default is pi/2. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
cat_frame (str) – Coordinate frame that cat_lon and cat_lat are given in. Only used for sidereal and ephem phase centers. Can be any of the several supported frames in astropy (a limited list: fk4, fk5, icrs, gcrs, cirs, galactic).
cat_epoch (str or float) – Epoch of the coordinates, only used when cat_frame = fk4 or fk5. Given in units of fractional years, either as a float or as a string with the epoch abbreviation (e.g, Julian epoch 2000.0 would be J2000.0).
cat_times (ndarray of floats) – Only used when cat_type=”ephem”. Describes the time for which the values of cat_lon and cat_lat are caclulated, in units of JD. Shape is (Npts,).
cat_pm_ra (float) – Proper motion in RA, in units of mas/year. Only used for sidereal phase centers.
cat_pm_dec (float) – Proper motion in Dec, in units of mas/year. Only used for sidereal phase centers.
cat_dist (float or ndarray of float) – Distance of the source, in units of pc. Only used for sidereal and ephem phase centers. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
cat_vrad (float or ndarray of float) – Radial velocity of the source, in units of km/s. Only used for sidereal and ephem phase centers. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
ignore_name (bool) – Nominally, this method will only look at entries where cat_name matches the name of an entry in the catalog. However, by setting this to True, the method will search all entries in the catalog and see if any match all of the provided data (excluding cat_name).
target_cat_id (int) – Optional argument to specify a particular cat_id to check against.
phase_dict (dict) – Instead of providing individual parameters, one may provide a dict which matches that format used within phase_center_catalog for checking for existing entries. If used, all other parameters (save for ignore_name and cat_name) are disregarded.
- Returns:
cat_id (int or None) – The unique ID number for the phase center added to the internal catalog. This value is used in the phase_center_id_array attribute to denote which source a given baseline-time corresponds to. If no catalog entry matches, then None is returned.
cat_diffs (int) – The number of differences between the information provided and the catalog entry contained within phase_center_catalog. If everything matches, then cat_diffs=0.
- pyuvdata.utils.phase_center_catalog.look_for_name(phase_center_catalog, cat_name)[source]
Look up catalog IDs which match a given name.
- Parameters:
phase_center_catalog (dict) – Catalog to look for matching names in.
cat_name (str or list of str) – Name to match against entries in phase_center_catalog.
- Returns:
cat_id_list (list) – List of all catalog IDs which match the given name.
- pyuvdata.utils.phase_center_catalog.print_phase_center_info(phase_center_catalog, catalog_identifier=None, *, hms_format=None, return_str=False, print_table=True)[source]
Print out the details of the phase centers.
Prints out an ASCII table that contains the details of the supploed phase center catalog, which typically acts as the internal source catalog for various UV objects.
- Parameters:
phase_center_catalog (dict) – Dict containing the list of phase centers (and corresponding data) to be printed out.
catalog_identifier (str or int or list of str or int) – Optional parameter which, if provided, will cause the method to only return information on the phase center(s) with the matching name(s) or catalog ID number(s). Default is to print out information on all catalog entries.
hms_format (bool) – Optional parameter, which if selected, can be used to force coordinates to be printed out in Hours-Min-Sec (if set to True) or Deg-Min-Sec (if set to False) format. Default is to print out in HMS if all the objects have coordinate frames of icrs, gcrs, fk5, fk4, and top; otherwise, DMS format is used.
return_str (bool) – If set to True, the method returns an ASCII string which contains all the table infrmation. Default is False.
print_table (bool) – If set to True, prints the table to the terminal window. Default is True.
- Returns:
table_str (bool) – If return_str=True, an ASCII string containing the entire table text
- Raises:
ValueError – If cat_name matches no keys in phase_center_catalog.
- pyuvdata.utils.phase_center_catalog.generate_new_phase_center_id(phase_center_catalog=None, *, cat_id=None, old_id=None, reserved_ids=None)[source]
Update a phase center with a new catalog ID number.
- Parameters:
phase_center_catalog (dict) – Catalog to be updated. Note that the supplied catalog will be modified in situ.
cat_id (int) – Optional argument. If supplied, then the method will check to see that the supplied ID is not in either the supplied catalog or in the reserved IDs. provided value as the new catalog ID, provided that an existing catalog If not supplied, then the method will automatically assign a value, defaulting to the value in cat_id if supplied (and assuming that ID value has no conflicts with the reserved IDs).
old_id (int) – Optional argument, current catalog ID of the phase center, which corresponds to a key in phase_center_catalog.
reserved_ids (array-like in int) – Optional argument. An array-like of ints that denotes which ID numbers are already reserved. Useful for when combining two separate catalogs.
- Returns:
new_id (int) – New phase center ID.
- Raises:
ValueError – If there’s no entry that matches cat_id, or of the value new_id is already taken.
- pyuvdata.utils.phase_center_catalog.generate_phase_center_cat_entry(cat_name=None, *, cat_type=None, cat_lon=None, cat_lat=None, cat_frame=None, cat_epoch=None, cat_times=None, cat_pm_ra=None, cat_pm_dec=None, cat_dist=None, cat_vrad=None, info_source='user', force_update=False, cat_id=None)[source]
Add an entry to a object/source catalog or find a matching one.
This is a helper function for identifying and adding a phase center to a catalog, typically contained within the attribute phase_center_catalog. If a matching phase center is found, the catalog ID associated with that phase center is returned.
- Parameters:
cat_name (str) – Name of the phase center to be added.
cat_type (str) –
- Type of phase center to be added. Must be one of:
“sidereal” (fixed RA/Dec), “ephem” (RA/Dec that moves with time), “driftscan” (fixed az/el position), “unprojected” (no w-projection, equivalent to the old phase_type == “drift”). “near-field” (equivalent to sidereal with the addition of near-field corrections)
cat_lon (float or ndarray) – Value of the longitudinal coordinate (e.g., RA, Az, l) in radians of the phase center. No default unless cat_type=”unprojected”, in which case the default is zero. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
cat_lat (float or ndarray) – Value of the latitudinal coordinate (e.g., Dec, El, b) in radians of the phase center. No default unless cat_type=”unprojected”, in which case the default is pi/2. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
cat_frame (str) – Coordinate frame that cat_lon and cat_lat are given in. Only used for sidereal and ephem targets. Can be any of the several supported frames in astropy (a limited list: fk4, fk5, icrs, gcrs, cirs, galactic).
cat_epoch (str or float) – Epoch of the coordinates, only used when cat_frame = fk4 or fk5. Given in units of fractional years, either as a float or as a string with the epoch abbreviation (e.g, Julian epoch 2000.0 would be J2000.0).
cat_times (ndarray of floats) – Only used when cat_type=”ephem”. Describes the time for which the values of cat_lon and cat_lat are caclulated, in units of JD. Shape is (Npts,).
cat_pm_ra (float) – Proper motion in RA, in units of mas/year. Only used for sidereal phase centers.
cat_pm_dec (float) – Proper motion in Dec, in units of mas/year. Only used for sidereal phase centers.
cat_dist (float or ndarray of float) – Distance of the source, in units of pc. Only used for sidereal and ephem phase centers. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
cat_vrad (float or ndarray of float) – Radial velocity of the source, in units of km/s. Only used for sidereal and ephem phase centers. Expected to be a float for sidereal and driftscan phase centers, and an ndarray of floats of shape (Npts,) for ephem phase centers.
info_source (str) – Optional string describing the source of the information provided. Used primarily in UVData to denote when an ephemeris has been supplied by the JPL-Horizons system, user-supplied, or read in by one of the various file interpreters. Default is ‘user’.
force_update (bool) – Normally, _add_phase_center will throw an error if there already exists a phase_center with the given cat_id. However, if one sets force_update=True, the method will overwrite the existing entry in phase_center_catalog with the parameters supplied. Note that doing this will _not_ update other attributes of the UVData object. Default is False.
cat_id (int) – An integer signifying the ID number for the phase center, used in the phase_center_id_array attribute. If a matching phase center entry exists already, that phase center ID will be returned, which may be different than the value specified to this parameter. The default is for the method to assign this value automatically.
- Returns:
phase_center_entry (dict) – Catalog containing the phase centers.
cat_id (int) – The unique ID number for the phase center that either matches the specified parameters or was added to the internal catalog. If a matching entry was found, this may not be the value passed to the cat_id parameter. This value is used in the phase_center_id_array attribute to denote which source a given baseline-time corresponds to.
- Raises:
ValueError – If attempting to add a non-unique source name or if adding a sidereal source without coordinates.
Functions for working with phasing
Utilities for phasing.
- pyuvdata.utils.phasing.old_uvw_calc(ra, dec, initial_uvw)[source]
Calculate old uvws from unphased ones in an icrs or gcrs frame.
This method should not be used and is only retained for testing the undo_old_uvw_calc method, which is needed for fixing phases.
This code expects input uvws relative to the telescope location in the same frame that ra/dec are in (e.g. icrs or gcrs) and returns phased ones in the same frame.
- Parameters:
ra (float) – Right ascension of phase center.
dec (float) – Declination of phase center.
initial_uvw (ndarray of float) – Unphased uvws or positions relative to the array center, shape (Nlocs, 3).
- Returns:
uvw (ndarray of float) – uvw array in the same frame as initial_uvws, ra and dec.
- pyuvdata.utils.phasing.undo_old_uvw_calc(ra, dec, uvw)[source]
Undo the old phasing calculation on uvws in an icrs or gcrs frame.
This code expects phased uvws or positions in the same frame that ra/dec are in (e.g. icrs or gcrs) and returns unphased ones in the same frame.
- Parameters:
ra (float) – Right ascension of phase center.
dec (float) – Declination of phase center.
uvw (ndarray of float) – Phased uvws or positions relative to the array center, shape (Nlocs, 3).
- Returns:
unphased_uvws (ndarray of float) – Unphased uvws or positions relative to the array center, shape (Nlocs, 3).
- pyuvdata.utils.phasing.polar2_to_cart3(*, lon_array, lat_array)[source]
Convert 2D polar coordinates into 3D cartesian coordinates.
This is a simple routine for converting a set of spherical angular coordinates into a 3D cartesian vectors, where the x-direction is set by the position (0, 0).
- Parameters:
lon_array (float or ndarray) – Longitude coordinates, which increases in the counter-clockwise direction. Units of radians. Can either be a float or ndarray – if the latter, must have the same shape as lat_array.
lat_array (float or ndarray) – Latitude coordinates, where 0 falls on the equator of the sphere. Units of radians. Can either be a float or ndarray – if the latter, must have the same shape as lat_array.
- Returns:
xyz_array (ndarray of float) – Cartesian coordinates of the given longitude and latitude on a unit sphere. Shape is (3, coord_shape), where coord_shape is the shape of lon_array and lat_array if they were provided as type ndarray, otherwise (3,).
- pyuvdata.utils.phasing.cart3_to_polar2(xyz_array)[source]
Convert 3D cartesian coordinates into 2D polar coordinates.
This is a simple routine for converting a set of 3D cartesian vectors into spherical coordinates, where the position (0, 0) lies along the x-direction.
- Parameters:
xyz_array (ndarray of float) – Cartesian coordinates, need not be of unit vector length. Shape is (3, coord_shape).
- Returns:
lon_array (ndarray of float) – Longitude coordinates, which increases in the counter-clockwise direction. Units of radians, shape is (coord_shape,).
lat_array (ndarray of float) – Latitude coordinates, where 0 falls on the equator of the sphere. Units of radians, shape is (coord_shape,).
- pyuvdata.utils.phasing._rotate_matmul_wrapper(*, xyz_array, rot_matrix, n_rot)[source]
Apply a rotation matrix to a series of vectors.
This is a simple convenience function which wraps numpy’s matmul function for use with various vector rotation functions in this module. This code could, in principle, be replaced by a cythonized piece of code, although the matmul function is _pretty_ well optimized already. This function is not meant to be called by users, but is instead used by multiple higher-level utility functions (namely those that perform rotations).
- Parameters:
xyz_array (ndarray of floats) – Array of vectors to be rotated. When nrot > 1, shape may be (n_rot, 3, n_vec) or (1, 3, n_vec), the latter is useful for when performing multiple rotations on a fixed set of vectors. If nrot = 1, shape may be (1, 3, n_vec), (3, n_vec), or (3,).
rot_matrix (ndarray of floats) – Series of rotation matricies to be applied to the stack of vectors. Must be of shape (n_rot, 3, 3)
n_rot (int) – Number of individual rotation matricies to be applied.
- Returns:
rotated_xyz (ndarray of floats) – Array of vectors that have been rotated, of shape (n_rot, 3, n_vectors,).
- pyuvdata.utils.phasing._rotate_one_axis(xyz_array, *, rot_amount, rot_axis)[source]
Rotate an array of 3D positions around the a single axis (x, y, or z).
This function performs a basic rotation of 3D vectors about one of the priciple axes – the x-axis, the y-axis, or the z-axis.
Note that the rotations here obey the right-hand rule – that is to say, from the perspective of the positive side of the axis of rotation, a positive rotation will cause points on the plane intersecting this axis to move in a counter-clockwise fashion.
- Parameters:
xyz_array (ndarray of float) – Set of 3-dimensional vectors be rotated, in typical right-handed cartesian order, e.g. (x, y, z). Shape is (Nrot, 3, Nvectors).
rot_amount (float or ndarray of float) – Amount (in radians) to rotate the given set of coordinates. Can either be a single float (or ndarray of shape (1,)) if rotating all vectors by the same amount, otherwise expected to be shape (Nrot,).
rot_axis (int) – Axis around which the rotation is applied. 0 is the x-axis, 1 is the y-axis, and 2 is the z-axis.
- Returns:
rotated_xyz (ndarray of float) – Set of rotated 3-dimensional vectors, shape (Nrot, 3, Nvector).
- pyuvdata.utils.phasing._rotate_two_axis(xyz_array, *, rot_amount1, rot_amount2, rot_axis1, rot_axis2)[source]
Rotate an array of 3D positions sequentially around a pair of axes (x, y, or z).
This function performs a sequential pair of basic rotations of 3D vectors about the priciple axes – the x-axis, the y-axis, or the z-axis.
Note that the rotations here obey the right-hand rule – that is to say, from the perspective of the positive side of the axis of rotation, a positive rotation will cause points on the plane intersecting this axis to move in a counter-clockwise fashion.
- Parameters:
xyz_array (ndarray of float) – Set of 3-dimensional vectors be rotated, in typical right-handed cartesian order, e.g. (x, y, z). Shape is (Nrot, 3, Nvectors).
rot_amount1 (float or ndarray of float) – Amount (in radians) of rotatation to apply during the first rotation of the sequence, to the given set of coordinates. Can either be a single float (or ndarray of shape (1,)) if rotating all vectors by the same amount, otherwise expected to be shape (Nrot,).
rot_amount2 (float or ndarray of float) – Amount (in radians) of rotatation to apply during the second rotation of the sequence, to the given set of coordinates. Can either be a single float (or ndarray of shape (1,)) if rotating all vectors by the same amount, otherwise expected to be shape (Nrot,).
rot_axis1 (int) – Axis around which the first rotation is applied. 0 is the x-axis, 1 is the y-axis, and 2 is the z-axis.
rot_axis2 (int) – Axis around which the second rotation is applied. 0 is the x-axis, 1 is the y-axis, and 2 is the z-axis.
- Returns:
rotated_xyz (ndarray of float) – Set of rotated 3-dimensional vectors, shape (Nrot, 3, Nvector).
- pyuvdata.utils.phasing.calc_uvw(*, app_ra=None, app_dec=None, frame_pa=None, lst_array=None, use_ant_pos=True, uvw_array=None, antenna_positions=None, antenna_numbers=None, ant_1_array=None, ant_2_array=None, old_app_ra=None, old_app_dec=None, old_frame_pa=None, telescope_lat=None, telescope_lon=None, from_enu=False, to_enu=False)[source]
Calculate an array of baseline coordinates, in either uvw or ENU.
This routine is meant as a convenience function for producing baseline coordinates based under a few different circumstances:
Calculating ENU coordinates using antenna positions
Calculating uvw coordinates at a given sky position using antenna positions
Converting from ENU coordinates to uvw coordinates
Converting from uvw coordinate to ENU coordinates
Converting from uvw coordinates at one sky position to another sky position
Different conversion pathways have different parameters that are required.
- Parameters:
app_ra (ndarray of float) – Apparent RA of the target phase center, required if calculating baseline coordinates in uvw-space (vs ENU-space). Shape is (Nblts,), units are radians.
app_dec (ndarray of float) – Apparent declination of the target phase center, required if calculating baseline coordinates in uvw-space (vs ENU-space). Shape is (Nblts,), units are radians.
frame_pa (ndarray of float) – Position angle between the great circle of declination in the apparent frame versus that of the reference frame, used for making sure that “North” on the derived maps points towards a particular celestial pole (not just the topocentric one). Required if not deriving baseline coordinates from antenna positions, from_enu=False, and a value for old_frame_pa is given. Shape is (Nblts,), units are radians.
old_app_ra (ndarray of float) – Apparent RA of the previous phase center, required if not deriving baseline coordinates from antenna positions and from_enu=False. Shape is (Nblts,), units are radians.
old_app_dec (ndarray of float) – Apparent declination of the previous phase center, required if not deriving baseline coordinates from antenna positions and from_enu=False. Shape is (Nblts,), units are radians.
old_frame_pa (ndarray of float) – Frame position angle of the previous phase center, required if not deriving baseline coordinates from antenna positions, from_enu=False, and a value for frame_pa is supplied. Shape is (Nblts,), units are radians.
lst_array (ndarray of float) – Local apparent sidereal time, required if deriving baseline coordinates from antenna positions, or converting to/from ENU coordinates. Shape is (Nblts,).
use_ant_pos (bool) – Switch to determine whether to derive uvw values from the antenna positions (if set to True), or to use the previously calculated uvw coordinates to derive new the new baseline vectors (if set to False). Default is True.
uvw_array (ndarray of float) – Array of previous baseline coordinates (in either uvw or ENU), required if not deriving new coordinates from antenna positions. Shape is (Nblts, 3).
antenna_positions (ndarray of float) – List of antenna positions relative to array center in ECEF coordinates, required if not providing uvw_array. Shape is (Nants, 3).
antenna_numbers (ndarray of int) – List of antenna numbers, ordered in the same way as antenna_positions (e.g., antenna_numbers[0] should given the number of antenna that resides at ECEF position given by antenna_positions[0]). Shape is (Nants,), requred if not providing uvw_array. Contains all unique entires of the joint set of ant_1_array and ant_2_array.
ant_1_array (ndarray of int) – Antenna number of the first antenna in the baseline pair, for all baselines Required if not providing uvw_array, shape is (Nblts,).
ant_2_array (ndarray of int) – Antenna number of the second antenna in the baseline pair, for all baselines Required if not providing uvw_array, shape is (Nblts,).
telescope_lat (float) – Latitude of the phase center, units radians, required if deriving baseline coordinates from antenna positions, or converting to/from ENU coordinates.
telescope_lon (float) – Longitude of the phase center, units radians, required if deriving baseline coordinates from antenna positions, or converting to/from ENU coordinates.
from_enu (boolean) – Set to True if uvw_array is expressed in ENU coordinates. Default is False.
to_enu (boolean) – Set to True if you would like the output expressed in ENU coordinates. Default is False.
- Returns:
new_coords (ndarray of float64) – Set of baseline coordinates, shape (Nblts, 3).
- pyuvdata.utils.phasing.transform_sidereal_coords(*, longitude, latitude, in_coord_frame, out_coord_frame, in_coord_epoch=None, out_coord_epoch=None, time_array=None)[source]
Transform a given set of coordinates from one sidereal coordinate frame to another.
Uses astropy to convert from a coordinates from sidereal frame into another. This function will support transforms from several frames, including GCRS, FK5 (i.e., J2000), FK4 (i.e., B1950), Galactic, Supergalactic, CIRS, HCRS, and a few others (basically anything that doesn’t require knowing the observers location on Earth/other celestial body).
- Parameters:
lon_coord (float or ndarray of floats) – Logitudinal coordinate to be transformed, typically expressed as the right ascension, in units of radians. Can either be a float, or an ndarray of floats with shape (Ncoords,). Must agree with lat_coord.
lat_coord (float or ndarray of floats) – Latitudinal coordinate to be transformed, typically expressed as the declination, in units of radians. Can either be a float, or an ndarray of floats with shape (Ncoords,). Must agree with lon_coord.
in_coord_frame (string) – Reference frame for the provided coordinates. Expected to match a list of those supported within the astropy SkyCoord object. An incomplete list includes ‘gcrs’, ‘fk4’, ‘fk5’, ‘galactic’, ‘supergalactic’, ‘cirs’, and ‘hcrs’.
out_coord_frame (string) – Reference frame to output coordinates in. Expected to match a list of those supported within the astropy SkyCoord object. An incomplete list includes ‘gcrs’, ‘fk4’, ‘fk5’, ‘galactic’, ‘supergalactic’, ‘cirs’, and ‘hcrs’.
in_coord_epoch (float) – Epoch for the input coordinate frame. Optional parameter, only required when using either the FK4 (B1950) or FK5 (J2000) coordinate systems. Units are in fractional years.
out_coord_epoch (float) – Epoch for the output coordinate frame. Optional parameter, only required when using either the FK4 (B1950) or FK5 (J2000) coordinate systems. Units are in fractional years.
time_array (float or ndarray of floats) – Julian date(s) to which the coordinates correspond to, only used in frames with annular motion terms (e.g., abberation in GCRS). Can either be a float, or an ndarray of floats with shape (Ntimes,), assuming that either lat_coord and lon_coord are floats, or that Ntimes == Ncoords.
- Returns:
new_lat (float or ndarray of floats) – Longitudinal coordinates, in units of radians. Output will be an ndarray if any inputs were, with shape (Ncoords,) or (Ntimes,), depending on inputs.
new_lon (float or ndarray of floats) – Latidudinal coordinates, in units of radians. Output will be an ndarray if any inputs were, with shape (Ncoords,) or (Ntimes,), depending on inputs.
- pyuvdata.utils.phasing.transform_icrs_to_app(*, time_array, ra, dec, telescope_loc, telescope_frame='itrs', ellipsoid=None, epoch=2000.0, pm_ra=None, pm_dec=None, vrad=None, dist=None, astrometry_library=None)[source]
Transform a set of coordinates in ICRS to topocentric/apparent coordinates.
This utility uses one of three libraries (astropy, NOVAS, or ERFA) to calculate the apparent (i.e., topocentric) coordinates of a source at a given time and location, given a set of coordinates expressed in the ICRS frame. These coordinates are most typically used for defining the phase center of the array (i.e, calculating baseline vectors).
As of astropy v4.2, the agreement between the three libraries is consistent down to the level of better than 1 mas, with the values produced by astropy and pyERFA consistent to bettter than 10 µas (this is not surprising, given that astropy uses pyERFA under the hood for astrometry). ERFA is the default as it outputs coordinates natively in the apparent frame (whereas NOVAS and astropy do not), as well as the fact that of the three libraries, it produces results the fastest.
- Parameters:
time_array (float or array-like of float) – Julian dates to calculate coordinate positions for. Can either be a single float, or an array-like of shape (Ntimes,).
ra (float or array-like of float) – ICRS RA of the celestial target, expressed in units of radians. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (with the exception of telescope location parameters).
dec (float or array-like of float) – ICRS Dec of the celestial target, expressed in units of radians. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (with the exception of telescope location parameters).
telescope_loc (array-like of floats or EarthLocation or MoonLocation) – ITRS latitude, longitude, and altitude (rel to sea-level) of the phase center of the array. Can either be provided as an astropy EarthLocation, or a tuple of shape (3,) containing (in order) the latitude, longitude, and altitude, in units of radians, radians, and meters, respectively.
telescope_frame (str, optional) – Reference frame for telescope location. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
epoch (int or float or str or Time object) – Epoch of the coordinate data supplied, only used when supplying proper motion values. If supplying a number, it will assumed to be in Julian years. Default is J2000.0.
pm_ra (float or array-like of float) – Proper motion in RA of the source, expressed in units of milliarcsec / year. Proper motion values are applied relative to the J2000 (i.e., RA/Dec ICRS values should be set to their expected values when the epoch is 2000.0). Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Note that units are in dRA/dt, not cos(Dec)*dRA/dt. Not required.
pm_dec (float or array-like of float) – Proper motion in Dec of the source, expressed in units of milliarcsec / year. Proper motion values are applied relative to the J2000 (i.e., RA/Dec ICRS values should be set to their expected values when the epoch is 2000.0). Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Not required.
vrad (float or array-like of float) – Radial velocity of the source, expressed in units of km / sec. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Not required.
dist (float or array-like of float) – Distance of the source, expressed in milliarcseconds. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Not required.
astrometry_library (str) – Library used for running the coordinate conversions. Allowed options are ‘erfa’ (which uses the pyERFA), ‘novas’ (which uses the python-novas library), and ‘astropy’ (which uses the astropy utilities). Default is erfa unless the telescope_location is a MoonLocation object, in which case the default is astropy.
- Returns:
app_ra (ndarray of floats) – Apparent right ascension coordinates, in units of radians, of shape (Ntimes,).
app_dec (ndarray of floats) – Apparent declination coordinates, in units of radians, of shape (Ntimes,).
- pyuvdata.utils.phasing.transform_app_to_icrs(*, time_array, app_ra, app_dec, telescope_loc, telescope_frame='itrs', ellipsoid='SPHERE', astrometry_library=None)[source]
Transform a set of coordinates in topocentric/apparent to ICRS coordinates.
This utility uses either astropy or erfa to calculate the ICRS coordinates of a given set of apparent source coordinates. These coordinates are most typically used for defining the celestial/catalog position of a source. Note that at present, this is only implemented in astropy and pyERFA, although it could hypothetically be extended to NOVAS at some point.
- Parameters:
time_array (float or ndarray of float) – Julian dates to calculate coordinate positions for. Can either be a single float, or an ndarray of shape (Ntimes,).
app_ra (float or ndarray of float) – ICRS RA of the celestial target, expressed in units of radians. Can either be a single float or array of shape (Ncoord,). Note that if time_array is not a singleton value, then Ncoord must be equal to Ntimes.
app_dec (float or ndarray of float) – ICRS Dec of the celestial target, expressed in units of radians. Can either be a single float or array of shape (Ncoord,). Note that if time_array is not a singleton value, then Ncoord must be equal to Ntimes.
telescope_loc (tuple of floats or EarthLocation) – ITRF latitude, longitude, and altitude (rel to sea-level) of the phase center of the array. Can either be provided as an astropy EarthLocation, or a tuple of shape (3,) containing (in order) the latitude, longitude, and altitude, in units of radians, radians, and meters, respectively.
telescope_frame (str, optional) – Reference frame for telescope location. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
astrometry_library (str) – Library used for running the coordinate conversions. Allowed options are ‘erfa’ (which uses the pyERFA), and ‘astropy’ (which uses the astropy utilities). Default is erfa unless the telescope_location is a MoonLocation object, in which case the default is astropy.
- Returns:
icrs_ra (ndarray of floats) – ICRS right ascension coordinates, in units of radians, of either shape (Ntimes,) if Ntimes >1, otherwise (Ncoord,).
icrs_dec (ndarray of floats) – ICRS declination coordinates, in units of radians, of either shape (Ntimes,) if Ntimes >1, otherwise (Ncoord,).
- pyuvdata.utils.phasing.calc_parallactic_angle(*, app_ra, app_dec, lst_array, telescope_lat)[source]
Calculate the parallactic angle between RA/Dec and the AltAz frame.
- Parameters:
app_ra (ndarray of floats) – Array of apparent RA values in units of radians, shape (Ntimes,).
app_dec (ndarray of floats) – Array of apparent dec values in units of radians, shape (Ntimes,).
telescope_lat (float) – Latitude of the observatory, in units of radians.
lst_array (float or ndarray of float) – Array of local apparent sidereal timesto calculate position angle values for, in units of radians. Can either be a single float or an array of shape (Ntimes,).
- pyuvdata.utils.phasing.calc_frame_pos_angle(*, time_array, app_ra, app_dec, telescope_loc, ref_frame, ref_epoch=None, telescope_frame='itrs', ellipsoid='SPHERE', offset_pos=0.008726646259971648)[source]
Calculate an position angle given apparent position and reference frame.
This function is used to determine the position angle between the great circle of declination in apparent coordinates, versus that in a given reference frame. Note that this is slightly different than parallactic angle, which is the difference between apparent declination and elevation.
Paramters
- time_arrayndarray of floats
Array of julian dates to calculate position angle values for, of shape (Ntimes,).
- app_randarray of floats
Array of apparent RA values in units of radians, shape (Ntimes,).
- app_decndarray of floats
Array of apparent dec values in units of radians, shape (Ntimes,).
- telescope_loctuple of floats or EarthLocation
ITRF latitude, longitude, and altitude (rel to sea-level) of the observer. Can either be provided as an astropy EarthLocation, or an array-like of shape (3,) containing the latitude, longitude, and altitude, in that order, with units of radians, radians, and meters, respectively.
- ref_framestr
Coordinate frame to calculate position angles for. Can be any of the several supported frames in astropy (a limited list: fk4, fk5, icrs, gcrs, cirs, galactic).
- ref_epochstr or flt
Epoch of the coordinates, only used when ref_frame = fk4 or fk5. Given in unites of fractional years, either as a float or as a string with the epoch abbreviation (e.g, Julian epoch 2000.0 would be J2000.0).
- telescope_frame: str, optional
Reference frame for telescope location. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
- ellipsoidstr
Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
- offset_posfloat
Distance of the offset position used to calculate the frame PA. Default is 0.5 degrees, which should be sufficent for most applications.
- returns:
frame_pa (ndarray of floats) – Array of position angles, in units of radians.
- pyuvdata.utils.phasing.lookup_jplhorizons(target_name, time_array, *, telescope_loc=None, high_cadence=False, force_indv_lookup=None)[source]
Lookup solar system body coordinates via the JPL-Horizons service.
This utility is useful for generating ephemerides, which can then be interpolated in order to provide positional data for a target which is moving, such as planetary bodies and other solar system objects. Use of this function requires the installation of the astroquery module.
- Parameters:
target_name (str) – Name of the target to gather an ephemeris for. Must match the name in the JPL-Horizons database.
time_array (array-like of float) – Times in UTC Julian days to gather an ephemeris for.
telescope_loc (tuple of floats or EarthLocation) – ITRS latitude, longitude, and altitude (rel to sea-level) of the observer. Can either be provided as an EarthLocation object, or an array-like of shape (3,) containing the latitude, longitude, and altitude, in that order, with units of radians, radians, and meters, respectively.
high_cadence (bool) – If set to True, will calculate ephemeris points every 3 minutes in time, as opposed to the default of every 3 hours.
force_indv_lookup (bool) – If set to True, will calculate coordinate values for each value found within time_array. If False, a regularized time grid is sampled that encloses the values contained within time_array. Default is False, unless time_array is of length 1, in which the default is set to True.
- Returns:
ephem_times (ndarray of float) – Times for which the ephemeris values were calculated, in UTC Julian days.
ephem_ra (ndarray of float) – ICRS Right ascension of the target at the values within ephem_times, in units of radians.
ephem_dec (ndarray of float) – ICRS Declination of the target at the values within ephem_times, in units of radians.
ephem_dist (ndarray of float) – Distance of the target relative to the observer, at the values within ephem_times, in units of parsecs.
ephem_vel (ndarray of float) – Velocity of the targets relative to the observer, at the values within ephem_times, in units of km/sec.
- pyuvdata.utils.phasing.interpolate_ephem(*, time_array, ephem_times, ephem_ra, ephem_dec, ephem_dist=None, ephem_vel=None)[source]
Interpolates ephemerides to give positions for requested times.
This is a simple tool for calculated interpolated RA and Dec positions, as well as distances and velocities, for a given ephemeris. Under the hood, the method uses as cubic spline interpolation to calculate values at the requested times, provided that there are enough values to interpolate over to do so (requires >= 4 points), otherwise a linear interpolation is used.
- Parameters:
time_array (array-like of floats) – Times to interpolate positions for, in UTC Julian days.
ephem_times (array-like of floats) – Times in UTC Julian days which describe that match to the recorded postions of the target. Must be array-like, of shape (Npts,), where Npts is the number of ephemeris points.
ephem_ra (array-like of floats) – Right ascencion of the target, at the times given in ephem_times. Units are in radians, must have the same shape as ephem_times.
ephem_dec (array-like of floats) – Declination of the target, at the times given in ephem_times. Units are in radians, must have the same shape as ephem_times.
ephem_dist (array-like of floats) – Distance of the target from the observer, at the times given in ephem_times. Optional argument, in units of parsecs. Must have the same shape as ephem_times.
ephem_vel (array-like of floats) – Velocities of the target, at the times given in ephem_times. Optional argument, in units of km/sec. Must have the same shape as ephem_times.
- Returns:
ra_vals (ndarray of float) – Interpolated RA values, returned as an ndarray of floats with units of radians, and the same shape as time_array.
dec_vals (ndarray of float) – Interpolated declination values, returned as an ndarray of floats with units of radians, and the same shape as time_array.
dist_vals (None or ndarray of float) – If ephem_dist was provided, an ndarray of floats (with same shape as time_array) with the interpolated target distances, in units of parsecs. If ephem_dist was not provided, this returns as None.
vel_vals (None or ndarray of float) – If ephem_vals was provided, an ndarray of floats (with same shape as time_array) with the interpolated target velocities, in units of km/sec. If ephem_vals was not provided, this returns as None.
- pyuvdata.utils.phasing.calc_app_coords(*, lon_coord, lat_coord, coord_frame='icrs', coord_epoch=None, coord_times=None, coord_type='sidereal', time_array=None, lst_array=None, telescope_loc=None, telescope_frame='itrs', ellipsoid=None, pm_ra=None, pm_dec=None, vrad=None, dist=None, all_times_unique: bool | None = None)[source]
Calculate apparent coordinates for several different coordinate types.
This function calculates apparent positions at the current epoch.
- Parameters:
lon_coord (float or ndarray of float) – Longitudinal (e.g., RA) coordinates, units of radians. Must match the same shape as lat_coord.
lat_coord (float or ndarray of float) – Latitudinal (e.g., Dec) coordinates, units of radians. Must match the same shape as lon_coord.
coord_frame (string) – The requested reference frame for the output coordinates, can be any frame that is presently supported by astropy.
coord_epoch (float or str or Time object) – Epoch for ref_frame, nominally only used if converting to either the FK4 or FK5 frames, in units of fractional years. If provided as a float and the coord_frame is an FK4-variant, value will assumed to be given in Besselian years (i.e., 1950 would be ‘B1950’), otherwise the year is assumed to be in Julian years.
coord_times (float or ndarray of float) – Only used when coord_type=”ephem”, the JD UTC time for each value of lon_coord and lat_coord. These values are used to interpolate lon_coord and lat_coord values to those times listed in time_array.
coord_type (str) –
Type of source to calculate coordinates for. Must be one of:
“sidereal” (fixed RA/Dec),
“ephem” (RA/Dec that moves with time),
“driftscan” (fixed az/el position),
“unprojected” (alias for “driftscan” with (Az, Alt) = (0 deg, 90 deg)).
“near_field” (equivalent to sidereal, with the addition of near-field corrections)
time_array (float or ndarray of float or Time object) – Times for which the apparent coordinates are to be calculated, in UTC JD. If more than a single element, must be the same shape as lon_coord and lat_coord if both of those are arrays (instead of single floats).
telescope_loc (array-like of floats or EarthLocation or MoonLocation) – ITRF latitude, longitude, and altitude (rel to sea-level) of the phase center of the array. Can either be provided as an astropy EarthLocation, a lunarsky Moonlocation, or a tuple of shape (3,) containing (in order) the latitude, longitude, and altitude for a position on Earth in units of radians, radians, and meters, respectively.
telescope_frame (str, optional) – Reference frame for telescope location. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
pm_ra (float or ndarray of float) – Proper motion in RA of the source, expressed in units of milliarcsec / year. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Not required, motion is calculated relative to the value of coord_epoch.
pm_dec (float or ndarray of float) – Proper motion in Dec of the source, expressed in units of milliarcsec / year. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Not required, motion is calculated relative to the value of coord_epoch.
vrad (float or ndarray of float) – Radial velocity of the source, expressed in units of km / sec. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Not required.
dist (float or ndarray of float) – Distance of the source, expressed in milliarcseconds. Can either be a single float or array of shape (Ntimes,), although this must be consistent with other parameters (namely ra_coord and dec_coord). Not required.
all_times_unique – Boolean specifying whether all the times that were passed are unique. Default is to determine this within the function, but specifying it here can improve performance.
- Returns:
app_ra (ndarray of floats) – Apparent right ascension coordinates, in units of radians.
app_dec (ndarray of floats) – Apparent declination coordinates, in units of radians.
- pyuvdata.utils.phasing.calc_sidereal_coords(*, time_array, app_ra, app_dec, telescope_loc, coord_frame, telescope_frame='itrs', ellipsoid=None, coord_epoch=None)[source]
Calculate sidereal coordinates given apparent coordinates.
This function calculates coordinates in the requested frame (at a given epoch) from a set of apparent coordinates.
- Parameters:
time_array (float or ndarray of float or Time object) – Times for which the apparent coordinates were calculated, in UTC JD. Must match the shape of app_ra and app_dec.
app_ra (float or ndarray of float) – Array of apparent right ascension coordinates, units of radians. Must match the shape of time_array and app_dec.
app_ra (float or ndarray of float) – Array of apparent right declination coordinates, units of radians. Must match the shape of time_array and app_dec.
telescope_loc (tuple of floats or EarthLocation) – ITRF latitude, longitude, and altitude (rel to sea-level) of the phase center of the array. Can either be provided as an astropy EarthLocation, or a tuple of shape (3,) containing (in order) the latitude, longitude, and altitude, in units of radians, radians, and meters, respectively.
coord_frame (string) – The requested reference frame for the output coordinates, can be any frame that is presently supported by astropy. Default is ICRS.
telescope_frame (str, optional) – Reference frame for telescope location. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
coord_epoch (float or str or Time object) – Epoch for ref_frame, nominally only used if converting to either the FK4 or FK5 frames, in units of fractional years. If provided as a float and the ref_frame is an FK4-variant, value will assumed to be given in Besselian years (i.e., 1950 would be ‘B1950’), otherwise the year is assumed to be in Julian years.
- Returns:
ref_ra (ndarray of floats) – Right ascension coordinates in the requested frame, in units of radians. Either shape (Ntimes,) if Ntimes >1, otherwise (Ncoord,).
ref_dec (ndarray of floats) – Declination coordinates in the requested frame, in units of radians. Either shape (Ntimes,) if Ntimes >1, otherwise (Ncoord,).
- pyuvdata.utils.phasing.uvw_track_generator(*, lon_coord=None, lat_coord=None, coord_frame='icrs', coord_epoch=None, coord_type='sidereal', time_array=None, telescope_loc=None, telescope_frame='itrs', ellipsoid=None, antenna_positions=None, antenna_numbers=None, ant_1_array=None, ant_2_array=None, uvw_array=None, force_postive_u=False)[source]
Calculate uvw coordinates (among other values) for a given position on the sky.
This function is meant to be a user-friendly wrapper around several pieces of code for effectively simulating a track.
- Parameters:
lon_coord (float or ndarray of float) – Longitudinal (e.g., RA) coordinates, units of radians. Must match the same shape as lat_coord.
lat_coord (float or ndarray of float) – Latitudinal (e.g., Dec) coordinates, units of radians. Must match the same shape as lon_coord.
coord_frame (string) – The requested reference frame for the output coordinates, can be any frame that is presently supported by astropy.
coord_epoch (float or str or Time object, optional) – Epoch for ref_frame, nominally only used if converting to either the FK4 or FK5 frames, in units of fractional years. If provided as a float and the ref_frame is an FK4-variant, value will assumed to be given in Besselian years (i.e., 1950 would be ‘B1950’), otherwise the year is assumed to be in Julian years.
coord_type (str) –
- Type of source to calculate coordinates for. Must be one of:
“sidereal” (fixed RA/Dec), “ephem” (RA/Dec that moves with time), “driftscan” (fixed az/el position), “unprojected” (alias for “driftscan” with (Az, Alt) = (0 deg, 90 deg)).
time_array (ndarray of float or Time object) – Times for which the apparent coordinates were calculated, in UTC JD. Must match the shape of lon_coord and lat_coord.
telescope_loc (array-like of floats or EarthLocation or MoonLocation) – ITRF latitude, longitude, and altitude (rel to sea-level) of the phase center of the array. Can either be provided as an astropy EarthLocation, a lunarsky Moonlocation, or a tuple of shape (3,) containing (in order) the latitude, longitude, and altitude for a position on Earth in units of degrees, degrees, and meters, respectively.
telescope_frame (str, optional) – Reference frame for latitude/longitude/altitude. Options are itrs (default) or mcmf. Only used if telescope_loc is not an EarthLocation or MoonLocation.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
antenna_positions (ndarray of float) – List of antenna positions relative to array center in ECEF coordinates, required if not providing uvw_array. Shape is (Nants, 3).
antenna_numbers (ndarray of int, optional) – List of antenna numbers, ordered in the same way as antenna_positions (e.g., antenna_numbers[0] should given the number of antenna that resides at ECEF position given by antenna_positions[0]). Shape is (Nants,), requred if supplying ant_1_array and ant_2_array.
ant_1_array (ndarray of int, optional) – Antenna number of the first antenna in the baseline pair, for all baselines Required if not providing uvw_array, shape is (Nblts,). If not supplied, then the method will automatically fill in ant_1_array with all unique antenna pairings for each time/position.
ant_2_array (ndarray of int, optional) – Antenna number of the second antenna in the baseline pair, for all baselines Required if not providing uvw_array, shape is (Nblts,). If not supplied, then the method will automatically fill in ant_2_array with all unique antenna pairings for each time/position.
uvw_array (ndarray of float, optional) – Array of baseline coordinates (in ENU), required if not deriving new coordinates from antenna positions. Setting this value will will cause antenna positions to be ignored. Shape is (Nblts, 3).
force_positive_u (bool, optional) – If set to true, then forces the conjugation of each individual baseline to be set such that the uvw coordinates land on the positive-u side of the uv-plane. Default is False.
- Returns:
obs_dict (dict) –
- Dictionary containing the results of the simulation, which includes:
”uvw” the uvw-coordinates (meters), “app_ra” apparent RA of the sources (radians), “app_dec” apparent Dec of the sources (radians), “frame_pa” ngle between apparent north and coord_frame north (radians), “lst” local apparent sidereal time (radians), “site_loc” EarthLocation or MoonLocation for the telescope site.
- pyuvdata.utils.phasing._get_focus_xyz(uvd, focus, ra, dec)[source]
Return the x,y,z coordinates of the focal point.
The focal point corresponds to the location of the near-field object of interest in the ENU frame centered on the median position of the antennas.
- Parameters:
uvd (UVData object) – UVData object
focus (float) – Focal distance of the array (km)
ra (float) – Right ascension of the focal point ie phase center (deg; shape (Ntimes,))
dec (float) – Declination of the focal point ie phase center (deg; shape (Ntimes,))
- Returns:
x, y, z (ndarray, ndarray, ndarray) – ENU-frame coordinates of the focal point (meters) (shape (Ntimes,))
- pyuvdata.utils.phasing._get_nearfield_delay(uvd, focus_x, focus_y, focus_z)[source]
Calculate near-field phase/delay along the Nblts axis.
- Parameters:
uvd (UVData object) – UVData object
focus_x, focus_y, focus_z (ndarray, ndarray, ndarray) – ENU-frame coordinates of focal point (Each of shape (Ntimes,))
- Returns:
new_w (ndarray) – The calculated near-field delay (or w-term) for each visibility along the Nblts axis
Functions for working with polarizations
Utilities for working with polarizations.
- pyuvdata.utils.pol.x_orientation_pol_map(x_orientation: str) dict[source]
Return map from “x” and “y” pols to “e” and “n” based on x_orientation.
- Parameters:
x_orientation (str) – String giving the x_orientation, one of “east” or “north”.
- Returns:
dict – Dictionary mapping “x” and “y” pols to “e” and “n” based on x_orientation.
- pyuvdata.utils.pol.polstr2num(pol: str | Iterable[str], *, x_orientation: str | None = None)[source]
Convert polarization str to number according to AIPS Memo 117.
Prefer ‘pI’, ‘pQ’, ‘pU’ and ‘pV’ to make it clear that these are pseudo-Stokes, not true Stokes, but also supports ‘I’, ‘Q’, ‘U’, ‘V’.
- Parameters:
pol (str) – polarization string
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings. See corresonding parameter on UVData for more details.
- Returns:
int – Number corresponding to string
- Raises:
ValueError – If the pol string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.pol.polnum2str(num, *, x_orientation=None)[source]
Convert polarization number to str according to AIPS Memo 117.
Uses ‘pI’, ‘pQ’, ‘pU’ and ‘pV’ to make it clear that these are pseudo-Stokes, not true Stokes
- Parameters:
num (int) – polarization number
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to convert to E/N strings. See corresonding parameter on UVData for more details.
- Returns:
str – String corresponding to polarization number
- Raises:
ValueError – If the polarization number cannot be converted to a polarization string.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.pol.jstr2num(jstr, *, x_orientation=None)[source]
Convert jones polarization str to number according to calfits memo.
- Parameters:
jstr (str or array_like of str) – antenna (jones) polarization string(s) to convert.
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings. See corresonding parameter on UVData for more details.
- Returns:
int or list of int – antenna (jones) polarization number(s) corresponding to the input string(s)
- Raises:
ValueError – If the jones string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.pol.jnum2str(jnum, *, x_orientation=None)[source]
Convert jones polarization number to str according to calfits memo.
- Parameters:
num (int or array_like of int) – antenna (jones) polarization number(s) to convert to strings
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to convert to E/N strings. See corresonding parameter on UVData for more details.
- Returns:
str or list of str – antenna (jones) polarization string(s) corresponding to number
- Raises:
ValueError – If the jones polarization number cannot be converted to a jones polarization string.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.pol.parse_polstr(polstr, *, x_orientation=None)[source]
Parse a polarization string and return pyuvdata standard polarization string.
See utils.POL_STR2NUM_DICT for options.
- Parameters:
polstr (str) – polarization string
x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings. See corresonding parameter on UVData for more details.
- Returns:
str – AIPS Memo 117 standard string
- Raises:
ValueError – If the pol string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.pol.parse_jpolstr(jpolstr, *, x_orientation=None)[source]
Parse a Jones polarization string and return pyuvdata standard jones string.
See utils.JONES_STR2NUM_DICT for options.
- Parameters:
jpolstr (str) – Jones polarization string
- Returns:
str – calfits memo standard string
- Raises:
ValueError – If the jones string cannot be converted to a polarization number.
- Warns:
UserWarning – If the x_orientation not recognized.
- pyuvdata.utils.pol.conj_pol(pol)[source]
Return the polarization for the conjugate baseline.
For example, (1, 2, ‘xy’) = conj(2, 1, ‘yx’). The returned polarization is determined by assuming the antenna pair is reversed in the data, and finding the correct polarization correlation which will yield the requested baseline when conjugated. Note this means changing the polarization for linear cross-pols, but keeping auto-pol (e.g. xx) and Stokes the same.
- Parameters:
pol (str or int) – Polarization string or integer.
- Returns:
cpol (str or int) – Polarization as if antennas are swapped (type matches input)
- pyuvdata.utils.pol.reorder_conj_pols(pols)[source]
Reorder multiple pols, swapping pols that are conjugates of one another.
For example (‘xx’, ‘xy’, ‘yx’, ‘yy’) -> (‘xx’, ‘yx’, ‘xy’, ‘yy’) This is useful for the _key2inds function in the case where an antenna pair is specified but the conjugate pair exists in the data. The conjugated data should be returned in the order of the polarization axis, so after conjugating the data, the pols need to be reordered. For example, if a file contains antpair (0, 1) and pols ‘xy’ and ‘yx’, but the user requests antpair (1, 0), they should get: [(1x, 0y), (1y, 0x)] = [conj(0y, 1x), conj(0x, 1y)]
- Parameters:
pols (array_like of str or int) – Polarization array (strings or ints).
- Returns:
conj_order (ndarray of int) – Indices to reorder polarization array.
- pyuvdata.utils.pol.determine_pol_order(pols, *, order='AIPS')[source]
Determine order of input polarization numbers.
Determines the order by which to sort a given list of polarizations, according to the ordering scheme. Two orders are currently supported: “AIPS” and “CASA”. The main difference between the two is the grouping of same-handed polarizations for AIPS (whereas CASA orders the polarizations such that same-handed pols are on the ends of the array).
- Parameters:
pols (array_like of str or int) – Polarization array (strings or ints).
order (str) – Polarization ordering scheme, either “CASA” or “AIPS”.
- Returns:
index_array (ndarray of int) – Indices to reorder polarization array.
- pyuvdata.utils.pol.convert_feeds_to_pols(feed_array: ndarray[tuple[Any, ...], dtype[str_]], include_cross_pols: bool = True, x_orientation: str | None = None, return_feed_pol_order: bool = False)[source]
Get the polarizations given a feed array.
- Parameters:
feed_array (ndarray of str) – Array of feed orientations. Options are: n/e or x/y or r/l.
include_cross_pols (bool) – Option to include the cross polarizations (e.g. xy and yx or en and ne). Defaults to True if more than one feed, set to False for only one feed.
x_orientation (str, optional) – Orientation of the x-axis. Options are ‘east’, ‘north’, ‘e’, ‘n’, ‘ew’, ‘ns’.
return_feed_pol_order (bool) – Option to return a list of tuples giving the ordering of the feeds for each pol. Default False.
- Returns:
polarization_array (ndarray of int) – Polarization integer array.
feed_pol_order (list of tuples of int, optional) – List of feed index tuples for each pol.
- pyuvdata.utils.pol._select_pol_helper(polarizations, obj_pol_array, obj_x_orientation=None, flex_pol=False, invert=False, strict=False, is_jones=False, warn_spacing=False)[source]
Get polarization indices in a select.
- Parameters:
polarizations (array_like of str or int) – The polarizations to keep in the object, each value passed here should exist in obj_pol_array (unless invert=True).
obj_pol_array (array_like of int) – The polarizations present in the object.
obj_x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings.
flex_pol (bool) – Demark whether or not the object is a flex-pol object, which by construct has no polarization axis to select on (it’s folded onto the spw-axis instead). Default is False.
invert (bool) – Normally indices matching given criteria are what are included in the subsequent list. However, if set to True, these indices are excluded instead. Default is False.
strict (bool or None) – Normally, select will warn when an element of the selection criteria does not match any element for the parameter, as long as the selection criteria results in at least one element being selected. However, if set to True, an error is thrown if any selection criteria does not match what is given for the object parameters element. If set to None, then neither errors nor warnings are raised, unless no records are selected. Default is False.
is_jones (bool) – Normally this function handles polarizations, but if set to True, Jones terms can be input instead. Default is False, it is recommended rather than using this setting directly one should use the function _select_jones_helper instead.
warn_spacing (bool) – Whether or not to warn about polarization spacing. Default is False.
- Returns:
pol_inds (list of int) – Indices of polarization to keep on the object.
selections (list of str) – list of selections done.
- pyuvdata.utils.pol._select_jones_helper(jones, obj_jones_array, obj_x_orientation=None, flex_jones=False, invert=False, strict=False, warn_spacing=False)[source]
Get Jones indices in a select.
- Parameters:
jones (array_like of str or int) – The Jones terms to keep in the object, each value passed here should exist in obj_jones_array (unless invert=True).
obj_jones_array (array_like of int) – The Jones terms present in the object.
obj_x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings.
flex_jones (bool) – Demark whether or not the object is a flex-Jones object, which by construct has no Jones axis to select on (it’s folded onto the spw-axis instead). Default is False.
invert (bool) – Normally indices matching given criteria are what are included in the subsequent list. However, if set to True, these indices are excluded instead. Default is False.
strict (bool or None) – Normally, select will warn when an element of the selection criteria does not match any element for the parameter, as long as the selection criteria results in at least one element being selected. However, if set to True, an error is thrown if any selection criteria does not match what is given for the object parameters element. If set to None, then neither errors nor warnings are raised, unless no records are selected. Default is False.
warn_spacing (bool) – Whether or not to warn about Jones spacing. Default is False.
- Returns:
jones_inds (list of int) – Indices of Jones terms to keep on the object.
selections (list of str) – list of selections done.
- pyuvdata.utils.pol._select_feed_helper(feeds, obj_feed_array, obj_x_orientation=None, feed_inds=None, invert=False, strict=False)[source]
Get Jones indices in a select.
- Parameters:
feeds (array_like of str) – The feeds to keep in the object, each value passed here should exist in obj_feed_array (unless invert=True).
obj_feed_array (array_like of str) – The Jones terms present in the object.
obj_x_orientation (str, optional) – Orientation of the physical dipole corresponding to what is labelled as the x polarization (“east” or “north”) to allow for converting from E/N strings.
invert (bool) – Normally indices matching given criteria are what are included in the subsequent list. However, if set to True, these indices are excluded instead. Default is False.
strict (bool or None) – Normally, select will warn when an element of the selection criteria does not match any element for the parameter, as long as the selection criteria results in at least one element being selected. However, if set to True, an error is thrown if any selection criteria does not match what is given for the object parameters element. If set to None, then neither errors nor warnings are raised, unless no records are selected. Default is False.
- Returns:
feed_inds (list of int) – Indices of feeds to keep on the object.
selections (list of str) – list of selections done.
- pyuvdata.utils.pol._check_pol_spacing(*, polarization_array, strict=True, allow_resort=False)[source]
Check if polarizations are evenly spaced.
This is a requirement for writing uvfits and beamfits files.
- Parameters:
polarization_array (array-like of int or UVParameter) – Array of polarization codes, shape (Npols,).
strict (bool) – If set to True, then the function will raise an error if checks are failed. If set to False, then a warning is raised instead. If set to None, then no errors or warnings are raised.
allow_resort (bool) – If set to False, polarizations are checked in their present order. If set to True, values are sorted prior to evaluating (useful for cases where the polarization index can be reindexed). Default is False.
- pyuvdata.utils.pol._check_jones_spacing(*, jones_array, strict=True, allow_resort=False)[source]
Check if Jones polarization terms are equally spaced.
This is a requirement for writing calfits files.
- Parameters:
jones_array (array-like of int or UVParameter) – Array of Jones codes, shape (Njones,).
strict (bool) – If set to True, then the function will raise an error if checks are failed. If set to False, then a warning is raised instead. If set to None, then no errors or warnings are raised.
allow_resort (bool) – If set to False, jones terms are checked in their present order. If set to True, values are sorted prior to evaluating (useful for cases where the jones index can be reindexed). Default is False.
- pyuvdata.utils.pol.get_feeds_from_pols(polarization_array)[source]
Return a list of expected feeds based on polarization values.
Translates values in polarization_array or jones_array into a list of feeds expected to be present in the underlying telescope.
- Parameters:
polarization_array (array_like of int) – Array listing the polarization codes present, based on the UVFITS numbering schedule. See utils.POL_NUM2STR_DICT for a mapping between codes and polarization types.
- Returns:
feed_array (list of str) – List of expected feed types given the polarizations present in the data. Will be one of “x”, “y”, “l”, “r”, and generally of length <= 2.
- pyuvdata.utils.pol.get_x_orientation_from_feeds(feed_array, feed_angle, tols=None)[source]
Determine x-orientation equivalent value based on feed information.
This is a helper function meant to provide a way of translating newer parameters (feed_array and feed_angle) describing feed orientation with the older “x-orientation” parameter.
- Parameters:
feed_array (array-like of str or None) – List of feeds for a given telescope, should be one of “x”, “y”, “l”, “r”. Shape (Nants, Nfeeds) or (Nfeeds,), must match that of feed_angle, dtype str.
feed_angle (array-like of float) – Orientation of the feed with respect to zenith (or with respect to north if pointed at zenith). Units is in rads, x-polarization is nominally pi / 2, and y-polarization (and l- and r-polarizations) is nominally 0. Shape (Nants, Nfeeds) or (Nfeeds,), must match that of feed_array, dtype float.
tols (tuple of float) – Tolerances for feed_angle, used with isclose.
- Returns:
x_orientation (str) – One of “east”, “north”, or None, based on values present in feed_array and feed_angle. None denotes that either one (or both) of feed_array and feed_angle were None, or that the values were inconsistent with either “north” or “east” orientation.
- pyuvdata.utils.pol.get_feeds_from_x_orientation(*, x_orientation, nants, feeds=None, feed_array=None, polarization_array=None, flex_polarization_array=None)[source]
Determine feed angles based on equivalent x-orientation.
This is a helper function meant to provide a way of translating the older “x-orientation” parameter into the newer parameters describing feed orientation (feed_array and feed_angle).
- Parameters:
x_orientation (str) – String describing the orientation of the x-polarization. Must be one of “east” or “north” (or the associated aliases “n”, “e”, “ns”, “ew”)
nants (int) – Number of antennas, used to determine the shape of the output.
feeds (str or array-like of str) – List of feeds expected for the telescope. Must be one of “x”, “y”, “l”, or “r”. A single feed type can be provided as a string, otherwise the list should contain no more than two elements. If not provided (and polarization_array is also not provided), default is [“x”, “y”]. Ignored if feed_array is set.
feed_array (array-like of str or None) – List of feeds, given on a per-antenna basis. Each feed will be listed as one of “x”, “y”, “l”, “r”. Shape (Nants, Nfeeds), dtype str (or None of x_orientation is None).
polarization_array (array-like of int or None) – Array listing the polarization codes present, based on the UVFITS numbering scheme. See utils.POL_NUM2STR_DICT for a mapping between codes and polarization types. Used with utils.pol.get_feeds_from_pols to determine feeds present if not supplied, ignored if flex_polarization_array is set to anything but None.
flex_polarization_array (array-like of int or None) – Array listing the polarization codes present per spectral window (used with certain “flexible-polarization” objects), based on the UVFITS numbering scheme. See utils.POL_NUM2STR_DICT for a mapping between codes and polarization types. Used with utils.pol.get_feeds_from_pols to determine feeds present if not supplied.
- Returns:
Nfeeds (int) – Length of feeds (or None of x_orientation is None).
feed_array (array-like of str or None) – List of feeds, given on a per-antenna basis. Each feed will be listed as one of “x”, “y”, “l”, “r”. Shape (Nants, Nfeeds), dtype str (or None of x_orientation is None).
feed_angle (array-like of float) – Orientation of the feed with respect to zenith (or with respect to north if pointed at zenith). Units is in rads, x-polarization is nominally pi / 2, and y-polarization (and l- and r-polarizations) is nominally 0. Shape (Nants, Nfeeds) (or None of x_orientation is None).
Functions for working with baseline redundancies
Utilities for working with redundant baselines.
- pyuvdata.utils.redundancy._adj_list(vecs, tol, n_blocks=None)[source]
Identify neighbors of each vec in vecs, to distance tol.
- pyuvdata.utils.redundancy.find_clusters(*, location_ids, location_vectors, tol, strict=False)[source]
Find clusters of vectors (e.g. redundant baselines, times).
- Parameters:
location_ids (array_like of int) – ID labels for locations.
location_vectors (array_like of float) – location vectors, can be multidimensional
tol (float) – tolerance for clusters
strict (bool) – Require that all adjacency lists be isolated maximal cliques. This ensures that vectors do not fall into multiple clusters. Default: False
- Returns:
list of list of location_ids
- pyuvdata.utils.redundancy.find_clusters_grid(location_ids, location_vectors, tol=1.0)[source]
Find redundant groups using a gridding algorithm developed by the HERA team.
This is essentially a gridding approach, but it only keeps track of the grid points that have baselines assigned to them. It iterates through the baselines and assigns each baseline to a an existing group if it is within a grid spacing or makes a new group if there is no group. The location of the group is the baseline vector of the first baseline assigned to it, rounded to the grid spacing, so the resulting assigned grid point can depend on the order in which baseline vectors are passed to it. It is possible for a baseline to be assigned to a group that is up to but strictly less than 4 times the grid spacing from its true location, so we use a grid a factor of 4 smaller than the passed tolerance (tol). This method is quite robust for regular arrays if the tolerance is properly specified, but may not behave predictably for highly non-redundant arrays.
- Parameters:
baselines (array_like of int) – Baseline numbers, shape (Nbls,)
baseline_vecs (array_like of float) – Baseline vectors in meters, shape (Nbls, 3).
tol (float) – Absolute tolerance of redundancy, in meters.
- Returns:
baseline_groups (list of lists of int) – list of lists of redundant baseline numbers
baseline_ind_conj (list of int) – List of baselines that are redundant when reversed. Only returned if include_conjugates is True
- pyuvdata.utils.redundancy.get_baseline_redundancies(baselines, baseline_vecs, *, tol=1.0, include_conjugates=None, use_grid_alg=True)[source]
Find redundant baseline groups.
- Parameters:
baselines (array_like of int) – Baseline numbers, shape (Nbls,)
baseline_vecs (array_like of float) – Baseline vectors in meters, shape (Nbls, 3).
tol (float) – Absolute tolerance of redundancy, in meters.
include_conjugates (bool) – Option to include baselines that are redundant under conjugation. Only used if use_antpos is False. Default is currently False but will become True in version 3.4.
use_grid_alg (bool) – Option to use the gridding based algorithm (developed by the HERA team) to find redundancies rather than the older clustering algorithm.
- Returns:
baseline_groups (list of lists of int) – list of lists of redundant baseline numbers
vec_bin_centers (list of array_like of float) – List of vectors describing redundant group centers
lengths (list of float) – List of redundant group baseline lengths in meters
baseline_ind_conj (list of int) – List of baselines that are redundant when reversed. Only returned if include_conjugates is True
- pyuvdata.utils.redundancy.get_antenna_redundancies(antenna_numbers, antenna_positions, *, tol=1.0, include_autos=False, use_grid_alg=True)[source]
Find redundant baseline groups based on antenna positions.
- Parameters:
antenna_numbers (array_like of int) – Antenna numbers, shape (Nants,).
antenna_positions (array_like of float) – Antenna position vectors in the ENU (topocentric) frame in meters, shape (Nants, 3).
tol (float) – Redundancy tolerance in meters.
include_autos (bool) – Option to include autocorrelations.
use_grid_alg (bool) – Option to use the gridding based algorithm (developed by the HERA team) to find redundancies rather than the older clustering algorithm.
- Returns:
baseline_groups (list of lists of int) – list of lists of redundant baseline numbers
vec_bin_centers (list of array_like of float) – List of vectors describing redundant group centers
lengths (list of float) – List of redundant group baseline lengths in meters
Notes
The baseline numbers refer to antenna pairs (a1, a2) such that the baseline vector formed from ENU antenna positions, blvec = enu[a1] - enu[a2] is close to the other baselines in the group.
This is achieved by putting baselines in a form of the u>0 convention, but with a tolerance in defining the signs of vector components.
To guarantee that the same baseline numbers are present in a UVData object,
UVData.conjugate_bls('u>0', uvw_tol=tol), where tol is the tolerance used here.
Functions for working with times and LSTs
Utilities for working LSTs.
- pyuvdata.utils.times.get_lst_for_time(jd_array=None, *, telescope_loc=None, latitude=None, longitude=None, altitude=None, astrometry_library=None, frame='itrs', ellipsoid=None)[source]
Get the local apparent sidereal time for a set of jd times at an earth location.
This function calculates the local apparent sidereal time (LAST), given a UTC time and a position on the Earth, using either the astropy or NOVAS libraries. It is important to note that there is an apporoximate 20 microsecond difference between the two methods, presumably due to small differences in the apparent reference frame. These differences will cancel out when calculating coordinates in the TOPO frame, so long as apparent coordinates are calculated using the same library (i.e., astropy or NOVAS). Failing to do so can introduce errors up to ~1 mas in the horizontal coordinate system (i.e., AltAz).
- Parameters:
jd_array (ndarray of float) – JD times to get lsts for.
telescope_loc (tuple or EarthLocation or MoonLocation) – Alternative way of specifying telescope lat/lon/alt, either as a 3-element tuple with latitude and longitude in degrees, or as an astropy EarthLocation (or lunarsky MoonLocation). Cannot supply both telescope_loc and latitute, longitude, or altitude.
latitude (float) – Latitude of location to get lst for in degrees. Cannot specify both latitute and telescope_loc.
longitude (float) – Longitude of location to get lst for in degrees. Cannot specify both longitude and telescope_loc.
altitude (float) – Altitude of location to get lst for in meters. Cannot specify both altitude and telescope_loc.
astrometry_library (str) – Library used for running the LST calculations. Allowed options are ‘erfa’ (which uses the pyERFA), ‘novas’ (which uses the python-novas library), and ‘astropy’ (which uses the astropy utilities). Default is erfa unless the telescope_location is a MoonLocation object, in which case the default is astropy.
frame (str) – Reference frame for latitude/longitude/altitude. Options are itrs (default) or mcmf. Not used if telescope_loc is an EarthLocation or MoonLocation object.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf. Not used if telescope_loc is an EarthLocation or MoonLocation object.
- Returns:
ndarray of float – LASTs in radians corresponding to the jd_array.
- pyuvdata.utils.times.check_lsts_against_times(*, jd_array, lst_array, lst_tols, latitude=None, longitude=None, altitude=None, frame='itrs', ellipsoid=None, telescope_loc=None)[source]
Check that LSTs are consistent with the time_array and telescope location.
This just calls get_lst_for_time, compares that result to the lst_array and warns if they are not within the tolerances specified by lst_tols.
- Parameters:
jd_array (ndarray of float) – JD times to get lsts for.
lst_array (ndarray of float) – LSTs to check to see if they match the jd_array at the location.
latitude (float) – Latitude of location to check the lst for in degrees.
longitude (float) – Longitude of location to check the lst for in degrees.
altitude (float) – Altitude of location to check the lst for in meters.
lst_tops (tuple of float) – A length 2 tuple giving the (relative, absolute) tolerances to check the LST agreement to. These are passed directly to numpy.allclose.
frame (str) – Reference frame for latitude/longitude/altitude. Options are itrs (default) or mcmf.
ellipsoid (str) – Ellipsoid to use for lunar coordinates. Must be one of “SPHERE”, “GSFC”, “GRAIL23”, “CE-1-LAM-GEO” (see lunarsky package for details). Default is “SPHERE”. Only used if frame is mcmf.
telescope_loc (tuple or EarthLocation or MoonLocation) – Alternative way of specifying telescope lat/lon/alt, either as a 3-element tuple or as an astropy EarthLocation (or lunarsky MoonLocation). Cannot supply both telescope_loc and latitute, longitude, or altitude.
- Returns:
None
- Warns:
If the `lst_array` does not match the calculated LSTs to the lst_tols.
- pyuvdata.utils.times._select_times_helper(*, times, time_range, lsts, lst_range, obj_time_array, obj_time_range, obj_lst_array, obj_lst_range, time_tols, lst_tols, time_inds=None, invert=False, strict=False, warn_spacing=False)[source]
Get time indices in a select.
- Parameters:
times (array_like of float) – The times to keep in the object, each value passed here should exist in the time_array. Can be None, cannot be set with time_range, lsts or lst_array.
time_range (array_like of float) – The time range in Julian Date to keep in the object, must be length 2. Some of the times in the object should fall between the first and last elements. Can be None, cannot be set with times, lsts or lst_array.
lsts (array_like of float) – The local sidereal times (LSTs) to keep in the object, each value passed here should exist in the lst_array. Can be None, cannot be set with times, time_range, or lst_range.
lst_range (array_like of float) – The local sidereal time (LST) range in radians to keep in the object, must be of length 2. Some of the LSTs in the object should fall between the first and last elements. If the second value is smaller than the first, the LSTs are treated as having phase-wrapped around LST = 2*pi = 0, and the LSTs kept on the object will run from the larger value, through 0, and end at the smaller value. Can be None, cannot be set with times, time_range, or lsts.
obj_time_array (array_like of float) – Time array on object. Can be None if object_time_range is set.
obj_time_range (array_like of float) – Time range on object. Can be None if object_time_array is set.
obj_lst_array (array_like of float) – LST array on object. Can be None if object_lst_range is set.
obj_lst_range (array_like of float) – LST range on object. Can be None if object_lst_array is set.
time_tols (tuple of float) – Length 2 tuple giving (rtol, atol) to use for time matching.
lst_tols (tuple of float) – Length 2 tuple giving (rtol, atol) to use for lst matching.
time_inds (array_like of int, optional) – The time indices to keep in the object. This is not commonly used.
invert (bool) – Normally indices matching given criteria are what are included in the subsequent list. However, if set to True, these indices are excluded instead. Default is False.
strict (bool or None) – Normally, select will warn when an element of the selection criteria does not match any element for the parameter, as long as the selection criteria results in at least one element being selected. However, if set to True, an error is thrown if any selection criteria does not match what is given for the object parameters element. If set to None, then neither errors nor warnings are raised, unless no records are selected. Default is False.
warn_spacing – Whether or not to warn about time spacing. Only used if no ranges from the object are supplied. Default is False.
- Returns:
time_inds (list of int) – Indices of times to keep on the object.
selections (list of str) – list of selections done.
- pyuvdata.utils.times._check_time_spacing(*, times_array, time_range=None, time_tols=None, integration_time=None, int_tols=None, strict=True)[source]
Check if times are evenly spaced.
This is a requirement for calfits files.
- Parameters:
times_array (array-like of float or UVParameter) – Array of times, shape (Ntimes,).
time_range (array-like of float or UVParameter) – Array of time ranges, shape (Ntime_ranges). Optional.
time_tols (tuple of float) – time_array tolerances (from uvobj._time_array.tols). Optional.
integration_time (array-like of float or UVParameter) – Array of integration times, shape (Ntimes,). Optional.
channel_width_tols (tuple of float) – integration_time tolerances (from uvobj._integration_time.tols). Optional.
strict (bool) – If set to True, then the function will raise an error if checks are failed. If set to False, then a warning is raised instead. If set to None, then no errors or warnings are raised. Default is True.
General utility functions
Basic utility functions.
- pyuvdata.utils.tools._combine_filenames(filename1, filename2)[source]
Combine the filename attribute from multiple UVBase objects.
The 4 cases are: 1. filename1 has been set, filename2 has not 2. filename1 has not been set, filename2 has 3. filename1 and filename2 both have been set 4. filename1 and filename2 both have not been set In case (1), we do not want to update the attribute, because it is already set correctly. In case (2), we want to replace filename1 with the value from filename2. In case (3), we want to take the union of the sets of the filenames. In case (4), we want the filename attribute to still be `None.
- Parameters:
filename1 (list of str or None) – The list of filenames for the first UVBase object. If it is not set, it should be None.
filename2 (list of str or None) – The list of filenames for the second UVData object. If it is not set, it should be None.
- Returns:
combined_filenames (list of str or None) – The combined list, with potentially duplicate entries removed.
- pyuvdata.utils.tools._convert_to_slices(indices, *, max_nslice_frac=0.1, max_nslice=None, return_index_on_fail=False)[source]
Convert list of indices to a list of slices.
- Parameters:
indices (list) – A 1D list of integers for array indexing (boolean ndarrays are also supported).
max_nslice_frac (float) – A float from 0 – 1. If the number of slices needed to represent input ‘indices’ divided by len(indices) exceeds this fraction, then we determine that we cannot easily represent ‘indices’ with a list of slices.
max_nslice (int) – Optional argument, defines the maximum number of slices for determining if indices can be easily represented with a list of slices. If set, then the argument supplied to max_nslice_frac is ignored.
return_index_on_fail (bool) – If set to True and the list of input indexes cannot easily be represented by a list of slices (as defined by max_nslice or max_nslice_frac), then return the input list of index values instead of a list of suboptimal slices.
- Returns:
slice_list (list) – Nominally the list of slice objects used to represent indices. However, if return_index_on_fail=True and input indexes cannot easily be represented, return a 1-element list containing the input for indices.
check (bool) – If True, indices is easily represented by slices (max_nslice_frac or max_nslice conditions met), otherwise False.
Notes
Example
if: indices = [1, 2, 3, 4, 10, 11, 12, 13, 14] then: slices = [slice(1, 5, 1), slice(11, 15, 1)]
- pyuvdata.utils.tools.slicify(ind: slice | None | Iterable[int], allow_empty: bool = False) slice | None | Iterable[int][source]
Convert an iterable of integers into a slice object if possible.
- Parameters:
ind (list) – A 1D list of integers for array indexing.
allow_empty (bool) – If set to False (default) and ind is a zero-length list, None is returned. If set to True, then a “zero-length slice” (e.g., slice(0,0)) is returned instead.
- Returns:
index_obj (slice or list) – If the list of indices can be represented by a slice, a slice is returned, otherwise the list of indices is returned.
- pyuvdata.utils.tools._multidim_ind2sub(dims_dict, dims)[source]
Build a flag index array based on a multi-dimensional index array.
- Parameters:
dims_dict (dict) – Dict whose keys are the axes being selected on, and the values are list of index positions along that axis.
dims (tuple) – Shape of the array being accessed.
- pyuvdata.utils.tools._test_array_constant(array, *, tols=None, mask=Ellipsis)[source]
Check if an array contains constant values to some tolerance.
Uses np.isclose on the min & max of the arrays with the given tolerances.
- Parameters:
array (np.ndarray or UVParameter) – UVParameter or array to check for constant values.
tols (tuple of float, optional) – length 2 tuple giving (rtol, atol) to pass to np.isclose, defaults to (0, 0) if passing an array, otherwise defaults to using the tolerance on the UVParameter.
mask (array-like (of ints or booleans) or Ellipses) – Mask which indicates which indices to evaluate. Default is all elements.
- Returns:
bool – True if the array is constant to the given tolerances, False otherwise.
- pyuvdata.utils.tools._test_array_consistent(array, deltas, *, tols=None, mask=Ellipsis)[source]
Check if an the spacing of an array is consistent with expect intervals.
- Parameters:
array (np.ndarray or UVParameter) – UVParameter or array to check for constant values.
deltas (np.ndarray or UVParameter) – Expected widths of each entry in array, should be >= 0.
tols (tuple of float, optional) – length 2 tuple giving (rtol, atol) to pass to np.isclose, defaults to (0, 0) if passing an array, otherwise defaults to using the tolerance on the UVParameter.
mask (array-like (of ints or booleans) or Ellipses) – Mask which indicates which indices to evaluate. Default is all elements.
- Returns:
bool – True if the array is constant to the given tolerances, False otherwise.
- pyuvdata.utils.tools._test_array_constant_spacing(array, *, tols=None, mask=Ellipsis, allow_resort=False)[source]
Check if an array is constantly spaced to some tolerance.
Calls _test_array_constant on the np.diff of the array.
- Parameters:
array (np.ndarray or UVParameter) – UVParameter or array to check for constant spacing.
tols (tuple of float, optional) – length 2 tuple giving (rtol, atol) to pass to np.isclose, defaults to (0, 0) if passing an array, otherwise defaults to using the tolerance on the UVParameter.
mask (array-like (of ints or booleans) or Ellipses) – Mask which indicates which indices to evaluate. Default is all elements.
allow_resort (bool) – If set to False, values in array are checked in their present order. If set to True, values are sorted prior to evaluating (useful for arrays that _can_ be reindexed). Default is False.
- Returns:
bool – True if the array spacing is constant to the given tolerances, False otherwise.
- pyuvdata.utils.tools._is_between(val, val_range, wrap=False, wrap_amount=6.283185307179586)[source]
Detect if a value is between a specified range(s).
- Parameters:
val (float or ndarray) – Value to evaluate, either float/singleton, otherwise of shape (Nranges,).
val_range (np.array) – Array of ranges, shape (Nranges, 2).
wrap (bool) – Apply wrapping. Default is False.
wrap_amount (float) – Top end of the range for the wrap (bottom is 0). Default is 2 * pi.
- Returns:
bool – True if any range overlaps
- pyuvdata.utils.tools._check_range_overlap(val_range, range_type='time')[source]
Detect if any val_range in an array overlap.
- Parameters:
val_range (np.array of float) – Array of ranges, shape (Nranges, 2).
range_type (str) – Type of range (for good error messages)
- Returns:
bool – True if any range overlaps.
- pyuvdata.utils.tools._sorted_unique_union(obj1, obj2=None)[source]
Determine the union of unique elements from two lists.
Convenience function for handling various actions with indices.
- Parameters:
obj1 (list or tuple or set or 1D ndarray) – First list from which to determine unique entries.
obj2 (list or tuple or set or 1D ndarray) – Second list from which to determine unique entries, which is joined with the first list. If None, the method will simply return the sorted list of unique elements in obj1.
- Returns:
sorted_unique (list) – List containing the union of unique entries between obj1 and obj2.
- pyuvdata.utils.tools._sorted_unique_intersection(obj1, obj2=None)[source]
Determine the intersection of unique elements from two lists.
Convenience function for handling various actions with indices.
- Parameters:
obj1 (list or tuple or set or 1D ndarray) – First list from which to determine unique entries.
obj2 (list or tuple or set or 1D ndarray) – Second list from which to determine unique entries, which is intersected with the first list. If None, the method will simply return the sorted list of unique elements in obj1.
- Returns:
sorted_unique (list) – List containing the intersection of unique entries between obj1 and obj2.
- pyuvdata.utils.tools._sorted_unique_difference(obj1, obj2=None)[source]
Determine the difference of unique elements from two lists.
Convenience function for handling various actions with indices.
- Parameters:
obj1 (list or tuple or set or 1D ndarray) – First list from which to determine unique entries.
obj2 (list or tuple or set or 1D ndarray) – Second list from which to determine unique entries, which is differenced with the first list. If None, the method will simply return the sorted list of unique elements in obj1.
- Returns:
sorted_unique (list) – List containing the difference in unique entries between obj1 and obj2.
- pyuvdata.utils.tools._strict_raise(err_msg: str, strict: bool | None, err_type=<class 'ValueError'>, warn_type=<class 'UserWarning'>)[source]
Determine whether to raise a warning or an error.
- Parameters:
err_msg (str) – Message to pass along with the warning/error.
strict (bool | None) – If True, raise an error. If False, raise a warning. If None, no message is raised at all (warning is silenced).
err_type (Exception) – Type of error to raise if strict=True. Default is ValueError.
warn_type (Warning) – Type of warning to raise if strict=False. Default is UserWarning.
- pyuvdata.utils.tools._eval_inds(inds, nrecs, name='inds', invert=False, strict=True)[source]
Determine if indices are outside of the expected range.
- Parameters:
inds (array-like of int) – Indices to check.
nrecs (int) – Number of records in the underlying array.
name (str) – Name of underlying array, default is “inds”.
invert (bool) – If False, inds are treated as the positions in the array that should be preserved, but if True, those positions are discarded instead. Default is False.
strict (bool) – If True, raise an error. If False, raise a warning.
- Returns:
inds (ndarray of int) – Array of well-conditioned, sorted index values (whose value will be within the range of [0, nrecs - 1]).
- pyuvdata.utils.tools._where_combine(mask, inds=None, invert=False, use_and=True)[source]
Combine masked array with an existing index list.
- Parameters:
mask (array-like of bool) – Array that marks whether or not entries meet matching criteria.
inds (array-like of int or None) – Existing list of index positions that meet matching criteria. Can be None, in which case only mask is evaluated.
invert (bool) – If False, then indices where mask == True are returned. But if set to True, indices where mask == False are returned instead. Default is False.
use_and (bool) – If True, then what is returned is the intersection of value derived from both mask and inds. If False, then the union of mask and inds is returned instead. Default is True.
- Returns:
new_inds (ndarray of int) – Index positions which meet the selection criterion recorded in mask and inds.
Applying calibration solutions to data
- pyuvdata.utils.uvcalibrate.uvcalibrate(uvdata, uvcal, *, inplace: bool = True, prop_flags: bool = True, d_term_cal: bool = False, flip_gain_conj: bool = False, delay_convention: Literal['minus', 'plus'] = 'minus', undo: bool = False, time_check: bool = True, ant_check: bool = True, freq_range_check: bool = True, uvc_pol_convention: Literal['sum', 'avg'] | None = None, uvd_pol_convention: Literal['sum', 'avg'] | None = None)[source]
Calibrate a UVData object with a UVCal object.
- Parameters:
uvdata (UVData object) – UVData object to calibrate.
uvcal (UVCal object) – UVCal object containing the calibration.
inplace (bool, optional) – if True edit uvdata in place, else return a calibrated copy
prop_flags (bool, optional) – if True, propagate calibration flags to data flags and doesn’t use flagged gains. Otherwise, uses flagged gains and does not propagate calibration flags to data flags.
Dterm_cal (bool, optional) – Calibrate the off-diagonal terms in the Jones matrix if present in uvcal. Default is False. Currently not implemented.
flip_gain_conj (bool, optional) – This function uses the UVData ant_1_array and ant_2_array to specify the antennas in the UVCal object. By default, the conjugation convention, which follows the UVData convention (i.e. ant2 - ant1), is that the applied gain = ant1_gain * conjugate(ant2_gain). If the other convention is required, set flip_gain_conj=True.
delay_convention (str, optional) – Exponent sign to use in conversion of ‘delay’ to ‘gain’ cal_type if the input uvcal is not inherently ‘gain’ cal_type. Default to ‘minus’.
undo (bool, optional) – If True, undo the provided calibration. i.e. apply the calibration with flipped gain_convention. Flag propagation rules apply the same.
time_check (bool) – Option to check that times match between the UVCal and UVData objects if UVCal has a single time or time range. Times are always checked if UVCal has multiple times.
ant_check (bool) – Option to check that all antennas with data on the UVData object have calibration solutions in the UVCal object. If this option is set to False, uvcalibrate will proceed without erroring and data for antennas without calibrations will be flagged.
freq_range_check (bool) – Option to check that frequency ranges on the UVCal object matches the channel frequencies given in the UVData object for a given spectral window. Only applicable for wide-band UVCal objects, default is True.
uvc_pol_convention (str, {“sum”, “avg”}, optional) – The convention for how instrumental polarizations (e.g. XX and YY) are assumed to have been converted to Stokes parameters in
uvcal. Options are ‘sum’ and ‘avg’, corresponding to I=XX+YY and I=(XX+YY)/2 (for linear instrumental polarizations) respectively. Only required ifpol_conventionis not set onuvcalitself. If it is not specified and is not set on the UVCal object, a deprecation warning is raised (will be an error in the future).uvd_pol_convention (str, {“sum”, “avg”}, optional) – The same polarization convention as
uvc_pol_convention, except that this represents either the convention that has been adopted inuvdata(in the case thatundo=True), or the convention that is desired for the resultingUVDataobject (ifundo=False).
- Returns:
UVData, optional – Returns if not inplace
- pyuvdata.utils.uvcalibrate._get_pol_conventions(uvdata, uvcal, undo: bool, uvc_pol_convention: Literal['sum', 'avg'] | None, uvd_pol_convention: Literal['sum', 'avg'] | None)[source]
- pyuvdata.utils.uvcalibrate._apply_pol_convention_corrections(uvdata, undo: bool, uvc_pol_convention: Literal['sum', 'avg'] | None, uvd_pol_convention: Literal['sum', 'avg'] | None)[source]
Apply corrections to calibration/de-calibration from differences in convention.
This function corrects the UVData
data_arrayin-place, when the polarization convention desired for the UVData is different from the convention that was used for the calibration. It also sets the correspondingpol_conventionattribute on the UVData object.The logic is as follows. If the convention of the calibration and UVData object are the same, no correction is applied. If they are different, the correction applied is either to multiply or divide by two. Let’s start with a default case: let’s say that the calibration solutions assume that instrumental polarizations are related to the stokes-I sky by the
avgconvention, in which case \(XX \sim I\), and we are calibrating data where we want the result to have thesumconvention, i.e. \(XX \sim I/2\). Then, for data that is in instrumental polarizations (i.e. XX) we would need to divide the result by 2. This is flipped (i.e. flips between multiply and divide) for every difference from the above scenario, i.e.If we are de-calibrated rather than calibrating
If the UVData is in stokes polarizations rather than instrumental (note that this is not currently possible anyway, so we do not provide the ability here).
If the conventions are swapped between the calibration solutions and the UVData.
To be clear, if two of these are true, the resulting correction will be “flipped twice” (i.e. remain as divide by two), but if only one or all three are true, then the correction will be flipped to be multiply by two.