GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions module

General utility functions for GUIBRUSHR atmospheric retrieval analysis.

This module contains a comprehensive collection of utility functions used throughout the GUIBRUSHR application for various tasks including:

  • Molecular data processing and opacity calculations

  • Spectroscopic data analysis and convolution operations

  • FITS file I/O operations

  • Cross-correlation analysis

  • Principal Component Analysis (PCA) for systematic noise removal

  • Temperature profile calculations

  • Plotting and visualization utilities

  • Mathematical operations for atmospheric modeling

The functions in this module support both high-resolution and low-resolution spectroscopic data processing, and are designed to work with the petitRADTRANS and PyratBay radiative transfer codes.

Dependencies:
  • numpy: Numerical computations

  • astropy: FITS file handling

  • matplotlib: Plotting

  • pandas: Data structure handling

  • scipy: Scientific computing

  • sklearn: Machine learning algorithms (PCA)

  • petitRADTRANS: Radiative transfer calculations

  • pyratbay: Alternative radiative transfer code

  • chemcat: Chemical abundance calculations

Author: GUIBRUSHR Development Team

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.make_smooth_mono_cmap(color: str, name: str = 'custom') LinearSegmentedColormap[source]

Create a smooth monochromatic colormap with 5 control points.

The colormap transitions from black through dark shade, saturated color, light shade, to white, creating a smooth gradient suitable for visualization.

Parameters:
  • color (str) – Hex color code or named color for the saturated color point

  • name (str, optional) – Name for the colormap. Defaults to ‘custom’.

Returns:

Matplotlib colormap object with 256 color levels

Return type:

LinearSegmentedColormap

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.make_pyratbay_config(output_folder: str, target: Any, pressure: Any, species: Any, wavelength: Any, resolution: Any, params) str[source]

Create a pyratbay configuration file based on guibrush configuration.

Parameters:
  • output_folder (str) – Folder where to store the outputs.

  • target – Target object containing stellar and planetary parameters.

  • pressure – Pressure configuration object.

  • species – Species configuration object.

  • wavelength – Wavelength configuration object.

  • resolution – Resolution configuration object.

  • params – List of input parameters.

Returns:

Path to the created configuration file.

Return type:

str

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.create_fits(data: ndarray, pathf: str | Path) None[source]

Create and save a FITS file from the provided data.

This function creates a primary HDU (Header/Data Unit) using the input data, encapsulates it in an HDUList, and writes the FITS file to the specified path. If a file with the same name exists, it will be overwritten.

Parameters:
  • data (np.ndarray) – The data array to be stored in the FITS file.

  • pathf (Union[str, Path]) – The destination file path for the FITS file.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.kernel_solid_body_rotation(omegad: float, f_rot_arr: ndarray, Teq: float, mu: float, gs: float, Rpj: float, rad_mode: str, index_nights_total: int, rv_sampling: float = 0.1) ndarray[source]

Compute a rotational broadening kernel for spectroscopic observations.

A planet rotating as a rigid body with angular frequency omega broadens spectral lines because different surface elements of the visible disk move at different line-of-sight velocities: an element at projected distance x from the rotation axis contributes flux at a radial velocity offset v = omega * x. The rotational kernel K(v) is the disk-integrated weight of all surface elements emitting at velocity v, and convolving a model spectrum with K(v) reproduces the line broadening induced by planetary rotation. The overall width of the kernel is set by the equatorial rotational velocity v_eq = omega * Rp.

The rotation rate omega is a free parameter of the retrieval and is not constrained to any particular value. For a tidally locked planet it equals 2*pi / P_orb, but the kernel is valid for any rotation rate.

The kernel geometry differs between emission and transmission spectroscopy:

  • In emission spectroscopy, only the planetary disk itself contributes. Each surface strip at projected distance x has a chord length 2*sqrt(Rp^2 - x^2), so K(v) is proportional to sqrt(1 - (v/v_eq)^2) for |v| < v_eq, and zero outside. This is the classical solid-body rotational kernel for a uniformly emitting disk: it peaks at v=0 (sub-observer point, longest chord) and drops to zero at v=±v_eq (planetary limb, chord=0).

  • In transmission spectroscopy, the relevant region is the atmospheric annulus between Rp and Rp + z, where z = 5*H is the effective atmospheric thickness and H = k_B * T_eq / (mu * m_H * g) is the scale height. Defining v_eq_atm = omega * (Rp + z), two velocity regions contribute differently:

    • v_eq <= |v| < v_eq_atm (annulus only): the line of sight passes only through the annulus, with weight sqrt((Rp+z)^2 - (v/omega)^2) / z.

    • |v| < v_eq (annulus above opaque disk): the line of sight passes through the full annulus minus the opaque planetary disk, with weight (sqrt((Rp+z)^2 - (v/omega)^2) - sqrt(Rp^2 - (v/omega)^2)) / z.

    An asymmetry parameter f_rot (stored as log10 in f_rot_arr) is applied to the receding hemisphere (v > 0) to allow for day/night asymmetries in the transmission signal. It is a free parameter of the retrieval.

