Parameters Utilities

Utility functions for handling simulation parameters in SynIM.

synim.params_utils.build_component_filename_part(component_config, component_type='dm', include_height=True, n_modes_override=None, full_config=None)

Build the DM/Layer-specific part of the filename.

Parameters:
  • component_config (dict) – DM or Layer configuration parameters

  • component_type (str) – Type of component (‘dm’ or ‘layer’)

  • include_height (bool) – Whether to include height in the output

  • n_modes_override (int, optional) – Number of modes ACTUALLY USED. Only adds suffix if < total nmodes.

  • full_config (dict, optional) – Full configuration for reference lookups

Returns:

DM or Layer filename component

Return type:

str

synim.params_utils.build_pupil_filename_part(pupil_params)

Build filename part for pupil parameters.

Parameters:

pupil_params (dict) – Pupil configuration

Returns:

Filename parts for pupil

Return type:

list

synim.params_utils.build_source_filename_part(source_config, zenith_angle=None)

Build the source-specific part of the filename.

Parameters:
  • source_config (dict) – Source configuration parameters

  • zenith_angle (float, optional) – Zenith angle override

Returns:

Source filename component

Return type:

str

synim.params_utils.build_wfs_filename_part(wfs_config, wfs_type=None)

Build the WFS-specific part of the filename.

Parameters:
  • wfs_config (dict) – WFS configuration parameters

  • wfs_type (str, optional) – WFS type for context

Returns:

WFS filename component

Return type:

str

synim.params_utils.compute_influence_functions_and_modalbases(root_dir, pixel_pupil, pixel_pitch, dm_altitudes, dm_nacts, layer_altitudes, layer_nacts, fov_arcsec=160, n_petals=6, obsratio=0.283, r0=0.15, L0=25.0, overwrite=False, verbose=False, return_pupil_mask=True)

Compute influence functions and modal bases for DMs and atmospheric layers.

This is a general-purpose function that can be used in workflows or standalone. It generates: - Pupil mask with spider (optional petals) - Influence functions for DMs at specified altitudes - Influence functions for atmospheric layers - Modal bases (KL modes) and M2C matrices - Inverse modal base for ground layer (altitude 0)

Parameters:
  • root_dir (str or Path) – Root directory for saving calibration files

  • pixel_pupil (int) – Number of pixels across pupil diameter

  • pixel_pitch (float) – Pixel size in meters

  • dm_altitudes (list) – List of DM altitudes in meters

  • dm_nacts (list) – List of number of actuators for each DM

  • layer_altitudes (list) – List of atmospheric layer altitudes in meters

  • layer_nacts (list) – List of number of actuators for each layer

  • fov_arcsec (float, optional) – Field of view in arcseconds. Default: 160

  • n_petals (int, optional) – Number of spider petals. Default: 6

  • obsratio (float, optional) – Central obstruction ratio. Default: 0.283

  • r0 (float, optional) – Fried parameter in meters. Default: 0.15

  • L0 (float, optional) – Outer scale in meters. Default: 25.0

  • overwrite (bool, optional) – Whether to overwrite existing files. Default: False

  • verbose (bool, optional) – Whether to print detailed information. Default: False

  • return_pupil_mask (bool, optional) – Whether to return the pupil mask. Default: True

Returns:

Dictionary with:
  • ’pupil_mask_tag’: Tag for the saved pupil mask

  • ’pupil_mask’: Pupil mask array (if return_pupil_mask=True)

  • ’ifunc_tags’: Dict mapping component names to ifunc tags

  • ’m2c_tags’: Dict mapping component names to m2c tags

  • ’ifunc_inv_tag’: Tag for the inverse basis (ground layer)

  • ’dm_indices’: List of DM indices

  • ’layer_indices’: List of layer indices

Return type:

dict

Example

>>> result = compute_influence_functions_and_modalbases(
...     root_dir='/path/to/calib',
...     pixel_pupil=160,
...     pixel_pitch=0.2406,
...     dm_altitudes=[600, 6500, 17500],
...     dm_nacts=[41, 37, 37],
...     layer_altitudes=[0, 2000, 4500, 11000, 15000, 18000, 22000],
...     layer_nacts=[41, 41, 41, 37, 37, 37, 37]
... )
>>> print(result['ifunc_tags'])
>>> print(result['m2c_tags'])
synim.params_utils.compute_layer_weights_from_turbulence(params, component_indices, component_type='layer', verbose=False)

Compute layer weights from atmospheric turbulence profile.

Associates each layer/DM with the nearest turbulence height and assigns the corresponding CN² contribution as weight.

