# selfisys.utils package

## Submodules

## selfisys.utils.examples_utils module

selfisys.utils.examples_utils.clear_large_plot(fig)

  Clear a figure to free up memory.

  Parameters:

    fig (matplotlib.figure.Figure) – The figure to clear.

## selfisys.utils.logger module

class selfisys.utils.logger.CustomLogger(name, level=0)

  Bases: `Logger`

  Custom logger class supporting custom verbosity levels in diagnostic messages.

  diagnostic(msg, *args, verbosity=3, **kwargs) → None

    Log a message with DIAGNOSTIC level.

    Parameters:

      - msg (str) – The message to log.

      - verbosity (int, optional) – The verbosity level required to log this message.

class selfisys.utils.logger.CustomLoggerHandler(level=0)

  Bases: `Handler`

  Custom logging handler to redirect Python logger messages to custom print functions, with support for verbosity levels in debug messages.

  emit(record)

    Emit a log record.

selfisys.utils.logger.INDENT()

  Indents the current level of outputs.

selfisys.utils.logger.PrintDiagnostic(verbosity, message)

  Prints a diagnostic to screen.

  Parameters:

    - (int) (verbosity)

    - (string) (message)

selfisys.utils.logger.PrintError(message)

  Prints an error to screen.

  Parameters:

    (string) (message)

selfisys.utils.logger.PrintInfo(message)

  Prints an information to screen.

  Parameters:

    (string) (message)

selfisys.utils.logger.PrintLeftType(message_type, FONT_COLOR)

  Prints the type of output to screen.

  Parameters:

    - (string) (FONT_COLOR)

    - (string)

selfisys.utils.logger.PrintWarning(message)

  Prints a warning to screen.

  Parameters:

    (string) (message)

selfisys.utils.logger.UNINDENT()

  Unindents the current level of outputs.

selfisys.utils.logger.getCustomLogger(name: str) → CustomLogger

  Get as CustomLogger instance to use the custom printing routines.

  Parameters:

    name (str) – The name of the logger.

  Returns:

    logger – The custom logger instance.

  Return type:

    logging.Logger

## selfisys.utils.low_level module

selfisys.utils.low_level.stderr_redirector(stream)

  A context manager that redirects stderr to the given stream. For instance, this can be used to redirect C code stderr to None (to avoid cluttering the log, e.g., when using tqdm).

  Use with caution.

  Parameters:

    stream (file-like object) – The stream to which stdout should be redirected.

selfisys.utils.low_level.stdout_redirector(stream)

  A context manager that redirects stdout to the given stream. For instance, this can be used to redirect C code stdout to None (to avoid cluttering the log, e.g., when using tqdm).

  Parameters:

    stream (file-like object) – The stream to which stdout should be redirected.

  Example

      >>> with stdout_redirector(stream):
      >>>     print("Hello world!") # Will be printed to stream
      >>>                           # instead of stdout.

## selfisys.utils.parser module

selfisys.utils.parser.bool_sh(value)

  Convert a string to a boolean.

  Parameters:

    value (str) – String to convert.

  Returns:

    Converted value.

  Return type:

    bool

selfisys.utils.parser.check_files_exist(files)

  Check if all files in the list exist.

  Parameters:

    files (list of str) – List of file paths to check.

  Returns:

    True if all files exist, False otherwise.

  Return type:

    bool

selfisys.utils.parser.intNone(value)

  Convert a string to None or int.

  Parameters:

    value (str) – String to convert.

  Returns:

    Converted value.

  Return type:

    None or int

selfisys.utils.parser.joinstrs(list_of_strs)

  Join a list of strings into a single string.

  Parameters:

    list_of_strs (list of str) – List of strings to join.

  Returns:

    Concatenated string.

  Return type:

    str

selfisys.utils.parser.joinstrs_only(list_of_strs)

  Join a list of strings into a single string, ignoring all non-string elements such as None values.

  Parameters:

    list_of_strs (list of str) – List of strings to join.

  Returns:

    Concatenated string.

  Return type:

    str