In both modes the kernel is normalized to unit sum before being returned, so that convolution preserves the total flux of the spectrum.

Parameters:
  • omegad (float) – Rotational angular frequency of the planet, in inverse days (d^-1). The equatorial rotational velocity is v_eq = omega * Rp, where omega is omegad converted to s^-1. This is a free parameter of the retrieval and is not assumed to equal any particular value.

  • f_rot_arr (np.ndarray) – Array of base-10 logarithms of the rotational asymmetry scaling factors, one per observing night. Used only in transmission mode: f_rot = 10^f_rot_arr[index_nights_total] is multiplied onto the kernel for v > 0 to model day/night hemisphere asymmetries. It is a free parameter of the retrieval.

  • Teq (float) – Equilibrium temperature of the planet, in Kelvin. Used to compute the atmospheric scale height H = k_B * T_eq / (mu * m_H * g), which defines the vertical extent z = 5*H of the transmission annulus. Only used in transmission mode.

  • mu (float) – Mean molecular weight of the atmosphere, in units of the hydrogen mass m_H. Used to compute the scale height. Only used in transmission mode.

  • gs (float) – Surface gravity of the planet, in cgs units (cm s^-2). Used to compute the scale height. Only used in transmission mode.

  • Rpj (float) – Planetary radius, in centimeters. Defines v_eq = omega * Rp (emission) and the inner boundary of the transmission annulus (transmission).

  • rad_mode (str) – Observing mode. Must be one of ConstantVariables.LIST_RAD_MODE: - LIST_RAD_MODE[0]: transmission spectroscopy (annulus kernel). - any other value: emission spectroscopy (solid disk kernel).

  • index_nights_total (int) – Index into f_rot_arr selecting the asymmetry factor for the current observing night. Only used in transmission mode.

  • rv_sampling (float, optional) – Velocity step of the radial velocity grid on which the kernel is computed, in km/s. Default is 0.1 km/s, fine enough to well-sample the kernel profile for any realistic v_eq.

Returns:

Normalized rotational broadening kernel, sampled on a velocity grid spanning -30 to +30 km/s with step rv_sampling. The kernel sums to unity by construction.

Return type:

np.ndarray

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.convolve_solid_body_rotation(wl: ndarray, model: ndarray, ker_rot: ndarray, rv_sampling: float = 0.1, n_el: int = 321) Tuple[ndarray, ndarray][source]

Convolve a model spectrum with a rotational broadening kernel.

This function is the second convolution step in the model preparation pipeline, applied after convolve_resolution. It takes the rotational kernel produced by kernel_solid_body_rotation (defined on a fine velocity grid with step rv_sampling) and convolves it with the model spectrum.

The procedure mirrors that of convolve_resolution:

  1. The pixel velocity step of the model wavelength grid is computed as dv = c * dlambda / lambda, constant by construction for a log-uniform grid (constant resolving power R_model).

  2. The kernel is resampled from its fine velocity grid (step rv_sampling, default 0.1 km/s) onto a coarser grid whose spacing matches the model pixel velocity step, using spline interpolation. This step is mandatory because discrete convolution requires kernel and signal to share the same grid spacing.

  3. The resampled kernel is convolved with the model in ‘valid’ mode (scipy.signal.convolve), discarding the n_el//2 edge pixels on each side where the kernel does not fully overlap the signal, and the result is normalized by the kernel sum to ensure flux conservation.

Note: unlike convolve_resolution, this function does not apply a radial velocity shift. The shift is handled entirely by convolve_resolution via kernel translation. This function is responsible only for the rotational line broadening.

Parameters:
  • wl (np.ndarray) – 1D array of wavelength values for the model spectrum. Must be log-uniform (constant resolving power R_model), so that the pixel velocity step dv = c / R_model is constant across the grid.

  • model (np.ndarray) – 1D array of spectral flux values corresponding to wl. This is the spectrum already convolved with the instrumental LSF by convolve_resolution.

  • ker_rot (np.ndarray) – Rotational broadening kernel computed by kernel_solid_body_rotation, sampled on a velocity grid from -30 to +30 km/s with step rv_sampling. Must be normalized to unit sum.

  • rv_sampling (float, optional) – Velocity step of the input kernel grid, in km/s. Must match the rv_sampling used in kernel_solid_body_rotation. Default is 0.1 km/s.

  • n_el (int, optional) – Number of elements in the resampled kernel. Must be odd to ensure symmetry around zero and avoid introducing a spurious velocity shift. The half-extent of the resampled grid is (n_el - 1) / 2 pixels. Default is 321, giving a half-extent of 160 pixels.

