Station calibrator subpackage

This subpackage implements station calibrator functionality for MCCS.

class CalibrationSchedule(poll_interval: float = 60.0)[source]

The calibration schedule and the pause window that suspends it.

Each entry keeps its own cron iterator, so ticks advance from where the entry has got to. Entries are handed out one at a time, soonest tick first. Entries that share a tick are handed out in the order they appear in the schedule.

A cron tick asks for a run in the minute it names. A run that cannot start inside that minute is dropped rather than started late, and so is a tick that falls inside a pause window. The test is made as the run is handed out, so an entry that waited behind a long run, a pause, or a blocked scheduler loses that tick and waits for its next one. Nothing queues up.

All methods take the current time, so a test can name it. All methods are safe to call from more than one thread.

__init__(poll_interval: float = 60.0) → None[source]

Initialise a new instance with no entries and no pause window.

Parameters:

poll_interval – the longest a caller should wait between passes, in seconds, whatever the schedule and the window say.

property entries: list[dict[str, Any]]

Return the schedule entries.

Returns:

the entries, each with a "cron" key and optional calibration parameter overrides.

next_due(now: datetime) → dict[str, Any] | None[source]

Return the next entry to run, soonest tick first, or None.

An entry is due only once its own tick has passed, so asking early returns nothing. A tick is dropped, and the entry moved on to its next one, if the minute it named is already out, if the pause window was open at that tick, or if the window is open now.

The pause is tested at both moments on purpose. Testing it now stops a run starting inside a window it did not begin in. Testing it at the tick keeps a suppressed run dropped rather than held over, so a window that closes soon after a tick does not release the run it suppressed.

The caller runs the entry, then asks again. Every entry still due is handed out in turn, and one whose moment has passed in the meantime is dropped rather than started late.

Parameters:

now – the current time.

Returns:

the entry to run now, or None if nothing is due.

property pause_window: PauseWindow | None

Return the pause window.

Returns:

the window, or None if no pause is set.

seconds_until_next_wake(now: datetime) → float[source]

Return how long the scheduler may wait before it looks again.

The wait runs to the first of the next tick, the next boundary of the pause window, and the poll interval.

Parameters:

now – the current time.

Returns:

the wait, in seconds, never less than zero.

set_entries(entries: list[dict[str, Any]], now: datetime) → None[source]

Replace the schedule entries, taking each entry’s first tick from now.

Parameters:
  • entries – the new entries, each with a "cron" key and optional calibration parameter overrides.

  • now – the current time.

set_pause_window(window: PauseWindow | None) → None[source]

Replace the pause window, dropping any window already set.

A window is replaced whole, so there is no stale boundary to clear and no order to write the two boundaries in.

The window in force is the one that decides. Cancelling or replacing a window therefore hands a tick from the last minute back to whatever window follows it, which may let that run go ahead. A tick is only good for the minute it names, so nothing older than that comes back.

Parameters:

window – the new window, or None to cancel the pause.

state(now: datetime) → CalibrationScheduleState[source]

Return the state of the scheduler at the given time.

The state follows entirely from the entries and the window. It is EMPTY with no entries, PAUSED while a window is open, and RUNNING otherwise.

Parameters:

now – the time to derive the state at.

Returns:

the state of the scheduler.

take_state(now: datetime) → tuple[CalibrationScheduleState, CalibrationScheduleState | None][source]

Return the state now, with the state it replaced if that has changed.

The schedule remembers the state each call hands out. Sampling and remembering happen together under the one lock, so a caller that logs transitions sees each transition once, and in the order the transitions happened, however many threads are calling.

Parameters:

now – the time to derive the state at.

Returns:

the state now, and the state before it, or None for the second when the state has not changed.

upcoming_runs(now: datetime, horizon: timedelta) → list[dict[str, Any]][source]

Return every run that falls due within the horizon, soonest first.

This looks ahead without touching the scheduler’s own ticks, so it reports what the entries say whether the scheduler is paused or not.

Parameters:
  • now – the time to look forward from.

  • horizon – how far ahead to look.

Returns:

the upcoming runs, each with a "scheduled_time" in ISO 8601 UTC plus that entry’s overrides.

class CalibrationScheduleState(value)[source]

Operational state of the calibration scheduler.

