karabo.imaging package

Submodules

karabo.imaging.image module

class Image(*, path: Path | str, data: Literal[None] = None, header: Literal[None] = None, **kwargs: Any)
class Image(*, path: Literal[None] = None, data: ndarray[Any, dtype[float64]], header: Header, **kwargs: Any)

Bases: object

circle() None

For each frequency channel and polarisation, cutout the pixel values, only keeping data for a circle of the computed radius, centered at the center of the image. This is an in-place transformation of the data.

Returns:

None (data of current Image instance is transformed in-place)

cutout(center_xy: Tuple[float, float], size_xy: Tuple[float, float]) Image

Cutout the image to the given size and center.

Parameters:
  • center_xy – Center of the cutout in pixel coordinates

  • size_xy – Size of the cutout in pixel coordinates

Returns:

Cutout of the image

property data: ndarray[Any, dtype[float64]]
get_2d_wcs(ra_dec_axis: Tuple[int, int] = (1, 2)) WCS
get_beam_parameters() BeamType

Gets the beam-parameters fom the image-header.

“bmaj”: FWHM of the major axis of the elliptical Gaussian beam in arcsec “bmin”: FWHM of the minor minor axis of the elliptical Gaussian beam in arcsec “bpa”: position angle of the major axis of the elliptical Gaussian beam in

degrees, counter-clock from the North direction

Returns:

“bmaj” (arcsec), “bmin” (arcsec), “bpa” (deg)

get_cellsize() float64
get_dimensions_of_image() List[int]

Get the sizes of the dimensions of this Image in an array. :return: list with the dimensions.

get_phase_center() Tuple[float, float]
get_power_spectrum(resolution: float = 0.0005, signal_channel: int | None = None) Tuple[ndarray[Any, dtype[float64]], ndarray[Any, dtype[float64]]]

Calculate the power spectrum of this image.

Parameters:
  • resolution – Resolution in radians needed for conversion from Jy to Kelvin

  • signal_channel – channel containing both signal and noise

(arr of same shape as nchan of Image), optional :return (profile, theta_axis)

profile: Brightness temperature for each angular scale in Kelvin theta_axis: Angular scale data in degrees

get_quality_metric() Dict[str, Any]

Get image statistics. Statistics include :

  • Shape of Image –> ‘shape’

  • Max Value –> ‘max’

  • Min Value –> ‘min’

  • Max Value absolute –> ‘max-abs’

  • Root mean square (RMS) –> ‘rms’

  • Sum of values –> ‘sum’

  • Median absolute –> ‘median-abs’

  • Median absolute deviation median –> ‘median-abs-dev-median’

  • Median –> ‘median’

  • Mean –> ‘mean’

Returns:

Dictionary holding all image statistics

get_squeezed_data() ndarray[Any, dtype[float64]]
get_wcs() WCS
has_beam_parameters() bool

Check if the image has the beam parameters in the header. :param image: Image to check :return: True if the image has the beam parameters in the header

header_has_parameters(parameters: List[str]) bool
overplot_with_skymodel(sky: SkyModel, filename: Path | str | None = None, block: bool = False, channel_index: int = 0, stokes_index: int = 0, vmin_image: float | None = None, vmax_image: float | None = None) None

Create a plot with the current image data, as well as an overlay of sources from a given SkyModel instance.

Parameters:
  • sky – a SkyModel instance, with sources to be plotted.

  • filename – path to the file where the final plot will be saved. If None, the plot is not saved.

  • block – whether plotting should block the remaining of the script.

  • channel_index – Which frequency channel to show in the plot. Defaults to 0.

  • stokes_index – Which polarisation to show in the plot. Defaults to 0 (stokesI).

  • vmax_image (vmin_image,) – Limits for colorbar of Image plot.

plot(title: str | None = None, xlim: Tuple[float, float] | None = None, ylim: Tuple[float, float] | None = None, figsize: Tuple[float, float] | None = None, colorbar_label: str | None = None, xlabel: str | None = None, ylabel: str | None = None, cmap: str | None = 'jet', origin: Literal['upper', 'lower'] | None = 'lower', wcs_enabled: bool = True, invert_xaxis: bool = False, filename: str | None = None, block: bool = False, **kwargs: Any) None

Plots the image