Returns:

  • wavelength (np.ndarray) – Wavelength array of the convolved spectrum, shorter than the input by n_el // 2 = 160 points on each side due to ‘valid’ mode convolution.

  • rconv (np.ndarray) – Rotationally broadened flux array, flux-conserving by construction.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.convolve_resolution(wavelength_model: ndarray, flux_model: ndarray, lsf_hwhm: float, radial_velocity_shift: float, lsf_grid_step: float = 0.1, kernel_size: int = 321) Tuple[ndarray, ndarray][source]

Degrade a high-resolution model spectrum to instrumental resolution and apply a Doppler shift.

A real spectrograph cannot reproduce an infinitely narrow spectral line: even a perfectly monochromatic source produces a broadened profile on the detector, due to diffraction, optical aberrations, slit width, and pixel sampling. This broadening is described by the Line Spread Function (LSF). To compare a synthetic model with observed data, the model must be degraded to the same instrumental resolution, i.e. convolved with the LSF.

The LSF is approximated as a Gaussian whose width is expressed in velocity units. Working in velocity space is convenient because the LSF width is approximately constant in velocity across the full spectral range, whereas in wavelength units it varies with lambda. The Half Width at Half Maximum is HWHM = c / (2R), where R is the nominal resolving power of the instrument, and the corresponding Gaussian standard deviation is sigma = HWHM / sqrt(2*ln(2)). The factor sqrt(2*ln(2)) ~ 1.177 comes from setting the Gaussian equal to half its peak value and solving for v: G(v_1/2) = exp(-v_1/2^2 / 2*sigma^2) = 1/2 gives v_1/2 = sigma * sqrt(2*ln(2)), which is by definition the HWHM.

The Doppler shift of the planet is applied by translating the kernel by +v_rad rather than shifting the spectrum itself. By the translation property of convolution these two operations are mathematically equivalent, but acting on the smooth 321-point kernel avoids interpolating the full model flux array, concentrating any numerical error on the kernel alone.

Parameters:
  • wavelength_model (np.ndarray) – 1D array of wavelength values for the model spectrum. Must be computed at constant resolving power R_model, so that the ratio dlambda/lambda = 1/R_model is constant by construction (log-uniform grid), yielding a constant velocity step dv = c / R_model per pixel.

  • flux_model (np.ndarray) – 1D array of flux values corresponding to wavelength_model.

  • lsf_hwhm (float) – Half Width at Half Maximum of the instrumental LSF, in km/s. Related to spectral resolution by: HWHM = c / (2R). Example: IGRINS (R ~ 45000) has HWHM ~ 3.3 km/s.

  • radial_velocity_shift (float) – Radial velocity shift to apply to the model, in km/s. Positive values correspond to redshift (planet receding), negative to blueshift. This is typically a free parameter of the MCMC retrieval, representing the velocity offset between model and observed data.

  • lsf_grid_step (float, optional) – Velocity step for the initial fine LSF kernel grid, in km/s. Must be small enough to well-sample the Gaussian peak. Default is 0.1 km/s.

  • kernel_size (int, optional) – Number of elements in the resampled convolution kernel. Must be odd to ensure the grid is symmetric around zero, which avoids introducing a spurious velocity shift during convolution. The half-extent of the resampled grid is (kernel_size - 1) / 2 pixels. Default is 321, giving a half-extent of 160 pixels.

Returns:

  • wavelength_out (np.ndarray) – Wavelength array of the convolved spectrum. Shorter than the input by kernel_size // 2 = 160 points on each side, because scipy.signal.convolve in ‘valid’ mode discards the edge pixels where the kernel does not fully overlap the signal (see Step 5).

  • flux_convolved (np.ndarray) – Convolved and velocity-shifted flux array, flux-conserving by construction.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.create_path_night(pathfolder: str | Path, target: str, rad_mode: str, instrument: str) str[source]

Construct and return the file path for a specific night’s observation data.

The path is built by concatenating the following components:
  • pathfolder: The base directory containing observation data.

  • target: The target object or observation name.

  • A constant subdirectory defined by ConstantVariables.HR_INSTRUMENTS, representing high-resolution instruments.

  • rad_mode: The radiative mode, which specifies the type of observation.

    This can be either ‘emission’ or ‘transmission’.

  • instrument: The instrument identifier.