selfisys.utils.parser.none_or_bool_or_str(value)

  Convert a string to None, bool, or str.

  Parameters:

    value (str) – String to convert.

  Returns:

    Converted value.

  Return type:

    None, bool, or str

selfisys.utils.parser.safe_npload(path)

  Load a numpy array from a file.

  Parameters:

    path (str) – Path to the file to load.

  Returns:

    Loaded array or None if the file does not exist.

  Return type:

    None or np.ndarray

## selfisys.utils.path_utils module

selfisys.utils.path_utils.file_names_evaluate(simdir: str, sd: str, d: int, i: int, sim_params: str, TimeSteps: list[int], prefix_mocks: str, abc: bool = False, gravity_on: bool = True) → dict

  Generate file paths for the given simulation id and parameters.

  Parameters:

    - simdir (str) – Path to the simulation directory.

    - sd (str) – Path to the simulation directory for the given direction.

    - d (int) – Direction index (-1 for mock data, 0 for the expansion point, or 1 to S).

    - i (int) – Simulation index.

    - sim_params (str) – Simulation parameters.

    - TimeSteps (list of int) – List of time steps.

    - prefix_mocks (str | None) – Prefix for mock data files. If None, defaults to “mocks”.

    - abc (bool, optional) – If True, appends the ABC index to the white noise path.

    - gravity_on (bool, optional) – Whether gravity is active. Default is True.

  Returns:

    Dictionary containing simulation inputs / outputs file paths.

  Return type:

    dict

selfisys.utils.path_utils.get_file_names(fsimdir: str, sim_id: int, sim_params: str, TimeSteps: list[int], prefix_mocks: str, gravity_on: bool = True, return_g: bool = False) → dict

  Generate file paths for a given simulation ID and parameters.

  Parameters:

    - fsimdir (str) – Path to the simulation directory.

    - sim_id (int) – Simulation ID.

    - sim_params (str) – Simulation parameters.

    - TimeSteps (list of int) – List of time steps.

    - prefix_mocks (str | None) – Prefix for mock data files. If None, defaults to “mocks”.

    - gravity_on (bool, optional) – Whether gravity is active. Default is True.

    - return_g (bool, optional) – If True, return the file name for the observed galaxy field. Default is False.

  Returns:

    Dictionary containing simulation inputs / outputs file paths.

  Return type:

    dict

## selfisys.utils.plot_examples module

selfisys.utils.plot_examples.plot_comoving_distance_redshift(zz, cosmo, means_com, L, Lcorner, wd, colours_list=['C4', 'C5', 'C6', 'C7'], display=True)

  Plot comoving distance as a function of redshift, highlighting key scales.

  Parameters:

    - zz (array-like) – Redshift range for the plot.

    - cosmo (astropy.cosmology object) – Cosmology instance for calculating comoving distances.

    - means_com (array-like) – Mean comoving distances of selection functions.

    - L (float) – Box side length in Gpc/h.

    - Lcorner (float) – Diagonal of the box (sqrt(3) * L) in Gpc/h.

    - wd (str) – Working directory for saving figures.

    - colours_list (list) – List of colours for selection function annotations.

    - display (bool, optional) – Whether to display the figure. Default is True.

selfisys.utils.plot_examples.plot_galaxy_field_slice(g, size, L, wd, id_obs, limits='minmax', display=True)

  Plot a 2D slice of the observed field.

  Parameters:

    - g (ndarray) – 2D array representing the observed field slice.

    - size (int) – Number of grid points along each axis.

    - L (float) – Size of the simulation box (in Mpc/h).

    - wd (str) – Working directory for saving output files.

    - id_obs (int or str) – Identifier for the observation, used in file naming.

    - limits (str, optional) – Colormap scaling method. Options: ‘minmax’, ‘truncate’, ‘max’.

    - display (bool, optional) – Whether to display the figure. Default is True.

