Classes#
Retrieval#
- assign_cloud_parameters(abundances_VMR: dict, cloud_vars: dict, press: ndarray, phys_vars: dict, condensation_pressures: float) Tuple[dict, dict, dict, int][source]#
Assign cloud parameters and update abundances.
This function takes in the abundances dictionary, cloud_vars dictionary, and pressure array. It calculates the bottom pressure of each cloud layer by adding its top pressure to its thickness. It sets all abundance values outside a given cloud layer to 0 (i.e., it removes them from consideration). It also creates a new cloud_radii dictionary that contains only the particle radii for each type of condensate.
- Parameters:
abundances_VMR (dict) – Dictionary of volume mixing ratios for each species
cloud_vars (dict) – Dictionary containing cloud parameters
press (ndarray) – Array of pressure levels
phys_vars (dict) – Dictionary of physical variables
condensation_pressures (float) – Pressures at which condensation occurs
- Returns:
A tuple containing updated abundances, cloud variables, cloud radii, cloud lognormal distribution parameter, cloud pressure, and cloud fraction
- Return type:
Tuple[dict, dict, dict, int, float, float]
- calculate_abundances(chem_vars: dict, press: ndarray, settings: dict) Tuple[dict, dict][source]#
Calculate the abundances of chemical species in an atmosphere.
This function takes chemical variables, pressure levels, and settings to compute the abundances of various molecules in an atmosphere. It can handle both Mass Mixing Ratio (MMR) and Volume Mixing Ratio (VMR) units.
- Parameters:
chem_vars (dict) – A dictionary containing the chemical variables for each molecule
press (ndarray) – An array of pressure levels in the atmosphere
settings (dict) – A dictionary containing configuration settings, including ‘abundance_units’
- Returns:
A tuple containing two dictionaries: The first dictionary contains the calculated abundances for each molecule; The second dictionary contains the chemical variables in VMR units (if conversion was needed)
- Return type:
Tuple[dict, dict]
Note
TBD CHECK HOW IT WORKS FOR SLOPES
- calculate_adiabat_profile(pressure: ndarray, temp_vars: dict, phys_vars: dict) ndarray[source]#
Calculate an adiabatic temperature profile.
This function calculates the temperature profile assuming an adiabatic atmosphere.
- Parameters:
pressure (ndarray) – The pressure values
temp_vars (dict) – The dictionary of temperature variables
phys_vars (dict) – The dictionary of physical variables
- Returns:
The adiabatic temperature profile for the given pressure levels
- Return type:
ndarray
- calculate_gravity(phys_vars: dict, config: dict) dict[source]#
Calculate the surface gravity of a planet.
This function calculates the surface gravity of a planet given its mass and radius. If the surface gravity is already provided, it will skip this step.
- Parameters:
phys_vars (dict) – Dictionary of all the physical variables
config (dict) – Dictionary containing all the config file settings/known values/parameters
- Returns:
Updated phys_vars dictionary
- Return type:
dict
- calculate_guillot_profile(pressure: ndarray, temp_vars: dict) ndarray[source]#
Calculate a Guillot temperature profile.
This function calculates the Guillot profile for a given set of parameters.
- Parameters:
pressure (ndarray) – The pressure array
temp_vars (dict) – The dictionary of temperature parameters to calculate the Guillot profile
- Returns:
The temperature profile for the given pressure levels
- Return type:
ndarray
- calculate_inert(abundances: dict) ndarray[source]#
Calculate the abundance of inert gases in the atmosphere.
This function computes the amount of inert gases present in the atmosphere by subtracting the sum of all known abundances from 1.
- Parameters:
abundances (dict) – A dictionary containing the abundances of various chemical species. Each key is a species name, and the corresponding value is an array of abundances at different atmospheric levels.
- Returns:
An array representing the abundance of inert gases at each atmospheric level.
- Return type:
ndarray
- calculate_isothermal_profile(pressure: ndarray, temp_vars: dict) ndarray[source]#
Calculate an isothermal temperature profile.
This function returns a constant temperature profile for all pressure levels, representing an isothermal atmosphere.
- Parameters:
pressure – The pressure array (not used in this function, but included for consistency)
temp_vars – A dictionary containing temperature variables. Should include ‘T_eq’ key.
- Returns:
An array of constant temperatures (T_eq) for all pressure levels
- calculate_line_profile(pressure: ndarray, temp_vars: dict, phys_vars: dict, R_star=699500000.0, T_star=5780.0, T_int=0.0, sma=149597870700.0)[source]#
Generate a PT profile based on input free parameters and pressure array.
If no inputs are provided, it will run in demo mode, using free parameters given by the Line 2013 paper and some dummy pressure parameters.
- Parameters:
pressure (ndarray) – Array of pressure values in bars
temp_vars (dict) – Dictionary containing temperature variables
phys_vars (dict) – Dictionary containing physical variables
R_star (float, optional) – Stellar radius (in meters), defaults to 6.995e8
T_star (float, optional) – Stellar effective temperature (in Kelvin degrees), defaults to 5780.0
T_int (float, optional) – Planetary internal heat flux (in Kelvin degrees), defaults to 0.0
sma (float, optional) – Semi-major axis (in meters), defaults to 1.0 * astropy.constants.au
- Returns:
Temperature array
- Return type:
ndarray
Note
The temp_vars dictionary should contain: - kappa: Planck thermal IR opacity in units cm^2/gr (in log10) - gamma1: Visible-to-thermal stream Planck mean opacity ratio (in log10) - gamma2: Visible-to-thermal stream Planck mean opacity ratio (in log10) - alpha: Visible-stream partition (0.0–1.0) - beta: A ‘catch-all’ for albedo, emissivity, and day-night redistribution (on the order of unity)
The phys_vars dictionary should contain: - grav: Planetary surface gravity (at 1 bar) in cm/second^2
Warning
The T_int_type parameter mentioned in the original docstring is not used in the function signature.
Note
Developers:
Madison Stemm : astromaddie@gmail.com
Patricio Cubillos : pcubillos@fulbrightmail.org
Modification History:
2014-09-12 Madison : Initial version, adapted from equations (13)-(16) in Line et al. (2013), Apj, 775, 137.
2014-12-10 patricio : Reviewed and updated code.
2015-01-22 patricio : Receive log10 of free parameters now.
2019-02-13 mhimes : Replaced params arg with each parameter for consistency with other PT models
2019-09-10 mhimes : Added T_int calculation from Thorngren et al. (2019)
- calculate_madhuseager_profile(pressure: ndarray, temp_vars: dict) ndarray[source]#
Calculate the temperature profile using the Madhusudhan & Seager (2009) model.
This function calculates the temperature profile of a planet using the Madhusudhan & Seager (2009) model.
- Parameters:
pressure (ndarray) – The pressure array
temp_vars (dict) – The dictionary of temperature parameters to calculate the Madhusudhan & Seager profile
- Returns:
The temperature profile for the given pressure levels
- Return type:
ndarray
- calculate_mmw_MMR(abundances_MMR: dict, settings: dict, inert: ndarray) ndarray[source]#
Calculate the mean molecular weight of each layer in the atmosphere.
This function computes the mean molecular weight for each atmospheric layer based on the provided mass mixing ratios (MMR) of different species, settings, and the weight of inert gas present.
- Parameters:
abundances_MMR (dict) – Dictionary containing the mass mixing ratios of different species
settings (dict) – Dictionary containing various settings for the calculation
inert (ndarray) – Array representing the weight of the inert gas in each layer
- Returns:
Array of mean molecular weights for each atmospheric layer
- Return type:
ndarray
- calculate_mmw_VMR(abundances_VMR: dict, settings: dict, inert: ndarray) ndarray[source]#
Calculate the mean molecular weight of each layer in the atmosphere.
This function calculates the mean molecular weight (MMW) for each layer of the atmosphere based on the provided volume mixing ratios (VMR) of different species, settings, and the weight of inert gas present.
- Parameters:
abundances_VMR (dict) – Dictionary containing the volume mixing ratios of different species
settings (dict) – Dictionary containing various settings for the calculation
inert (ndarray) – Array representing the weight of the inert gas in each layer
- Returns:
Array of mean molecular weights for each atmospheric layer
- Return type:
ndarray
- calculate_mod_madhuseager_profile(pressure: ndarray, temp_vars: dict) ndarray[source]#
Calculate the temperature profile using a modified Madhusudhan-Seager model.
This function calculates the temperature profile of a planet using a modified version of the Madhusudhan-Seager model.
- Parameters:
pressure (ndarray) – The pressure array
temp_vars (dict) – The dictionary of temperature values to calculate the modified Madhusudhan-Seager model
- Returns:
The temperature array
- Return type:
ndarray
- calculate_polynomial_profile(pressure: ndarray, temp_vars: dict) ndarray[source]#
Calculate a polynomial temperature profile.
This function takes in a pressure array and a dictionary of temperature variables, and returns an array of temperatures corresponding to the pressures using a polynomial function.
- Parameters:
pressure (ndarray) – The pressure values
temp_vars (dict) – The dictionary of a_i coefficients to calculate the polynomial
- Returns:
The temperature profile for the given pressure levels
- Return type:
ndarray
- calculate_spline_profile(pressure: ndarray, temp_vars: dict, phys_vars: dict, settings: dict) ndarray[source]#
Calculate a spline temperature profile.
This function takes in a pressure array and dictionaries of temperature variables, physical variables, and settings, and returns an array of temperatures corresponding to the pressures using a spline interpolation.
- Parameters:
pressure (ndarray) – The pressure values
temp_vars (dict) – The dictionary of temperature variables
phys_vars (dict) – The dictionary of physical variables
settings (dict) – The dictionary of settings
- Returns:
The temperature profile for the given pressure levels
- Return type:
ndarray
- calculate_vae_profile(pressure: ndarray, vae_pt, temp_vars: dict) ndarray[source]#
Calculate a temperature profile using a variational autoencoder (VAE).
This function takes in a pressure array, a VAE object, and a dictionary of temperature variables, and returns an array of temperatures corresponding to each pressure.
- Parameters:
pressure (ndarray) – The pressure values
vae_pt (object) – The VAE object to access the get_temperatures function
temp_vars (dict) – The dictionary of temperature coefficients
- Returns:
The temperature profile for the given pressure levels
- Return type:
ndarray
- condense_water(abundances_VMR, pressure, temperature, phys_vars, settings, drying=0.0)[source]#
Calculate the condensation of water in an atmosphere.
This function computes the condensation of water vapor in an atmosphere based on the given abundances, pressure, temperature, and other parameters.
- Parameters:
abundances_VMR (dict) – Dictionary of volume mixing ratios for atmospheric constituents
pressure (ndarray) – Array of pressure levels in the atmosphere
temperature (ndarray) – Array of temperature values corresponding to pressure levels
phys_vars (dict) – Dictionary of physical variables
settings (dict) – Dictionary of settings for the calculation
drying (float, optional) – Drying factor, defaults to 0.0
- Returns:
Tuple containing updated abundances_VMR and condensation pressures
- Return type:
tuple
Note
This function calculates the condensation of water vapor by comparing the partial pressure of water to its vapor pressure at each atmospheric level.
- condense_water_old(abundances_VMR, pressure, temperature, phys_vars, settings, drying=0.0)[source]#
Calculate the condensation of water in an atmosphere.
This function computes the condensation of water vapor in an atmosphere based on the given abundances, pressure, temperature, and other parameters.
- Parameters:
abundances_VMR (dict) – Dictionary of volume mixing ratios for atmospheric constituents
pressure (ndarray) – Array of pressure levels in the atmosphere
temperature (ndarray) – Array of temperature values corresponding to pressure levels
phys_vars (dict) – Dictionary of physical variables
settings (dict) – Dictionary of settings for the calculation
drying (float, optional) – Drying factor, defaults to 0.0
- Returns:
Tuple containing updated abundances_VMR and condensation pressures
- Return type:
tuple
Note
This function calculates the condensation of water vapor by comparing the partial pressure of water to its vapor pressure at each atmospheric level.
- convert_MMR_to_VMR(abundances_MMR: dict, settings: dict, inert_MMR: ndarray, mmw: ndarray) Tuple[dict, ndarray][source]#
Convert Mass Mixing Ratio (MMR) to Volume Mixing Ratio (VMR) for atmospheric species.
This function converts the mass mixing ratios of various atmospheric species to their corresponding volume mixing ratios. It also handles the conversion of inert gases if present.
- Parameters:
abundances_MMR (dict) – Dictionary containing mass mixing ratios of atmospheric species
settings (dict) – Dictionary containing various settings for the calculation
inert_MMR (ndarray) – Array representing the mass mixing ratio of inert gases in each layer
mmw (ndarray) – Array of mean molecular weights for each atmospheric layer
- Returns:
A tuple containing the dictionary of volume mixing ratios and the array of inert gas VMR
- Return type:
Tuple[dict, ndarray]
- convert_VMR_to_MMR(abundances_VMR: dict, settings: dict, inert_VMR: ndarray, mmw: ndarray) Tuple[dict, ndarray][source]#
Convert Volume Mixing Ratio (VMR) to Mass Mixing Ratio (MMR) for atmospheric species.
This function converts the volume mixing ratios of various atmospheric species to their corresponding mass mixing ratios. It also handles the conversion of inert gases if present.
- Parameters:
abundances_VMR (dict) – Dictionary containing volume mixing ratios of atmospheric species
settings (dict) – Dictionary containing various settings for the calculation
inert_VMR (ndarray) – Array representing the volume mixing ratio of inert gases in each layer
mmw (ndarray) – Array of mean molecular weights for each atmospheric layer
- Returns:
A tuple containing the dictionary of mass mixing ratios and the array of inert gas MMR
- Return type:
Tuple[dict, ndarray]
- get_mm(species: str) float[source]#
Get the molecular mass of a given species.
This function uses the molmass package to calculate the mass number for the standard isotope of an input species. If ‘all_iso’ is part of the input, it will return the mean molar mass.
- Parameters:
species (str) – The chemical formula of the compound, e.g., C2H2 or H2O
- Returns:
The molar mass of the compound in atomic mass units
- Return type:
float
- madhuseager_temperature_calculator(pressure_m: float, pressure_i: float, temperature_i: float, alpha: float, beta: float) float[source]#
Calculate the temperature of a parcel of air using the Madhusudhan-Seager equation.
This function calculates the temperature at a given pressure using the Madhusudhan-Seager equation.
- Parameters:
pressure_m (float) – The measured (or desired) pressure for which we want to calculate the temperature
pressure_i (float) – The initial (or reference) atmospheric pressure level
temperature_i (float) – The initial (or reference) atmospheric temperature
alpha (float) – A constant used to calculate the temperature gradient
beta (float) – A constant used to calculate the adiabatic lapse rate
- Returns:
The temperature at the pressure level m
- Return type:
float
- set_log_ground_pressure(phys_vars: dict, config: dict, knowns: dict, use_truth: bool = False) dict[source]#
Set the log of ground pressure.
This function checks if the surface pressure is provided or can be calculated from the provided parameters and brings it to the correct format for petitRADTRANS. A specific calculation is made in the case of settings_clouds=’opaque’.
- Parameters:
phys_vars (dict) – Dictionary of all the physical variables
config (dict) – Dictionary containing all the config file settings/known values/parameters
knowns (dict) – Dictionary containing all known quantities
use_truth (bool) – Boolean that allows to use the true value of the pressure rather than 10^{-4}
- Returns:
Updated phys_vars dictionary
- Return type:
dict
- water_ice_vapor_pressure(T, T_ST=373.15, p_ST=1.01325, T_0=273.16, p_i0=0.0061173)[source]#
Calculate the vapor pressure of water or ice using the Goff-Gratch equation.
This function computes the vapor pressure of water (for T >= T_0) or ice (for T < T_0) based on the given temperature using the Goff-Gratch equation.
- Parameters:
T (float) – Temperature in Kelvin
T_ST (float, optional) – Steam point temperature in Kelvin, defaults to 373.15 K (100°C)
p_ST (float, optional) – Steam point pressure in bars, defaults to 1.01325 bar (1 atm)
T_0 (float, optional) – Triple point temperature of water in Kelvin, defaults to 273.16 K (0.01°C)
p_i0 (float, optional) – Vapor pressure of ice at the triple point in bars, defaults to 6.1173e-3 bar
- Returns:
Vapor pressure of water or ice in bars
- Return type:
float
Note
The Goff-Gratch equation is used for its accuracy over a wide range of temperatures. For T >= T_0, the equation for water is used. For T < T_0, the equation for ice is used.
- xi(gamma: float, tau: ndarray) ndarray[source]#
Calculate Equation (14) of Line et al. (2013) Apj 775, 137
- Parameters:
gamma (float) – Visible-to-thermal stream Planck mean opacity ratio
tau (ndarray) – Gray IR optical depth
- Returns:
The calculated xi value
- Return type:
ndarray
Note
2014-12-10 patricio : Initial implementation.
Read in configuration files.
- read_data(self, retrieval=True, result_dir=None)[source]#
Reads the input data, trims to the wavelength range of interest and converts the units to CGS.
- read_var(self)[source]#
This function reads the config.ini file and fills up the three dictionaries: settings, params, knowns.
Read in configuration files.
- check_if_configs_match(config: dict) bool[source]#
The check_if_configs_match function checks if the config file in the retrieval directory matches the input.yaml file that was used to run a previous simulation. If they match, the function returns True; otherwise, it returns False.
- Parameters:
config – the configuration dictionary
:return True if the files are the same, False if they are different.
- get_check_opacity_path() Path[source]#
The get_check_opacity_path function checks that the PYRETLIFE_OPACITY_PATH environment variable is set. If it is not, an error message is printed and the program exits. If it is set, then a Path object pointing to the opacity folder in this directory will be returned. :returns: The path to the opacity folder
- get_check_prt_path() Path[source]#
The get_check_pRT_path function checks that the PYRETLIFE_PRT_PATH environment variable is set, and if so, checks that it points to a valid folder. If all these conditions are met, then the function returns a Path object pointing to this folder. :returns: The path to the petitRADTRANS folder
- get_retrieval_path() Path | str[source]#
The get_retrieval_path function checks that the PYRETLIFE_RETRIEVAL_PATH environment variable is set, and if so, then the function returns a Path object pointing to this folder. :returns: The path to the retrieval folder
- make_output_folder(folder_path: Path | str) None[source]#
The function creates a new folder at the specified path if it does not already exist.
- Parameters:
folder_path (Union[Path, str]) – The folder_path parameter is the path to the folder where you want to create a new folder. It can be either a Path object or a string representing the path
- populate_dictionaries(config: dict, knowns: dict, parameters: dict, settings: dict, units: UnitsUtil) Tuple[dict, dict, dict, UnitsUtil][source]#
- read_config_file(file_path: Path | str) dict[source]#
Read a configuration from a YAML file.
- Parameters:
file_path – Union[Path, str]: Path to a file with the configuration.
:return The configuration as a dictionary.
- save_configuration(input_path: Path | str, output_path: Path | str)[source]#
The function save_configuration copies a file from the input path to the output path if the output path does not already exist.
- Parameters:
input_path – The input_path parameter is the path to the configuration file that you want to
save. It can be either a Path object or a string representing the path to the file :type input_path: Union[Path, str] :param output_path: The output path is the path where the configuration file will be saved. It can be either a Path object or a string representing the path :type output_path: Union[Path, str]
- save_input_spectra(input_files: dict, output_path: Path | str)[source]#
The save_input_spectra function copies the input spectra to a new directory.
- Parameters:
input_files – dict: Define the input files to be copied
output_path – Union[Path: Specify the path to which the input spectra will be saved
str] – Specify that the output_path can be either a string or a path
PRIORS.py
Here, the unity cube is converted to prior cube by using either an uninformative, uniform prior, or a Gaussian prior. The variable cube has length equal to the number of parameters to be retrieved; the indexing follows the order of the params global list.
- assign_priors(dictionary: dict) dict[source]#
The assign_priors function takes a dictionary of parameters and assigns the appropriate prior function to each parameter. The prior functions are defined in the priors module. The assign_priors function is called by the read_parameters function, which reads in the parameters from a .yaml file.
- Parameters:
dictionary – Pass the dictionary containing all the parameters and their values
- Returns:
A dictionary with the prior function assigned to each parameter
- custom_prior(r: float, prior_specs: dict) float[source]#
The custom_prior function takes in a random number r and the prior_specs dictionary. It then returns the quantile of the data corresponding to that random number. This is useful for when you want to use your own data as a prior.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “data”
- Returns:
The number corresponding to the r-th quantile of the custom prior
- fourth_power_uniform_prior(r: float, prior_specs: dict) float[source]#
The fourth_power_uniform_prior function takes in a random number and prior specifications. It then returns the fourth power of a uniform distribution with lower and upper bounds specified by the prior_specs.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “fourth_lower” and “fourth_upper”
- Returns:
A random number like x^4 where x is generated from a uniform prior between [x1, x2]
- gaussian_prior(r: float, prior_specs: dict) float[source]#
Scales a random number generated in a uniform prior between 0 and 1 to the respective value corresponding to a gaussian prior centered at mu and of standard deviation sigma. This function is called by the assign_priors function.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “mean” and “sigma”
- Returns:
A random float generated from a gaussian prior G(mu,sigma).
- invalid_prior(par: str)[source]#
The invalid_prior function is used to raise an error if the user provides an invalid prior. It takes a single argument, par, which is the name of the parameter for which an invalid prior was provided. The function then raises a ValueError with a message explaining that the prior provided for par is invalid.
- Parameters:
par – A string containing the name of the parameter
- Raises:
ValueError –
- log_gaussian_prior(r: float, prior_specs: dict) float[source]#
Returns a number like 10^x, where x is generated by scaling a random number generated in a uniform prior between 0 and 1 to the respective value corresponding to a gaussian prior ranged between x1 and x2. This function is called by the assign_priors function.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “log_mean” and “log_sigma”
- Returns:
A random number whose exponent in base 10 is generated from a gaussian prior G(mu,sigma).
- log_uniform_prior(r: float, prior_specs: dict) float[source]#
Returns a number like 10^x, where x is generated by scaling a random number generated in a uniform prior between 0 and 1 to the respective value corresponding to a uniform prior ranged between x1 and x2. This function is called by the assign_priors function.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “log_lower” and “log_upper”
- Returns:
A random number whose exponent in base 10 is generated from a uniform prior between [x1, x2].
- second_power_uniform_prior(r: float, prior_specs: dict) float[source]#
The fourth_power_uniform_prior function takes in a random number and prior specifications. It then returns the fourth power of a uniform distribution with lower and upper bounds specified by the prior_specs.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “fourth_lower” and “fourth_upper”
- Returns:
A random number like x^4 where x is generated from a uniform prior between [x1, x2]
- third_power_uniform_prior(r: float, prior_specs: dict) float[source]#
The fourth_power_uniform_prior function takes in a random number and prior specifications. It then returns the fourth power of a uniform distribution with lower and upper bounds specified by the prior_specs.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “fourth_lower” and “fourth_upper”
- Returns:
A random number like x^4 where x is generated from a uniform prior between [x1, x2]
- twod_uniform_prior(r: float, R_pl: int) float[source]#
Scales a random number generated in a uniform prior between 0 and 1 to the respective value corresponding to a uniform prior ranged between the allowed mass values allowed by the current radius assigned prior. This function is only used for M_pl. Formula taken from Zeng et al. (2016) doi.org/10.3847/0004-637X/819/2/127.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
R_pl – The radius of the Planet in Earth radii.
- Returns:
A random number generated from a uniform prior between [x1, x2].
- uniform_prior(r: float, prior_specs: dict) float[source]#
Scales a random number generated in a uniform prior between 0 and 1 to the respective value corresponding to a uniform prior ranged between x1 and x2. This function is called by the assign_priors function.
A random number generated from a uniform prior between [x1, x2]. :param r: A random float generated from the uniform prior between [0, 1]. :param prior_specs: A dictionary of prior_specs containing the keywords “lower” and “upper” :return: A random number generated from a uniform prior between [x1, x2].
- upper_log_uniform_prior(r: float, prior_specs: dict) float[source]#
Returns a number like (1-10^x), where x is generated by scaling a random number generated in a uniform prior between 0 and 1 to the respective value corresponding to a uniform prior ranged between x1 and x2. This function is called by the assign_priors function.
- Parameters:
r – A random float generated from the uniform prior between [0, 1].
prior_specs – A dictionary of prior_specs containing the keywords “log_lower” and “log_upper”
- Returns:
A random number like (1-10^x) whose exponent in base 10 is generated from a uniform prior between [x1, x2].
- calculate_emission_flux(rt_object, settings: dict, temp: ndarray, abundances_MMR: dict, gravity: float, mmw: ndarray, cloud_radii: dict, cloud_lnorm: int, scat_vars: dict, em_contr=False, Pcloud=None) Tuple[ndarray, ndarray][source]#
Creates the pressure-temperature profile for the current atmosphere and calculates the corresponding emitted flux using petitRADTRANS. See the documentation for petitRADTRANS.radtrans.Radtrans.calculate_flux.
- define_linelists(config: dict, settings: dict, input_opacity_path: str | Path) Tuple[list, list, list, list][source]#
This module contains the RetrievalObject class, which is the main class of the pyretlife package.
- class RetrievalObject(run_retrieval: bool = True)[source]#
Bases:
objectThis class binds together all the different parts of the retrieval.
- Parameters:
run_retrieval
- config#
The configuration (i.e., the contents of the YAML or INI file for a given retrieval) as a dictionary.
- input_prt_path#
Path to the petitRADTRANS installation.
- input_opacity_path#
Path to the opacity data.
- ...
TODO: Keep adding attributes here to document them. TODO: Maybe also add an __repr__ method to this class?
- calculate_log_likelihood(cube)[source]#
Calculates the log(likelihood) of the forward model generated with parameters and known variables.
- calculate_pt_profile(parameterization, log_ground_pressure, log_top_pressure, layers)[source]#
Creates the pressure-temperature profile from the temperature parameters and the pressure.
Retrieval Plotting#
- VMR_to_MMR(abundances_VMR, settings)[source]#
Convert volume mixing ratio (VMR) abundances to mass mixing ratio (MMR) abundances.
This function takes the volume mixing ratio (VMR) abundances of various species in the atmosphere, computes the total atmospheric inert mass, calculates the mean molecular weight (MMW) of the atmosphere, and converts the VMR abundances to mass mixing ratios (MMR) using the derived MMW.
- Parameters:
abundances_VMR (dict) – A dictionary containing the volume mixing ratios (VMR) for various atmospheric species. The keys are the species names, and the values are arrays representing the VMR values at different pressure levels.
settings (dict) – A dictionary containing various settings for the calculation.
- Returns:
A dictionary containing the mass mixing ratios (MMR) for the same species as the input abundances_VMR. The keys are the species names, and the values are arrays representing the MMR values at different pressure levels.
- Return type:
dict
- Notes:
The inert mass is calculated as the difference between 1 and the total VMR, assuming the remaining volume is made up of inert species (e.g., He, H2).
The returned MMR abundances represent the mass fraction of each species in the atmosphere.
- abundance_profile_calculation(rp_object, layers=500, p_surf=4, use_truth=False)[source]#
Calculate abundance profiles for retrieved posterior distributions.
This function computes the volume mixing ratio (VMR) and mass mixing ratio (MMR) abundance profiles for a range of parameters drawn from the posterior distributions. The profiles are calculated for both retrieved and extrapolated pressure-temperature (P-T) profiles.
- Parameters:
rp_object (retrieval_plotting_object) – An instance of the retrieval_plotting_object class containing the retrieved fluxes, posteriors, wavelengths, and known system properties. This object provides all necessary information for the calculation.
layers (int, optional) – The number of layers to calculate for the extrapolated profile. Defaults to 500.
p_surf (float, optional) – The surface pressure (in log scale) to which the P-T profile is extrapolated. Defaults to 4.
use_truth (bool, optional) – Whether to use the true values of the parameters for physical variables. If True, the true values of the physical parameters are used instead of the retrieved values. Defaults to False.
- Returns:
A dictionary containing the calculated abundance profiles, including: - ‘pressures’: The pressures at which the abundance profiles are calculated. - ‘pressures_extrapolated’: The extrapolated pressures for abundance profiles. - For each species (key in rp_object.abundances_VMR), both ‘VMR’ (volume mixing ratio) and
’MMR’ (mass mixing ratio) profiles are stored for both the retrieved and extrapolated P-T profiles.
- Return type:
dict
- Notes:
Assumes that the rp_object contains the necessary posteriors, abundances, and settings for the calculation.
Abundances are calculated for each sample from the posterior distribution and stored for both retrieved and extrapolated profiles.
Extrapolation is performed to higher pressures, with abundances capped at the last retrieved value to avoid unrealistic results.
Prints progress updates, including the estimated time remaining for the calculation.
- add_secondary_parameter_to_parameters(parameters, name, unit, title, true_value=None)[source]#
Add a secondary parameter to the parameters dictionary.
This function updates the parameters dictionary by adding a new secondary parameter. Secondary parameters are typically derived quantities or parameters not directly retrieved but useful for analysis and plotting.
- Parameters:
parameters (dict) – A dictionary containing parameter definitions. Each key represents a parameter name, and the value is a dictionary with its attributes (e.g., units, priors, etc.).
name (str) – The name of the new secondary parameter to add.
unit (str or astropy.units.Unit) – The unit of the secondary parameter.
title (str) – A descriptive title for the secondary parameter, used in visualizations or summaries.
true_value (float or None, optional) – The true value of the secondary parameter, if known. Defaults to None.
- Returns:
The updated parameters dictionary with the new secondary parameter added.
- Return type:
dict
- Notes:
Secondary parameters are categorized as “SECONDARY PARAMETERS” in the type field.
The prior for secondary parameters is set to None by default, as they are typically not retrieved directly.
This function is useful for enriching the parameter set with derived quantities like the Bond albedo.
- bond_albedo_calculation(rp_object, stellar_luminosity, error_stellar_luminosity, planet_star_separation, error_planet_star_separation)[source]#
Calculate the Bond albedo and equilibrium temperature of a planet.
This routine computes the Bond albedo and equilibrium temperature of a planet based on the retrieved fluxes, stellar luminosity, and planet-star separation. It uses random sampling to account for uncertainties in stellar luminosity and planet-star separation.
- Parameters:
rp_object (retrieval_plotting_object) – An instance of the retrieval_plotting_object class containing the retrieved fluxes, posteriors, wavelengths, and known system properties. This object provides all necessary information for the calculation.
stellar_luminosity (float) – The stellar luminosity of the host star in solar luminosities (L_sun).
error_stellar_luminosity (float) – The uncertainty in the stellar luminosity, also in solar luminosities.
planet_star_separation (float) – The orbital distance between the planet and its host star in astronomical units (au).
error_planet_star_separation (float) – The uncertainty in the planet-star separation, also in astronomical units.
- Returns:
retrieved_equilibrium_temperature (numpy.ndarray): An array of equilibrium temperatures calculated for each sample in the posterior.
retrieved_bond_albedo (numpy.ndarray): An array of Bond albedos calculated for each sample in the posterior.
- Return type:
tuple
- Notes:
The Bond albedo is calculated using the planet’s equilibrium temperature and stellar luminosity, assuming energy balance between absorbed and emitted radiation.
The equilibrium temperature is derived by fitting a blackbody curve to the integrated flux of the planet.
- Methods:
Generates random samples of stellar luminosity and planet-star separation based on the provided errors to account for uncertainties.
Scales the retrieved planetary flux to account for distance and planetary radius.
Fits a blackbody spectrum to the integrated retrieved flux to compute the equilibrium temperature.
Uses the Stefan-Boltzmann law to compute the Bond albedo.
- calculate_profile_contours(rp_object, pressures_extrapolated, pressures, parameters_extrapolated, parameters, quantiles, plot_residual=False, smoothing=4, ax=None)[source]#
Calculate the contour profiles for a set of quantiles from pressure-temperature (P-T) profiles.
This function computes the contour lines corresponding to the specified quantiles for a set of pressure-temperature profiles (e.g., retrieved P-T profiles) and other atmospheric parameters. The contours represent the distribution of parameters (e.g., temperature, pressure) for the atmospheric layers at different quantile levels.
- Parameters:
rp_object (retrieval_plotting_object) – An instance of the retrieval_plotting_object class containing retrieved fluxes, posteriors, wavelengths, and known system properties. This object provides all necessary information for the calculation of the P-T profiles and other parameters.
pressures_extrapolated (ndarray) – An array representing the extrapolated pressure levels corresponding to the atmospheric layers for which quantiles are calculated.
pressures (ndarray) – An array representing the actual pressure levels of the retrieved profiles.
parameters_extrapolated (ndarray) – An array representing the extrapolated values of the atmospheric parameters (e.g., temperature, abundance) corresponding to each pressure level.
parameters (ndarray) – An array representing the retrieved atmospheric parameters (e.g., temperature, abundance) at different pressure levels.
quantiles (list) – A list of quantiles (e.g., [0.16, 0.5, 0.84]) for which to calculate the contours of the pressure-temperature profiles.
plot_residual (bool, optional) – A flag indicating whether to plot residuals (default is False). If True, the residuals (differences between the quantiles and the median) will be plotted.
smoothing (int, optional) – The smoothing factor applied to the contours (default is 4). A higher value increases the smoothness of the contours.
ax (matplotlib.axes.Axes, optional) – The axes object on which to plot the contours. If None, a new plot will be created.
- Returns:
A tuple containing: - pressure_contours: A list of arrays containing the pressure levels for each quantile contour. - parameter_contours: A list of arrays containing the corresponding atmospheric parameter values
(e.g., temperature, abundance) for each quantile contour.
pressure_max: The maximum pressure value from the contour calculation.
- Return type:
tuple
- Notes:
The function uses a 2D histogram to generate the initial surface pressure-temperature contours, which are then combined with the extrapolated P-T profile contours for the given quantiles.
The generate_quantile_color_levels and generate_color_map_from_levels functions are used to generate the color levels for contour plotting.
The smoothing parameter controls the degree of smoothing applied to the contour data.
The plot_residual flag enables plotting of residuals, which show the difference between the quantiles and the median profiles.
- calculate_profile_contours_new(data_extrapolated, pressures_extrapolated, pressures, volume_percentages=[0.3, 0.5, 0.7, 0.9], smoothing=3, data_lim=None, log_data=True, log_pressure=True, bins_data=None)[source]#
Calculate the contour profiles corresponding to specified volume percentages for a given set of extrapolated atmospheric data.
This function computes contour levels for atmospheric parameters (e.g., temperature, pressure) corresponding to specified volume percentages (e.g., 30%, 50%, 70%, 90%) within a set of pressure-temperature profiles. The contours are derived from a 2D histogram of the extrapolated data, smoothed to reduce noise, and then mapped to the desired volume percentages.
- Parameters:
data_extrapolated (ndarray) – An array representing the extrapolated atmospheric data (e.g., temperature, abundance) corresponding to each pressure level.
pressures_extrapolated (ndarray) – An array representing the extrapolated pressure levels corresponding to the atmospheric layers.
pressures (ndarray) – An array representing the actual pressure levels of the retrieved profiles.
volume_percentages (list, optional) – A list of volume percentages (default is [0.30, 0.50, 0.70, 0.90]) for which to calculate the contours of the atmospheric data.
smoothing (int, optional) – The smoothing factor applied to the contours (default is 3). A higher value increases the smoothness of the contours.
data_lim (list, optional) – Limits for the atmospheric data to avoid outliers or undefined values. The default is None, in which case it is automatically calculated.
log_data (bool, optional) – A flag indicating whether to log-transform the data values (default is True). If True, the data is log-transformed; otherwise, raw values are used.
log_pressure (bool, optional) – A flag indicating whether to log-transform the pressure values (default is True). If True, the pressures are log-transformed; otherwise, raw values are used.
bins_data (int, optional) – The number of bins for the data histogram (default is None). If None, it defaults to the number of layers.
- Returns:
A dictionary where the keys are the volume percentages and the values are dictionaries containing: - data_values: The smoothed data values corresponding to the contour. - pressure_values: The smoothed pressure values corresponding to the contour.
- Return type:
dict
- Notes:
The function first creates a 2D histogram from the extrapolated data and pressures, and applies a Gaussian filter for smoothing.
The contours are derived by finding the volume layer that corresponds to the specified volume percentages of the posterior distribution.
The smoothing parameter controls the degree of smoothing applied to the contour data.
If log_data or log_pressure is set to True, the data and pressure values are log-transformed before further analysis.
The function automatically sets values outside the specified limits (data_lim, pressure_lim) to NaN.
- parallel_pt_profile_calculation(rp_object, parameter_samples, skip=1, layers=500, p_surf=4, n_processes=None, process=None, use_truth=False)[source]#
Calculate Pressure-Temperature (PT) profiles for posterior distributions using parallel processing.
This function computes PT profiles corresponding to retrieved posterior parameter samples, utilizing an instance of the retrieval_plotting_object class for managing atmospheric and configuration data. Parallel processing is employed to enhance performance, and extrapolated profiles can be generated for additional atmospheric layers.
- Parameters:
rp_object (retrieval_plotting_object) – An instance of the retrieval_plotting_object class, which provides the necessary methods and data for assigning parameter values, calculating physical variables, and generating PT profiles.
parameter_samples (numpy.ndarray) – A 2D array of parameter samples from posterior distributions. Each row corresponds to a set of parameters.
skip (int, optional) – Interval for selecting parameter samples. For instance, skip=2 processes every second sample. Defaults to 1.
layers (int, optional) – Number of atmospheric layers for PT profile extrapolation. Defaults to 500.
p_surf (float, optional) – Logarithmic surface pressure value used for PT profile calculation. Defaults to 4.
n_processes (int, optional) – The number of parallel processes to use for computation. If None, the calculation is performed on a single CPU core. Defaults to None.
process (int, optional) – Identifier for the current process when executing in parallel. Defaults to None.
use_truth (bool, optional) – Flag indicating whether to use ground truth values for physical variables during calculations. Defaults to False.
- Returns:
A dictionary containing the computed PT profiles: - ‘pressures’: Pressure profiles for each parameter set, shape (size, n_layers). - ‘temperatures’: Temperature profiles for each parameter set, shape (size, n_layers). - ‘pressures_extrapolated’: Extrapolated pressure profiles, shape (size, layers). - ‘temperatures_extrapolated’: Extrapolated temperature profiles, shape (size, layers). - ‘pressures_cloud_top’: Cloud top pressures for each parameter set (if applicable). - ‘temperatures_cloud_top’: Cloud top temperatures for each parameter set (if applicable).
- Return type:
dict
- Notes:
The rp_object must be an instance of the retrieval_plotting_object class, properly initialized with required configuration settings, physical variables, and methods for PT profile calculations.
Progress updates and estimated time remaining are displayed for the master process (process=0).
- parallel_spectrum_calculation(rp_object, parameter_samples, skip=1, n_processes=None, process=None, use_truth=False, emission_contribution=True)[source]#
Calculate spectra for posterior distributions using parallel processing.
This function computes spectra corresponding to retrieved posterior parameter samples, utilizing an instance of the retrieval_plotting_object class for managing atmospheric and configuration data. It supports emission contribution and can account for additional fluxes, such as those from a moon.
- Parameters:
rp_object (retrieval_plotting_object) – An instance of the retrieval_plotting_object class, which provides the necessary methods and data for parameter assignment, PT profile calculation, abundance computation, and spectrum generation.
parameter_samples (numpy.ndarray) – A 2D array of parameter samples from posterior distributions. Each row corresponds to a set of parameters.
skip (int, optional) – Interval for selecting parameter samples. For instance, skip=2 processes every second sample. Defaults to 1.
n_processes (int, optional) – The number of parallel processes to use for computation. If None, the calculation is performed on a single CPU core. Defaults to None.
process (int, optional) – Identifier for the current process when executing in parallel. Defaults to None.
use_truth (bool, optional) – Flag indicating whether to use ground truth values for physical variables during calculations. Defaults to False.
emission_contribution (bool, optional) – If True, computes and stores the emission contribution for each layer in the atmosphere. Defaults to True.
- Returns:
A dictionary containing the calculated spectra and related data: - ‘wavelengths’: Array of wavelengths corresponding to the computed fluxes. - ‘gravity’: Gravitational acceleration for each parameter set. - ‘fluxes’: Flux spectra for each parameter set, shape (size, n_wavelengths). - ‘emission_contribution’: Emission contribution profiles for each layer, shape (size, n_layers, n_wavelengths)
(if applicable).
’moon_fluxes’: Flux contributions from the moon, if include_moon is enabled in rp_object.settings.
- Return type:
dict
- Notes:
The rp_object must be an instance of the retrieval_plotting_object class and initialized with required configuration settings, physical variables, and methods for spectrum calculations.
Progress updates and estimated time remaining are displayed for the master process (process=0).
- print_task_assignment(calculation_type, n_processes, dimension)[source]#
Print the task assignment details for parallel computation.
This function outputs the distribution of tasks among multiple processes, providing clarity on which range of calculations is assigned to each process.
- Parameters:
calculation_type (str) – A string indicating the type of calculation being performed (e.g., ‘PT-Profile’, ‘Spectrum’). Used in the printed output for context.
n_processes (int) – The total number of processes involved in the computation.
dimension (int) – The total number of calculations to be distributed among the processes.
- Returns:
None
- Return type:
None
- Notes:
The function divides the range [1, dimension] into approximately equal parts, one for each process, and prints the task range assigned to each process.
The output provides a clear summary of task distribution, which is helpful for debugging and monitoring parallel computations.
- task_assignment(calculation_type, n_processes, dimension, process)[source]#
Assign tasks to different processes for parallel computation.
This function divides a computational task into segments based on the number of processes and the total dimension of the task. Each process is assigned a range of indices to handle.
- Parameters:
calculation_type (str) – A string indicating the type of calculation being performed (e.g., ‘PT-Profile’, ‘Spectrum’). Used for informational purposes when printing task assignments.
n_processes (int or None) – The total number of processes available for computation. If None, no parallelization is assumed, and the entire task is assigned to a single process.
dimension (int) – The total number of items (e.g., samples) to be processed.
process (int or None) – The identifier of the current process. If None, defaults to single-process execution (process 0).
- Returns:
process (int): The process ID. Defaults to 0 if no parallelization is used.
ind_start (int): The starting index of the task range assigned to the process.
ind_end (int): The ending index (exclusive) of the task range assigned to the process.
- Return type:
tuple
- Notes:
If both n_processes and process are provided, the task is divided among the specified number of processes, and the range assigned to the given process is returned.
If either n_processes or process is None, the entire range [0, dimension) is assigned to a single process with ID 0.
For process=0, task assignment details are printed via the print_task_assignment function.
This module contains the RetrievalPlottingObject class, which is the main class used to generate plots of the pyretlife retrievals.
- generate_color_map_from_levels(Z, color_levels, level_thresholds)[source]#
Generate a colormap for a 2D histogram based on specified percentage levels.
This function creates a colormap by dividing the values in a 2D histogram (Z) into bins, identifying the bin ranges that correspond to specified percentage thresholds, and assigning colors from a predefined set of color levels to these bins. The function ensures that the colormap is scaled according to the cumulative counts in the histogram.
- Parameters:
Z (numpy.ndarray) – A 2D array representing the histogram counts. The values in Z represent the frequency or density in each bin of the histogram.
color_levels (numpy.ndarray) – A numpy array of RGBA color levels corresponding to the histogram bins. These colors will be applied to the histogram based on the percentage thresholds.
level_thresholds (list) – A list of thresholds representing percentage levels that divide the cumulative distribution of the histogram. For example, [0.16, 0.5, 0.84] for a 68% confidence interval.
- Returns:
map: The generated colormap.
norm: The normalization object used for mapping values to the colormap.
levels: A list of the bin counts that correspond to the specified threshold levels.
- Return type:
tuple
- Notes:
The function first sorts the histogram bins in ascending order and then identifies the bin values that correspond to the specified quantile thresholds.
The colormap is created using col.from_levels_and_colors, which requires predefined color levels.
The resulting colormap can be used in visualizations like contour plots or heatmaps where the color scale reflects the distribution of values in the 2D histogram.
- generate_quantile_color_levels(color, quantiles)[source]#
Generate color levels for a set of provided quantiles based on a base color.
This function calculates color levels corresponding to a set of quantiles, generating a smooth transition between the specified base color and its variations based on the quantile values. The color levels are represented as RGBA values, and the quantile thresholds are computed accordingly.
- Parameters:
color (str or tuple) – The base color for the levels. It can be provided as a string (e.g., ‘blue’), a hex code (e.g., ‘#0000FF’), or an RGB(A) tuple (e.g., (0, 0, 1, 1)).
quantiles (list) – A list of quantile values for which to generate the corresponding color levels. Typically, this might include quantiles like [0.16, 0.5, 0.84] for a 68% confidence interval.
- Returns:
color_levels: A numpy array of RGBA color levels corresponding to the specified quantiles.
level_thresholds: A list of the quantile thresholds for the color levels.
N_levels: The number of color levels calculated.
- Return type:
tuple
- Notes:
The color levels are generated by interpolating the base color across the quantile range.
The color transition is done in the RGB channels, and the alpha (opacity) is assumed to be constant for all levels.
This function is particularly useful for visualizing quantile-based data distributions in plots, such as in contour plots or heatmaps where different levels represent different quantile ranges.
- generate_uniform_color_map(color_map)[source]#
Generate a uniform colormap based on two input colors.
This function creates a colormap that smoothly transitions between two specified colors. The colormap is uniformly distributed and can be used for visualizations where a smooth gradient between two colors is desired.
- Parameters:
color_map (list or tuple) – A list or tuple containing two colors that define the start and end of the colormap. The colors can be specified in any valid format accepted by matplotlib.colors.to_rgba, such as a string (e.g., ‘red’, ‘#FF0000’), or a tuple of RGBA values (e.g., (1, 0, 0, 1)).
- Returns:
A colormap object that smoothly transitions between the two specified colors.
- Return type:
matplotlib.colors.ListedColormap
- Notes:
The function creates a smooth gradient of 1000 color levels between the two input colors.
The resulting colormap can be used for visualizations such as heatmaps or contour plots where a uniform color gradient is needed.
The input colors are expected to be in a format compatible with matplotlib.colors.to_rgba (e.g., hex, named colors).
- class Handles(text_props=None)[source]#
Bases:
HandlerBaseHandler class to create custom legend artists for various types of data representations.
This class defines how different data representations should appear in a legend, using custom markers and line styles. It supports multiple types of handles, including CloudTopPressure, SurfacePressure, ErrorBar, SNR, and others, each with their own visual representation in the legend.
- Parameters:
text_props (dict, optional) – A dictionary of text properties (e.g., font size, style) that can be applied to text in the legend. If not provided, defaults to an empty dictionary.
- create_artists(legend, orig_handle, x0, y0, width, height, fontsize, trans)[source]#
Creates custom legend artists (lines, markers, etc.) based on the original handle type. This method handles the visual representation of the data in the legend.
- create_artists(legend, orig_handle, x0, y0, width, height, fontsize, trans)[source]#
Create custom legend artists (lines, markers, etc.) based on the provided orig_handle.
This method generates the visual elements to represent various types of data in the legend, such as markers, lines, and patterns, for specific handle types like ‘CloudTopPressure’, ‘SurfacePressure’, ‘ErrorBar’, and others. Each type is customized with specific line styles, markers, and colors.
- Parameters:
legend (matplotlib.legend.Legend) – The legend instance to which the artists are being added.
orig_handle (str) – The original handle (identifier) for the data type being represented. For example, it could be a string like ‘CloudTopPressure’, ‘SNR5’, etc.
x0 (float) – The x-coordinate for the legend position.
y0 (float) – The y-coordinate for the legend position.
width (float) – The width of the legend entry.
height (float) – The height of the legend entry.
fontsize (float) – The font size for the legend text.
trans (matplotlib.transforms.Transform) – The transformation applied to the legend (e.g., scale or rotation).
- Returns:
A list of matplotlib Line2D objects or other artists that represent the custom legend entry.
- Return type:
list of matplotlib.artist.Artist
- class MulticolorPatch(colors, alpha)[source]#
Bases:
objectInitialize a MulticolorPatch object with specified colors and transparency.
This class represents a multicolor gradient patch that can be used in legends to display a gradient of colors with a specified level of transparency.
- Parameters:
colors (list of str or tuple) – A list of colors to be used in the patch. Each color can be specified as a string (e.g., ‘red’, ‘#FF0000’) or as an RGBA tuple (e.g., (1, 0, 0, 1)).
alpha (float) – The transparency level of the patch, ranging from 0 (completely transparent) to 1 (completely opaque).
- colors#
The list of colors used for the gradient in the patch.
- Type:
list of str or tuple
- alpha#
The transparency level of the patch.
- Type:
float
Notes
This class allows the creation of a color gradient with specified transparency, which can be used in plotting libraries like Matplotlib for creating customized legends or other visual representations where a gradient is needed.
- class MulticolorPatchHandler[source]#
Bases:
objectHandler for creating a legend artist for the MulticolorPatch object.
This class defines a custom handler for the MulticolorPatch object, which can be used to create a legend entry with a gradient of colors and transparency levels.
- legend_artist(legend, orig_handle, fontsize, handlebox):
Creates the legend artist, representing a gradient of colors with varying transparency, based on the original MulticolorPatch object.
- legend_artist(legend, orig_handle, fontsize, handlebox)[source]#
Create the legend artist for the MulticolorPatch.
This method creates a custom legend entry, which consists of a gradient of color patches representing the MulticolorPatch object in the legend.
- Parameters:
legend (matplotlib.legend.Legend) – The matplotlib.legend.Legend instance that holds the legend information.
orig_handle (MulticolorPatch) – The original handle, which is a MulticolorPatch object containing the colors and transparency levels for the gradient.
fontsize (int) – The font size for the legend text. It is currently unused in this method.
handlebox (matplotlib.legend.HandlerBase.HandleBox) – The matplotlib.legend.HandlerBase.HandleBox object, which provides the dimensions for the legend entry.
- Returns:
A collection of patch objects that form the custom legend entry.
- Return type:
matplotlib.collections.PatchCollection
- Notes:
This method creates a series of rectangles to represent the gradient of colors from the MulticolorPatch object. The transparency levels are also taken into account.
The method uses matplotlib.patches.Rectangle to create each color patch and matplotlib.collections.PatchCollection to group them together for the legend.
The returned PatchCollection can then be added to the legend in a Matplotlib plot.
This module contains the RetrievalPlottingObject class, which is the main class used to generate plots of the pyretlife retrievals.
- add_inlay_plot(loc_surface, ax, h_cover=0.45, Off_h=0.02)[source]#
Add an inset plot to a given axis at a specified location.
This function creates an inset plot (an inlay plot) within a larger plot and positions it according to the specified location. The inset plot is a smaller plot placed inside the original plot, and its size and position can be customized based on the given parameters.
- Parameters:
loc_surface (str) – The location of the inset plot relative to the main plot. Possible values are ‘lower left’, ‘lower right’, ‘upper left’, and ‘upper right’.
ax (matplotlib.axes.Axes) – The main matplotlib axis where the inset plot will be added.
h_cover (float, optional) – The height coverage of the inset plot as a fraction of the main plot height. Default is 0.45.
Off_h (float, optional) – The offset for the inset plot’s vertical position, as a fraction of the main plot height. Default is 0.02.
- Returns:
The axis object of the created inset plot.
- Return type:
matplotlib.axes.Axes
- add_inlay_plot_labels(ax2, ax2_xlabel, ax2_ylabel, loc_surface)[source]#
Add labels to the axes of an inset plot at a specified location.
This function adds the x and y axis labels to the inset plot and adjusts their positions based on the specified location of the inset plot within the main plot. It allows for customized positioning of axis labels in different corners of the plot.
- Parameters:
ax2 (matplotlib.axes.Axes) – The inset axis to which the labels will be applied.
ax2_xlabel (str) – The label for the x-axis of the inset plot.
ax2_ylabel (str) – The label for the y-axis of the inset plot.
loc_surface (str) – The location of the inset plot relative to the main plot. Possible values are ‘lower left’, ‘lower right’, ‘upper left’, and ‘upper right’.
- Returns:
None
- Return type:
None
This module contains the RetrievalPlottingObject class, which is the main class used to generate plots of the pyretlife retrievals.
- class parallel(num_proc)[source]#
Bases:
objectA class used to represent parallel function execution across multiple processes.
This class enables parallelization of a function across a specified number of processes using Python’s multiprocessing module. It manages the creation of processes, distributes tasks, and collects the results in a shared memory dictionary.
- num_proc#
The number of processes to be used for parallel execution.
- Type:
int
- manager#
A manager object to handle shared data between processes.
- Type:
mp.Manager
- result#
A dictionary to store the results from each process.
- Type:
mp.Manager.dict
- jobs#
A list of process objects representing the parallel tasks.
- Type:
list
- __init__(num_proc)[source]#
Initializes the parallel execution setup with the specified number of processes.
- calculate(results_directory, function, function_args)[source]#
Executes the given function in parallel across the specified number of processes.
- __worker(process, results_directory, function, function_args)#
The worker method executed by each process to run the given function and store the results.
- calculate(results_directory, function, function_args)[source]#
Executes the provided function in parallel using multiple processes.
This method initializes the processes, starts the calculations, and waits until all processes are done. The results are stored in a shared dictionary and returned once all processes finish.
- Parameters:
results_directory (str) – Directory where the results will be saved or accessed.
function (callable) – The function to be executed in parallel.
function_args (dict) – Arguments to be passed to the function.
- Returns:
A dictionary containing the results from each process.
- Return type:
dict
- Corner_Plot(parameters, data, titles, truths, quantiles1d=[0.16, 0.5, 0.84], quantiles2d=[0.025, 0.15, 0.25, 0.35, 0.65, 0.75, 0.85, 0.975], color='k', color_truth='C3', bins=50, add_table=False, ULU=None, ULU_lim=[-0.15, 0.75])[source]#
Generate a corner plot to visualize the distributions and correlations of parameters.
This function creates a corner plot for a set of parameters, displaying 1D histograms on the diagonal and 2D histograms below the diagonal to show correlations between pairs of parameters. The plot also includes optional vertical lines indicating quantiles, the option to overlay ground truth values, and an optional table of retrieved and true values with uncertainties. Customization options for color, bin size, and contour levels are also provided.
- Parameters:
parameters (list of str) – List of parameter names to be plotted (e.g., [‘param1’, ‘param2’, …]).
data (dict) – Dictionary where keys are parameter names and values are lists or arrays of parameter data.
titles (dict) – Dictionary where keys are parameter names and values are titles for the respective parameters.
truths (dict) – Dictionary of true parameter values, where keys match the parameter names. True values to be plotted as vertical lines.
quantiles1d (list of float, optional) – List of quantiles (0 to 1) to be marked on the 1D histograms as vertical lines. Default is [0.16, 0.5, 0.84].
quantiles2d (list of float, optional) – List of quantiles (0 to 1) for contour levels in the 2D histograms. Default is [0.025,0.15,0.25,0.35,0.65,0.75,0.85,0.975].
color (str, optional) – Color for the histograms and contours. Default is ‘k’ (black).
color_truth (str, optional) – Color for the vertical lines representing the true parameter values. Default is ‘C3’ (matplotlib default).
bins (int, optional) – Number of bins for the histograms. Default is 50.
add_table (bool, optional) – If True, adds a table showing true and retrieved parameter values with uncertainties. Default is False.
ULU (list of str, optional) – List of parameter names for which specific upper limit uncertainty correction should be applied. Default is None.
ULU_lim (list of float, optional) – Limits for the ULU correction (lower bound and smoothing factor). Default is [-0.15, 0.75].
- Returns:
The generated corner plot figure and axes.
- Return type:
tuple of (matplotlib.figure.Figure, numpy.ndarray of matplotlib.axes.Axes)
- Generate_Parameter_Titles(rp_object)[source]#
Generate and assign titles to parameters in the rp_object based on their type.
This function reads the parameters from the rp_object (an instance of retrieval_plotting_object) and assigns appropriate titles for each parameter depending on its type, such as “CHEMICAL COMPOSITION PARAMETERS”, “PHYSICAL PARAMETERS”, “TEMPERATURE PARAMETERS”, “MOON PARAMETERS”, or “CLOUD PARAMETERS”. The titles are formatted with LaTeX-style math formatting.
- Parameters:
rp_object (retrieval_plotting_object) – The retrieval_plotting_object instance that contains the parameters to be processed.
- Returns:
None
- Return type:
None
- Posterior_Plot(data, title, truth, quantiles1d=[0.16, 0.5, 0.84], color='k', color_truth='C3', bins=50, lw=2, ax=None, histtype='stepfilled', alpha=0.5, hatch=None, ULU=False, ULU_lim=[-0.15, 0.75])[source]#
Generate a posterior distribution plot with optional ground truth and quantiles.
This function creates a histogram of posterior parameter distributions with optional quantile lines, a vertical line for the ground truth value, and the option to apply upper limit uncertainty corrections (ULU). The plot can be customized with parameters such as color, histogram type, alpha transparency, and bin size.
- Parameters:
data (array-like or list) – Array-like or list containing the posterior parameter data.
title (str) – Title of the plot to describe the parameter being visualized.
truth (float or None) – Ground truth value to be marked with a vertical line on the plot. If None, no line is drawn.
quantiles1d (list of float, optional) – List of quantiles (0 to 1) to be marked on the histogram. Default is [0.16, 0.5, 0.84].
color (str, optional) – Color for the histogram. Default is ‘k’ (black).
color_truth (str, optional) – Color for the ground truth vertical line. Default is ‘C3’ (matplotlib default).
bins (int, optional) – Number of bins for the histogram. Default is 50.
lw (int, optional) – Line width for the plot. Default is 2.
ax (matplotlib.axes.Axes or None, optional) – Optional axes object for the plot. If None, a new figure and axis are created.
histtype (str, optional) – The type of histogram to draw. Default is ‘stepfilled’.
alpha (float, optional) – Transparency level for the histogram. Default is 0.5.
hatch (str or None, optional) – Pattern to hatch the histogram bars. Default is None (no hatch).
ULU (bool, optional) – If True, applies upper limit uncertainty correction to the data. Default is False.
ULU_lim (list of float, optional) – Limits for the ULU correction, specifying the lower bound and smoothing factor. Default is [-0.15, 0.75].
- Returns:
The figure and axes objects if ax is None, or the axes object and histogram data if ax is provided.
- Return type:
tuple of (matplotlib.figure.Figure, matplotlib.axes.Axes) or (matplotlib.axes.Axes, tuple)
- Note:
1. The quantiles1d parameter allows users to mark specific quantiles (e.g., 16%, 50%, and 84%) on the histogram, useful for displaying uncertainty ranges. 2. The ULU parameter, when set to True, applies a specific correction for upper limit uncertainties, which is useful in the case of censored data. 3. If truth is provided, the function will plot a vertical line at the ground truth value to help visually compare the estimated posterior distribution with the true value. 4. The plot will display the title with the median value and the 1-sigma uncertainties if quantiles are provided. 5. The hatch parameter allows for a pattern to be applied to the histogram bars, which can be useful for distinguishing multiple datasets or distributions.
- Scale_Posteriors(rp_object, local_post, local_truths, local_titles, parameters, log_pressures=True, log_mass=True, log_abundances=True, log_particle_radii=True)[source]#
Adjusts a local copy of the posterior for plotting.
This function modifies the local_post, local_truths, and local_titles dictionaries for plotting purposes, by applying logarithmic transformations to certain parameters based on their type. It allows customization for logarithmic scaling of abundances, particle radii, mass, and pressures in the posterior distribution.
- Parameters:
rp_object (retrieval_plotting_object) – The retrieval_plotting_object instance containing parameter types and units.
local_post (dict) – A dictionary containing the posterior values for each parameter.
local_truths (dict) – A dictionary containing the true values for each parameter.
local_titles (dict) – A dictionary containing the titles for each parameter.
parameters (list) – A list of parameters to adjust for plotting.
log_pressures (bool, optional) – Whether to apply a logarithmic transformation to pressures. Default is True.
log_mass (bool, optional) – Whether to apply a logarithmic transformation to mass. Default is True.
log_abundances (bool, optional) – Whether to apply a logarithmic transformation to abundances. Default is True.
log_particle_radii (bool, optional) – Whether to apply a logarithmic transformation to particle radii. Default is True.
- Returns:
The modified local_post, local_truths, and local_titles dictionaries.
- Return type:
tuple of dicts