Parameters:
  • pathfolder (Union[str, Path]) – The base directory path.

  • target (str) – The target object or observation name.

  • rad_mode (str) – The radiative mode; valid options are ‘emission’ or ‘transmission’.

  • instrument (str) – The instrument identifier.

Returns:

The fully constructed file path as a string.

Return type:

str

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.get_csv_value(df: DataFrame, search_value: Any, search_column: str = 'Variable', target_column: str = 'Value') Any | None[source]

Retrieve a value from a DataFrame based on a search condition.

This function searches for rows in the provided DataFrame where the value in search_column matches search_value. If a matching row is found, the function returns the value in the corresponding target_column from the first match. If no match is found, the function returns None.

Parameters:
  • df (pd.DataFrame) – The DataFrame to search.

  • search_value (Any) – The value to look for in the search_column.

  • search_column (str, optional) – The column name to search within. Defaults to “Variable”.

  • target_column (str, optional) – The column name from which to retrieve the value. Defaults to “Value”.

Returns:

The value from the target_column of the first matching row,

or None if no match is found.

Return type:

Optional[Any]

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.plot_tp_profile(range_min_pressures: float, range_max_pressures: float, n_layers: int, parameters_tp_profile: Any, gravity: float, format_temperature: str, path_imm: str | Path, err: Any, rng: Any) None[source]

Plot the pressure-temperature (PT) profile for an atmosphere and save the figure.

Parameters:
  • range_min_pressures (float) – Log10 of the minimum pressure (bar).

  • range_max_pressures (float) – Log10 of the maximum pressure (bar).

  • n_layers (int) – Number of pressure layers.

  • parameters_tp_profile (Any) – Parameters for the temperature profile.

  • gravity (float) – Surface gravity.

  • format_temperature (str) – Name of the temperature profile method to use.

  • path_imm (Union[str, Path]) – Path to save the output image.

  • err (Any) – Error parameter for the temperature profile.

  • rng (Any) – Random number generator or seed for the temperature profile.

Returns:

None

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.plot_corner_metallicity(array_molecules, names_molecules_corner, folder_retrieval, filename, title_figure)[source]

Generate and save a corner plot for molecular abundance posteriors.

Parameters:
  • array_molecules (np.ndarray) – 2D array of posterior samples (n_samples x n_params).

  • names_molecules_corner (list) – Labels for each parameter axis.

  • folder_retrieval (str) – Path to the retrieval output folder.

  • filename (str) – Base filename for the saved plot.

  • title_figure (str) – Title displayed on the plot window.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.opacities_contribution_plot(path_results: str | Path, opacities_contribution: Dict[str, Any], resolution: str, function: str = 'plot', wl_scale: str = 'log', invert_y_axis: int = 0, instruments_LR=None, offsetLR_arr=None, rp=None, rs=None, rad_mode: str = 'Transmission') None[source]

Plot and save the contribution of different opacity sources to the atmospheric model.

This function creates a visualization showing how different opacity sources (line species, gas continua, clouds, etc.) contribute to the total atmospheric opacity. The plot is saved as a high-resolution image in the specified output directory.

Parameters:
  • path_results (Union[str, Path]) – Directory path where the output plot will be saved.

  • opacities_contribution (Dict[str, Any]) – Dictionary containing opacity contributions from different sources. Keys are source types (e.g., ‘line_species’, ‘cloud_species’), values are dictionaries mapping species names to their contribution data.

  • resolution (str) – Resolution identifier used in the plot title and filename.

  • function (str, optional) – Plotting function to use (‘plot’, ‘scatter’, etc.). Defaults to “plot”.

  • wl_scale (str, optional) – Scale for the wavelength axis (‘log’ or ‘linear’). Defaults to “log”.

  • invert_y_axis (int, optional) – Whether to invert the y-axis. Defaults to False.

  • instruments_LR – Dictionary containing the instruments and their LR values.

  • offsetLR_arr – Array containing the offset LR values.

  • rp – Radius of the planet.

  • rs – Radius of the star.

  • rad_mode – Radiative mode.

Returns:

None

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.calculate_mass_molecule(elements, periodic_table)[source]

Calculate the total molecular mass of a molecule from its elemental composition.

This function parses element strings that may contain mass numbers, atom counts, and ionization states, then calculates the total molecular mass using atomic masses from the periodic table.

Parameters:
  • elements – List of element strings with format like ‘H2’, ‘16O’, ‘C1+’, etc.

  • periodic_table – DataFrame containing periodic table data with columns ‘Symbol’, ‘NumberofProtons’, ‘NumberofNeutrons’

