Measurement Sets

Contents

Measurement Sets#

Tools for reading, inspecting, selecting, and fringe-fitting CASA Measurement Sets.

Public interface#

avica.ms.read_df_vis(vis, corr=[], spw=[], dcol='DATA', sel_row=[])#
Parameters:
avica.ms.read_df_vis_single(vis, tb_data, field_name, antenna_name, data_desc_spw, sel_corr=0, sel_chan=0, sel_row=[])#

assumes dimensions: (corr, chan, row)

Parameters:
avica.ms.get_dic_an(vis, spw_col)#
avica.ms.add_spwid_totab(tb, spwid_missing, warnonly=True, dic_an_spw={})#

NOTE: This code is redundant. FIXME : This assumes that the FEED1 and FEED2 are always 0. the dic_an_spw now has feedid as well. FIXME: existing bug, mask of antenna selection does not assume mask on spw.

avica.ms.fix_feedid(vis, spw_col='SPECTRAL_WINDOW_ID', warnonly=True, verbose=True)#
avica.ms.remap_gain_curve_spws(vis, selected_spws, verbose=True)#

Repair GAIN_CURVE after mstransform has selected a subset of SPWs.

CASA mstransform can renumber the main MS/DATA_DESCRIPTION/SYSCAL SPWs while leaving GAIN_CURVE rows with the original FITS-IDI SPW ids. gencal then reads the wrong DPFU rows for the output SPWs. selected_spws must be the input-MS SPW ids used to create this output MS, in output order.

avica.ms.check_and_fix_spw_partitioning(vis, selected_spws, verbose=True)#

After mstransform splits a subset of SPWs the main MS is reindexed, but sub-tables (listed in SPW_FIXABLE_TABLES) may still carry the original input SPW ids and overflow that range. This may write wrong gain tables.

Each sub-table is opened read-only first; only the ones that actually need editing are reopened with readonly=False.

Vis:

the MS to check and fix

Selected_spws:

the input-MS SPW ids used to create vis.

avica.ms.select_long_scans(field_id, fields, scan_df)#

sort the scan by number of rows and select the first five as list

Example —

scannos = select_long_scans(fid) scannos = “,”.join(scannos)

avica.ms.vals_fromtab(caltable)#
avica.ms.get_sci_ant(vis, tbls, target, msmd=None)#
avica.ms.get_calib_df_sorted_desc(vis, tbls, target, calibs, msmd=None, dic=False)#
avica.ms.ants_intbls_unique(vis=None, msmd=None, tbls=None)#
avica.ms.generic_df_fromtab(tbl, colnames=[])#
avica.ms.df_fromtables(tbl_names)#
avica.ms.df_fromtb(vis, tbls, msmd)#

TODO: following is outdated. returns dataframes containing: “ANTENNA2”, “SNR_median”, “FIELD_ID”, “SNR_FIELD”

CASA uses “ANTENNA2” as the reference antenna used for the table.

avica.ms.splitms_mpi(vis, outvis, fids)#
avica.ms.ff_to_tbl_names(vis, meta, metafile, refants=None, sources=None, spws=None, target='', gaintable=None, new_tbls=False, mpi=False)#
avica.ms.find_refant_fromtbls(vis, tbls, fields, verbose=False, wt_d=1.0, wt_snr=0.9, wt_tsys=0.8)#

finds refants from Short Fringe Fit tables

avica.ms.params_check(vis, sources, refants, spws, ff_tbls, new_meta, new_tbls, mpi)#
  • sanitizes arguments

  • loads metadata

avica.ms.identify_refant_casa(vis, selected_sources=None, refants=None, spws=None, target='', ff_tbls=None, new_meta=False, new_tbls=False, mpi=False, verbose=True)#

Returns refant_list, calib_dictionary

Refant_list:

[refants]

Calib_dictionary:

{‘FIELD_NAME’: [sources], {‘SNR_FIELD’:[snr_sources]}} snr_sources: median values of all scans, antennas in the field

avica.ms.get_scanlist_seq(msmd)#
avica.ms.get_sourcenames(msmd)#
avica.ms.coordinate_for_sources(vis, sourcenames)#

Return source coordinates from a Measurement Set.

Parameters:
  • vis (str) – Measurement Set path.

  • sourcenames (dict) – Source names to include.

Returns:

Mapping from source name to an (ra, dec) tuple in radians.

Return type:

dict

avica.ms.check_bands_ms(msmd)#

Group Measurement Set spectral windows by observing band.

