hyri.interface.ms2mat#

Convert Measurement Set data into pyHyperRI MAT files.

This module provides the hyri-ms2mat command-line implementation and helper functions for turning Measurement Set rows into the MAT layout consumed by the pyHyperRI data loader.

Functions

convert_ms_to_mat

Convert a Measurement Set into pyHyperRI's MAT measurement layout.

ms2mat

Run the MS-to-MAT converter from command-line arguments.

parse_ms2mat_arguments

Parse command-line arguments for the MS-to-MAT converter.

Class

MsChannel

Describe one sorted output channel.

MsChannelMember

Describe one physical MS channel that contributes to an output channel.

class hyri.interface.ms2mat.MsChannelMember(spectral_window_id: int, channel_id: int)#

Bases: object

Describe one physical MS channel that contributes to an output channel.

The pair stores the spectral-window row index and channel index used to retrieve data from the Measurement Set.

spectral_window_id: int#
channel_id: int#
class hyri.interface.ms2mat.MsChannel(output_index: int, frequency_hz: float, members: tuple[MsChannelMember, ...])#

Bases: object

Describe one sorted output channel.

One output channel may merge same-frequency channels from different spectral windows. The output index is global after frequency sorting, so partial conversion keeps filenames consistent with the full Measurement Set.

output_index: int#
frequency_hz: float#
members: tuple[MsChannelMember, ...]#
hyri.interface.ms2mat.parse_ms2mat_arguments(argv: list[str] | None = None) → Namespace#

Parse command-line arguments for the MS-to-MAT converter.

Parameters:

argv (list[str] | None, optional) – Command-line arguments without the program name. Default: None, which reads from sys.argv.

Returns:

Parsed converter arguments.

Return type:

argparse.Namespace

hyri.interface.ms2mat.convert_ms_to_mat(ms_path: str | Path, output_path: str | Path = 'data', src_name: str | None = None, src_id: int = 0, ch_start: int = 1, ch_last: int | None = None, min_uv: float = 1e-06, data_column: str = 'CORRECTED_DATA', write_imaging_weight: bool = True, flag_zero_data: bool = True, freq_tol_hz: float = 1e-05, dry_run: bool = False) → Path#

Convert a Measurement Set into pyHyperRI’s MAT measurement layout.

Parameters:
  • ms_path (str | Path) – Path to the input Measurement Set directory.

  • output_path (str | Path, optional) – Root output directory. Files are written under output_path/src_name. Default: “data”.

  • src_name (str | None, optional) – Output source folder name. If None, the Measurement Set filename is used with a trailing .ms removed. Default: None.

  • src_id (int, optional) – FIELD_ID value to convert. Default: 0.

  • ch_start (int, optional) – First global frequency-sorted channel to convert, using one-based indexing. Default: 1.

  • ch_last (int | None, optional) – Last global frequency-sorted channel to convert, inclusive. If None, converts through the last channel. Default: None.

  • min_uv (float, optional) – Minimum projected baseline in metres. Rows with sqrt(u**2 + v**2) <= min_uv are flagged. Default: 1e-6.

  • data_column (str, optional) – Preferred visibility column. If unavailable, the converter falls back to DATA. Default: “CORRECTED_DATA”.

  • write_imaging_weight (bool, optional) – Whether to write weightsImg when MS imaging weights are available. Default: True.

  • flag_zero_data (bool, optional) – Whether to flag selected correlations that are exactly zero. Default: True.

  • freq_tol_hz (float, optional) – Frequency tolerance in Hz for grouping matching channels across spectral windows. Default: 1e-5.

  • dry_run (bool, optional) – Whether to print the channel plan without writing MAT files. Default: False.

Returns:

Output source directory path.

Return type:

Path

Raises:
  • ImportError – If python-casacore cannot be imported.

  • FileNotFoundError – If a required Measurement Set subtables is missing.

  • ValueError – If required columns, channel ranges, or valid visibilities are missing.

Examples

>>> convert_ms_to_mat("target.ms", output_path="data", dry_run=True)
PosixPath('data/target')
hyri.interface.ms2mat.ms2mat(argv: list[str] | None = None) → Path#

Run the MS-to-MAT converter from command-line arguments.