Returns:

Total molecular mass in atomic mass units (u)

Return type:

float

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.get_condensed_line_list()[source]

Retrieve condensed molecule information from petitRADTRANS opacity data.

This function scans the condensed molecule opacity files in the petitRADTRANS installation and extracts information about available condensed species including their chemical formulas, names, masses, and visualization names.

Returns:

A tuple containing:
  • np.ndarray: Array of condensed molecule chemical formulas

  • np.ndarray: Array of condensed molecule file names

  • np.ndarray: Array of calculated molecular masses (in u)

  • np.ndarray: Array of visualization names for display

Return type:

tuple

Note

If no condensed molecules are found, returns arrays with [“None”] and mass [-999] as placeholders.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.get_line_lists()[source]

Retrieve line lists, isotopes, opacity_line_list identifiers, and compute isotopic masses from molecular opacity data used by petitRADTRANS.

This function performs the following steps:

  1. Reads the periodic table data from a CSV file to obtain numbers of protons and neutrons for each element.

  2. Scans the ‘line_by_line’ directory (within the opacities folder) for molecule directories.

  3. For each molecule, lists its available isotopes (each isotope is represented by a directory).

  4. Parses each isotope’s name (which encodes its elemental composition) to determine the elemental symbols and their corresponding mass numbers, compute the total mass of the isotope using predefined atomic masses (proton: 1.007276 u, neutron: 1.008665 u, electron: 0.000548579909 u), and adjust the electron count based on the number of ‘+’ symbols.

  5. For each isotope, retrieves the available opacity_line_list file names (by removing the “.xsec.petitRADTRANS.h5” suffix).

Returns:

A tuple containing:
  • np.ndarray: Sorted array of molecule names.

  • dict: Dictionary mapping each molecule to an array of its isotope names.

  • dict: Dictionary mapping each isotope to an array of HR opacity_line_list identifiers.

  • dict: Dictionary mapping each isotope to an array of LR opacity_line_list identifiers.

  • dict: Dictionary mapping each isotope to its computed total mass (in atomic mass units).

Return type:

tuple

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.generate_chemcat(min_pressure: float, max_pressure: float, nlayersf: int, path_default: str | Path) Tuple[ndarray, chemcat.Network, List[str]][source]

Generate a chemical catalog and retrieve molecular masses for atmospheric modeling.

This function creates a chemical network with specified pressure layers and temperature, and prepares molecular data for atmospheric modeling.

Parameters:
  • min_pressure (float) – Logarithm of minimum pressure (bar)

  • max_pressure (float) – Logarithm of maximum pressure (bar)

  • nlayersf (int) – Number of pressure layers

  • path_default (Union[str, Path]) – Base path to default files directory

Returns:

  • np.ndarray: Array of molecular masses for selected molecules

  • chemcat.Network: Chemical network object

  • List[str]: List of species names compatible with petitRADTRANS

Return type:

Tuple containing

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.read_fits(path_fits: str | Path, transpose: bool = False, intransit: ndarray | None = None) ndarray[source]

Read data from a FITS file and optionally apply slicing and transposition.

Parameters:
  • path_fits (Union[str, Path]) – Path to the FITS file

  • transpose (bool, optional) – Whether to transpose the data array. Defaults to False.

  • intransit (Optional[np.ndarray], optional) – Indices to slice the data along the second axis. If provided, data is sliced as data[:, intransit, :]. Defaults to None.

Returns:

The processed data array from the FITS file

Return type:

np.ndarray

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.get_depth_filename(rad_mode: str) str[source]

Return the depth FITS filename based on the radiative transfer mode.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.read_depth_fits(folder: str | Path, rad_mode: str, **kwargs) ndarray[source]

Read the depth FITS file with fallback to legacy transit_depth.fits.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.plot_vmr(pressures: ndarray, vmr_dict: Dict[str, ndarray], folder_plot: str | Path) None[source]

Plot volume mixing ratio (VMR) profiles for different chemical species groups.

This function creates a 2x3 grid of plots showing VMR profiles for: - All species - HCNO neutrals - Ions - Alkali metals - Metals - Metal oxides

Parameters:
  • pressures (np.ndarray) – Pressure values (in bar)

  • vmr_dict (Dict[str, np.ndarray]) – Dictionary mapping species names to their VMR profiles

  • folder_plot (Union[str, Path]) – Directory where the plot will be saved

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.get_medians(folder_retrieval_final: str | Path, arr_values, remove_chain: bool, corner_plot_or_simulation: bool, best_fit_method: str, n_samples: int = 500) BestFitParametersAndResults[source]