selfisys.utils.plot_examples.plot_power_spectrum(G_sim, true_P, k_s, planck_Pk, Pbins, Pbins_bnd, size, L, wd, title=None, display=True)

  Plot a power spectrum over Fourier modes, its linear interpolation over specified support points, and a given binning for comparison.

  Parameters:

    - G_sim (pysbmy.power.FourierGrid) – Fourier grid object containing the k_modes attribute.

    - true_P (pysbmy.power.PowerSpectrum) – Power spectrum object containing the powerspectrum attribute.

    - k_s (array-like) – Support points in k-space.

    - planck_Pk (array-like) – Power spectrum values at the support points.

    - Pbins (array-like) – Centres of the Φ bins in k-space.

    - Pbins_bnd (array-like) – Boundaries of the Φ bins in k-space.

    - size (float) – Box size in number of grid cells.

    - L (float) – Box length in Mpc/h.

    - wd (str) – Working directory path for saving the figure.

    - title (str, optional) – Title for the figure. Default is None.

    - display (bool, optional) – Whether to display the figure. Default is True.

  Return type:

    None

selfisys.utils.plot_examples.plot_selection_functions_def_in_z(xx_of_zs, res, res_mis, z_means, cosmo, L, stds_z, wd, display=True)

  Plot radial lognormal (in redshift) selection functions against comoving distances.

  Parameters:

    - xx_of_zs (array-like) – Comoving distances mapped from redshift.

    - res (list of array-like) – Selection functions for the well-specified model.

    - res_mis (list of array-like) – Selection functions for the mis-specified model.

    - z_means (array-like) – Mean redshifts of every galaxy population.

    - cosmo (object) – Cosmology object.

    - L (float) – Box side length in comoving distance units.

    - stds_z (array-like) – Standard deviations of redshift distributions.

    - wd (str) – Working directory for saving figures.

    - display (bool, optional) – Whether to display the figure. Default is True.

  Return type:

    None

selfisys.utils.plot_examples.redshift_distance_conversion(zz, cosmo, means_com, L, Lcorner, xx, wd, colours_list=['C4', 'C5', 'C6', 'C7'], display=True)

  Plot the conversion between comoving distance and redshift; return the redshifts corresponding to the selection functions’ means.

  Parameters:

    - zz (array-like) – Redshift range for the plot.

    - cosmo (astropy.cosmology object) – Cosmology instance for calculating comoving distances.

    - means_com (array-like) – Mean comoving distances of selection functions.

    - L (float) – Box side length in Gpc/h.

    - Lcorner (float) – Diagonal of the box (sqrt(3) * L) in Gpc/h.

    - xx (array-like) – Comoving distances at which to compute redshift.

    - wd (str) – Working directory for saving figures.

    - colours_list (list) – List of colours for selection function annotations.

    - display (bool, optional) – Whether to display the figure. Default is True.

  Returns:

    spline – Linear interpolator to convert comoving distances to redshifts.

  Return type:

    scipy.interpolate.UnivariateSpline

selfisys.utils.plot_examples.relative_error_analysis(G_sim, true_P, k_s, planck_Pk, Pbins, Pbins_bnd, size, L, wd, display=True)

  Compute and plot the relative error between the interpolated and true power spectra.

  Parameters:

    - G_sim (pysbmy.power.FourierGrid) – Fourier grid object containing the k_modes attribute.

    - true_P (pysbmy.power.PowerSpectrum) – Power spectrum object containing the powerspectrum attribute.

    - k_s (array-like) – Support points in k-space.

    - planck_Pk (array-like) – Power spectrum values at the support points.

    - Pbins (array-like) – Centres of the Φ bins in k-space.

    - Pbins_bnd (array-like) – Boundaries of the Φ bins in k-space.

    - size (float) – Box size in number of grid cells.

    - L (float) – Box length in Mpc/h.

    - wd (str) – Working directory path for saving the figure.

    - display (bool, optional) – Whether to display the figure. Default is True.

  Return type:

    None

## selfisys.utils.plot_params module

class selfisys.utils.plot_params.ScalarFormatterForceFormat_11(useOffset=True, useMathText=True, useLocale=None)

  Bases: `object`

  Custom scalar formatter to enforce a specific number format with an offset.

  This formatter displays tick labels with one decimal place and includes the offset notation for powers of ten.

  get_offset()
  set_scientific(b)
  set_useOffset(b)