class MccsStationCalibrator(*args: Any, **kwargs: Any)[source]

An implementation of a station calibrator Tango device for MCCS.

GenerateCalibrationSolution(**kwargs: Any) → ska_tango_base.type_hints.TaskFunctionType[source]

Perform a frequency sweep and generate solutions for recorded channels.

This command takes as input a JSON string that conforms to the following schema:

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://skao.int/MccsStationCalibrator_GenerateCalibrationSolution.json",
    "title": "MccsStationCalibrator GenerateCalibrationSolution schema",
    "description": "Schema for MccsStationCalibrator's GenerateCalibrationSolution command",
    "type": "object",
    "properties": {
        "calibration_id": {
            "description": "Unique identifier for the calibration. If not provided, a random identifier of the form `job_<8 hex chars>` is generated.",
            "type": [
                "string",
                "null"
            ]
        },
        "eep_filebase": {
            "description": "Start of EEP filenames before the frequency specification. For X/phi this gives eep_path/eep_filebase<freq>MHz_Xpol_phi.npy. Default is 'FEKO_AAVS3_vogel_256_elem_50ohm_'.",
            "type": [
                "string",
                "null"
            ]
        },
        "jones_solve": {
            "description": "Whether to call the polarised solver after initial calibration. Default is False.",
            "type": [
                "boolean",
                "null"
            ]
        },
        "adjust_solar_model": {
            "description": "Whether to adjust the sky model after initial calibration to limit differences between galactic and solar flux scales. Default is True.",
            "type": [
                "boolean",
                "null"
            ]
        },
        "masked_antennas": {
            "description": "List of antennas which should not be used for calibration. Default is an empty list (no antennas masked).",
            "type": [
                "array",
                "null"
            ],
            "items": {
                "type": "number"
            }
        },
        "skymodel": {
            "description": "Either a model visibility xarray to calibrate against or the name of a sky model type to generate. Supported sky models are `gsm` and `sun`. The `gsm` model combines components of the PyGDSM GlobalSkyModel16 Galactic sky model that are above the horizon with a point-source solar model, while sun uses only the point-source solar model. Default is 'gsm'.",
            "type": [
                "string",
                "null"
            ]
        },
        "min_uv": {
            "description": "Minimum baseline length used in calibration (in metres). The default value is zero.",
            "type": [
                "number",
                "null"
            ]
        },
        "refant": {
            "description": "Antenna to use for phase referencing. Should be one of the zero-based indices used in the visibility dataset. Default is 1. Both polarisations are phase referenced against the X polarisation of refant, as a non-zero XY-phase is expected and solved for.",
            "type": [
                "integer",
                "null"
            ],
            "minimum": 0
        },
        "ignore_eeps": {
            "description": "If True, EEP files will not be imported and station beam patterns and rotations will be ignored when modelling visibilities. Sky model components will be added with equal amplitude in XX and YY and zeros amplitude in XY and YX. Default is False.",
            "type": [
                "boolean",
                "null"
            ]
        },
        "gain_threshold": {
            "description": "Fractional threshold used to reject antennas with low gains. Any antenna with either an X or Y gain amplitude less than the median is flagged as bad. The default value is 0.25.",
            "type": [
                "number",
                "null"
            ]
        },
        "station_config_path": {
            "type": [
                "array"
            ],
            "items": {
                "type": "string",
                "pattern": "^[^\\s]+$"
            },
            "minItems": 2,
            "maxItems": 2,
            "uniqueItems": true
        },
        "nside": {
            "description": "Healpix nside at which to generate sky model. Defaults to 32 for channels below 320 and 64 for channels 320 and above. nside=32 corresponds to approximately 110 arcminutes and is adequate at low frequencies; nside=64 (approximately 55 arcminutes) is used at higher frequencies where the beam is narrower.",
            "type": [
                "integer",
                "null"
            ],
            "default": 32,
            "minimum": 1
        },
        "niter": {
            "description": "Number of iterations for solver. Default is 200.",
            "type": [
                "integer",
                "null"
            ],
            "default": 200,
            "minimum": 1
        },
        "first_channel": {
            "description": "The lowest channel in the loop. Default is 64 (50 MHz with an 800 MHz ADC clock and 512 channels).",
            "type": [
                "integer",
                "null"
            ],
            "minimum": 0,
            "maximum": 511
        },
        "last_channel": {
            "description": "The final channel to use in loop. Default is 448.",
            "type": [
                "integer",
                "null"
            ],
            "minimum": 0,
            "maximum": 511
        },
        "daq_mode": {
            "description": "The DAQ mode to use for acquiring data. This is expected to be one of 'TCC' or 'xGPU'. Default is 'TCC'.",
            "type": [
                "string",
                "null"
            ],
            "enum": [
                "TCC",
                "xGPU",
                null
            ]
        },
        "daq_config": {
            "description": "Any overrides to pass to DAQ for configuration purposes. Default is an empty dict.",
            "type": [
                "object",
                "null"
            ],
            "additionalProperties": true
        }
    },
    "required": [],
    "additionalProperties": false
}
Parameters:

kwargs – keyword arguments unpacked from the JSON argument.

Returns:

a task function to be submitted to the task executor.

GetCalibration(frequency_channel: int, calibration_id: str | None = None) → list[float][source]

Get a calibration from the calibration store.

This command takes as input a JSON string that conforms to the following schema:

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://skao.int/MccsStationCalibrator_GetCalibration.json",
    "title": "MccsStationCalibrator GetCalibration schema",
    "description": "Schema for MccsStationCalibrator's GetCalibration command",
    "type": "object",
    "properties": {
        "frequency_channel": {
            "description": "Freqency channel to calibrate for",
            "type": "integer",
            "minimum": 0,
            "maximum": 511
        }
    },
    "required": ["frequency_channel"]
}
Parameters:
  • frequency_channel – the frequency channel to calibrate for.

  • calibration_id – optional unique identifier for calibration.

Returns:

a calibration from the calibration store.

GetFittedSolutions(frequency_channels: list[int], calibration_id: str | None = None) → list[float][source]

Get fitted calibration solutions for a set of frequency channels.

Fetches phase fit parameters from the calibration store once and reconstructs gains for all requested channels in a single call, avoiding per-channel round-trips from MccsStation.ApplyConfiguration.

This command takes as input a JSON string that conforms to the following schema:

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$id": "https://skao.int/MccsStationCalibrator_GetFittedSolutions.json",
    "title": "MccsStationCalibrator GetFittedSolutions schema",
    "description": "Schema for MccsStationCalibrator's GetFittedSolutions command",
    "type": "object",
    "properties": {
        "frequency_channels": {
            "description": "List of frequency channel indices to compute fitted solutions for.",
            "type": "array",
            "items": {
                "type": "integer",
                "minimum": 0,
                "maximum": 511
            },
            "minItems": 1
        },
        "calibration_id": {
            "description": "Optional unique identifier for the calibration.",
            "type": "string"
        }
    },
    "required": ["frequency_channels"]
}
Parameters:
  • frequency_channels – channel indices to compute solutions for.

  • calibration_id – optional unique identifier for the calibration.

Returns:

flat float array of shape (n_freqs * n_ant * 8,).

__init__(*args: Any, **kwargs: Any) → None[source]

Initialise this device object.

Parameters:
  • args – positional args to the init

  • kwargs – keyword args to the init

calibrationSchedule(value: str) → None[source]

Set the calibration schedule.

Parameters:

value – a JSON array of schedule entries, each with a "cron" key and optional calibration parameter overrides, or an empty string to clear the schedule.

Raises:

ValueError – if any entry is missing "cron", contains an invalid cron expression, or sets "calibration_id".

create_component_manager() → StationCalibratorComponentManager[source]

Create and return a component manager for this device.

Returns:

a component manager for this device.

init_device() → None[source]

Initialise the device.

isLoopRunning() → bool[source]

Return whether or not a scheduled calibration job is currently running.

This is True while the scheduler executes a calibration job.

Returns:

whether or not a scheduled calibration job is currently running.

is_GenerateCalibrationSolution_allowed(request_type: LRCReqType | None = ska_tango_base.long_running_commands.LRCReqType.ENQUEUE_REQ) → bool[source]

Return whether the GenerateCalibrationSolution command is allowed.

Parameters:

request_type – The request type

Returns:

True if command is allowed.

Raises:

CmdNotAllowedError – if a scheduled run is in progress or the schedule is running.

jobsInQueue() → int[source]

Return number of correlator files left to process.

Returns:

number of correlator files left to process.

latestPreferredJobId() → str[source]

Return the user_friendly_name of the most recent preferred calibration job.

Returns:

the user_friendly_name of the most recent preferred calibration job, or an empty string if no preferred job exists.

pauseWindow(value: str) → None[source]

Set the window over which the scheduler holds off firing runs.

The window is written whole, so its two boundaries can never disagree. Leave out "start" to pause from now, and leave out "end" to pause with no deadline. The scheduler moves to PAUSED when the window opens and back to RUNNING when it closes.

Example:

>>> {"start": "2025-06-11T08:00:00+00:00",
      "end": "2025-06-11T10:00:00+00:00"}
Parameters:

value – a JSON object with an optional "start" and an optional "end", both ISO 8601 timestamps, naive values being interpreted as UTC, or an empty string to cancel the pause.

scheduleState() → CalibrationScheduleState[source]

Return the current state of the calibration scheduler.

The state is read-only and derived from the other scheduling attributes. It is EMPTY if no calibrationSchedule is set, PAUSED while the pauseWindow is open, and RUNNING otherwise. Suspend the scheduler by setting a pause window, not by writing this attribute.

Returns:

EMPTY if no schedule is set, PAUSED if suspended, RUNNING if actively firing runs.

scheduledSweeps() → str[source]

Return all calibration runs scheduled within the next 24 hours.

Each item in the returned array has a "scheduled_time" (ISO 8601 UTC) and any per-run parameter overrides from the schedule entry.

Returns:

a JSON array of upcoming runs, sorted by time, or "[]" if no schedule is set.

class NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Converts numpy types to JSON.

default(obj: Any) → Any[source]

Dereturn the encoded value.

Parameters:

obj – the object.

Returns:

the encoded value.

class PauseWindow(start: datetime, end: datetime | None = None)[source]

The period over which the calibration scheduler holds off firing runs.

The window is a half open interval. It is active from its start, up to but not including its end. A window with no end never closes on its own.

The window is written and stored whole, so its two boundaries can never disagree with each other. It is also immutable, so the scheduler thread always reads a window that is fully applied.

__init__(start: datetime, end: datetime | None = None) → None
classmethod from_json(text: str, now: datetime) → PauseWindow | None[source]

Build a window from the JSON object written to the device.

The object takes an optional "start" and an optional "end", both ISO 8601 timestamps. A missing start means “from now”, and is resolved here, so a stored window always names both of its own terms. A missing end means the pause has no deadline.

With the start missing, an end that has already passed describes a pause that is over. That window is spent, so it is accepted and returns no window at all. This is what a memorised window replays into when the device restarts after the pause has closed.

Parameters:
  • text – the JSON object, or an empty string for no window.

  • now – the time that a missing start resolves to.

Returns:

the window, or None if there is no window, or if the window it describes is already spent.

Raises:

ValueError – if the text is not a JSON object with valid timestamps, or if the window it describes is not a valid period.

is_active(now: datetime) → bool[source]

Return whether the window holds off runs at the given time.

Parameters:

now – the time to test the window against.

Returns:

whether scheduled runs are suppressed.

next_boundary(now: datetime) → datetime | None[source]

Return the next time at which the window opens or closes.

Parameters:

now – the time to look forward from.

Returns:

the boundary still to come, or None if the window has opened and has no deadline, or is already spent.

to_json() → str[source]

Return the window as the JSON object the device reads back.

Returns:

the JSON object, always naming the start, and naming the end only when the pause has a deadline.

class StationCalibratorComponentManager(*args: Any, **kwargs: Any)[source]

A component manager for a station calibrator.

__init__(logger: Logger, station_name: str, station_id: int, calibration_store_name: str, calibration_solver_trl: str, station_config_path: list[str], communication_state_callback: Callable[[ska_control_model.CommunicationStatus], None], component_state_callback: Callable[[...], None], channels_to_ignore: list[int] | None = None, event_serialiser: ska_low_mccs_common.EventSerialiser | None = None) → None[source]

Initialise a new instance.