Extract and process parameter statistics from MCMC chains.

This function processes MCMC chain data to compute median values and other statistics for fitted parameters. It handles chain rejection based on chi2 criteria and performs burn-in removal.

Parameters:
  • folder_retrieval_final (Union[str, Path]) – Path to the final retrieval folder

  • arr_values – Array containing parameter information

  • remove_chain (bool) – Whether to remove chains based on chi2 criteria

  • corner_plot_or_simulation (bool) – Whether to process data for corner plots

  • best_fit_method – Method used to extract best fit parameters

  • n_samples – Number of samples to use for random model extraction

Returns:

Object containing processed parameter statistics

Return type:

BestFitParametersAndResults

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.pre_plot(folder_retrieval_final: str | ~pathlib.Path, arr_values: ~numpy.ndarray, remove_chain: [<class 'bool'>, <class 'int'>], corner_plot: [<class 'bool'>, <class 'int'>], best_fit_method: str) Tuple[int, float, float, float, ndarray, List[str], ndarray, ndarray, List[float], List[str], str, str, List[str], ndarray][source]

Prepare posterior chain statistics and parameter labels for plotting.

Parameters:
  • folder_retrieval_final (Union[str, Path]) – Path to the final retrieval folder

  • arr_values (np.ndarray) – Array containing parameter information

  • remove_chain (bool) – Whether to remove chains based on chi2 criteria

  • corner_plot (bool) – Whether to process data for corner plots

  • best_fit_method (str) – Method used to extract best fit parameters

Returns:

  • int: Number of bad chains

  • float: AIC value

  • float: Last maximum likelihood

  • float: Current maximum likelihood

  • np.ndarray: Flattened chi2 values

  • List[str]: Best-fit parameter names

  • np.ndarray: Chain parameters

  • np.ndarray: Parameter medians

  • List[float]: Fixed parameter values

  • List[str]: Fixed parameter names

  • str: Summary string

  • str: Parameter names string

  • List[str]: Parameter labels

  • np.ndarray: Parameter errors

Return type:

Tuple containing

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.cross_correlation(type_cc: str, arr1: ndarray, arr2: ndarray, sigma: ndarray | None = None) float[source]

Compute cross-correlation between two arrays using different methods.

Parameters:
  • type_cc (str) – Type of correlation to compute (‘numpy’, ‘normal’, or ‘weighted’)

  • arr1 (np.ndarray) – First input array

  • arr2 (np.ndarray) – Second input array

  • sigma (Optional[np.ndarray]) – Error array for weighted correlation

Returns:

Correlation coefficient

Return type:

float

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.c_correlate(s_1: ndarray, s_2: ndarray, lags) ndarray[source]

Compute normalized cross-correlation of two signals at specified lags.

Parameters:
  • s_1 (np.ndarray) – First input signal

  • s_2 (np.ndarray) – Second input signal

  • lags – Array of lags at which to compute correlation

Returns:

Array of correlation values for each lag

Return type:

np.ndarray

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.w_correlate(s_1: ndarray, s_2: ndarray, es_1: ndarray) ndarray[source]

Compute weighted cross-correlation between two signals.

Parameters:
  • s_1 (np.ndarray) – First input signal

  • s_2 (np.ndarray) – Second input signal

  • es_1 (np.ndarray) – Error array for the first signal

Returns:

Array containing the weighted correlation value

Return type:

np.ndarray

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.linear_solver(topca_l: ndarray, res_l: ndarray)[source]

Solve a linear system using Singular Value Decomposition (SVD).

This function solves the linear system Ax = b using SVD decomposition, where A is the design matrix (res_l) and b is the target vector (topca_l). The solution is computed in a numerically stable way using SVD.

Parameters:
  • topca_l (np.ndarray) – Target vector b in the system Ax = b

  • res_l (np.ndarray) – Design matrix A in the system Ax = b

Returns:

The reconstructed array after solving the linear system Error: Whether the linear system was solved successfully

Return type:

Results

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.skewed_gaussian(x, amp, center, width, skew)[source]

Calculate a skewed Gaussian distribution.

Parameters:
  • x – Input values

  • amp – Amplitude of the distribution

  • center – Center position

  • width – Width parameter

  • skew – Skewness parameter

Returns:

Values of the skewed Gaussian distribution

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.estimate_continuum(spectrum_new, num_windows=40, top_window=10, check_gaussian=False)[source]

Estimate and remove the continuum from a spectrum using windowed median fitting.