selfisys.utils.plot_params.create_all_colormaps()

  Create all custom colormaps.

  Returns:

    colormaps – Dictionary containing all custom colormaps.

  Return type:

    dict

selfisys.utils.plot_params.create_colormap(name)

  Create a custom colormap based on the specified name.

  Parameters:

    name (str) – The name of the colormap to create.

  Returns:

    The requested custom colormap.

  Return type:

    ListedColormap

  Raises:

    ValueError – If the specified colormap name is not recognised.

selfisys.utils.plot_params.dynamic_text_scaling(fig_height)

  Dynamically scale text sizes based on the vertical height of the figure.

  Parameters:

    fig_height (float) – Height of the figure in inches.

  Returns:

    Dictionary of scaled font sizes for consistent appearance.

  Return type:

    dict

selfisys.utils.plot_params.get_contours(Z, nBins, confLevels=(0.3173, 0.0455, 0.0027))

  Compute contour levels for given confidence levels.

  Parameters:

    - Z (ndarray) – 2D histogram or density estimate.

    - nBins (int) – Number of bins along one axis.

    - confLevels (tuple of float) – Confidence levels for which to compute contour levels.

  Returns:

    chainLevels – Contour levels corresponding to the provided confidence levels.

  Return type:

    ndarray

selfisys.utils.plot_params.reset_plotting()

selfisys.utils.plot_params.setup_plotting()

  Configure Matplotlib plotting settings for consistent appearance.

## selfisys.utils.plot_utils module

selfisys.utils.plot_utils.plot_C(C_0, X, Y, Pbins, CMap, binning=True, suptitle=None, savepath=None, force=False)

  Plot covariance matrix.

  Parameters:

    - C_0 (ndarray) – Covariance matrix.

    - X (ndarray) – X-axis grid for plotting.

    - Y (ndarray) – Y-axis grid for plotting.

    - Pbins (ndarray) – Vector of bin boundaries for the summary statistics.

    - CMap (str) – Colormap for the plot.

    - binning (bool, optional) – Whether to overlay bin lines on the plot. Default is True.

    - suptitle (str, optional) – Title for the plot. If None, a default title is used.

    - savepath (str or Path, optional) – Path to save the plot. If None, the plot is displayed.

    - force (bool, optional) – If True, displays the plot even if savepath is specified.

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plot_fisher(F0, params_names_fisher, title=None, path=None)

  Plot the Fisher matrix as a heatmap.

  Parameters:

    - F0 (ndarray) – Fisher matrix.

    - params_names_fisher (list of str) – Names for the axes.

    - title (str, optional) – Title of the plot. Default is “Fisher matrix”.

    - path (str or Path, optional) – Path to save the plot. If None, the plot is displayed.

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plot_gradients(Pbins, P, df_16_full, df_32_full, df_48_full, df_full, k_s, X, Y, fixscale=False, force=False, suptitle='', savepath=None)

  Plot gradients.

  Parameters:

    - Pbins (ndarray) – Vector of bin boundaries for the summary statistics.

    - P (int) – Number of bins.

    - df_16_full (ndarray) – Derivative with respect to the 16th input.

    - df_32_full (ndarray) – Derivative with respect to the 32nd input.

    - df_48_full (ndarray) – Derivative with respect to the 48th input.

    - df_full (ndarray) – Full derivative.

    - k_s (ndarray) – Wavenumbers.

    - X (ndarray) – X-axis grid.

    - Y (ndarray) – Y-axis grid.

    - fixscale (bool, optional) – Fix the y-axis scale. Default is False.

    - force (bool, optional) – Display plot even if savepath is set.

    - suptitle (str, optional) – Title for the plot.

    - savepath (str or Path, optional) – Path to save the plot. If None, the plot is displayed.

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plot_histogram(data, recmahal, suptitle, savepath, bins=30, alpha=0.5, color='blue')

  Plot a Mahalanobis distance histogram with key reference lines.

  Parameters:

    - data (array-like) – Collection of Mahalanobis distances.

    - recmahal (float) – Single Mahalanobis distance for the reconstruction (e.g. posterior vs. prior mean).

    - suptitle (str) – Figure title.

    - savepath (str) – Full path (including filename) to save the resulting plot.

    - bins (int, optional) – Number of bins for the histogram. Default is 30.

    - alpha (float, optional) – Transparency level for the histogram bars. Default is 0.5.

    - color (str, optional) – Colour of the histogram bars. Default is “blue”.

  Raises:

    - OSError – If the file cannot be saved to the specified path.

    - RuntimeError – For unexpected plotting failures.