Parameters:
  • params (dict) – Configuration dictionary with ‘atmo’ section

  • component_indices (list) – List of component indices to compute weights for

  • component_type (str) – Type of component (‘layer’ or ‘dm’)

  • verbose (bool) – Whether to print detailed information

Returns:

Normalized weights for each component (sum to 1)

Return type:

numpy.ndarray

Raises:

ValueError – If ‘atmo’ section or required fields are missing

synim.params_utils.compute_mmse_reconstructor(interaction_matrix, C_atm, noise_variance=None, C_noise=None, cinverse=False, xp=<module 'numpy' from '/home/docs/checkouts/readthedocs.org/user_builds/synim/envs/latest/lib/python3.11/site-packages/numpy/__init__.py'>, dtype=<class 'numpy.float32'>, verbose=False)

Compute the Minimum Mean Square Error (MMSE) reconstructor.

Parameters:
  • interaction_matrix (numpy.ndarray) – Interaction matrix A relating modes to slopes

  • C_atm (numpy.ndarray) – Covariance matrix of atmospheric modes (Cx)

  • noise_variance (list, optional) – List of noise variances per WFS. Used to build C_noise if C_noise is None.

  • C_noise (numpy.ndarray, optional) – Covariance matrix of measurement noise (Cz). If None, it’s built from noise_variance.

  • cinverse (bool, optional) – If True, C_atm and C_noise are already inverted.

  • xp (module, optional) – Numerical library to use (e.g., numpy or cupy).

  • dtype (data-type, optional) – Data type for computations.

  • verbose (bool, optional) – Whether to print detailed information during computation.

Returns:

MMSE reconstructor matrix

Return type:

numpy.ndarray

synim.params_utils.determine_source_type(wfs_name)

Determine the source type from a WFS name.

Parameters:

wfs_name (str) – Name of the WFS

Returns:

Source type (‘lgs’, ‘ngs’, or ‘ref’)

Return type:

str

synim.params_utils.extract_dm_list(config)

Extract all DM configurations from config

synim.params_utils.extract_layer_list(config)

Extract all layer configurations from config

synim.params_utils.extract_opt_list(params)

Extract list of optical sources (source_optX) from parameters.

Parameters:

params (dict) – Configuration dictionary

Returns:

List of dictionaries with optical source information:
  • ’name’: Source name (e.g., ‘source_opt1’)

  • ’index’: Source index (1-based, as integer)

  • ’config’: Configuration dictionary for this source

Return type:

list

synim.params_utils.extract_projection_params(params)
synim.params_utils.extract_source_coordinates(config, wfs_key)

Extract polar coordinates for a given source.

Parameters:
  • config (dict) – Configuration dictionary

  • wfs_key (str) – Key of the WFS in the config

Returns:

[distance, angle] polar coordinates

Return type:

list

synim.params_utils.extract_source_height(config, wfs_key)

Extracts the actual height of the source from the configuration. If zenithAngleInDeg is present, returns height * airmass. If height is not present, returns np.inf.

synim.params_utils.extract_source_info(config, wfs_name)

Extract source information related to a specific WFS

synim.params_utils.extract_wfs_list(config)

Extract all WFS configurations from config

synim.params_utils.find_subapdata(cm, wfs_params, wfs_key, params, verbose=False)

Find and load SubapData for valid subapertures.

NOTE: Returns numpy array from disk - caller should convert with to_xp if needed

Returns:

Array of valid subaperture indices (numpy) or None

Return type:

numpy.ndarray

synim.params_utils.generate_cov_filename(component_config, pup_diam_m, r0, L0, full_config=None)

Generate a unique filename for a covariance matrix, handling _tag/_object. :param component_config: DM or layer config :type component_config: dict :param component_type: ‘dm’ or ‘layer’ :type component_type: str :param pup_diam_m: pupil diameter in meters :type pup_diam_m: float :param r0: Fried parameter :type r0: float :param L0: Outer scale :type L0: float :param full_config: overall config :type full_config: dict

Returns:

filename

Return type:

str

synim.params_utils.generate_filter_matrix_from_intmat(intmat, n_modes, n_modes_filtered, cut_modes=0, w_vec=None, smooth_tt=True, verbose=False)

Generate a filter matrix from an interaction matrix.

Creates a filtmat that can be used to filter specific modes (typically tip, tilt, focus) from WFS slopes. The filtmat contains both the interaction matrix subset and the corresponding reconstruction matrix.