Parameters:

msmd – Open CASA Measurement Set metadata tool.

Returns:

Band names (for example "C", "X", or "S") mapped to reference frequencies in Hz and spectral-window IDs.

Return type:

dict

avica.ms.get_target_in_bands(msmd, target, bands_dict)#
avica.ms.coordinate_for_target(vis, target, sourcenames)#

Returns —

(tuple)

other_names, c_other, c_target

Other_names:

(list) list of other source names

C_other:

(tuple) (astropy.units.radian, astropy.units.radian)

C_target:

(tuple) (astropy.units.radian, astropy.units.radian)

avica.ms.identify_sources_fromtarget_ms(vis, target_source, caliblist_file=None, flux_thres=0.15, min_flux=0.025, ncalib=20, flux_df=None, sourcenames=None, hard_selection=False, metafolder=None)#

TODO: change caliblist_file name to calibrator catalog file

avica.ms.identify_sources_fromsnr_ms(vis, target_source, caliblist_file=None, snr_metafile=None, outfile='', flux_thres=18.0, min_flux=7.0, ncalib=9, msmd=<avica.ms.compat.CasaMSMetadata object>)#
avica.ms.get_antenna_name(vis)#
avica.ms.has_table(vis, *tbl)#
avica.ms.get_reffreq(vis)#
avica.ms.get_axes(vis)#
avica.ms.get_fid(vis, target)#
avica.ms.find_phasecenter_inms(fitsfile, vis, class_searchcoord_file, sep=0.85)#

uses the coordinate, fits_target columns in the dataframe from class_searchcoord_file to find fields need phaseshift when separation in arcsec >{sep}”

avica.ms.get_num_chan(vis, spw=0)#
Parameters:
Return type:

float

avica.ms.get_scan_lengths(vis, target)#
Parameters:
avica.ms.get_alluniquecomb_spws(vis)#

when there are similar band for multiple spws

avica.ms.get_best_spws(vis)#

Metadata#

class avica.ms.meta.BandInfoMS(vis, min_expt, verbose=True, min_ant_scans=None)#

Bases: object


Retrieve band information from a Measurement Set.

Returns a dictionary of band metadata including band name, spectral windows, and reference frequencies, structured as follows:

BandInfoMS(vis, min_expt=1.5).check_bands_ms
{
    "<band>": {
        "spws":     [spw_id, ...],
        "reffreqs": [freq_hz, ...],
        "nobs":     int,
        "obs=<OBSID>": {
            "scans": {
                spw_id: [scan_id, ...]
            }
        }
    }
}
Returns:

Band information keyed by band name.

Return type:

dict


check_bands_ms()#

Retrieve band information from a Measurement Set.

Returns a dictionary of band metadata including band name, spectral windows, and reference frequencies, structured as follows:

BandInfoMS(vis, min_expt=1.5).check_bands_ms
{
    "<band>": {
        "spws":     [spw_id, ...],
        "reffreqs": [freq_hz, ...],
        "nobs":     int,
        "obs=<OBSID>": {
            "scans": {
                spw_id: [scan_id, ...]
            }
        }
    }
}
Returns:

Band information keyed by band name.

Return type:

dict

missing_antennas(band)#
get_band_detail(band)#
spws(band)#

Tables#

avica.ms.tables.get_tb_data(vis, axs=[])#

get table data from the table by specifying valid columns in axs.

Parameters:
  • vis (str) – measurement set file path.

  • axs (list, optional) – name of the columns to read from the measurement set. Defaults to [].

Raises:

NameError – if specified column not found.

Returns:

list of data corresponding to the columns specified.

Return type:

list

avica.ms.tables.select_long_scans(vis, fids=[], sources=[], nscan=5)#

takes visibility file path, source ID or source name as list and returns the top nscan long scans

Parameters:
  • vis (str) – measurement set file path

  • fids (list, optional) – list of field ID associated to the measurement set, infers from sources if fids not provided. Defaults to [].

  • sources (list, optional) – list of sources. Defaults to [].

  • nscan (int, optional) – number of top scans to choose based on the scan durations. Defaults to 5.

Returns:

dict of fid with assoicated scan numbers for each fids

Return type:

res (dict)

avica.ms.tables.getremovableant_fromsource(vis, source)#
avica.ms.tables.an_dic(vis, source=None, antenna=[], notantenna=[])#

Antenna dictionary with median distance to centroid and standard deviation in TSYS