selfisys.utils.plot_utils.plot_mocks(NORM, N, P, Pbins, phi_obs, Phi_0, f_0, C_0, X, Y, CMap, suptitle=None, force_plot=False, savepath=None)

  Plot mocks.

  Parameters:

    - NORM (float) – Normalisation factor.

    - N (int) – Number of mocks.

    - P (int) – Number of bins.

    - Pbins (ndarray) – Vector of bin boundaries for the summary statistics.

    - phi_obs (ndarray) – Observed power spectrum.

    - Phi_0 (ndarray) – Mock power spectra.

    - f_0 (ndarray) – Averaged power spectrum.

    - C_0 (ndarray) – Covariance matrix.

    - X (ndarray) – X-axis grid.

    - Y (ndarray) – Y-axis grid.

    - CMap (str) – Colormap.

    - suptitle (str, optional) – Title for the plot.

    - force_plot (bool, optional) – Display plot even if savepath is set.

    - savepath (str or Path, optional) – Path to save the plot. If None, the plot is displayed.

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plot_mocks_compact(NORM, N, P, Pbins, phi_obs, Phi_0, f_0, C_0, suptitle=None, force_plot=False, savepath=None)

  Plot and compare observed and simulated power spectra.

  Parameters:

    - NORM (float) – Normalisation factor for the observed spectra.

    - N (int) – Number of mock data realisations.

    - P (int) – Number of bins for the summaries.

    - Pbins (ndarray) – Vector of bin boundaries for the summary statistics.

    - phi_obs (ndarray) – Observed power spectrum.

    - Phi_0 (ndarray) – Mock realisations of the power spectrum.

    - f_0 (ndarray) – Mean power spectrum.

    - C_0 (ndarray) – Covariance matrix of the mock summaries.

    - suptitle (str, optional) – Title for the plot.

    - force_plot (bool, optional) – If True, displays the plot even if a path is specified.

    - savepath (str or Path, optional) – Path to save the plot.

  Raises:

    RuntimeError – If an unexpected error occurs during plotting.