Parameters:
  • title – the title of the colormap

  • xlim – RA-limit of plot

  • ylim – DEC-limit of plot

  • figsize – figsize as tuple

  • title – plot title

  • xlabel – xlabel

  • ylabel – ylabel

  • cmap – matplotlib color map

  • origin – place the [0, 0] index of the array in

the upper left or lower left corner of the Axes :param wcs_enabled: Use wcs transformation? :param invert_xaxis: Do you want to invert the xaxis? :param filename: Set to path/fname to save figure (set extension to fname to overwrite .png default) :param block: Whether plotting should block the remaining of the script :param kwargs: matplotlib kwargs for scatter & Collections, e.g. customize s, vmin or vmax

plot_power_spectrum(resolution: float = 0.0005, signal_channel: int | None = None, path: Path | str | None = None, block: bool = False) None

Plot the power spectrum of this image.

Parameters:
  • resolution – Resolution in radians needed for conversion from Jy to Kelvin

  • signal_channel – channel containing both signal and noise

(arr of same shape as nchan of Image), optional :param save_png: True if result should be saved, default = False :param block: Whether plotting should block the remaining of the script

plot_side_by_side_with_skymodel(sky: SkyModel, filename: Path | str | None = None, block: bool = False, channel_index: int = 0, stokes_index: int = 0, vmin_sky: float = 0, vmax_sky: float = inf, vmin_image: float = 0, vmax_image: float = inf) None

Create a plot with two panels: 1. the current image data, and 2. a scatter plot of sources from a given SkyModel instance.

Parameters:
  • sky – a SkyModel instance, with sources to be plotted.

  • filename – path to the file where the final plot will be saved. If None, the plot is not saved.

  • block – whether plotting should block the remaining of the script.

  • channel_index – Which frequency channel to show in the plot. Defaults to 0.

  • stokes_index – Which polarisation to show in the plot. Defaults to 0 (stokesI).

  • vmax_sky (vmin_sky,) – Limits for colorbar of SkyModel scatter plot.

  • vmax_image (vmin_image,) – Limits for colorbar of Image plot.

static read_from_file(path: Path | str) Image
resample(shape: Tuple[int, ...], **kwargs: Any) None

Resamples the image to the given shape using SciPy’s RegularGridInterpolator for bilinear interpolation. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html

Parameters:
  • shape – The desired shape of the image

  • kwargs – Keyword arguments for the interpolation function

split_image(N: int, overlap: int = 0) List[Image]

Split the image into N x N equal-sized sections with optional overlap.

Parameters

Nint

The number of sections to split the image into along one axis. The total number of image sections will be N^2. It is assumed that the image can be divided into N equal parts along both axes. If this is not the case (e.g., image size is not a multiple of N), the sections on the edges will have fewer pixels.

overlapint, optional

The number of pixels by which adjacent image sections will overlap. Default is 0, meaning no overlap. Negative overlap means that there will be empty sections between the cutouts.

Returns

cutoutslist

A list of cutout sections of the image. Each element in the list is a 2D array representing a section of the image.

Notes

The function calculates the step size for both the x and y dimensions by dividing the dimension size by N. It then iterates over N steps in both dimensions to generate starting and ending indices for each cutout section, taking the overlap into account.

The cutout function (not shown) is assumed to take the center (x, y) coordinates and the (width, height) of the desired cutout section and return the corresponding 2D array from the image.

The edge sections will be equal to or smaller than the sections in the center of the image if the image size is not an exact multiple of N.

Examples

>>> # Assuming `self.data` is a 4D array with shape (C, Z, X, Y)
>>> # and `self.cutout` method is defined
>>> image = Image()
>>> cutouts = image.split_image(4, overlap=10)
>>> len(cutouts)
16  # because 4x4 grid
to_2dNNData() NDData
to_NNData() NDData
static update_header_from_image_header(new_header: Header, old_header: Header, keys_to_copy: List[str] | None = None) Header
write_to_file(path: Path | str, overwrite: bool = False) None

Write an Image to path as .fits

class ImageMosaicker(reproject_function: ~typing.Callable[[...], ~typing.Any] = <function reproject_interp>, combine_function: str = 'mean', match_background: bool = False, background_reference: int | None = None)

Bases: object

A class to handle the combination of multiple images into a single mosaicked image. See: https://reproject.readthedocs.io/en/stable/mosaicking.html