Parameters:

argv (list[str] | None, optional) – Command-line arguments without the program name. Default: None, which reads from sys.argv.

Returns:

Output source directory path.

Return type:

Path

Examples

>>> ms2mat(["target.ms", "--dry_run"])
PosixPath('data/target')
hyri.interface.ms2mat._bool_argument(text: str) → bool#

Parse a boolean command-line value.

Parameters:

text (str) – Text value supplied by argparse.

Returns:

Parsed boolean value.

Return type:

bool

Raises:

argparse.ArgumentTypeError – If text is not a recognised boolean value.

hyri.interface.ms2mat._validate_required_columns(colnames: set[str]) → None#

Validate required main-table Measurement Set columns.

Parameters:

colnames (set[str]) – Available column names in the main MS table.

Raises:

ValueError – If a required column is absent.

hyri.interface.ms2mat._resolve_data_column(colnames: set[str], data_column: str) → str#

Return the visibility column to read.

Parameters:
  • colnames (set[str]) – Available column names in the main MS table.

  • data_column (str) – Preferred visibility column name.

Returns:

Resolved visibility column name.

Return type:

str

Raises:

ValueError – If neither the requested column nor DATA is available.

hyri.interface.ms2mat._read_data_description_spws(ms_path: Path) → ndarray#

Read spectral-window IDs from the DATA_DESCRIPTION subtable.

Parameters:

ms_path (Path) – Path to the Measurement Set directory.

Returns:

Integer array mapping DATA_DESC_ID to SPECTRAL_WINDOW_ID.

Return type:

np.ndarray

Raises:

FileNotFoundError – If the DATA_DESCRIPTION subtable is missing.

hyri.interface.ms2mat._read_channel_frequencies(ms_path: Path) → list[ndarray]#

Read channel frequencies for every spectral window.

Parameters:

ms_path (Path) – Path to the Measurement Set directory.

Returns:

One frequency vector per spectral window, in Hz.

Return type:

list[np.ndarray]

hyri.interface.ms2mat._print_dry_run_summary(channel_frequencies: Sequence[ndarray], channels: list[MsChannel], requested_freq_tol_hz: float) → None#

Print channel-frequency inspection output for --dry_run.

Parameters:
  • channel_frequencies (Sequence[np.ndarray]) – Raw per-SPW channel frequency arrays.

  • channels (list[MsChannel]) – Selected grouped output channels.

  • requested_freq_tol_hz (float) – User-requested grouping tolerance in Hz.

hyri.interface.ms2mat._sorted_channels(chan_freq: ndarray | Sequence[ndarray], ch_start: int = 1, ch_last: int | None = None, freq_tol_hz: float = 0.0) → list[MsChannel]#

Return 1-based output channels sorted by frequency.

Equal frequencies are merged into one output channel. A positive freq_tol_hz also merges adjacent sorted frequencies within that tolerance.

Parameters:
  • chan_freq (np.ndarray | Sequence[np.ndarray]) – Channel frequencies in Hz. A 1D array represents one SPW; a 2D array represents (spw, channel); a sequence allows ragged SPWs.

  • ch_start (int, optional) – First one-based output channel to return. Default: 1.

  • ch_last (int | None, optional) – Last one-based output channel to return, inclusive. Default: None.

  • freq_tol_hz (float, optional) – Requested grouping tolerance in Hz. Default: 0.0.

Returns:

Frequency-sorted channels with global one-based output_index values.

Return type:

list[MsChannel]

Raises:

ValueError – If the channel range is invalid, frequencies are non-finite, or grouping would merge channels from the same SPW.

hyri.interface.ms2mat._normalise_channel_frequencies(chan_freq: ndarray | Sequence[ndarray]) → list[ndarray]#

Return channel frequencies as one 1D array per spectral window.

Parameters:

chan_freq (np.ndarray | Sequence[np.ndarray]) – Channel-frequency input.

Returns:

Normalised per-SPW frequency arrays.

Return type:

list[np.ndarray]

Raises:

ValueError – If an ndarray input is not 1D or 2D.

hyri.interface.ms2mat._select_channel_range(channels: list[MsChannel], ch_start: int = 1, ch_last: int | None = None) → list[MsChannel]#