selfisys.utils.plot_utils.plot_observations(k_s, theta_gt, planck_Pk_EH, P_0, Pbins, phi_obs, Npop, path=None, force_plot=False)

  Plot the observed power spectra and related quantities.

  Parameters:

    - k_s (ndarray) – Array of wavenumbers.

    - theta_gt (ndarray) – Ground truth theta values.

    - planck_Pk_EH (ndarray) – Planck power spectrum values.

    - P_0 (float) – Normalisation constant for power spectra.

    - Pbins (ndarray) – Vector of bin boundaries for the summary statistics.

    - phi_obs (ndarray) – Observed summaries.

    - Npop (int) – Number of populations.

    - path (str, optional) – Path to save the output plot.

    - force_plot (bool, optional) – If True, displays the plot even if a path is specified.

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plot_prior_and_posterior_covariances(X, Y, k_s, prior_theta_covariance, prior_covariance, posterior_theta_covariance, P_0, force_plot=False, suptitle='', savepath=None)

  Plot prior and posterior covariance matrices.

  Parameters:

    - X (ndarray) – X-axis grid.

    - Y (ndarray) – Y-axis grid.

    - k_s (ndarray) – Wavenumbers.

    - prior_theta_covariance (ndarray) – Prior covariance matrix for normalised spectra.

    - prior_covariance (ndarray) – Prior covariance matrix for unnormalised spectra.

    - posterior_theta_covariance (ndarray) – Posterior covariance matrix for normalised spectra.

    - P_0 (ndarray) – Fiducial power spectrum used for normalisation.

    - force_plot (bool, optional) – Display plot even if savepath is set.

    - suptitle (str, optional) – Title for the plot.

    - savepath (str or Path, optional) – Path to save the plot. If None, the plot is displayed.

    - verbose (int, optional) – Verbosity level (0=silent, 1=default, 2=detailed).

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plot_reconstruction(k_s, Pbins, prior_theta_mean, prior_theta_covariance, posterior_theta_mean, posterior_theta_covariance, theta_gt, P_0, phi_obs=None, suptitle=None, theta_fid=None, savepath=None, force_plot=False, legend_loc='upper right', enforce_ylims=True)

  Plot the prior, posterior and ground truth power spectra.

  Parameters:

    - k_s (ndarray) – Array of wavenumbers.

    - Pbins (ndarray) – Vector of bin boundaries for the summary statistics.

    - prior_theta_mean (ndarray) – Mean of the prior distribution.

    - prior_theta_covariance (ndarray) – Covariance of the prior distribution.

    - posterior_theta_mean (ndarray) – Mean of the posterior distribution.

    - posterior_theta_covariance (ndarray) – Covariance of the posterior distribution.

    - theta_gt (ndarray) – Ground truth power spectrum.

    - P_0 (float) – Normalisation constant for the power spectrum.

    - phi_obs (ndarray, optional) – Observed summaries.

    - suptitle (str, optional) – Plot title. Leave empty for no title.

    - theta_fid (ndarray, optional) – Fiducial theta for hyperparameter tuning (for some priors).

    - savepath (str or Path, optional) – Path to save the plot.

    - force_plot (bool, optional) – If True, displays the plot even if a path is specified.

    - legend_loc (str, optional) – Location of the plot legend.

    - enforce_ylims (bool, optional) – Enforce y-axis limits.

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plot_selection_functions(x, res, res_mis, params, L, corner, axis='com', zz=None, zcorner=None, z_L=None, path=None, force_plot=False, labsAB=True)

  Plot selection functions.

  Parameters:

    - x (array-like) – x-axis values (e.g., comoving distances or redshifts).

    - res (list of array-like) – Selection functions for Model A.

    - res_mis (list of array-like, optional) – Selection functions for Model B (optional).

    - params (tuple of (array-like, array-like, array-like), optional) – Standard deviations, means, and normalisation factors for the multiple galaxy populations.

    - L (float) – Box size.

    - corner (float) – Diagonal box size.

    - axis (str, optional) – x-axis type (‘com’ for comoving distance, ‘redshift’ for redshift).

    - zz (array-like, optional) – Mapping between comoving distances and redshifts.

    - zcorner (float, optional) – Redshift corresponding to the diagonal box size.

    - z_L (float, optional) – Redshift corresponding to the box side length.

    - path (str, optional) – Path to save the output plot.

    - force_plot (bool, optional) – If True, displays the plot even if a path is specified.

    - labsAB (bool, optional) – If True, labels models as ‘Model A’ and ‘Model B’.

  Raises:

    RuntimeError – If unexpected errors occur during plotting.

selfisys.utils.plot_utils.plotly_3d(field, size=128, L=None, colormap='RdYlBu', limits='max')

  Create an interactive 3D plot of volume slices using Plotly.

  Parameters:

    - field (array-like) – 3D data field to visualise.

    - size (int, optional) – Size of the field along one dimension. Default is 128.

    - L (float, optional) – Physical size of the field in Mpc/h. Used for axis labels only.

    - colormap (str, optional) – Colour map for visualisation. Default is ‘RdYlBu’.

    - limits (str, optional) – Colour scale limits (‘max’, ‘truncate’, or ‘default’). Default is ‘max’.

  Returns:

    Plotly figure object.

  Return type:

    go.Figure

## selfisys.utils.timestepping module

selfisys.utils.timestepping.merge_nTS(ts_path_list, merged_path)

  Merge multiple time-stepping objects into a single file.

  Parameters:

    - ts_path_list (list of str) – Paths to the individual time-stepping files to be merged.

    - merged_path (str) – Path to save the merged time-stepping file.

  Return type:

    None