Parameters More information on the parameters can be found in the documentation: https://reproject.readthedocs.io/en/stable/api/reproject.mosaicking.reproject_and_coadd.html # noqa: E501 However, here the most common to tune are explained. ———- reproject_function : callable, optional

The function to use for the reprojection.

combine_function{‘mean’, ‘sum’}

The type of function to use for combining the values into the final image.

match_backgroundbool, optional

Whether to match the backgrounds of the images.

background_referenceNone or int, optional

If None, the background matching will make it so that the average of the corrections for all images is zero. If an integer, this specifies the index of the image to use as a reference.

Methods

get_optimal_wcs(images, projection=’SIN’, **kwargs)

Get the optimal WCS for the given images. See: https://reproject.readthedocs.io/en/stable/api/reproject.mosaicking.find_optimal_celestial_wcs.html # noqa: E501

process(

images ) Combine the provided images into a single mosaicked image.

get_optimal_wcs(images: List[Image], projection: str = 'SIN', **kwargs: Any) Tuple[WCS, tuple[int, int]]

Set the optimal WCS for the given images. See: https://reproject.readthedocs.io/en/stable/api/reproject.mosaicking.find_optimal_celestial_wcs.html # noqa: E501

Parameters

imageslist

A list of images to combine.

projectionstr, optional

Three-letter code for the WCS projection, such as ‘SIN’ or ‘TAN’.

**kwargsdict, optional

Additional keyword arguments to be passed to the reprojection function.

Returns

WCS

The optimal WCS for the given images.

tuple

The shape of the optimal WCS.

mosaic(images: List[Image], wcs: Tuple[WCS, Tuple[int, int]] | None = None, input_weights: List[str | fits.HDUList | fits.PrimaryHDU | NDArray[np.float64]] | None = None, hdu_in: int | str | None = None, hdu_weights: int | str | None = None, shape_out: Tuple[int] | None = None, image_for_header: Image | None = None, **kwargs: Any) Tuple[Image, NDArray[np.float64]]

Combine the provided images into a single mosaicked image.

Parameters

imageslist

A list of images to combine.

wcstuple, optional

The WCS to use for the mosaicking. Will be calculated with get_optimal_wcs if not passed.

input_weightslist, optional

If specified, an iterable with the same length as images, containing weights for each image.

shape_outtuple, optional

The shape of the output data. If None, it will be computed from the images.

hdu_inint or str, optional

If one or more items in input_data is a FITS file or an HDUList instance, specifies the HDU to use.

hdu_weightsint or str, optional

If one or more items in input_weights is a FITS file or an HDUList instance, specifies the HDU to use.

image_for_headerImage, optional

From which image the header should be used to readd the lost information by the mosaicking because some information is not propagated.

**kwargsdict, optional

Additional keyword arguments to be passed to the reprojection function.

Returns

fits.PrimaryHDU

The final mosaicked image as a FITS HDU.

np.ndarray

The footprint of the final mosaicked image.

Raises

ValueError

If less than two images are provided.

karabo.imaging.imager_base module

Base classes for dirty imagers and image cleaners.

class DirtyImager

Bases: ABC

Abstract base class for a dirty imager.

A dirty imager creates dirty images from visibilities.

config: DirtyImagerConfig
abstract create_dirty_image(visibility: Visibility | Visibility, output_fits_path: Path | str | None = None) Image

Creates a dirty image from a visibility.

Args:
visibility (Union[Visibility, RASCILVisibility]): Visibility object

from which to create the dirty image. Contains the visibilities of an observation.

output_fits_path (Optional[FilePathType]): Path to write the dirty image to.

Example: /tmp/dirty.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Image: Dirty image

class DirtyImagerConfig(imaging_npixel: int, imaging_cellsize: float, combine_across_frequencies: bool = True)

Bases: object

Base class for the config / parameters of a dirty imager.

Contains basic parameters common across all dirty imagers. Inherit and add parameters specific to a dirty imager implementation.

Attributes:

imaging_npixel (int): Image size imaging_cellsize (float): Scale of a pixel in radians combine_across_frequencies (bool): Whether or not to combine images

across all frequency channels into one image. Defaults to True.

combine_across_frequencies: bool = True
imaging_cellsize: float
imaging_npixel: int
class ImageCleaner

Bases: ABC

