Utility functions for TLS retrievals
Created on Wed May 10 12:34:45 2023
@author: caroline
Stellar retrieval utility functions
- stctm.stellar_retrieval_utilities.BIC(chi2, nDataPoints, nPara)
Calculate BIC
Adapted from auxbenneke/utilities.py Liddle, A.R., 2007. Information criteria for astrophysical model selection. Monthly Notices of the Royal Astronomical Society: Letters 377, L74–L78. https://doi.org/10.1111/j.1745-3933.2007.00306.x The BIC assumes that the data points are independent and identically distributed, which may or may not be valid depending on the data set under consideration
- Parameters:
chi2 (float) – chi2 of the model
nDataPoints (int) – number of data points
nPara (int) – number of fitted parameters
- Returns:
BIC – BIC value
- Return type:
float
- stctm.stellar_retrieval_utilities.Dlam_obs(Dlam, fspot, ffac, Fphot_int, Fspot_int, Ffac_int)
model for observed transit depth (Rackham+2018) wrapper around combine_components(…, mode=’depth’).
- stctm.stellar_retrieval_utilities.calc_stctm_model_and_integrate(Dlam, fspot, ffac, spec, model_wv, model_phot_fixR, model_spot_fixR, model_fac_fixR)
Same as Dlam_obs but returns both the model integrated in each obs. bandpass and the fixed-R model
- Parameters:
Dlam (bare-rock transit depth)
fspot (spot covering fraction)
ffac (facula covering fraction)
spec (planet spectrum)
model_wv (model wavelength array)
model_phot_fixR (photosphere model at fixed R)
model_spot_fixR (spot model at fixed R)
model_fac_fixR (faculae model at fixed R)
- Return type:
model integrated in each obs. bandpass, the fixed-R contaminated transit depth model
- stctm.stellar_retrieval_utilities.chainplot(samples, labels=None, nwalkers=None, fontsize=None, lw=1, stepRange=None)
Create a chain plot from the samples adapted from auxbenneke/utilities.py
- Parameters:
samples (numpy array) – array of shape (nsamp, npara) or (nwalkers, nsamp, npara)
labels (list of str, optional) – list of parameter names
nwalkers (int, optional) – number of walkers (if samples is of shape (nsamp, npara))
fontsize (int, optional) – font size to set
lw (int, optional) – line width
stepRange (list of two int, optional) – range of steps to plot (if None, plot all steps)
- Returns:
fig (matplotlib.figure.Figure) – figure object
axes (numpy array of matplotlib.axes.Axes)
- stctm.stellar_retrieval_utilities.combine_components(mode, base, fspot, ffac, Fphot, Fspot, Ffac, *, allow_excess=False, eps=1e-12)
Combine photosphere, spot, and facula components in either flux or depth space.
- Parameters:
mode ({"flux","depth"}) –
- “flux”: return scaled flux model:
base * [(1 - fspot - ffac) * Fphot + fspot * Fspot + ffac * Ffac]
- ”depth”: return contaminated transit depth:
base * 1 / (1 - fspot*(1 - Fspot/Fphot) - ffac*(1 - Ffac/Fphot)) (Rackham+2018)
base (float) – Scaling value: - flux mode: Fscale - depth mode: Dlam (bare/true transit depth)
fspot (float) – Covering fractions in [0,1). If fspot+ffac >= 1 and allow_excess=False, raises ValueError.
ffac (float) – Covering fractions in [0,1). If fspot+ffac >= 1 and allow_excess=False, raises ValueError.
Fphot (array_like) – Component flux arrays on the same wavelength grid (for “flux”) or arrays already integrated to the observed bins (for “depth”).
Fspot (array_like) – Component flux arrays on the same wavelength grid (for “flux”) or arrays already integrated to the observed bins (for “depth”).
Ffac (array_like) – Component flux arrays on the same wavelength grid (for “flux”) or arrays already integrated to the observed bins (for “depth”).
allow_excess (bool, optional) – If True, skip the fspot+ffac < 1 check.
eps (float, optional) – Small number to avoid division-by-zero when normalizing by Fphot.
- Returns:
Combined model (flux or contaminated depth), shape broadcast with inputs.
- Return type:
ndarray
- stctm.stellar_retrieval_utilities.config_get(cfg, table, key, default=None, required=True)
Helper to fetch nested TOML keys.
- Parameters:
cfg (dict of parameter values)
table (subsection in the TOML file)
key (key to fetch)
default (default value)
required (boolean: if True, raise error if the entry is missing.)
- Return type:
Fetched value for the key in the cfg file
- stctm.stellar_retrieval_utilities.convertIntensity(Iin, LambdaInput, InputUnit='W/(m**2*Hz)', WavelengthUnit='um', OutputUnit='W/(m**2*um)')
adapted from auxbenneke/radutils.py
- Parameters:
Iin (input intensity)
LambdaInput (input wavelength)
InputUnit (input unit (str))
WavelengthUnit (input wavelength unit (str))
OutputUnit (output unit (str))
- Return type:
Iout=Iin converted to OutputUnit
- stctm.stellar_retrieval_utilities.convertWave(inp, unit1, unit2)
adapted from auxbenneke/radutils.py
- Parameters:
inp (input array)
unit1 (input unit (str))
unit2 (output unit (str))
- Return type:
inp array converted to unit2
- stctm.stellar_retrieval_utilities.convertWaveToSi(inp, unit1)
adapted from auxbenneke/radutils.py
- Parameters:
inp (input array)
unit1 (input unit (str))
- Returns:
wavelength [m]
f [Hz]
wavenumber [1/m]
- stctm.stellar_retrieval_utilities.format_param_str(param, fitparanames=None, *, mode=None, include_fit_list=False, wrap_at=None)
Format a compact, human-readable summary of stellar and fitted parameters.
Works for both TLS retrieval (depth mode) and ExoTUNE (flux mode). If mode is not provided, it is inferred from the available keys in param.
- Parameters:
param (dict) – Dictionary of default/fitted parameter values.
fitparanames (list[str] or None) – Names of the parameters varied in the fit (optional, used only if include_fit_list=True).
mode ({"flux","depth",None}, optional) – “flux” for ExoTUNE (may include Fscale/errInfl), “depth” for TLS (may include Dscale). If None, inferred from keys present in param.
include_fit_list (bool) – If True, include a first line “Fitted params: […]”.
wrap_at (int or None) – If set, wraps the “Fitted params” line at ~wrap_at characters.
- Returns:
A multi-line summary string.
- Return type:
str
- stctm.stellar_retrieval_utilities.generate_PHOENIX_grid_fixedR(wv_target, wv_edges, feh=0.0, Teff_range=[], logg_range=[], Teffstep=20, loggstep=0.1, fname_save='', use_pymsg=True, pymsg_specgrid=None)
Generate a grid of PHOENIX models at fixed R for a range of temperatures and logg values
- Parameters:
wv_target (numpy 1d array) – target wavelength array
wv_edges (numpy 1d array) – wavelength edges of the target wavelength array
feh (float) – metallicity of the models
Teff_range (list of float) – range of temperatures for the grid (min, max)
logg_range (list of float) – range of logg values for the grid (min, max)
Teffstep (float) – step size in temperature
loggstep (float) – step size in logg
fname_save (str) – file name to save the grid
use_pymsg (bool) – True to use the pymsg package to load the models
pymsg_specgrid (msg.SpecGrid object) – pre-loaded from the file name of the targeted spectral models grid
- Returns:
Teffs_grid (numpy 1d array) – grid of temperatures
loggs_grid (numpy 1d array) – grid of logg values
models_grid (3d array) – grid of models with varying temperatures and loggs, at fixed R
- stctm.stellar_retrieval_utilities.get_and_plot_bestfitcorr_spec(spec, flat_st_ctm_models, bestfit, ind_bestfit, pad=0.25)
Correct the observed spectrum using the best-fit stellar contamination model and plot the corrected spectrum.
- Parameters:
spec (TransSpec object) – Observed spectrum object
flat_st_ctm_models (array-like) – Array of stellar contamination models from the posterior.
bestfit (pandas.Series or DataFrame) – DataFrame containing best-fit parameter values including ‘Dscale’.
ind_bestfit (int) – Index of the best-fit model in flat_st_ctm_models.
pad (float, default 0.25) – Padding to extend the x-axis plot limits.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib figure object.
ax (matplotlib.axes.Axes) – The axis with the corrected spectrum.
corrected_spec (object) – Spectrum object corrected by dividing out the best-fit model.
- stctm.stellar_retrieval_utilities.get_and_plot_residual_spec(spec, flat_st_ctm_models, ind_bestfit)
Compute and plot the residual spectrum after subtracting the best-fit stellar contamination model.
- Parameters:
spec (TransSpec object) – Observed spectrum object
flat_st_ctm_models (array-like) – Array of stellar contamination models from the posterior.
ind_bestfit (int) – Index of the best-fit model to subtract.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib figure object.
ax (matplotlib.axes.Axes) – The axis with the plotted residual spectrum.
residual_spec (object) – The spectrum object with residual values (original - best-fit model).
- stctm.stellar_retrieval_utilities.get_and_plot_stctmcorr_spec(spec, flat_st_ctm_models, samples, fitparanames, nsamp=1000, pad=0.25)
Correct the observed spectrum using an ensemble of posterior stellar contamination models and plot the result.
- Parameters:
spec (TransSpec object) – Observed spectrum object
flat_st_ctm_models (ndarray) – Array of stellar contamination spectra from the posterior.
samples (pandas.DataFrame) – Posterior samples, including ‘Dscale’ values.
fitparanames (list of str) – Names of the fitted parameters (not directly used but included for consistency).
nsamp (int, default 1000) – Number of posterior samples to use for correction.
pad (float, default 0.25) – Padding to extend the x-axis plot limits.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib figure object.
ax (matplotlib.axes.Axes) – Axis with the plotted corrected spectrum.
spec_stctmcorr (object) – Corrected spectrum object, updated with uncertainty from posterior correction.
- stctm.stellar_retrieval_utilities.get_closest_models_from_grid(param, models_grid_fixedR, T_grid, logg_grid)
Given the parameter values, get the closest stellar model in terms of Teff, logg
- Parameters:
param (dict) – dictionary of default param values.
grid_models_fixedresP (numpy array) – grid of fixed-resolution models to choose from.
T_grid (numpy 1d array) – grid of temperatures for the grid of models (models_grid)
logg_grid (numpy 1d array) – grid of loggs for the grid of models (models_grid)
- Return type:
tuple containing photosphere, spot, and faculae model flux
- stctm.stellar_retrieval_utilities.get_default_logg(params)
Get the default values for the stellar and heterogeneity log g
- Parameters:
params (dict)
file (Dictionary obtained when reading in the ini)
- Return type:
None (dictionary updated in place with 2 more entries)
- stctm.stellar_retrieval_utilities.get_derived_param(param)
Compute derived stellar/fit parameters from the input dictionary.
- Parameters:
param (dict) – Dictionary of default/fitted parameter values.
- Returns:
Updated dictionary with derived parameters added/overwritten.
- Return type:
dict
- stctm.stellar_retrieval_utilities.get_labels_from_fitparanames(fitparanames)
Get the labels for the corner plot from the fit parameter names
- Parameters:
fitparanames (labels of fitted parameters in the retrieval)
- Return type:
labels to use in the corner plot
- stctm.stellar_retrieval_utilities.get_labels_from_fitparanames_master(fitparanames, include_units=False)
Build LaTeX labels for corner/trace plots, accepting SRU and XTU param names.
- Parameters:
fitparanames (list[str])
include_units (bool) – If True, include [K] on temperature-related labels (XTU style). If False, omit units (SRU style).
- Returns:
list[str]
- Return type:
labels aligned with fitparanames
- stctm.stellar_retrieval_utilities.get_param_priors(param, gaussparanames, hyperp_gausspriors=[], fitLogfSpotFac=[False, False], hyperp_logpriors=[], T_grid=[2300.0, 10000.0], logg_grid=[2.5, 5.5], Dscale_guess=7000.0)
Get parameter priors for the stellar retrieval.
- Parameters:
param (dict) – Dictionary of default parameter values.
gaussparanames (list of str) – List of parameter names that have Gaussian priors.
hyperp_gausspriors (list of lists, optional) – List of [mean, std] for each Gaussian prior parameter.
fitLogfSpotFac (list of bool, optional) – List of two booleans indicating if fspot and ffac are fitted in log space.
hyperp_logpriors (list of lists, optional) – List of [min, max] for log priors on heterogeneity fractions.
T_grid (list of float, optional) – Temperature grid for the stellar models. Default is [2300., 10000.].
logg_grid (list of float, optional) – Log g grid for the stellar models. Default is [2.5, 5.5].
Dscale_guess (float, optional) – Initial guess for the Dscale parameter (for TLS retrieval). Default is 7000.
- Returns:
Dictionary of parameter priors in the form of [low, high] for uniform priors.
- Return type:
dict
- stctm.stellar_retrieval_utilities.get_param_priors_master(param, gaussparanames, hyperp_gausspriors=None, fitLogfSpotFac=(False, False), hyperp_logpriors=None, T_grid=(2300.0, 10000.0), logg_grid=(2.5, 5.5), mode='flux', Fscale_guess=1.0, Dscale_guess=7000.0)
Query for parameter prior values.
- Parameters:
param (dict) – dictionary of default param values.
gaussparanames (list of str) – list of the fitted parameters with Gaussian priors.
hyperp_gausspriors (list of lists) – list of [mean, std] for all the Gauss prios
fitLogfSpotFac (list of bool) – list of two bools, first is True if fspot is fitted in log space, second is True if ffac is fitted in log space.
hyperp_logpriors (list of lists) – list of [min, max] for all the log priors
T_grid (numpy 1d array) – grid of temperatures for the grid of models (models_grid)
logg_grid (numpy 1d array) – grid of loggs for the grid of models (models_grid)
mode (str) – “flux” for ExoTUNE, “depth” for TLS Retrieval.
Fscale_guess (float) – Initial guess for Fscale parameter (for exotune). Default is 1.0.
Dscale_guess (float) – Initial guess for Dscale parameter (for TLS retrieval). Default is 7000.
- Return type:
dictionary of parameter priors in the form of [low, high] for uniform priors.
- stctm.stellar_retrieval_utilities.get_percentile_blobs(arr, percentiles=(0.2, 2.3, 15.9, 50.0, 84.1, 97.7, 99.8), axis=0)
Compute percentile envelopes along a samples axis.
- Parameters:
arr (ndarray) – Array of model outputs with the samples dimension along axis.
percentiles (sequence of float, optional) – Percentiles (0–100) to compute. Defaults to ~±1/2/3σ plus median for a Gaussian.
axis (int, optional) – Axis corresponding to samples (default 0).
- Returns:
Percentile slices with shape: (len(percentiles), …) where the samples axis is reduced.
- Return type:
ndarray
- stctm.stellar_retrieval_utilities.get_stctm_amplitude(spec, stctm_percentiles)
Get amplitude of stellar contamination signature from the retrieval
- Parameters:
spec (TransSpec object)
stctm_percentiles (spectra obtained for each of the computed percentiles)
- Return type:
amplitude of the stellar contamination component at 1, 2, 3 sigma
- stctm.stellar_retrieval_utilities.get_stctm_blobs(stctm_models_blobs, percentiles=[0.2, 2.3, 15.9, 84.1, 97.7, 99.8])
Get the median, 1, 2 and 3sigma prediction spectrum from the blobs
- Parameters:
stctm_models_blobs (array of blobs)
percentiles (list of percentiles to compute)
- Return type:
spectrum corresponding to each percentile
- stctm.stellar_retrieval_utilities.get_stellar_model_grid(input_para, preprocessed=False)
Load a stellar model grid based on user-defined input parameters.
- Parameters:
input_para (dict) – dictionary of input parameters
preprocessed (bool) – whether or not the parameter ranges already have the right format
- Returns:
A tuple containing: - wv_template_thisR: ndarray, wavelength array - wv_template_edges_thisR: ndarray, wavelength bin edges - models_grid_fixedR: ndarray, model grid values
- Return type:
tuple
- stctm.stellar_retrieval_utilities.init_default_and_fitted_param(Tphot, met, logg_phot, fitspot=True, fitfac=True, fitThet=False, fitTphot=False, fitDscale=False, fitlogg_phot=False, fitlogg_het=False, fitLogfSpotFac=[0, 0], Dscale_guess=7000, logg_het_guess=None)
Initialize default and fitted parameters.
- Parameters:
Tphot (float) – photosphere temperature in K.
met (float) – log stellar metallicity.
logg_phot (float) – log surface gravity of the star (photosphere)
fitspot (bool) – True to include spots in the model.
fitfac (bool) – True to include faculae in the mode.
fitThet (bool) – True to fit temperature(s) of heterogeneity(ies).
fitTphot (bool) – True to fit stellar photosphere temperature
fitDscale (bool) – True to fit for the scaling factor D. Default is False.
fitlogg_phot (bool) – True to fit for logg_phot. Default is False.
fitlogg_het (bool) – True to fit for logg_het. Default is False.
fitLogfSpotFac (list of bool) – list of two bools, first is True if fspot is fitted in log space, second is True if ffac is fitted in log space.
Dscale_guess (float) – Initial guess for Dscale parameter. Default is 7000.
logg_het_guess (float) – Initial guess for logg_het. Default is None.
- Return type:
dict of default param values and list of fitted parameters.
- stctm.stellar_retrieval_utilities.init_default_and_fitted_param_fromDict(input_para, Dscale_guess=7000)
Use an input dictionary to initialize default and fitted parameters
- Parameters:
input_para (dict) – dictionary of input parameters
Dscale_guess (float) – Initial guess for Dscale parameter. Default is 7000.
- Return type:
dict of default param values and list of fitted parameters.
- stctm.stellar_retrieval_utilities.integ_model(lam_min, lam_max, wave, F)
Integrate model in wavelength range (bin-averaged)
- Parameters:
lam_min (-)
lam_max (-)
wave (-)
F (-)
- Return type:
integral of F over the wavelength range
- stctm.stellar_retrieval_utilities.lnlike(theta, param, fitparanames, spec, models_baseline, T_grid, logg_grid, model_wv, models_grid)
log-likelihood function
- Parameters:
theta (array) – array of fitted parameter values.
param (dict) – dictionary of values for all the model parameters.
fitparanames (list of str) – list of the fitted parameters.
spec (spectrum data)
models_baseline (list of arrays) – baseline models for the photosphere, spots, and faculae at fixed R.
T_grid (numpy 1d array) – grid of temperatures for the grid of models (models_grid)
logg_grid (numpy 1d array) – grid of loggs for the grid of models (models_grid)
model_wv (numpy 1d array) – wavelength array of fixed R models
models_grid (3d array) – grid of models with varying temperatures and loggs, at fixed R
- Returns:
ln likelihood value for parameters theta.
- Return type:
int
- stctm.stellar_retrieval_utilities.lnprior(theta, param, fitparanames, gaussparanames, hyperp_gausspriors, fitLogfSpotFac, hyperp_logpriors, T_grid, logg_grid, Dscale_guess)
log-prior function
- Parameters:
theta (array) – array of fitted parameter values.
param (dict) – dictionary of values for all the model parameters.
fitparanames (list of str) – list of the fitted parameters.
gaussparanames (list of str) – list of the fitted parameters with Gaussian priors.
hyperp_gausspriors (list of lists) – list of [mean, std] for all the Gauss prios
fitLogfSpotFac ([True/False, True/False]) – first item is True if fspot is fitted in log space, second item is True if ffac is fitted in log space.
hyperp_logpriors (list of lists) – list of [min, max] for all the log priors
T_grid (numpy 1d array) – grid of temperatures for the grid of models (models_grid)
logg_grid (numpy 1d array) – grid of loggs for the grid of models (models_grid)
Dscale_guess (float) – initial guess for Dscale
- Returns:
ln prior value for parameters theta.
- Return type:
int
- stctm.stellar_retrieval_utilities.lnprob(theta, spec, param, fitparanames, gaussparanames, hyperp_gausspriors, fitLogfSpotFac, hyperp_logpriors, models_baseline_fixR, T_grid, logg_grid, model_wv, models_grid_fixR)
log-probability function
- Parameters:
theta (array) – array of fitted parameter values.
spec (transmission spectrum data)
param (dict) – dictionary of values for all the model parameters.
fitparanames (list of str) – list of the fitted parameters.
gaussparanames (list of str) – list of the fitted parameters with Gaussian priors.
hyperp_gausspriors (list of lists) – list of [mean, std] for all the Gauss prios
fitLogfSpotFac ([True/False, True/False]) – first item is True if fspot is fitted in log space, second item is True if ffac is fitted in log space.
hyperp_logpriors (list of lists) – list of [min, max] for all the log priors
models_baseline_fixR (list of arrays) – baseline models for the photosphere, spots, and faculae at fixed R.
T_grid (numpy 1d array) – grid of temperatures for the grid of models (models_grid)
logg_grid (numpy 1d array) – grid of loggs for the grid of models (models_grid)
model_wv (numpy 1d array) – wavelength array of fixed R models
models_grid_fixR (3d array) – grid of models with varying temperatures and loggs, at fixed R
- Returns:
ln probability value for parameters theta.
- Return type:
float
- stctm.stellar_retrieval_utilities.load_phoenix_model(Teff, M, logG, wv_target=None, wv_edges=None, resPower_target=None, wv_min_um=0.2, wv_max_um=6.0, use_pymsg=True, pymsg_specgrid=None)
Load a PHOENIX model given stellar model parameters
- Parameters:
Teff (float) – Star effective temperature.
M (float) – Star metallicity.
logG (float) – Star log g.
wv_target (array, optional) – Target wavelength array. The default is None.
wv_edges (array, optional) – Wavelength edges for pymsg. The default is None.
resPower_target (float, optional) – Target wavelength array resolving power
wv_min_um (float, optional) – min wavelength of the array, in um. The default is 0.2.
wv_max_um (float, optional) – max wavelength of the array, in um. The default is 6.0.
use_pymsg (bool, optional) – whether or not to use pymsg to load the model
pymsg_specgrid (msg.SpecGrid() object) – pymsg grid already loaded from file name
- Returns:
wavePhoenix (array) – wavelength array.
fStarSurfPhoenix (array) – flux array.
- stctm.stellar_retrieval_utilities.load_phoenix_models_from_param(param, resPower_target=10000, use_pymsg=True, pymsg_specgrid=None)
Load the Phoenix models for the photosphere, spots, and faculae from the parameter values
- Parameters:
param (dict) – dictionary of default param values.
resPower_target (int) – target resolution of the models
use_pymsg (bool) – True to use the pymsg package to load the models
pymsg_specgrid (msg.SpecGrid object) – pre-loaded from the file name
- Returns:
model_wv (numpy 1d array) – wavelength array of the models
model_fl_phot_spot_fac (tuple of arrays) – tuple of arrays containing the photosphere, spots, and faculae models
- stctm.stellar_retrieval_utilities.make_wavelength_array(wv_min_um=0.2, wv_max_um=6.0, resPower=1000, use_pymsg=True)
- Parameters:
wv_min_um (float, optional) – min wavelength of the array, in um. The default is 0.2.
wv_max_um (float, optional) – max wavelength of the array, in um. The default is 6.0.
resPower (float, optional) – target resPower. The default is 1000.
use_pymsg (bool, optional) – whether or not the wave edges should be returned for pymsg
- Return type:
wavelength array at the specified resolving power
- stctm.stellar_retrieval_utilities.parse_all_input_iniFile(iniFile)
Parse a TOML (new, preferred) file, or a legacy INI configuration file and command-line style arguments into a parameter dictionary.
- Parameters:
iniFile (str) – Path to the INI configuration file
- Returns:
params – A dictionary where keys are parameter names and values are parsed from the INI file. This dictionary can be used directly in downstream modeling and fitting code (after a bit of further parsing).
- Return type:
dict
- stctm.stellar_retrieval_utilities.parse_gaussian_inputs(input_para)
Parse Gaussian parameter names and corresponding hyperparameter priors.
- Parameters:
input_para (dict) – dictionary of input parameters
- Returns:
- gaussparanamesnp.ndarray
Array of parameter names.
- hyperp_gausspriorslist of lists
List of [mean, std] values for each parameter.
- Return type:
tuple
- stctm.stellar_retrieval_utilities.parse_range_string(s, as_type=<class 'float'>, sep=None, allow_single=False)
Convert a string representing numbers into a list of typed values.
- Parameters:
s (str) – Typical forms: “1.4_5.4”, “1.4 5.4”, “1.4,5.4”.
as_type (type, optional) – Type to cast each token to (float or int). Default: float.
sep (str or None, optional) – Explicit separator. If None, tries ‘_’, then ‘,’, then whitespace.
allow_single (bool, optional) – If True, returns a one-element list if only one number is present. Otherwise, requires at least two numbers.
- Returns:
List of numbers cast to as_type.
- Return type:
list
- Raises:
ValueError – If input is empty, not a string, or cannot be parsed into the required number of values.
- stctm.stellar_retrieval_utilities.plot_blobs_spectrum(spec, model_blobs, ind_bestfit, *, ax=None, kind='stctm', bestfit_color='k', color='b', plot3sig=True, plot2sig=True, plot1sig=True, plotmedian=True, plotbestfit=True, legend_loc=1, save_csv=False, results_folder='', runname='', percentiles=(0.2, 2.3, 15.9, 50.0, 84.1, 97.7, 99.8))
Plot spectra obtained from the retrieval with uncertainty from blobs.
- Parameters:
spec (TransSpec-like or StellSpec-like object) – Must support .plot(ax=…) and expose wavelength as either spec[‘wave’] or spec.wave.
model_blobs (array-like) – array of model outputs sampled from the posterior distribution.
ind_bestfit (int) – Index of the max-like model in stctm_models_blobs
ax (matplotlib.axes.Axes, optional) – Matplotlib axis object to plot on. If None, a new axis is created.
bestfit_color (str, default 'k') – Color used to plot the best-fit model.
color (str, default 'b') – Color used for median, 1, 2, 3 sigma contours.
plot3sig (bool, default True) – If True, plot the 3-sigma uncertainty region.
plot2sig (bool, default True) – If True, plot the 2-sigma uncertainty region.
plot1sig (bool, default True) – If True, plot the 1-sigma uncertainty region.
plotmedian (bool, default True) – If True, plot the median model prediction.
plotbestfit (bool, default True) – If True, plot the best-fit model.
legend_loc (int, default 1) – Location of the legend in the plot (uses matplotlib legend location codes).
save_csv (bool, default False) – If True, save a CSV file with the quantiles and best-fit predictions.
results_folder (str, optional) – Directory path where the CSV file should be saved (if save_csv=True).
runname (str, optional) – Base name used for the saved CSV file (if save_csv=True).
- Returns:
ax – The axis object with the plot drawn on it.
- Return type:
matplotlib.axes.Axes
- stctm.stellar_retrieval_utilities.plot_corner(samples, plotparams, plot_datapoints=False, smooth=1.0, quantiles=[0.16, 0.5, 0.84], title_kwargs={'fontsize': 12}, hist_kwargs={'linewidth': 3}, rg=None, show_titles=True, levels=(0.393, 0.865, 0.989), **kwargs)
Corner plot for an emcee fit of the water mass fraction that matches the observed planet params
- Parameters:
samples (generated by emcee sampler)
plotparams (plot params)
args (other)
- Return type:
figure with the corner plot
- stctm.stellar_retrieval_utilities.plot_corner_master(samples, *, labels=None, color='coral', plot_datapoints=False, smooth=1.0, quantiles=(0.16, 0.5, 0.84), title_kwargs=None, hist_kwargs=None, rg=None, show_titles=True, levels=(0.393, 0.865, 0.989), truths=None, truth_color='k', **kwargs)
One master for both TLS and exotune retrieval corner plots.
Parameters largely mirror corner.corner. - samples can be a numpy array or a pandas DataFrame. - labels: if None and samples is a DataFrame, uses DataFrame columns.
- Returns:
fig
- Return type:
matplotlib.figure.Figure
- stctm.stellar_retrieval_utilities.plot_custom_corner(samples, fitparanames, parabestfit)
Plot a custom corner plot with the parameters in a specific order
- Parameters:
samples (array of posterior samples)
fitparanames (labels for the fitted parameters)
parabestfit (fitted parameters for the best-fit model)
- Returns:
fig – The matplotlib figure object.
- Return type:
matplotlib.figure.Figure
- stctm.stellar_retrieval_utilities.plot_maxlike_and_maxprob(spec, param, parabestfit, ind_maxprob, ind_bestfit, fitparanames, models_flat, *, pad=0.25, legend_loc=4, title='Best-fit model', best_label='Max. Likelihood', prob_label='Max. Probability', best_color='r', prob_color='slateblue', best_alpha=0.6, prob_alpha=1.0, best_marker='.', prob_marker='o', best_ms=50, prob_ms=30, show_param_text=True, formatter=None, include_units=False, text_xy=None, text_rel=(0.02, 0.92), text_fontsize=10, text_color='k', text_bbox=None, text_ha='left', text_va='top')
Plot the maximum likelihood and maximum probability stellar contamination model spectra. Works with TLS retrieval dict-like spec (spec[“wave”]) or exotune-retrieval attribute spec (spec.wave).
- Parameters:
spec (TransSpec object) – Observed spectrum object
param (dict) – Default parameter dictionary to be updated with the best-fit values.
parabestfit (array-like) – Best-fit parameter values from the retrieval.
ind_maxprob (int) – Index of the highest posterior probability model in flat_st_ctm_models.
ind_bestfit (int) – Index of the maximum likelihood model in flat_st_ctm_models.
fitparanames (list of str) – Names of parameters included in the fit.
flat_st_ctm_models (array-like) – Array of stellar contamination models from the posterior.
pad (float, default 0.25) – Padding around wavelength range for plot limits.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib figure object.
ax (matplotlib.axes.Axes) – The axis with the plotted spectrum.
- stctm.stellar_retrieval_utilities.plot_stctm_amplitude(spec, stctm_models_blobs, ax=None, color='b', plot3sig=True, plot2sig=True, plot1sig=True)
Plot the amplitude of the stellar contamination signature from the retrieval
- Parameters:
spec (TransSpec object) – Observed planet spectrum
stctm_models_blobs (array) – Blobs containing the models integrated within the bandpass of each data point
ax (matplotlib.axes.Axes, optional) – Matplotlib axis object to plot on. If None, a new figure and axis are created.
color (str, default 'b') – Base color for uncertainty shading and median spectrum line.
plot3sig (bool, default True) – If True, plot the 3-sigma (99.8%) confidence region.
plot2sig (bool, default True) – If True, plot the 2-sigma (95.4%) confidence region.
plot1sig (bool, default True) – If True, plot the 1-sigma (68.3%) confidence region.
- Returns:
fig (matplotlib.figure.Figure or None) – The matplotlib figure object. None if an existing axis was passed.
ax (matplotlib.axes.Axes) – The axis containing the plot.
- stctm.stellar_retrieval_utilities.plot_stctm_blobs(spec, stctm_models_blobs, ind_bestfit, ax=None, bestfit_color='k', color='b', plot3sig=True, plot2sig=True, plot1sig=True, plotmedian=True, plotbestfit=True, legend_loc=1, save_csv=False, results_folder='', runname='')
Plot spectra obtained from the retrieval with uncertainty from blobs.
- Parameters:
spec (TransSpec object) – (planet atmosphere observations in transmission)
stctm_models_blobs (array-like) – array of model outputs sampled from the posterior distribution.
ind_bestfit (int) – Index of the max-like model in stctm_models_blobs
ax (matplotlib.axes.Axes, optional) – Matplotlib axis object to plot on. If None, a new axis is created.
bestfit_color (str, default 'k') – Color used to plot the best-fit model.
color (str, default 'b') – Color used for median, 1, 2, 3 sigma contours.
plot3sig (bool, default True) – If True, plot the 3-sigma uncertainty region.
plot2sig (bool, default True) – If True, plot the 2-sigma uncertainty region.
plot1sig (bool, default True) – If True, plot the 1-sigma uncertainty region.
plotmedian (bool, default True) – If True, plot the median model prediction.
plotbestfit (bool, default True) – If True, plot the best-fit model.
legend_loc (int, default 1) – Location of the legend in the plot (uses matplotlib legend location codes).
save_csv (bool, default False) – If True, save a CSV file with the quantiles and best-fit predictions.
results_folder (str, optional) – Directory path where the CSV file should be saved (if save_csv=True).
runname (str, optional) – Base name used for the saved CSV file (if save_csv=True).
- Returns:
fig (matplotlib.figure.Figure)
ax (matplotlib.axes.Axes) – The axis object with the plot drawn on it.
- stctm.stellar_retrieval_utilities.plot_stctm_samples_res(spec, param, fitparanames, ind_bestfit, post_burnin_samples, T_grid, logg_grid, modelgrid_wave, grid_models_fixedresP, sample_spectra=None, modelgrid_resP=10000, target_resP=100, N_samp=1000, ax=None, bestfit_color='k', color='b', plot3sig=True, plot2sig=True, plot1sig=True, plotmedian=True, plotbestfit=True, legend_loc=1, save_csv=True, results_folder='', runname='')
Plot model spectra at chosen fixed R from a stellar contamination retrieval
This function generates a forward-modeled stellar contamination spectrum using either provided sample spectra or by computing spectra from posterior samples. It plots the median, 1/2/3-sigma confidence intervals, and optionally the maximum likelihood (best-fit) spectrum.
- Parameters:
spec (TransSpec object) – (planet atmosphere observations in transmission)
param (dict) – Dictionary of default or initialized model parameters.
fitparanames (list of str) – Names of parameters varied in the fit.
ind_bestfit (int) – Index of the maximum likelihood (best-fit) sample in post_burnin_samples.
post_burnin_samples (pandas.DataFrame) – Posterior samples (after burn-in)
T_grid (array-like) – Grid of stellar temperatures used to interpolate model spectra
logg_grid (array-like) – Grid of surface gravities used to index model spectra.
modelgrid_wave (array-like) – Wavelength grid corresponding to the model grid spectra.
grid_models_fixedresP (ndarray) – Array containing model spectra at fixed resolution, indexed by temperature and gravity.
sample_spectra (ndarray, optional) – Pre-computed array of posterior model spectra (shape: [N_samp, n_wave]). If None, spectra are generated from samples.
modelgrid_resP (int, default 10000) – Resolving power of the model grid (used to determine convolution kernel width).
target_resP (int, default 100) – Target resolving power for the final spectrum, used for spectral convolution.
N_samp (int, default 1000) – Number of posterior samples to draw for uncertainty estimation.
ax (matplotlib.axes.Axes, optional) – Matplotlib axis object to plot on. If None, a new figure and axis are created.
bestfit_color (str, default 'k') – Line color for the best-fit model spectrum.
color (str, default 'b') – Base color for uncertainty shading and median spectrum line.
plot3sig (bool, default True) – If True, plot the 3-sigma (99.8%) confidence region.
plot2sig (bool, default True) – If True, plot the 2-sigma (95.4%) confidence region.
plot1sig (bool, default True) – If True, plot the 1-sigma (68.3%) confidence region.
plotmedian (bool, default True) – If True, plot the median model spectrum.
plotbestfit (bool, default True) – If True, plot the best-fit (maximum likelihood) spectrum.
legend_loc (int, default 1) – Location of the legend (matplotlib legend code).
save_csv (bool, default True) – If True, save a CSV file with the best-fit and quantile spectra.
results_folder (str, optional) – Path to the folder where results (CSV) should be saved.
runname (str, optional) – Custom string used in the saved CSV file name.
- Returns:
fig (matplotlib.figure.Figure or None) – The matplotlib figure object. None if an existing axis was passed.
ax (matplotlib.axes.Axes) – The axis containing the plot.
sample_spectra (ndarray) – Array of model spectra generated from posterior samples.
- stctm.stellar_retrieval_utilities.samp2bestfit(samp)
- Parameters:
samp (pandas dataframe containing the posterior samples)
- Return type:
pandas dataframe containing statistical info on the posterior
- stctm.stellar_retrieval_utilities.save_bestfit_stats(spec, ind_bestfit, fitparanames, flat_models, results_folder, runname, prefix='stctm', save_fit=True)
Compute and save summary statistics (chi2, red-chi2, BIC) for the best-fit model.
- Parameters:
spec (dict-like or object) – Observed spectrum. Must provide observed values and uncertainties as either keys (“yval”, “yerrLow”) or attributes (yval, yerrLow).
ind_bestfit (int) – Index of the best-fit model.
fitparanames (list of str) – Names of the fit parameters (used for degrees of freedom).
flat_models (ndarray) – Array of model spectra (post-burn-in).
results_folder (str) – Path to save the output.
runname (str) – Identifier for this run.
prefix (str, default="stctm") – Filename prefix to distinguish different pipelines (“stctm”, “exotune”).
save_fit (bool, default=True) – If True, writes results to CSV.
- Returns:
Table with chi2, redchi2, BIC, etc.
- Return type:
astropy.table.Table
- stctm.stellar_retrieval_utilities.save_mcmc_to_pandas(results_folder, runname, sampler, burnin, ndim, fitparanames, save_fit, prefix='stctm')
Save the MCMC results to Pandas DataFrame, Astropy Table, and CSVs.
- Parameters:
results_folder (str) – Path to the directory where output files should be saved.
runname (str) – Identifier for this run.
sampler (emcee.EnsembleSampler) – The MCMC sampler containing the chains and log-probabilities.
burnin (int) – Number of steps per walker to discard as burn-in.
ndim (int) – Number of fitted parameters.
fitparanames (list of str) – Names of the fitted parameters.
save_fit (bool) – If True, write CSV files for the samples and best-fit parameters.
prefix (str, optional) – Prefix to use in output filenames (“stctm” or “exotune”).
- Returns:
bestfit (pandas.DataFrame) – DataFrame containing best-fit parameter values (including MaxLike).
ind_bestfit (int) – Index of the median/quantile-based best fit sample.
ind_maxprob (int) – Index of the maximum-likelihood sample.
parabestfit (ndarray) – Parameter values corresponding to the MaxLike sample.
samples (pandas.DataFrame) – Flattened MCMC samples after burn-in.
t_res (astropy.table.Table) – Astropy table representation of the samples.
- stctm.stellar_retrieval_utilities.save_ref_files(this_dir, this_script, iniFile, utils_script, res_dir, names=None, verbose=True, preserve_meta=True)
Copy the main run script, INI file, and a utilities script into res_dir.
- Parameters:
this_dir (str) – Directory where the source files live (may be ‘’ if paths are absolute).
this_script (str) – Filename of the main run script (e.g., ‘stellar_retrieval_runfile.py’).
iniFile (str) – Filename of the INI file.
utils_script (str) – Filename or path to the utilities script.
res_dir (str) – Destination directory (created if missing).
names (dict or None) –
Optional mapping for target filenames: {
”script_name”: “stellar_retrieval_runfile_thisrun.py”, “utils_script_name”: “stellar_retrieval_utilities_thisrun.py”, “ini_name”: “iniFile_thisrun.py”
} If None, SRU-style defaults are used.
verbose (bool) – Print what’s happening.
preserve_meta (bool) – Use shutil.copy2 (preserve metadata) if True, else shutil.copy.
- stctm.stellar_retrieval_utilities.setAxesFontSize(ax, fontsize)
Set the font size of the axes adapted from auxbenneke/utilities.py
- Parameters:
ax (matplotlib.axes.Axes) – axis to set the font size
fontsize (int) – font size to set
- Return type:
None
- stctm.stellar_retrieval_utilities.xspeclog(ax, xlim=None, level=1, fmt='%2.1f')
Set the x-axis to a log scale with major and minor ticks adapted from auxbenneke/utilities.py
- Parameters:
ax (matplotlib.axes.Axes) – axis to set the x-axis to log scale
xlim (list of two float, optional) – x-axis limits
level (int, optional) – level of detail for the ticks (0.5, 1, 2, 3, 4)
fmt (str, optional) – format for the major ticks
- Return type:
None