Return an inclusive one-based channel range without renumbering.

Parameters:
  • channels (list[MsChannel]) – Full grouped channel list.

  • ch_start (int, optional) – First one-based channel to keep. Default: 1.

  • ch_last (int | None, optional) – Last one-based channel to keep, inclusive. Default: None.

Returns:

Selected channel objects with original output_index values preserved.

Return type:

list[MsChannel]

Raises:

ValueError – If the requested range is invalid.

hyri.interface.ms2mat._safe_frequency_grouping_tolerance(spw_freqs: Sequence[ndarray], requested_tolerance: float) → float#

Cap grouping tolerance below within-SPW channel spacing.

Parameters:
  • spw_freqs (Sequence[np.ndarray]) – Per-SPW channel frequency arrays.

  • requested_tolerance (float) – User-requested frequency tolerance in Hz.

Returns:

Effective grouping tolerance in Hz.

Return type:

float

Note

The cap prevents neighbouring channels in the same SPW from being grouped when the user supplies a large tolerance.

hyri.interface.ms2mat._group_channels_by_frequency(sorted_channels: list[tuple[float, int, int]], freq_tol_hz: float) → list[tuple[float, list[tuple[int, int]]]]#

Group sorted physical channels by observation frequency.

Parameters:
  • sorted_channels (list[tuple[float, int, int]]) – Tuples of (frequency_hz, spectral_window_id, channel_id) sorted by frequency.

  • freq_tol_hz (float) – Effective grouping tolerance in Hz.

Returns:

Grouped frequency and member channel IDs.

Return type:

list[tuple[float, list[tuple[int, int]]]]

Raises:

ValueError – If a frequency is non-finite or a group contains repeated SPW IDs.

hyri.interface.ms2mat._validate_unique_spw_per_group(grouped_channels: list[tuple[float, list[tuple[int, int]]]]) → None#

Validate that a grouped frequency has at most one channel per SPW.

Parameters:

grouped_channels (list[tuple[float, list[tuple[int, int]]]]) – Grouped channel descriptors from _group_channels_by_frequency().

Raises:

ValueError – If a group contains multiple channels from one SPW.

hyri.interface.ms2mat._resolve_natural_weight_column(colnames: set[str]) → str#

Return the MS column used for natural visibility weights.

Parameters:

colnames (set[str]) – Available column names in the main MS table.

Returns:

"WEIGHT_SPECTRUM" when available, otherwise "WEIGHT".

Return type:

str

Raises:

ValueError – If neither WEIGHT_SPECTRUM nor WEIGHT is present.

Note

WEIGHT_SPECTRUM is channel-dependent and follows the selected physical channel. WEIGHT is channel-independent and is used for all channels in the row.

hyri.interface.ms2mat._read_single_channel(tab, data_column_name: str, natural_weight_column: str, imaging_weight_column: str | None, channel: MsChannel, member: MsChannelMember, channel_count: int, base_flag: ndarray, flag_zero_data: bool, write_imaging_weight: bool) → tuple[ndarray, ndarray, ndarray, ndarray | None]#

Read one physical channel from a selected MS row subset.

Parameters:
  • tab – Casacore table view containing one FIELD_ID and one DATA_DESC_ID.

  • data_column_name (str) – Visibility column to read, usually DATA or CORRECTED_DATA.

  • natural_weight_column (str) – Natural-weight column, either WEIGHT_SPECTRUM or WEIGHT.

  • imaging_weight_column (str | None) – Optional imaging-weight column.

  • channel (MsChannel) – Output channel descriptor used for logging.

  • member (MsChannelMember) – Physical SPW/channel member to read.

  • channel_count (int) – Number of channels in the member’s SPW.

  • base_flag (np.ndarray) – Row-level invalid mask aligned to tab.

  • flag_zero_data (bool) – Whether zero-valued selected correlations are invalid.

  • write_imaging_weight (bool) – Whether optional imaging weights should be returned.

Returns:

Stokes I values, natural whitening weights, full invalid-row flags, and optional imaging-weight multipliers. All arrays are aligned to tab rows.

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray | None]

Raises:

ValueError – If a column shape does not match the supported MS convention.