Abstract base class for an image cleaner.

An image cleaner creates clean images from dirty images or directly from visibilities, in that case including the dirty imaging process.

abstract create_cleaned_image(ms_file_path: Path | str, dirty_fits_path: Path | str | None = None, output_fits_path: Path | str | None = None) Image

Creates a clean image from a dirty image or from visibilities.

Args:
ms_file_path (FilePathType): Path to measurement set from which

a clean image should be created.

dirty_fits_path (Optional[FilePathType]): Path to dirty image FITS file that

should be reused to create a clean image. If None, dirty image will be created first from the measurement set. Defaults to None.

output_fits_path (Optional[FilePathType]): Path to write the clean image to.

Example: /tmp/restored.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Image: Clean image

class ImageCleanerConfig(imaging_npixel: int, imaging_cellsize: float)

Bases: object

Base class for the config / parameters of an image cleaner.

Contains basic parameters common across all image cleaners. Inherit and add parameters specific to an image cleaner implementation.

Attributes:

imaging_npixel (int): Image size imaging_cellsize (float): Scale of a pixel in radians

imaging_cellsize: float
imaging_npixel: int

karabo.imaging.imager_oskar module

class OskarDirtyImager(config: OskarDirtyImagerConfig)

Bases: DirtyImager

Dirty imager based on the OSKAR library.

Attributes:
config (OskarDirtyImagerConfig): Config containing parameters for

OSKAR dirty imaging.

create_dirty_image(visibility: Visibility | Visibility, output_fits_path: Path | str | None = None) Image

Creates a dirty image from a visibility.

Args:
visibility (Union[Visibility, RASCILVisibility]): Visibility object

from which to create the dirty image. Contains the visibilities of an observation.

output_fits_path (Optional[FilePathType]): Path to write the dirty image to.

Example: /tmp/dirty.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Image: Dirty image

class OskarDirtyImagerConfig(imaging_npixel: int, imaging_cellsize: float, combine_across_frequencies: bool = True, imaging_phase_centre: str | None = None)

Bases: DirtyImagerConfig

Config / parameters of an OskarDirtyImager.

Adds parameters specific to OskarDirtyImager.

Attributes:

imaging_npixel (int): see DirtyImagerConfig imaging_cellsize (float): see DirtyImagerConfig combine_across_frequencies (bool): see DirtyImagerConfig imaging_phase_centre (Optional[str]): Phase centre (in SkyCoord string format).

Defaults to None.

imaging_phase_centre: str | None = None

karabo.imaging.imager_rascil module

class RascilDirtyImager(config: RascilDirtyImagerConfig)

Bases: DirtyImager

Dirty imager based on the RASCIL library.

Attributes:
config (RascilDirtyImagerConfig): Config containing parameters for

RASCIL dirty imaging.

create_dirty_image(visibility: Visibility | Visibility, output_fits_path: Path | str | None = None) Image

Creates a dirty image from a visibility.

Args:
visibility (Union[Visibility, RASCILVisibility]): Visibility object

from which to create the dirty image. Contains the visibilities of an observation.

output_fits_path (Optional[FilePathType]): Path to write the dirty image to.

Example: /tmp/dirty.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Image: Dirty image

class RascilDirtyImagerConfig(imaging_npixel: int, imaging_cellsize: float, combine_across_frequencies: bool = True, override_cellsize: bool = False)

Bases: DirtyImagerConfig

Config / parameters of a RascilDirtyImager.

Adds parameters specific to RascilDirtyImager.

Attributes:

imaging_npixel (int): see DirtyImagerConfig imaging_cellsize (float): see DirtyImagerConfig combine_across_frequencies (bool): see DirtyImagerConfig override_cellsize (bool): Override the cellsize if it is

above the critical cellsize. Defaults to False.

override_cellsize: bool = False
class RascilImageCleaner(config: RascilImageCleanerConfig)

Bases: ImageCleaner

Image cleaner based on the RASCIL library.

Attributes:
config (RascilImageCleanerConfig): Config containing parameters for

RASCIL image cleaning.

create_cleaned_image(ms_file_path: Path | str, dirty_fits_path: Path | str | None = None, output_fits_path: Path | str | None = None) Image

Creates a clean image from a dirty image or from visibilities.

Args:
ms_file_path (FilePathType): Path to measurement set from which