Parameters:
  • vis (str) – measurement set file path.

  • source (str, optional) – source name. Defaults to None.

  • antenna (list, optional) – filter only specified antenna names. Defaults to [].

  • notantenna (list, optional) – remove antennas from selection. Defaults to [].

Returns:

Antenna dictionary {int:ANNAME:str}

Return type:

dict

avica.ms.tables.get_name_dict(vis, tab)#
avica.ms.tables.get_ant_scans(vis, fids)#

Dictionary with antenna and scan availability for each field.

Parameters:
  • vis (str) – measurement set file.

  • fids (List) – field ids.

Returns:

{fid:{antid:set(scans)}}

Return type:

Dict

avica.ms.tables.read_df_vis(vis, corr=[], spw=[], dcol='DATA', sel_row=[])#
Parameters:
avica.ms.tables.read_df_vis_single(vis, tb_data, field_name, antenna_name, data_desc_spw, sel_corr=0, sel_chan=0, sel_row=[])#

assumes dimensions: (corr, chan, row)

Parameters:
avica.ms.tables.repair_mixed_single_pol_syscal_tsys(vis)#

Replace missing TSYS slots only for consistently single-pol SYSCAL tables.

avica.ms.tables.dead_corr_mask(flag, data, corr_axis)#

True for each correlation that is fully flagged or non-finite in the sample.

avica.ms.tables.live_correlations(vis, spws, nchunks=8, chunk_rows=50)#

Return {spw: (corr_types, [live corr index, ...])} for the cross-correlations of vis.

A correlation is dead when every sampled FLAG is set or every sampled DATA value is non-finite. Reads nchunks contiguous blocks of chunk_rows rows spread over each spw: contiguous reads stay tile-friendly on large (4096-channel) MSs, unlike a row stride.

avica.ms.tables.choose_live_correlation(live)#

Pick the single mstransform correlation selection from live_correlations output.

Returns the correlation name (e.g. 'LL') only when every spw has exactly one live correlation and it is the same one; otherwise '' (keep all correlations).

avica.ms.tables.chk_tbl(subt1, subt2, relax_order=False)#

subt1 and subt2 are subtables in polars dataframe Checks if subt2 has multiple copies of subt1. For each iteration i, compare row n from subt1 with row n * i from subt2

avica.ms.tables.verifysubt_byeachelem(refvis, newvis)#
avica.ms.tables.verifysubt_nrows(refvis, newvis)#
avica.ms.tables.read_gain(vis, query='')#
avica.ms.tables.read_antenna(vis, query='')#
avica.ms.tables.read_weather(vis, query='')#
avica.ms.tables.read_syscal(vis, query='')#
avica.ms.tables.read_phasecal(vis, query='')#
avica.ms.tables.fix_duplicatedrows(refvis, newvis, nomodify=True)#

TODO: not tested with the readonly.

Fringe fitting#

class avica.ms.fringefit.ObservationInp(**kwargs)#

Bases: Config

science_target = None#
calibrators_instrphase = None#
calibrators_bandpass = None#
calibrators_rldly = None#
calibrators_phaseref = None#
property data#
class avica.ms.fringefit.ArrayInp(**kwargs)#

Bases: Config

refant = ''#
property data#
class avica.ms.fringefit.FringeDetectionRating(vis, caltable_folder=None, n_refant=5, n_calib=6, n_scans=10, iter_scan_count=5, selected_sources=None, selected_scans=None, selected_ants=None, selected_spws=[], gaintables=[], interp=[], metafolder='', target=None, verbose=False)#

Bases: object

Parameters:
select_good_scans(nscans=9, anid=None)#

selects nscans with longest duration and maximum antenna availability

Parameters:

nscans (int, optional) – number of scans. Defaults to 9.

get_dic_ant_with_scans()#
exec_FFT_fringefit(multiband=True)#
avica.ms.fringefit.casatask_fringefit(vis, fid, scannos, refant, ff_caltable, gt=[], interp=[], spws=[], antenna=[], minsnr=3, multiband=False, mpiclient=None)#

execute CASA task fringefit in MPI mode if MPI mode was activated else on single core.

Parameters:
  • vis (str) – measurement set file.

  • fid (str) – field id of the source

  • scannos (str) – scan numbers joined.

  • refant (str) – refant selected.

  • ff_caltable (str) – output calibration table name.

  • gt (List, optional) – gain tables. Defaults to [].

  • interp (List[str], optional) – interpolation on the gain tables. Defaults to [].

  • spws (List, optional) – spws selected. Defaults to [].

  • antenna (List, optional) – antenna selected. Defaults to [].

  • minsnr (int, optional) – minimum SNR. Defaults to 3.

  • multiband (bool, optional) – choose multiband vs sinle band. Defaults to False.

  • mpiclient (_type_, optional) – MPICLIENT from the casampi module. Defaults to None.