Parameters:
  • spectrum_new (np.ndarray) – Input spectrum array.

  • num_windows (int) – Number of windows to divide the spectrum into.

  • top_window (int) – Number of top values per window used for continuum estimation.

  • check_gaussian (bool) – If True, fit a skewed Gaussian instead of a polynomial.

Returns:

(continuum, model_after_processing) where continuum is the estimated

continuum and model_after_processing is the spectrum normalized by it.

Return type:

tuple

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.trpca(lcr_mask: ndarray, lcrm_mask_nomask: ndarray, good_pixel: ndarray, ncomp: int, smooth_on: bool, smooth_size: int, apply_standardize: bool, model_reprocessing_type: str, subtract_mean_spectrum: bool = False, pca_mode: str = 'spatial')[source]

Process light curve residuals by removing systematic components using PCA.

This function processes light curve residuals by: 1. Normalizing the data by subtracting column-wise means 2. Optionally applying PCA-based component removal 3. Updating the output array for good pixels 4. Optionally applying smoothing

Parameters:
  • lcr_mask (np.ndarray) – 2D array of light curve residuals with telluric mask

  • lcrm_mask_nomask (np.ndarray) – 2D array to store processed residuals

  • good_pixel (np.ndarray) – Boolean mask or indices of good pixels

  • ncomp (int) – Number of PCA components to use

  • smooth_on (bool) – Whether to apply smoothing

  • smooth_size (int) – Window size for smoothing filter

  • apply_standardize (bool) – Whether to apply standardization

  • model_reprocessing_type (str) – Processing mode, either “hard” or “soft”

  • subtract_mean_spectrum (bool) – Whether to subtract mean spectrum

  • pca_mode (str) – PCA mode - “spatial” (samples=images, features=pixels) or “temporal” (samples=pixels, features=images). Default: “spatial”

Returns:

Processed light curve residuals error: Whether the processing was successful

Return type:

np.ndarray

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.get_keys_by_value(dictionary: Dict[str, Any], target_value: Any) str | None[source]

Find the first key in a dictionary whose value contains the target value.

This function searches through the dictionary values to find the first key whose value contains the target value. It’s useful for reverse lookups in dictionaries where values are collections.

Parameters:
  • dictionary (Dict[str, Any]) – Dictionary to search through

  • target_value (Any) – Value to search for in the dictionary values

Returns:

The first key whose value contains target_value,

or None if no match is found

Return type:

Optional[str]

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.compute_adjusted_abundance(pressure: ndarray, temperature: ndarray, coeff, base_vmr) ndarray[source]

Compute adjusted abundance accounting for dissociation effects.

This function calculates the adjusted abundance of a species by considering both the base volume mixing ratio and dissociation effects. The dissociation is modeled using a pressure and temperature dependent function.

Parameters:
  • pressure (np.ndarray) – Pressure values in bar

  • temperature (np.ndarray) – Temperature values in Kelvin

  • coeff – Coefficients [a, b, c] for dissociation calculation

  • base_vmr – Base volume mixing ratio from reference layer

Returns:

Adjusted abundance values

Return type:

np.ndarray

The calculation follows these steps: 1. Compute dissociation factor (Ad) using pressure and temperature 2. Convert to inverse dissociation factor (1/Ad) 3. Combine with inverse base abundance (1/A0) in quadrature 4. Return final adjusted abundance (A)

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.spectral_convolution_ptr(wavelength, spectrum, pixel_dv)[source]

Convolve a spectrum to instrumental resolution using petitRADTRANS.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.get_stellar_model(path_pkl, min_wl_cm, max_wl_cm)[source]

Load a stellar spectrum from a pickle file and optionally trim to a wavelength range (cm).

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.generate_star_model_hr(path_pkl, pixel_dv, min_wl=None, max_wl=None)[source]

Generate a stellar spectrum model from a pickled file.

This function loads a stellar spectrum from a pickle file, convolves it with the instrumental resolution, and creates a spline interpolation model.

Parameters:
  • path_pkl (str or Path) – Path to the pickle file containing stellar spectrum data

  • pixel_dv (float) – Pixel velocity width for resolution calculation

  • min_wl (float) – Minimum wavelength for interpolation model in cm

  • max_wl (float) – Maximum wavelength for interpolation model in cm

Returns:

Spline representation of the stellar spectrum model

Return type:

tuple

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.rv_planet_and_star(eccentricity, target, ecc_retrieval, opi_retrieval, kp_retrieval, night_obj, mode, index_night_in_current_instrument, dVsys_arr, counter_derivative_params)[source]

Compute planetary and stellar radial velocities for a given night.