a clean image should be created.

dirty_fits_path (Optional[FilePathType]): Path to dirty image FITS file that

should be reused to create a clean image. If None, dirty image will be created first from the measurement set. Defaults to None.

output_fits_path (Optional[FilePathType]): Path to write the clean image to.

Example: /tmp/restored.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Image: Clean image

create_cleaned_image_variants(ms_file_path: Path | str, deconvolved_fits_path: Path | str | None = None, restored_fits_path: Path | str | None = None, residual_fits_path: Path | str | None = None) Tuple[Image, Image, Image]

Creates a clean image from visibilities.

Args:
ms_file_path (FilePathType): Path to measurement set from which

a clean image should be created

deconvolved_fits_path (Optional[FilePathType], optional): Path to write the

deconvolved image to. Example: /tmp/deconvolved.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

restored_fits_path (Optional[FilePathType], optional): Path to write the

restored image to. Example: /tmp/restored.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

residual_fits_path (Optional[FilePathType], optional): Path to write the

residual image to. Example: /tmp/residual.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Tuple[Image, Image, Image]: Tuple of deconvolved, restored, residual images

class RascilImageCleanerConfig(imaging_npixel: int, imaging_cellsize: float, ingest_dd: ~typing.List[int] = <factory>, ingest_vis_nchan: int | None = None, ingest_chan_per_vis: int = 1, imaging_nchan: int = 1, imaging_w_stacking: bool | str = True, imaging_flat_sky: bool | str = False, override_cellsize: bool = False, imaging_uvmax: float | None = None, imaging_uvmin: float = 0, imaging_dft_kernel: ~typing.Literal['cpu_looped', 'gpu_raw'] | None = None, client: ~distributed.client.Client | None = None, use_dask: bool = False, n_threads: int = 1, use_cuda: bool = False, img_context: ~typing.Literal['awprojection', '2d', 'ng', 'wg'] = 'ng', clean_algorithm: ~typing.Literal['hogbom', 'msclean', 'mmclean'] = 'hogbom', clean_beam: ~typing.Dict[~typing.Literal['bmaj', 'bmin', 'bpa'], float] | None = None, clean_scales: ~typing.List[int] = <factory>, clean_nmoment: int = 4, clean_nmajor: int = 5, clean_niter: int = 1000, clean_psf_support: int = 256, clean_gain: float = 0.1, clean_threshold: float = 0.0001, clean_component_threshold: float | None = None, clean_component_method: ~typing.Literal['fit', 'extract'] = 'fit', clean_fractional_threshold: float = 0.3, clean_facets: int = 1, clean_overlap: int = 32, clean_taper: ~typing.Literal['none', 'linear', 'tukey'] = 'tukey', clean_restore_facets: int = 1, clean_restore_overlap: int = 32, clean_restore_taper: ~typing.Literal['none', 'linear', 'tukey'] = 'tukey', clean_restored_output: ~typing.Literal['taylor', 'list', 'integrated'] = 'list')

Bases: ImageCleanerConfig

Config / parameters of a RascilImageCleaner.

Adds parameters specific to RascilImageCleaner.

Attributes:

imaging_npixel (int): see ImageCleanerConfig imaging_cellsize (float): see ImageCleanerConfig ingest_dd (List[int]): Data descriptors in MS to read (all must have the same

number of channels). Defaults to [0].

ingest_vis_nchan (Optional[int]): Number of channels in a single data

descriptor in the MS. Defaults to None.

ingest_chan_per_vis (int): Number of channels per blockvis (before any average).

Defaults to 1.

imaging_nchan (int): Number of channels per image. Defaults to 1. imaging_w_stacking (Union[bool, str]): Use the improved w stacking method

in Nifty Gridder?. Defaults to True.

imaging_flat_sky (Union[bool, str]): If using a primary beam, normalise to flat sky? Defaults to False. override_cellsize (bool): Override the cellsize if it is above

the critical cellsize? Defaults to False.

imaging_uvmax (Optional[float]): TODO. Defaults to None. imaging_uvmin (float): TODO. Defaults to 0. imaging_dft_kernel (Optional[DftKernelType]): DFT kernel: cpu_looped | gpu_raw.

Defaults to None.