Parameters:
  • logger – the logger to be used by this object.

  • station_name – the name of this calibrator’s station

  • station_id – the id of the station.

  • calibration_store_name – the name of this calibrator’s calibration store

  • calibration_solver_trl – the trl of the solver device.

  • station_config_path – TMData reference [source, yaml_path] for the station configuration, used as the default when not supplied in a command.

  • communication_state_callback – callback to be called when the status of the communications channel between the component manager and its component changes.

  • component_state_callback – callback to be called when the component state changes.

  • channels_to_ignore – channel indices with known RFI to skip when solving.

  • event_serialiser – the event serialiser to be used by this object.

property calibration_schedule: list[dict[str, Any]]

Return the active schedule entries.

Returns:

the list of active schedule entries.

cleanup() → None[source]

Cleanup resources held by the component manager.

This includes cleaning up resources held by all sub-component managers.

do_generate_calibration_solution(task_callback: Callable | None = None, task_abort_event: Event | None = None, **kwargs: Any) → None[source]

Generate the calibration solution.

Parameters:
  • task_callback – optional callback

  • task_abort_event – optional abort event

  • kwargs – see schema for keyword argument definitions

Raises:

ValueError – if unexpected result code received

get_calibration(frequency_channel: int, calibration_id: str | None = None) → list[float][source]

Get a calibration from the calibration store.

Parameters:
  • frequency_channel – the frequency channel to calibrate for

  • calibration_id – Unique identifier for calibration.

Returns:

A list of calibration values

get_fitted_solutions(frequency_channels: list[int], calibration_id: str | None = None) → list[float][source]

Get fitted calibration solutions for a set of frequency channels.

Calls GetFittedSolutions on the calibration store once, returning gains reconstructed from the stored phase fit parameters for every requested channel in a single round-trip.

Parameters:
  • frequency_channels – channel indices to compute solutions for.

  • calibration_id – optional unique identifier for the calibration.

Returns:

flat float array of shape (n_freqs * n_ant * 8,).

property latest_preferred_job_id: str

Return the user_friendly_name of the most recent preferred job for this station.

Returns:

the user_friendly_name of the most recent preferred job, or an empty string if none exists.

property pause_window: PauseWindow | None

Return the window over which the scheduler holds off firing runs.

Returns:

the pause window, or None if no pause is set.

property schedule_state: CalibrationScheduleState

Return the current scheduler state.

The state is derived and never set. It is EMPTY with no schedule, PAUSED while a pause window is open, and RUNNING otherwise. To suspend the scheduler, set a pause window through pause_window.

Returns:

the current scheduler state.

start_communicating() → None[source]

Establish communication with the StationCalibrator components.

stop_communicating() → None[source]

Break off communication with the StationCalibrator components.

upcoming_runs(horizon: timedelta) → list[dict[str, Any]][source]

Return every run that falls due within the horizon, soonest first.

Parameters:

horizon – how far ahead to look.

Returns:

the upcoming runs, each with a "scheduled_time" in ISO 8601 UTC plus that entry’s overrides.

class StationCalibratorHealthModel(*args: Any, **kwargs: Any)[source]

A health model for a station calibrator.

At present this uses the base health model; this is a placeholder for a future, better implementation.

entry_overrides(entry: dict[str, Any]) → dict[str, Any][source]

Return one schedule entry’s calibration parameter overrides.

An entry is its cron expression plus the parameters to override on the run it fires, so the overrides are everything but the cron expression.

Parameters:

entry – the schedule entry.

Returns:

the entry without its "cron" key.

fit_gains(channels: ndarray, phases: ndarray) → tuple[ndarray, ndarray, ndarray, ndarray][source]

Fit a linear delay model to the observed phase data.

For each antenna and polarisation, fits phase = offset + 2π·f·delay over the supplied channels. The resulting parameters can be evaluated at any frequency, including channels the correlator skipped.

Parameters:
  • channels – 1-D array of channel indices that were actually observed.

  • phases – 2-D array of phases, shape [n_channels, n_ant * 4], where the inner axis layout per antenna is [xx, xy, yx, yy].

Returns:

A tuple of (offsets, delays, cov_matrices, costs), each shaped for 256 * 4 Jones elements with XX at stride-4 index 0 and YY at stride-4 index 3.