Returns: (dict/str)

dict result from the MPI run in MPI mode else ‘None’

avica.ms.fringefit.task_fringefit_fft_only(vis, dic_ant_with_scans, caltable_folder, gt=[], interp=[], spws=[], iter_scan_count=5, multiband=False, verbose=True)#

calls casatasks.fringefit with/without MPI with default values set to do either multiband/single fringefit without global solve.

Parameters:
  • vis (str) – measurement set file.

  • dic_ant_with_scans (dict) – input dictionary {anid:{‘scans’:[scan], ‘name’:ANNAME}}

  • caltable_folder (str) – calibration table folder to produce tables from fringefit task.

  • gt (List[str]) – input gain tables for the fringefit.

  • interp (List[str]) – interpolation for gain tables.

  • spws (List) – list of spws to consider during fringefit.

  • iter_scan_count (int, optional) – number of scans to do fringefit in a single run. Defaults to 5.

  • multiband (bool, optional) – choose between multiband/single band. Defaults to False.

  • verbose (bool, optional) – print output. Defaults to True.

Raises:

FileNotFoundError – if the folder for calibration doesn’t exist

Returns:

dictionary containing key : refant_joinedscans for values mpi_ids, scan numbers, fringefit caltable, error. And a key with complete table path . {tbl_names:[..], refant_joinedscannos:{…}}

Return type:

dic_result (dict)

avica.ms.fringefit.df_fromables(tbl_names)#

Efficiently loads and concatenates multiple tables into a Dask DataFrame.

Parameters:

tbl_names (List[str]) – path of calibration tables from the fringefit task.

Returns:

concatenated tables from the calibration tables.

Return type:

df_tb (pl.DataFrame)

avica.ms.fringefit.select_df_refant_sources(tbls, an_dict, autocorr=False, minsnr=3.0, calib_snr_thres=7.0, wt_d=1.0, wt_tsys=0.0, wt_occ=0.85, wt_snr=1.0)#

get DataFrame containing reference antenna and another DataFrame containing tables from the fringefit calibration with merged columns from antenna selection DataFrame.

Parameters:
  • tbls (List[str]) – fringefit calibration tables path

  • an_dict (Dict) – dictionary of antenna from avica.ms.tables.an_dic

  • autocorr (bool, optional) – whether to consider autocorr. Defaults to False.

  • minsnr (float, optional) – minimum SNR threshold. Defaults to 3.0.

  • calib_snr_thres (float, optional) – deprecated. Defaults to 7.0.

  • wt_d (float, optional) – weight to apply on Distance column. Defaults to 1.0.

  • wt_tsys (float, optional) – weight to apply on STD_TSYS column. Defaults to 0.0.

  • wt_occ (float, optional) – weight to apply on antenna occurance column. Defaults to 0.85.

  • wt_snr (float, optional) – weight to apply on SNR column. Defaults to 1.0.

  • n_refant (int, optional) – Number of refant to select. Defaults to 5.

Returns: (tuple)

res (pl.DataFrame): polars DataFrame containing result of refant selection. df_tbl (pl.DataFrame): polars DataFrame containing fringefit calibration table data.

avica.ms.fringefit.find_refant_fromdf(tbls, an_dict, sources_dict, autocorr=False, minsnr=3.0, calib_snr_thres=7.0, n_refant=4, n_calib=6, verbose=True, target_ants=None, field_ant_scans=None)#

takes fringefit calibration tables path and gives refant and calibrators

Parameters:
  • tbls (List[str]) – fringefit calibration tables path

  • an_dict (Dict) – dictionary of antenna from avica.ms.tables.an_dic

  • sources_dict (Dict) – dictionary of sources {FIELD_ID:NAME}

  • autocorr (bool, optional) – whether to consider autocorr. Defaults to False.

  • minsnr (float, optional) – minimum SNR threshold. Defaults to 3.0.

  • calib_snr_thres (float, optional) – deprecated. Defaults to 7.0.

  • n_refant (int, optional) – Number of refant to select. Defaults to 4.

  • n_calib (int, optional) – Number of calibrators to select. Defaults to 6.

  • verbose (bool, optional) – print output. Defaults to True.

  • target_ants (List[int], optional) – antenna ids present on science target (with gc/tsys, see avica.ms.tables.an_dic). ant_availability is the fraction [0-1] of these antennas present in each FIELD_ID. If not provided, ant_availability is set to 1.0 for every FIELD_ID.

  • field_ant_scans (dict, optional) – {FIELD_ID: {ANTENNA_ID: scans}} map from the original MS, used to check antenna presence per field.