client (Optional[Client]): Dask client. Defaults to None. use_dask (bool): Use dask? Defaults to False. n_threads (int): n_threads per worker. Defaults to 1. use_cuda (bool): Use CUDA for Nifty Gridder? Defaults to False. img_context (ImageContextType): Which nifty gridder to use. Defaults to “ng”. clean_algorithm (CleanAlgorithmType): Deconvolution algorithm

(hogbom or msclean or mmclean). Defaults to “hogbom”.

clean_beam (Optional[Dict[CleanBeamInDegType, float]]): major axis, minor axis,

position angle (deg). Defaults to None.

clean_scales (List[int]): Scales for multiscale clean (pixels) e.g. [0, 6, 10].

Defaults to [0].

clean_nmoment (int): Number of frequency moments in mmclean

(1=constant, 2=linear). Defaults to 4.

clean_nmajor (int): Number of major cycles in cip or ical. Defaults to 5. clean_niter (int): Number of minor cycles in CLEAN. Defaults to 1000. clean_psf_support (int): Half-width of psf used in cleaning (pixels).

Defaults to 256.

clean_gain (float): Clean loop gain. Defaults to 0.1. clean_threshold (float): Clean stopping threshold (Jy/beam). Defaults to 1e-4. clean_component_threshold (Optional[float]): Sources with absolute flux

> this level (Jy) are fit or extracted using skycomponents. Defaults to None.

clean_component_method (CleanComponentMethodType): Method to convert sources

in image to skycomponents: “fit” in frequency or “extract” actual values. Defaults to “fit”.

clean_fractional_threshold (float): Fractional stopping threshold for major

cycle. Defaults to 0.3.

clean_facets (int) Number of overlapping facets in faceted clean along each

axis. Defaults to 1.

clean_overlap (int): Overlap of facets in clean (pixels). Defaults to 32. clean_taper (CleanTaperType): Type of interpolation between facets in

deconvolution: none or linear or tukey. Defaults to “tukey”.

clean_restore_facets (int): Number of overlapping facets in restore step

along each axis. Defaults to 1.

clean_restore_overlap (int): Overlap of facets in restore step (pixels).

Defaults to 32.

clean_restore_taper (CleanTaperType): Type of interpolation between facets in

restore step (none, linear or tukey). Defaults to “tukey”.

clean_restored_output (CleanRestoredOutputType): Type of restored image output:

taylor, list, or integrated. Defaults to “list”.

clean_algorithm: Literal['hogbom', 'msclean', 'mmclean'] = 'hogbom'
clean_beam: Dict[Literal['bmaj', 'bmin', 'bpa'], float] | None = None
clean_component_method: Literal['fit', 'extract'] = 'fit'
clean_component_threshold: float | None = None
clean_facets: int = 1
clean_fractional_threshold: float = 0.3
clean_gain: float = 0.1
clean_niter: int = 1000
clean_nmajor: int = 5
clean_nmoment: int = 4
clean_overlap: int = 32
clean_psf_support: int = 256
clean_restore_facets: int = 1
clean_restore_overlap: int = 32
clean_restore_taper: Literal['none', 'linear', 'tukey'] = 'tukey'
clean_restored_output: Literal['taylor', 'list', 'integrated'] = 'list'
clean_scales: List[int]
clean_taper: Literal['none', 'linear', 'tukey'] = 'tukey'
clean_threshold: float = 0.0001
client: Client | None = None
imaging_dft_kernel: Literal['cpu_looped', 'gpu_raw'] | None = None
imaging_flat_sky: bool | str = False
imaging_nchan: int = 1
imaging_uvmax: float | None = None
imaging_uvmin: float = 0
imaging_w_stacking: bool | str = True
img_context: Literal['awprojection', '2d', 'ng', 'wg'] = 'ng'
ingest_chan_per_vis: int = 1
ingest_dd: List[int]
ingest_vis_nchan: int | None = None
n_threads: int = 1
override_cellsize: bool = False
use_cuda: bool = False
use_dask: bool = False

karabo.imaging.imager_wsclean module

class WscleanDirtyImager(config: DirtyImagerConfig)

Bases: DirtyImager

Dirty imager based on the WSClean library.

WSClean is integrated by calling the wsclean command line tool. The parameters in the config (DirtyImagerConfig) attribute are passed to wsclean. Use the create_image_custom_command function if you need to set params not available in DirtyImagerConfig.