Parameters:
  • intmat (numpy.ndarray or Intmat) – Interaction matrix [n_slopes, n_modes_total] or SPECULA Intmat object

  • n_modes (int) – Number of modes to use for reconstruction

  • n_modes_filtered (int) – Number of modes to filter out (e.g., 3 for tip/tilt/focus)

  • cut_modes (int, optional) – Number of singular values to cut in SVD. Default: 0

  • w_vec (numpy.ndarray, optional) – Weight vector for reconstruction. Default: None

  • smooth_tt (bool, optional) – Whether to smooth tip/tilt slopes by replacing with median. Default: True

  • verbose (bool, optional) – Whether to print detailed information. Default: False

Returns:

(intmat_subset, recmat_subset)
  • intmat_subset: Interaction matrix for filtered modes [n_slopes, n_modes_filtered]

  • recmat_subset: Reconstruction matrix for filtered modes [n_modes_filtered, n_slopes]

Return type:

tuple

Example

>>> from specula.data_objects.intmat import Intmat
>>> intmat_obj = Intmat.restore('intmat.fits')
>>> im_filt, rec_filt = generate_filter_matrix_from_intmat(
...     intmat_obj, n_modes=1000, n_modes_filtered=3
... )
>>> print(f"Filter IM: {im_filt.shape}, Filter rec: {rec_filt.shape}")
synim.params_utils.generate_filter_matrix_from_intmat_file(intmat_filename, n_modes, n_modes_filtered, output_filename, cut_modes=0, w_vec=None, smooth_tt=True, overwrite=False, verbose=False)

Convenience function to load an intmat from file, generate filter matrix, and save it.

This is a high-level wrapper that combines: 1. Loading interaction matrix from FITS file 2. Generating filter matrix 3. Saving filter matrix to FITS file

Parameters:
  • intmat_filename (str or Path) – Path to interaction matrix FITS file

  • n_modes (int) – Number of modes to use for reconstruction

  • n_modes_filtered (int) – Number of modes to filter (e.g., 3 for tip/tilt/focus)

  • output_filename (str or Path) – Path for output filtmat FITS file

  • cut_modes (int, optional) – Number of singular values to cut. Default: 0

  • w_vec (numpy.ndarray, optional) – Weight vector for reconstruction. Default: None

  • smooth_tt (bool, optional) – Whether to smooth tip/tilt. Default: True

  • overwrite (bool, optional) – Whether to overwrite existing output file. Default: False

  • verbose (bool, optional) – Whether to print detailed information. Default: False

Example

>>> generate_filter_matrix_from_intmat_file(
...     'intmat_lgs1_layer0.fits',
...     n_modes=1000,
...     n_modes_filtered=3,
...     output_filename='filtmat_lgs1.fits',
...     overwrite=True,
...     verbose=True
... )
synim.params_utils.generate_im_filename(params_file, wfs_type=None, wfs_index=None, dm_index=None, layer_index=None, n_modes=None, slope_method='derivatives', timestamp=False, verbose=False)

Generate the interaction matrix filename for a given WFS-DM/Layer combination.

Parameters:
  • params_file (str or dict) – Path to configuration file or dictionary

  • wfs_type (str, optional) – Type of WFS source (‘lgs’, ‘ngs’, ‘ref’)

  • wfs_index (int, optional) – Index of the WFS (1-based)

  • dm_index (int, optional) – Index of the DM (1-based)

  • layer_index (int, optional) – Index of the Layer (1-based)

  • n_modes (int, optional) – Number of modes used (if limited)

  • slope_method (str) – Slope computation method (‘derivatives’ or ‘telsum’). When not ‘derivatives’, the method name is appended to the filename.

  • timestamp (bool) – Whether to include a timestamp in the filename

  • verbose (bool) – Whether to print detailed information

Returns:

Generated filename

Return type:

str

synim.params_utils.generate_pm_filename(config_file, opt_index=None, dm_index=None, layer_index=None, timestamp=False, verbose=False)

Generate a specific projection matrix filename based on optical source and DM/layer indices.

Parameters:
  • config_file (str or dict) – Path to YAML/PRO configuration file or config dictionary

  • opt_index (int, optional) – Index of the optical source to use (1-based)

  • dm_index (int, optional) – Index of the DM to use (1-based)

  • layer_index (int, optional) – Index of the layer to use (1-based)

  • timestamp (bool, optional) – Whether to include timestamp in the filename

  • verbose (bool, optional) – Whether to print verbose output

Returns:

Filename for the projection matrix with the specified parameters

Return type:

str

synim.params_utils.generate_pm_filenames(config_file, timestamp=False)