## selfisys.utils.tools module

selfisys.utils.tools.cosmo_vector_to_Simbelmyne_dict(x, kmax=1.4)

  Convert a vector of cosmological parameters into a dictionary compatible with pysbmy.

  Parameters:

    - x (array-like) – Vector of cosmological parameters.

    - kmax (float, optional) – Maximum wavenumber for the power spectrum computation.

  Returns:

    Dictionary of cosmological parameters compatible with pysbmy.

  Return type:

    dict

selfisys.utils.tools.cosmo_vector_to_class_dict(x, lmax=2500, kmax=1.4)

  Convert a vector of cosmological parameters into a dictionary compatible with classy.

  Parameters:

    - x (array-like) – Vector of cosmological parameters.

    - lmax (int, optional) – Maximum multipole for the power spectrum computation.

    - kmax (float, optional) – Maximum wavenumber for the power spectrum computation.

  Returns:

    Dictionary of cosmological parameters compatible with classy.

  Return type:

    dict

selfisys.utils.tools.custom_stat(vec)

  Compute a custom statistic for use with scipy.stats.binned_statistic.

  Assumes the data power spectrum is inverse-Gamma distributed (as in [jasche2010bayesian] and [leclercq2019primordial]). Returns “NaN” for vectors with insufficient elements, as expected by scipy.stats.binned_statistic.

  Parameters:

    vec (array-like) – Input vector for computation.

  Returns:

    Custom statistic or NaN if input is invalid.

  Return type:

    float or str

selfisys.utils.tools.fisher_rao(Com, Com_obs, F0)

  Compute the Fisher-Rao distance between two summaries.

  Parameters:

    - Com (array-like) – Computed summary.

    - Com_obs (array-like) – Observed summary.

    - F0 (array-like) – Fisher information matrix.

  Returns:

    Fisher-Rao distance.

  Return type:

    float

selfisys.utils.tools.get_k_max(L, size)

  Compute the maximum wavenumber for a given box size.

  Parameters:

    - L (float) – Size of the box in Mpc/h.

    - size (int) – Number of grid cells along each dimension.

  Returns:

    Maximum wavenumber in h/Mpc.

  Return type:

    float

selfisys.utils.tools.get_summary(params_vals, params_ids, Omegas_fixed, bins, normalisation=None, kmax=1.4)

  Compute the normalised power spectrum summary for a given parameter set.

  Parameters:

    - params_vals (array-like) – Parameter values to update.

    - params_ids (array-like) – Indices of the parameters to update.

    - Omegas_fixed (array-like) – Fixed base values of parameters.

    - bins (array-like) – Power spectrum bins.

    - normalisation (float, optional) – Normalisation factor for the summary.

    - kmax (float, optional) – Maximum wavenumber for power spectrum computation.

  Returns:

    Normalised power spectrum summary.

  Return type:

    array

selfisys.utils.tools.none_or_bool_or_str(value)

  Convert string representations of None, True, and False to their respective Python objects; otherwise, return the input value.

selfisys.utils.tools.params_ids_to_Simbelmyne_dict(params_vals, params_ids, fixed, kmax)

  Convert a list of cosmological parameters into a dictionary compatible with pysbmy.

  Fixed parameters remain unchanged unless overridden by params_vals.

  Parameters:

    - params_vals (array-like) – Values of the parameters to be modified.

    - params_ids (array-like) – Indices of the parameters to be modified.

    - fixed (array-like) – Base values of the parameters.

    - kmax (float) – Maximum wavenumber for the power spectrum computation.

  Returns:

    Dictionary of cosmological parameters compatible with pysbmy.

  Return type:

    dict

selfisys.utils.tools.sample_omega_from_prior(nsample, omega_mean, omega_cov, params_ids, seed=None)

  Sample cosmological parameters from a prior distribution.

  Ensures physical validity by clipping values to [eps, 1-eps].

  Parameters:

    - nsample (int) – Number of samples to draw.

    - omega_mean (array-like) – Prior mean vector.

    - omega_cov (array-like) – Prior covariance matrix.

    - params_ids (array-like) – Indices of the parameters to sample.

    - seed (int, optional) – Seed for the random number generator.

  Returns:

    Sampled cosmological parameters.

  Return type:

    array