hyri.interface.ms2mat._read_channel_correlations(tab, column_name: str, channel_id: int, channel_count: int, expected_corr_count: int | None = None) → ndarray#

Read all correlations for one physical channel with getcolslice.

Parameters:
  • tab – Casacore table view to read.

  • column_name (str) – Array column name, such as DATA, FLAG, or WEIGHT_SPECTRUM.

  • channel_id (int) – Zero-based channel index inside the SPW.

  • channel_count (int) – Number of channels in the SPW.

  • expected_corr_count (int | None, optional) – Expected number of correlations. If given, the selected column must match it. Default: None.

Returns:

Array with shape (row, correlation).

Return type:

np.ndarray

Raises:

ValueError – If the column is not shaped as (channel, correlation) per MS row, or if the correlation count does not match expected_corr_count.

Note

This converter intentionally supports one in-memory MS convention: python-casacore exposes spectrum-like cells as (channel, correlation). Tables exposing another axis order should fail here instead of producing silently transposed data.

hyri.interface.ms2mat._resolve_imaging_weight_column(colnames: set[str]) → str | None#

Return the preferred optional imaging-weight column.

Parameters:

colnames (set[str]) – Available column names in the main MS table.

Returns:

IMAGING_WEIGHT, IMAGING_WEIGHT_SPECTRUM, or None.

Return type:

str | None

hyri.interface.ms2mat._correlation_weight_sum(corr_weights: ndarray) → ndarray#

Sum first and last correlation weights.

Parameters:

corr_weights (np.ndarray) – Natural-weight array with shape (row, correlation) or (correlation,).

Returns:

Per-row first-plus-last correlation weight.

Return type:

np.ndarray

Raises:

ValueError – If no correlation axis is present.

hyri.interface.ms2mat._stokes_i_and_weight(corr_values: ndarray, corr_weights: ndarray) → tuple[ndarray, ndarray, ndarray]#

Combine first and last correlations into Stokes I and whitening weights.

Parameters:
  • corr_values (np.ndarray) – Complex visibility values with shape (row, correlation).

  • corr_weights (np.ndarray) – Natural weights with shape (row, correlation).

Returns:

Stokes I values, sqrt(w_first + w_last) whitening weights, and invalid-row mask.

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray]

Raises:

ValueError – If visibility and weight row counts differ or correlation axes are empty.

hyri.interface.ms2mat._invalid_correlations(data_values: ndarray, flags: ndarray, flag_zero_data: bool) → ndarray#

Return invalid rows from selected data and flag correlations.

Parameters:
  • data_values (np.ndarray) – Complex visibility values with shape (row, correlation).

  • flags (np.ndarray) – Boolean MS flags with shape (row, correlation).

  • flag_zero_data (bool) – Whether exact zero selected correlations are invalid.

Returns:

Boolean invalid-row mask.

Return type:

np.ndarray

hyri.interface.ms2mat._write_ms_specs(output_dir: Path, freqs: ndarray, uvw: ndarray) → None#

Write shared Measurement Set metadata to msSpecs.mat.

Parameters:
  • output_dir (Path) – Output source directory.

  • freqs (np.ndarray) – Full grouped frequency list in Hz.

  • uvw (np.ndarray) – Selected MS UVW coordinates in metres.

hyri.interface.ms2mat._write_channel_data(output_dir: Path, channel: MsChannel, data_i: ndarray, weights_nat: ndarray, flag: ndarray, weights_img: ndarray | None = None) → None#

Write one output channel MAT file in the loader-compatible layout.

Parameters:
  • output_dir (Path) – Output source directory.

  • channel (MsChannel) – Output channel descriptor.

  • data_i (np.ndarray) – Stokes I visibility values for unflagged rows.

  • weights_nat (np.ndarray) – Natural whitening weights for unflagged rows.

  • flag (np.ndarray) – Full invalid-sample mask aligned to msSpecs.uvw.

  • weights_img (np.ndarray | None, optional) – Optional imaging-weight multipliers for unflagged rows. Default: None.

Raises:

ValueError – If the unflagged row count implied by flag does not match data_i, weights_nat, or weights_img.

Note

load_data.py expects flag to keep the full UVW length, while data_I and weights contain only the unflagged samples.