Parameters:
  • eccentricity (bool) – Whether to use eccentric orbit model.

  • target – Target object with orbital parameters.

  • ecc_retrieval (float) – Retrieved eccentricity value.

  • opi_retrieval (float) – Retrieved argument of periastron.

  • kp_retrieval (float) – Retrieved planetary radial velocity semi-amplitude (km/s).

  • night_obj – Night object containing phase and barycentric velocity data.

  • mode (str) – Operating mode (‘CC’, ‘Retrieval’, or synthetic).

  • index_night_in_current_instrument (int) – Index of the night within the instrument.

  • dVsys_arr – Array of systemic velocity offsets per night.

  • counter_derivative_params (int) – Counter for derivative parameter indexing.

Returns:

(vtot, vtot_star, kpph) planetary velocity, stellar velocity, and Kp*phase arrays.

Return type:

tuple

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.calculate_rv_planet_and_star(hjd0, times_of_observation, eccentricity, period, ecc, opi, kp, ks, phases, coeff_vtot, systemic_velocity, barycentric, dvsys, vsys_extra=0)[source]

Calculate planetary and stellar radial velocities from orbital parameters.

Returns:

(vtot, vtot_star, kpph) total velocity shift for planet, for star, and Kp*phase.

Return type:

tuple

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.rv_DopplerShadow(target, phases)[source]

Compute the Rossiter-McLaughlin (Doppler shadow) radial velocity anomaly.

Based on Cegla, H. M., et al. 2016, A&A, 588, A127.

Parameters:
  • target – Target object with projected_obliquity, a_Rs_ratio, inclination, v_sini, and systemic_velocity attributes.

  • phases (np.ndarray) – Orbital phase array.

Returns:

Radial velocity anomaly plus systemic velocity (km/s).

Return type:

np.ndarray

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.ask_stellar_params(parent=None, stellar_teff: float | None = None) Tuple[float | None, float | None, float | None][source]

Open stellar parameter dialog and return user-specified stellar properties.

This convenience function creates and displays a modal dialog for entering stellar atmospheric parameters needed for synthetic spectrum generation. The dialog allows input of effective temperature, surface gravity, and metallicity with validation and reasonable defaults.

Parameters:
  • parent (tk.Misc or None, optional) – Parent widget for the dialog. If None, uses default root window or creates a new Tk instance, by default None

  • stellar_teff (float or None, optional) – Initial effective temperature value to populate in the dialog, by default None

Returns:

Tuple containing stellar parameters: - T_eff : Effective temperature in Kelvin (rounded to 5 digits) - log_g : Surface gravity in cgs units (log10(g)) - Fe_H : Metallicity [Fe/H] in dex

Returns (None, None, None) if user cancels or closes dialog

Return type:

tuple[float or None, float or None, float or None]

Notes

The stellar parameters are used to select appropriate stellar atmosphere models for synthetic spectrum generation. The dialog provides validation to ensure physically reasonable values are entered.

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.download_star_spectrum(figure_tk, target_obj, folder_stellar_spc)[source]

Download and save a PHOENIX stellar spectrum if not already present.

Parameters:
  • figure_tk – Parent Tkinter widget for the stellar parameter dialog.

  • target_obj – Target object with stellar_effective_temperature attribute.

  • folder_stellar_spc (str) – Directory for storing the stellar spectrum file.

Returns:

Path to the stellar spectrum pickle file, or None if cancelled.

Return type:

str or None

GUIBRUSHR.General_Constants.FunctionsAndConstants.general_functions.compute_transit_durations(period, a_Rs, k, inc_deg, ecc=0.0, omega=1.5707963267948966)[source]

Compute transit durations T14, T23, T12 (=T34) for circular and eccentric orbits.

Parameters:
  • period (float) – Orbital period in days.

  • a_Rs (float) – Semi-major axis in units of stellar radii (a / R_star).

  • k (float) – Planet-to-star radius ratio (Rp / Rs).

  • inc_deg (float) – Orbital inclination in degrees.

  • ecc (float, optional) – Orbital eccentricity (default 0 for circular).

  • omega (float, optional) – Argument of periastron of the STAR in radians (default pi/2).

Returns:

‘T14’, ‘T23’, ‘T12’ : durations in days ‘T14_hours’, ‘T23_hours’, ‘T12_hours’ : durations in hours ‘b’ : impact parameter ‘ecc_factor’ : eccentricity correction factor (1.0 if circular) ‘grazing’ : True if grazing transit (T23 = 0) ‘limph_T14’, ‘limph_T12’ : phase limits = T / (2*P)

Return type:

dict with keys

References

Winn (2010), “Transits and Occultations”, arXiv:1001.2010, Eq. 14-16. Kipping (2010), MNRAS 407, 301, arXiv:1004.3819.