Utils#

ADI Tools#

fours.utils.adi_tools.cadi_psf_subtraction(images, angles)#

Perform Classical Angular Differential Imaging (cADI) PSF subtraction to suppress stellar light from astronomical images.

CADI is a widely acclaimed technique for high-contrast imaging that suppresses point spread function (PSF) noise caused by the central star. The method works by creating a median frame from the input images, subtracting the median to create a residual image sequence, and derotating the residual images using the corresponding parallactic angles. The derotated residual stack is then combined using the mean to generate the final high-contrast image.

Parameters
  • images (ndarray) – A 3D NumPy array of shape (N, H, W) representing the input image stack. Here, N is the number of images, and H and W are the height and width of each image.

  • angles (ndarray) – A 1D NumPy array of length N containing the parallactic angles corresponding to each input image in radians.

Return type

ndarray

Returns

A 2D NumPy array of shape (H, W) representing the final high-contrast residual image after PSF subtraction.

fours.utils.adi_tools.cadi_psf_subtraction_gpu(device, images, angles)#

Perform GPU-accelerated Classical Angular Differential Imaging (cADI) PSF subtraction to suppress stellar light from astronomical images.

This function leverages PyTorch to execute computations on GPU hardware, enhancing speed for large datasets. It calculates and subtracts the median frame, derotates residual frames using parallactic angles, and combines them to create a high-contrast image.

Parameters
  • device (str) – The PyTorch device indicating the computation hardware (e.g., ‘cuda’ for GPU or ‘cpu’).

  • images (ndarray) – A 3D NumPy array of shape (N, H, W) representing the input image sequence, where N is the number of images, and H and W are the height and width of each image.

  • angles (ndarray) – A 1D NumPy array of length N containing the parallactic angles in radians, used for de-rotation of the residual frames.

Return type

ndarray

Returns

A 2D NumPy array of shape (H, W) representing the final high-contrast residual image computed after PSF subtraction and derotation.

fours.utils.adi_tools.combine_residual_stack(residual_stack, angles, combine='mean', subtract_temporal_average=False, num_cpus=4)#

Derotate and combine the residual image stack using parallactic angles to suppress speckle noise and generate the final high-contrast image.

This function processes a sequence of residual images by spatially derotating each frame based on its parallactic angle and then combines the derotated stack into a single output frame. The processing pipeline includes an optional subtraction of the temporal average from each residual frame, configurable combination methods (mean or median), and multi-processing support.

Parameters
  • residual_stack (ndarray) – A 3D NumPy array of shape (N, H, W) representing residual images from which PSF noise is to be suppressed. N is the number of images, H and W are the height and width of the images, respectively.

  • angles (ndarray) – A 1D NumPy array of length N containing parallactic angles, measured in radians, corresponding to each image in the residual stack. These angles dictate the derotation applied to each frame.

  • combine (str) –

    Specifies the method to combine the derotated stack. Accepted values are:

    1. ”mean” - Compute the arithmetic mean of derotated frames.

    2. ”median” - Compute the median frame from the stack.

  • subtract_temporal_average (bool) – If set to True, the temporal average image across all frames (computed using either the mean or median) is subtracted from each residual image before derotation. This step helps mitigate temporal contamination.

  • num_cpus (int) – The number of CPU cores to utilize for parallel processing using Python’s multiprocessing.Pool. If num_cpus is set to 1, sequential processing will be executed. For multi-core processing, each frame is rotated in parallel.

Return type

ndarray

Returns

A 2D NumPy array of shape (H, W) representing the final high-contrast image obtained after derotation and combination of the residual frames.

Data Handling#

fours.utils.data_handling.load_adi_data(hdf5_dataset, data_tag, psf_template_tag, para_tag='PARANG')#

Loads Angular Differential Imaging (ADI) data from an HDF5 dataset. See “Examples” in the Documentation.

Parameters
  • hdf5_dataset (str) – Path to the HDF5 file containing the data.

  • data_tag (str) – HDF5 key for the science data cube (e.g., images at multiple wavelengths or observations).

  • psf_template_tag (str) – HDF5 key for the PSF template data.

  • para_tag (str) – HDF5 key for the parallactic angles array. Default is “PARANG”.

Return type

Tuple[ndarray, ndarray, ndarray]

Returns

  1. A numpy array representing the science data cube.

  2. A numpy array of parallactic angles in radians.

  3. A numpy array representing the PSF template.

fours.utils.data_handling.save_as_fits(data, file_name, overwrite=False)#

Saves data as .fits file.

Parameters
  • data (ndarray) – The data to be saved.

  • file_name (str) – The filename of the fits file.

  • overwrite (bool) – Overwrite existing files