Generate projection matrix filenames for all optical source and DM combinations.

Parameters:
  • config_file (str or dict) – Path to YAML/PRO file or config dictionary

  • timestamp (bool, optional) – Whether to include timestamp in filenames

Returns:

List of projection matrix filenames

Return type:

list

synim.params_utils.get_tag_or_object(params, base_key, look_for_tag=False, full_config=None)

Looks for and returns the value associated with ‘{base_key}_tag’ or ‘{base_key}_object’ or ‘{base_key}_ref’ in params. Returns None if neither is present.

synim.params_utils.is_simple_config(config)

Detect if this is a simple SCAO config or a complex MCAO config.

Parameters:

config (dict) – Configuration dictionary

Returns:

True for simple SCAO config, False for complex MCAO config

Return type:

bool

synim.params_utils.load_filter_matrix(filename, verbose=False)

Load a filter matrix from FITS file.

Parameters:
  • filename (str or Path) – Path to FITS filtmat file

  • verbose (bool, optional) – Whether to print detailed information. Default: False

Returns:

(intmat_subset, recmat_subset)
  • intmat_subset: Interaction matrix [n_slopes, n_modes_filtered]

  • recmat_subset: Reconstruction matrix [n_modes_filtered, n_slopes]

Return type:

tuple

Example

>>> im_filt, rec_filt = load_filter_matrix('filtmat_lgs1.fits')
>>> print(f"Loaded filter: IM {im_filt.shape}, Rec {rec_filt.shape}")
synim.params_utils.load_influence_functions(cm, dm_params, pixel_pupil, verbose=False, is_inverse_basis=False, full_config=None)

Load or generate DM influence functions.

Parameters:
  • cm (CalibManager) – SPECULA calibration manager

  • dm_params (dict) – DM parameters

  • pixel_pupil (int) – Number of pixels across pupil

  • verbose (bool) – Whether to print details

  • is_inverse_basis (bool) – If True, don’t convert to 3D (for projection matrices)

  • full_config (dict) – Full configuration dictionary (optional)

Returns:

(dm_array, dm_mask) - For DM: 3D array, For inverse basis: 2D array

Return type:

tuple

synim.params_utils.load_pupilstop(cm, pupilstop_params, pixel_pupil, pixel_pitch, verbose=False)

Load or create a pupilstop.

NOTE: Returns numpy array from disk - caller should convert with to_xp if needed

synim.params_utils.parse_params_file(file_path)

Parse a parameters file (YAML or .pro) and return its contents as a dictionary.

Parameters:

file_path (str) – Path to the parameters file.

Returns:

Parsed data as a dictionary.

Return type:

dict

synim.params_utils.save_filter_matrix(intmat_subset, recmat_subset, output_filename, overwrite=False, verbose=False)

Save the filtering matrix (filtmat) in FITS format. Replicates the PASSATA/IDL format.

The filtmat is saved as a 3D FITS array with shape [2, n_slopes, n_modes]: - filtmat[0, :, :] = intmat_subset (interaction matrix for filtered modes) - filtmat[1, :, :] = recmat_subset.T (transposed reconstruction matrix)

Parameters:
  • intmat_subset (numpy.ndarray) – Interaction matrix [n_slopes, n_modes_filtered]

  • recmat_subset (numpy.ndarray) – Reconstruction matrix [n_modes_filtered, n_slopes]

  • output_filename (str or Path) – FITS output filename

  • overwrite (bool, optional) – Whether to overwrite existing file. Default: False

  • verbose (bool, optional) – Whether to print detailed information. Default: False

Example

>>> im_filt, rec_filt = generate_filter_matrix_from_intmat(...)
>>> save_filter_matrix(im_filt, rec_filt, 'filtmat_lgs1.fits', overwrite=True)
synim.params_utils.update_component_calibration_metadata(component_config=None, ifunc_tag=None, m2c_tag=None, meta_pupil_pixels=None, pixel_pitch=None, ifunc_nmodes_raw=None, m2c_nmodes=None)

Build and optionally persist generated calibration metadata.

synim.params_utils.validate_opt_sources(params, verbose=False)

Validate optical source configurations.

Parameters:
  • params (dict) – Configuration dictionary

  • verbose (bool) – Whether to print validation messages

Returns:

True if all sources are valid

Return type:

bool

Raises:

ValueError – If validation fails

synim.params_utils.wfs_fov_from_config(wfs_params)

Extract field of view value from WFS parameters.

Parameters:

wfs_params (dict) – Dictionary with WFS parameters

Returns:

Field of view in arcseconds

Return type:

float