Attributes:
config (DirtyImagerConfig): Config containing parameters for

dirty imaging

OUTPUT_FITS_DIRTY = 'wsclean-dirty.fits'
TMP_PREFIX_DIRTY = 'WSClean-dirty-'
TMP_PURPOSE_DIRTY = 'Disk cache for WSClean dirty images'
create_dirty_image(visibility: Visibility | Visibility, output_fits_path: Path | str | None = None) Image

Creates a dirty image from a visibility.

Args:
visibility (Union[Visibility, RASCILVisibility]): Visibility object

from which to create the dirty image. Contains the visibilities of an observation.

output_fits_path (Optional[FilePathType]): Path to write the dirty image to.

Example: /tmp/dirty.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Image: Dirty image

class WscleanImageCleaner(config: WscleanImageCleanerConfig)

Bases: ImageCleaner

Image cleaner based on the WSClean library.

WSClean is integrated by calling the wsclean command line tool. The parameters in the config (WscleanImageCleanerConfig) attribute are passed to wsclean. Use the create_image_custom_command function if you need to set params not available in WscleanImageCleanerConfig. Parameters in the config that are explicitly set to None will not be passed to the command line tool, which will then resort to its own default values.

Attributes:
config (WscleanImageCleanerConfig): Config containing parameters for

WSClean image cleaning.

OUTPUT_FITS_CLEANED = 'wsclean-image.fits'
TMP_PREFIX_CLEANED = 'WSClean-cleaned-'
TMP_PURPOSE_CLEANED = 'Disk cache for WSClean cleaned images'
create_cleaned_image(ms_file_path: Path | str, dirty_fits_path: Path | str | None = None, output_fits_path: Path | str | None = None) Image

Creates a clean image from a dirty image or from visibilities.

Args:
ms_file_path (FilePathType): Path to measurement set from which

a clean image should be created.

dirty_fits_path (Optional[FilePathType]): Path to dirty image FITS file that

should be reused to create a clean image. If None, dirty image will be created first from the measurement set. Defaults to None.

output_fits_path (Optional[FilePathType]): Path to write the clean image to.

Example: /tmp/restored.fits. If None, will be set to a temporary directory and a default file name. Defaults to None.

Returns:

Image: Clean image

class WscleanImageCleanerConfig(imaging_npixel: int, imaging_cellsize: float, niter: int | None = 50000, mgain: float | None = 0.8, auto_threshold: int | None = 3)

Bases: ImageCleanerConfig

Config / parameters of a WscleanImageCleaner.

Adds parameters specific to WscleanImageCleaner.

Attributes:
niter (Optional[int]): Maximum number of clean iterations to perform.

Defaults to 50000.

mgain (Optional[float]): Cleaning gain for major iterations: Ratio of peak that

will be subtracted in each major iteration. To use major iterations, 0.85 is a good value. Defaults to 0.8.

auto_threshold (Optional[int]): Relative clean threshold. Estimate noise level

using a robust estimator and stop at sigma x stddev. Defaults to 3.

auto_threshold: int | None = 3
mgain: float | None = 0.8
niter: int | None = 50000
create_image_custom_command(command: str, output_filenames: str | List[str] = 'wsclean-image.fits') Image | List[Image]

Create a dirty or cleaned image using your own command.

Allows the use of the full WSClean functionality with all parameters. Command has to start with ‘wsclean ‘. The working directory the command runs in will be a temporary directory. Use absolute paths to reference files or directories like the measurement set.

Args:
command (str): Command to execute. Example: wsclean -size 2048 2048

-scale 0.0022222222222222222deg -niter 50000 -mgain 0.8 -abs-threshold 100µJy /tmp/measurements.MS

output_filenames (Union[str, List[str]], optional): WSClean output filename(s)

(relative to the working directory) that should be returned as Image objects. Can be a string for one file or a list of strings for multiple files. Example 1: “wsclean-image.fits” Example 2: [‘wsclean-image.fits’, ‘wsclean-residual.fits’] Defaults to “wsclean-image.fits”.

Returns:
Union[Image, List[Image]]: If output_filenames is a string, returns an Image

object of the file output_filenames. If output_filenames is a list of strings, returns a list of Image objects, one object per filename in output_filenames.

karabo.imaging.util module