Return type

None

fours.utils.data_handling.read_fours_root_dir()#

Reads the root directory for the FOURS dataset from an environment variable.

The function checks if the FOURS_ROOT_DIR environment variable is correctly set to a valid directory path, prints its location, and returns it. Raises an IOError if the directory does not exist.

Return type

str

Returns

A string representing the path to the FOURS_ROOT_DIR.

Raises
  • IOError – If the directory specified in the FOURS_ROOT_DIR environment

  • variable does not exist.

FWHM Estimation#

fours.utils.fwhm.get_fwhm(psf_template)#

Compute the Full Width at Half Maximum (FWHM) of a 2D point spread function (PSF) template using a Moffat model.

Parameters

psf_template (ndarray) – A 2D array representing the PSF intensity distribution.

Return type

float

Returns

The computed FWHM value, rounded to one decimal place.

Logging#

fours.utils.logging.setup_logger()#

Sets up and configures a logger object with a specific format and stream handler for output to the console.

Returns

Configured logger instance with a DEBUG logging level.

Return type

logging.Logger

fours.utils.logging.print_message(message_in)#

Logs a message at the INFO level using the logger named ‘main’.

Parameters

message_in (str) – The string message to be logged.

Return type

None

fours.utils.logging.normalize_for_tensorboard(frame_in)#

Normalizes an input image array to be scaled between 0 and 1 for visualization in TensorBoard.

The function takes a NumPy array as input, creates a deep copy to avoid modifying the original array, and scales it so that the minimum value becomes 0 and the maximum value becomes 1.

Parameters

frame_in (ndarray) – The input image or array that needs normalization.

Return type

ndarray

Returns

A normalized version of the input array with values between 0 and 1.

Mask Creation#

fours.utils.masks.construct_round_rfrr_template(radius, psf_template_in)#

Constructs a circular Right for Right Reasons Mask (RFRR) template for a given radius and PSF (Point Spread Function) input.

Parameters
  • radius (float) – The radius of the circular template (pixel).

  • psf_template_in (ndarray) – The input PSF template used to generate the RFRR template.

Return type

Tuple[ndarray, ndarray]

Returns

  1. The resulting RFRR template after applying the circular mask.

  2. The circular mask used to create the template.

fours.utils.masks.construct_rfrr_mask(cut_off_radius, psf_template_in, mask_size_in, use_template=False)#

Constructs the right reason mask for the full model parameter matrix. The mask is created by shifting the RFRR template (see function above).

Parameters
  • cut_off_radius (float) – The radius of the circular template. (pixel)

  • psf_template_in (ndarray) – The input PSF template used to generate the mask stack.

  • mask_size_in (int) – The dimensions (size x size) of the final mask.

  • use_template (bool) – Whether to directly use the template as the mask. Defaults to False. This feature is not used in the paper.

Return type

ndarray

Returns

The full right reason mask for the model parameter matrix.

PCA based PSF Subtraction#

fours.utils.pca.pca_psf_subtraction_gpu(images, angles, pca_numbers, device, approx_svd=-1, subsample_rotation_grid=1, verbose=False, combine='mean')#

Perform PCA-based PSF subtraction on GPU for a data set taken with pupil-tracking. The PCA components are computed from the input images and then subtracted from the input images. This is a fast GPU implementation that uses PyTorch.

Parameters
  • images (ndarray) – 3D array of shape (n_frames, height, width) representing the input image frames.

  • angles (ndarray) – 1D array of parallactic angles corresponding to the image frames.

  • pca_numbers (ndarray) – Array of integers specifying the number of PCA components to use for reconstruction.

  • device (str) – Device to use for computation (e.g., ‘cuda’ or ‘cpu’).

  • approx_svd (int) – Number of iterations for low-rank SVD approximation (-1 for exact SVD). Defaults to -1.

  • subsample_rotation_grid (int) – Subsampling factor for the rotation grid. Defaults to 1.

  • verbose (bool) – If True, print progress updates. Defaults to False.

  • combine (str) – Method to combine rotated residual images, either “mean” or “median”. Defaults to “mean”.

Return type

ndarray

Returns

Array of PCA-subtracted residual mean or median images, shape (len(pca_numbers), height, width).

fours.utils.pca.pca_tensorboard_logging(log_dir, pca_residuals, pca_numbers)#

Log PCA-subtracted residual images to TensorBoard for visualization.

Parameters
  • log_dir (str) – Directory to save TensorBoard logs.

  • pca_residuals (ndarray) – Array containing PCA residual images, of shape (n_components, height, width).

  • pca_numbers (ndarray) – Array of PCA component numbers corresponding to each residual image.

Return type

None