selfisys.utils.tools.summary_to_score(params_ids, omega0, F0, F0_inv, f0, dw_f0, C0_inv, phi)

  Compute the Fisher score.

  Parameters:

    - params_ids (array-like) – Indices of the parameters.

    - omega0 (array-like) – Cosmological parameters at the expansion point.

    - F0 (array-like) – Fisher information matrix.

    - F0_inv (array-like) – Inverse Fisher information matrix.

    - f0 (array-like) – Mean model at the expansion point.

    - dw_f0 (array-like) – Derivative of the mean model.

    - C0_inv (array-like) – Inverse covariance matrix.

    - phi (array-like) – Observed summary.

  Returns:

    Fisher score.

  Return type:

    array

## selfisys.utils.workers module

selfisys.utils.workers.Simbelmyne_worker(args) → Tuple[float, Any]

  Worker function used for implicit likelihood inference of cosmological parameters.

  Parameters:

    args (tuple) – A tuple of arguments to be unpacked for the worker routine: (index, param_val, param_id, fsimdir, k_s, Pbins_bnd, selection_params, norm_csts, P_ss_obj_path, obs_density, lin_bias, noise, survey_mask_path, G_sim_path, G_ss_path, Np0, Npm0, seedphase_init, seednoise_init, size, L, radial_selection, sim_params, wd, batch_idx, dbg, modeldir, local_mask_prefix, TimeStepDistribution, indices_steps_cumul, eff_redshifts, poolname_abc, setup_only, prefix_mocks).

  Returns:

    (param_val, Phi) where param_val is the parameter value used, and Phi is the resulting summary from evaluating the model.

  Return type:

    tuple

  Raises:

    - OSError – If file I/O (reading or writing mock data) fails.

    - RuntimeError – For unexpected errors in the worker routine.

selfisys.utils.workers.evaluate_gradient_of_Symbelmyne(omega, param_index: int, k_s, coeffs: List[float] = [0.6666666666666666, -0.08333333333333333], deltas_x: List[float] = [0.01, 0.02], delta: float = 0.01, kmax: float = 1.4)

  Estimate the gradient of CLASS with respect to the cosmological parameters using central finite differences of arbitrary order.

  Parameters:

    - omega (ndarray) – Base cosmological parameter vector.

    - param_index (int) – Index of the parameter to differentiate against.

    - k_s (ndarray) – Wavenumbers for the power spectrum.

    - coeffs (list of float, optional) – Coefficients for the finite-difference scheme, typically [2/3, -1/12] etc. Default is [2/3.0, -1/12.0].

    - deltas_x (list of float, optional) – Step sizes. The corresponding negative steps are generated automatically. Default is [0.01, 0.02].

    - delta (float, optional) – Scale for the finite difference in the denominator. Default is 1e-2.

    - kmax (float, optional) – Maximum wavenumber for the power spectrum. Default is 1.4.

  Returns:

    The gradient of the power spectrum wrt the specified parameter.

  Return type:

    ndarray

  Raises:

    RuntimeError – If the gradient evaluation fails.

selfisys.utils.workers.worker_gradient_Symbelmyne(coeff: float, delta_x: float, omega, param_index: int, k_s, delta: float, kmax: float)

  Worker function for evaluating the gradient of the power spectrum using finite differences.

  Parameters:

    - coeff (float) – Coefficient for the finite difference.

    - delta_x (float) – Step size in the parameter space.

    - omega (ndarray) – Base cosmological parameter vector.

    - param_index (int) – Index of the parameter being varied.

    - k_s (ndarray) – Array of wavenumbers.

    - delta (float) – Denominator for finite differences (scaled).

    - kmax (float) – Maximum wavenumber for power spectrum.

  Returns:

    The gradient of the power spectrum wrt the specified parameter.

  Return type:

    ndarray

  Raises:

    RuntimeError – If the gradient evaluation fails.

## Module contents