auto_choose_dirty_imager_from_sim(simulator_backend: SimulatorBackend, config: DirtyImagerConfig) DirtyImager

Automatically choose a suitable dirty imager based on a simulator.

Temporary function until all dirty imagers support all simulators.

Args:

simulator_backend (SimulatorBackend): Simulator backend being used config (DirtyImagerConfig): Config to initialize dirty imager

object with.

Returns:

DirtyImager: The created dirty imager object

auto_choose_dirty_imager_from_vis(visibility: Visibility | Visibility, config: DirtyImagerConfig) DirtyImager

Automatically choose a suitable dirty imager based on a visibility object.

Temporary function until we have a general visibility object and functions to convert general objects to implementation-specific objects on demand.

Args:

visibility (Union[Visibility, RASCILVisibility]): Visibility object config (DirtyImagerConfig): Config to initialize dirty imager

object with.

Returns:

DirtyImager: The created dirty imager object

get_MGCLS_images(regex_pattern: str, verbose: bool = False) List[Image]

MeerKAT Galaxy Cluster Legacy Survey Data Release 1 (MGCLS DR1) https://doi.org/10.48479/7epd-w356 The first data release of the MeerKAT Galaxy Cluster Legacy Survey (MGCLS) consists of the uncalibrated visibilities, a set of continuum imaging products, and several source catalogues. All clusters have Stokes-I products, and approximately 40% have Stokes-Q and U products as well. For full details, including caveats for usage, see the survey overview and DR1 paper (Knowles et al., 2021).

When using any of the below products, please cite Knowles et al. (2021) and include the following Observatory acknowledgement: “MGCLS data products were provided by the South African Radio Astronomy Observatory and the MGCLS team and were derived from observations with the MeerKAT radio telescope. The MeerKAT telescope is operated by the South African Radio Astronomy Observatory, which is a facility of the National Research Foundation, an agency of the Department of Science and Innovation.”

The final enhanced image data products are five-plane cubes (referred to as the 5pln cubes in the following) in which the first plane is the brightness at the reference frequency, and the second is the spectral index, a**1656/908 , both determined by a least-squares fit to log(I) vs. log(v) at each pixel. The third plane is the brightness uncertainty estimate, fourth is the spectral index uncertainty, and fifth is the χ2 of the least-squares fit. Uncertainty estimates are only the statistical noise component and do not include calibration or other systematic effects. The five planes are accessible in the Xarray.Image in the frequency dimension (first dimension).

Data will be accessed from the karabo_public folder. The data was downloaded from https://archive-gw-1.kat.ac.za/public/repository/10.48479/7epd-w356/ data/enhanced_products/bucket_contents.html

Parameters:

regex_patternstr

Regex pattern to match the files to download. Best is to check in the bucket and paper which data is available and then use the regex pattern to match the files you want to download.

verbosebool, optional

If True, prints out the files being downloaded. Defaults to False.

Returns:

List[SkaSdpImage]

List of images from the MGCLS Enhanced Products bucket.

guess_beam_parameters(img: Image) BeamType

Fit a two-dimensional Gaussian to img using astropy.modeling.

This function is usually applied on a PSF-image. Therefore, just images who don’t have beam-params in the header (e.g. dirty image) may need a beam-guess.

Source: https://gitlab.com/ska-telescope/sdp/ska-sdp-func-python/-/blob/main/src/ska_sdp_func_python/image/deconvolution.py # noqa: E501

Args:

img: Image to guess the beam

Returns:

major-axis (arcsec), minor-axis (arcsec), position-angle (degree)

project_sky_to_image(sky: SkyModel, phase_center: List[int] | List[float], imaging_cellsize: float, imaging_npixel: int, filter_outlier: bool = True, invert_ra: bool = True) Tuple[ndarray[Any, dtype[float64]], ndarray[Any, dtype[int64]]]

Calculates the pixel coordinates sky sources as floats. If you want to have integer indices, just round them.

Parameters:
  • skySkyModel with the sources

  • phase_center – [RA,DEC]

  • imaging_cellsize – Image cellsize in radian (pixel coverage)

  • imaging_npixel – Number of pixels of the image

  • filter_outlier – Exclude source outside of image?

  • invert_ra – Invert RA axis?

Returns:

image-coordinates as np.ndarray[px,py] and

SkyModel sources indices as np.ndarray[idxs]

Module contents