Returns:

(dic_field, refants, pp_out) dic_field (dict): {‘FIELD_ID’: […], ‘NAME’: […], ‘SNR’: […], ‘ant_availability’: […]} refants (List[str]): […] pp_out (str): printable string output

avica.ms.fringefit.get_scan_durations(vis, sids)#

gets a dictionary containing scan duration reading the measurement set file.

Parameters:
  • vis (str) – measurement set file.

  • sids (List[int]) – list of scan number.

Returns:

dictionary containing scan duration. {scan_id:scan_duration}

Return type:

dict

avica.ms.fringefit.get_df_scans(vis, dict_field_ant_with_scans)#

_summary_

Parameters:
  • vis (str) – measurement set file.

  • dict_field_ant_with_scans (dict) – input dictionary {fid:{anid:[scan]}}

Returns:

DataFrame containing fid, anid, scan columns

Return type:

pl.DataFrame

avica.ms.fringefit.get_best_scans(df_scans, nscans)#

returns best scans from the scan duration

Parameters:
  • df_scans (pl.DataFrame) – input polars DataFrame

  • nscans (int) – number of scans

Returns:

dictionary containing best scans {fid:[scan]}

Return type:

dict_res (Dict[List])

CASA compatibility#

avica.ms.compat.ctable(path=None, readonly=True, **_)#
class avica.ms.compat.CasaMSMetadata#

Bases: object

open(vis)#
Parameters:

vis (str)

Return type:

None

done()#
Return type:

None

close()#
Return type:

None

spwsforfields()#

{str(field_id): sorted unique spws in MAIN for that field} (keys are strings, as in casatools).

Return type:

dict

nobservations()#
Return type:

int

fieldnames()#
Return type:

list[str]

scansforfield(field, obsid=-1, arrayid=-1)#

Unique scans for a field given as zero-based ID (int) or name (str).

Return type:

list[int]

scansforspws(obsid=None)#

{str(spw_id): sorted unique int scans}, optionally restricted to obsid.

Matches casatools: keys are strings, scan numbers are integers. (casatools defaults obsid=0; here None means all observations.)

Parameters:

obsid (int | None)

Return type:

dict

reffreq(spw)#

Mimic casatools shape: {‘m0’: {‘value’: hz, ‘unit’: ‘Hz’}, …}.

Parameters:

spw (int)

Return type:

dict

meanfreq(spw)#
Parameters:

spw (int)

Return type:

float

chanwidths(spw)#
Parameters:

spw (int)

Return type:

numpy.ndarray

bandwidths(spw)#
Parameters:

spw (int)

Return type:

float

exposuretime(scan, spwid, obsid)#
Parameters:
Return type:

dict

antennasforscan(scan)#
Parameters:

scan (int)

Return type:

numpy.ndarray

timesforscan(scan)#
Parameters:

scan (int)

Return type:

numpy.ndarray

antennanames(antid=None)#
Return type:

list

antennaids(name)#

Antenna IDs whose NAME matches. Accepts str or iterable of str.

Return type:

numpy.ndarray

scannumbers()#

All unique scan numbers in MAIN.

Return type:

numpy.ndarray

fieldsforscan(scan)#

Field IDs that appear in MAIN for the given scan.

Parameters:

scan (int)

Return type:

numpy.ndarray

fieldsforsource(source=-1)#

{source_id: [field_ids]} from FIELD.SOURCE_ID.

Parameters:

source (int)

Return type:

dict

spwsforfield(field)#

SPW IDs in MAIN rows of a field given as zero-based ID (int) or name (str).

Parameters:

field (str | int)

Return type:

numpy.ndarray

namesforfields(fid=None)#

Names of given field IDs (or all if None).

Return type:

list

fieldsforname(name)#

Field IDs whose NAME equals the given string.

Parameters:

name (str)

Return type:

numpy.ndarray

MPI client#

avica.ms.mpiclient.get_mpi_client()#

Returns the existing client or starts a new one if needed.

avica.ms.mpiclient.start_mpi()#