Utility functions for stellar spectrum retrievals
Created on Thu Oct 31 12:34:45 2023
@author: caroline
Stellar model fitting utility functions
- stctm.exotune_utilities.BIC(chi2, nDataPoints, nPara)
Calculate the Bayesian Information Criterion (BIC) for model comparison.
Simple wrapper around stellar_retrieval_utilities.BIC to compute the BIC value :param chi2: The chi-squared statistic of the model fit. :type chi2: float :param nDataPoints: The number of independent data points used in the model fitting. :type nDataPoints: int :param nPara: The number of free parameters in the model. :type nPara: int
- Returns:
The Bayesian Information Criterion value. Lower values indicate a more favorable model under the BIC framework.
- Return type:
float
References
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
- stctm.exotune_utilities.Fscale_obs(Fscale, fspot, ffac, model_phot_fixR, model_spot_fixR, model_fac_fixR)
Compute the model spectrum scaled by a flux factor. Wrapper around stellar_retrieval_utilities’ combine_components function.
- Parameters:
Fscale (float) – Flux scaling factor to apply to the combined model spectrum.
fspot (float) – Spot covering fraction on the stellar surface.
ffac (float) – Facula covering fraction on the stellar surface.
model_phot_fixR (array_like) – Flux values of the photosphere model at each wavelength.
model_spot_fixR (array_like) – Flux values of the spot model at each wavelength.
model_fac_fixR (array_like) – Flux values of the facula model at each wavelength.
- Returns:
Scaled full stellar model spectrum.
- Return type:
ndarray
- class stctm.exotune_utilities.FunctionCache
A global container for storing a target function and its associated arguments, intended to minimize pickling overhead when using multiprocessing.
- lnprob
The target function to be evaluated in parallel.
- Type:
callable
- lnprob_args
Positional arguments to pass to the function.
- Type:
tuple
- lnprob_kwargs
Keyword arguments to pass to the function.
- Type:
dict
- class stctm.exotune_utilities.FunctionWrapper(func, args)
A simple function wrapper to bundle a function and its shared arguments, useful for serialization-safe function calls.
- func
The function to wrap.
- Type:
callable
- args
The shared arguments to pass to the function.
- Type:
tuple
- class stctm.exotune_utilities.MyPool(processes, lnprob, lnprob_args=(), lnprob_kwargs={})
A lightweight multiprocessing pool that avoids pickling large argument objects by using a shared global cache (FunctionCache).
- map(func, iterable)
Applies the cached function over an iterable using worker processes.
- close()
Easy stop of pool.
- terminate()
Force stops the pool.
- close()
Closes the pool and waits for all worker processes to exit.
- join()
Waits for the worker processes to exit.
- map(func, iterable)
Applies the cached function to every item in the iterable using the pool.
- Parameters:
func (callable) – Ignored; required to match map() signature.
iterable (iterable) – Inputs to evaluate the function on.
- Returns:
List of function results.
- Return type:
list
- terminate()
Immediately terminates all worker processes.
- stctm.exotune_utilities.calc_and_plot_timeMasked_mednorm_lc(timeUnique, optspec2D, params)
Calculate and plot a median-normalized light curve from a time-series spectrum, optionally applying smoothing and masking specified time ranges.
- Parameters:
timeUnique (ndarray) – 1D array of time values (e.g., BJD) for the spectral time series.
optspec2D (ndarray) – 2D array of spectral data with shape (n_times, n_wavelengths).
params (dict) –
- Dictionary of parameters including:
”kern_size”: (int or None) Kernel size for median filtering.
”mask_range”: (tuple or list) One or more (start, end) time ranges to mask.
”jd_range_mask”: list of lists or strings defining time intervals to be masked.
- Returns:
fig1 (matplotlib.figure.Figure) – The matplotlib figure containing the light curve plot.
timeUnique (ndarray) – The time array after applying any specified masks.
optspec2D (ndarray) – The 2D spectral array after masking the specified time intervals.
- stctm.exotune_utilities.calc_spectrum_model_and_integrate(Fscale, fspot, ffac, spec, model_wv, model_phot_fixR, model_spot_fixR, model_fac_fixR)
Compute a stellar model and integrate it over spectral bandpasses.
- Parameters:
Fscale (float) – Flux scaling factor to apply to the integrated model.
fspot (float) – Spot covering fraction on the stellar surface.
ffac (float) – Facula covering fraction on the stellar surface.
spec (tuple) –
- Tuple containing:
waveMin (array_like): Lower bounds of wavelength bins.
waveMax (array_like): Upper bounds of wavelength bins.
yval (array_like): Observed flux values (not used here).
yerrLow (array_like): Lower error values (not used here).
model_wv (array_like) – Wavelength array for the model spectra.
model_phot_fixR (array_like) – Flux values of the photosphere model at each wavelength.
model_spot_fixR (array_like) – Flux values of the spot model at each wavelength.
model_fac_fixR (array_like) – Flux values of the facula model at each wavelength.
- Returns:
Flux-calibrated model integrated over the specified wavelength bins.
- Return type:
ndarray
- stctm.exotune_utilities.chainplot(samples, labels=None, nwalkers=None, fontsize=None, lw=1, stepRange=None)
Plot parameter chains from MCMC sampling results.
Wrapper around stellar_retrieval_utilities.chainplot :param samples: MCMC samples, either 2D (nsamples, nparameters) or 3D (nwalkers, nsteps, nparameters). :type samples: ndarray :param labels: List of parameter names to label each subplot’s y-axis. Should match the number of parameters. :type labels: list of str, optional :param nwalkers: Number of walkers used in the MCMC sampling. Required if reshaping 2D samples to 3D. :type nwalkers: int, optional :param fontsize: Font size to apply to subplot labels and tick labels. :type fontsize: int or float, optional :param lw: Line width for the chain plots. :type lw: float, default=1 :param stepRange: If provided, defines the (start, end) of the x-axis range for each walker chain plot.
Used to simulate a time/step axis for 3D samples.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib figure object containing the chain plots.
axes (ndarray of matplotlib.axes.Axes) – 2D array of subplot axes, each showing the chain for one parameter.
Notes
This function is adapted from auxbenneke/utilities.py.
- stctm.exotune_utilities.config_get(cfg, logical_table, key, default=None, required=False)
Unified accessor for config values from INI or TOML.
- Parameters:
cfg (dict) – Dictionary of parsed configuration tables.
logical_table (str) – Logical table name (e.g., “stellar params”). Underscore/space variants are handled.
key (str) – Key to fetch from the table.
default (Any, optional) – Default value if the key is missing (default: None).
required (bool, optional) – If True, raises an error if the key is missing (default: False).
- Returns:
The value from the config or the default.
- Return type:
Any
- stctm.exotune_utilities.convert_to_bool(x)
Convert a value into a boolean.
- Parameters:
x (Any) – Value to convert. Can be bool, str, int, or None.
- Returns:
Converted boolean value.
- Return type:
bool
- stctm.exotune_utilities.format_param_str(param, fitparanames)
Generate a formatted summary string of stellar and fitted parameters.
Wrapper around stellar_retrieval_utilities.format_param_str :param param: Dictionary of default model parameters. :type param: dict :param fitparanames: List of parameter names that were varied in the fit. :type fitparanames: list of str
- Returns:
str1 – A formatted string summary of the best fit parameters
- Return type:
str
- stctm.exotune_utilities.get_StellSpec_from_spec_timeseries(waveUnique, optspec2D, params, flux_calibrated=True)
Compute the median spectrum from a spectral time series and initialize a StellSpec object.
- Parameters:
waveUnique (ndarray) – 1D array of unique wavelength values corresponding to the spectrum.
optspec2D (ndarray) – 2D array of optimal extraction spectral data with shape (n_times, n_wavelengths).
params (dict) –
- Dictionary of parameters including:
”save_median_spectrum”: (bool) Whether to save the median spectrum to file.
”path_save_median_spectrum”: (str) Path to save the median spectrum file.
flux_calibrated (bool, optional) – If True, assumes the spectral flux is already flux-calibrated. Default is True.
- Returns:
spec – A StellSpec object containing the median spectrum.
- Return type:
psspec.StellSpec
Notes
The spectral values and uncertainties are scaled by 1e10 for plotting purposes.
- stctm.exotune_utilities.get_closest_models_from_grid(param, models_grid_fixedR, Teffs_grid, loggs_grid)
Retrieve the closest-matching model spectra for the photosphere, spot, and faculae components based on input stellar parameters.
Wrapper around the function compatible with both retrieval modalities in stellar_retrieval_utilities.
- Parameters:
param (dict) – Dictionary containing stellar parameters. Must include:
models_grid_fixedR (ndarray) – Grid of model spectra, indexed by [Teff index, logg index], assumed to be at fixed radius.
Teffs_grid (array-like) – Grid of effective temperatures corresponding to the first dimension of the model grid.
loggs_grid (array-like) – Grid of surface gravities corresponding to the second dimension of the model grid.
- Returns:
model_phot_fixR (array-like) – Model spectrum corresponding to the closest match for the photosphere.
model_spot_fixR (array-like) – Model spectrum corresponding to the closest match for the spot.
model_fac_fixR (array-like) – Model spectrum corresponding to the closest match for the faculae.
- stctm.exotune_utilities.get_default_logg(params)
Get the default values for the stellar log g
- Parameters:
params (dict)
file (Dictionary obtained when reading in the ini)
logg_phot_default (This dictionary is updated with)
- Return type:
None
- stctm.exotune_utilities.get_derived_param(param)
Wrapper around stellar_retrieval_utilities.get_derived_param to calculate derived parameters :param param: dictionary of default param values . :type param: dict
- Return type:
param with derived parameters updated
- stctm.exotune_utilities.get_exotune_blobs(exotune_models_blobs, percentiles=[0.2, 2.3, 15.9, 84.1, 97.7, 99.8])
Compute percentiles of ExoTUNE model blobs across MCMC samples.
- Parameters:
exotune_models_blobs (ndarray) – A 3D array of shape (nsamples, …), where each entry corresponds to a model output stored during MCMC sampling.
percentiles (list of float, optional) – List of percentiles to compute (in the range 0–100). Default corresponds to +/- 1,2,3 sigma intervals.
- Returns:
exotune_percentiles – Array of the same shape as exotune_models_blobs without the first dimension, but with a new first dimension equal to the number of percentiles. For example, shape will be (n_percentiles, …) corresponding to each computed percentile.
- Return type:
ndarray
- stctm.exotune_utilities.get_labels_from_fitparanames(fitparanames)
Generate LaTeX-formatted plot labels for a list of fitted parameter names.
- Parameters:
fitparanames (list of str) – List of parameter names as used in the model and MCMC fitting.
- Returns:
labels – List of corresponding LaTeX-formatted labels suitable for plot axes.
- Return type:
list of str
Notes
Parameters not explicitly listed are ignored and not included in the output.
- stctm.exotune_utilities.get_median_spectrum_and_unc(wave_um, spec_ts, flux_calibrated=False)
Compute the median stellar spectrum and associated uncertainties.
This function calculates the median spectrum across a time series of spectra and estimates the uncertainty in each wavelength bin using the standard deviation across the time series. Optionally, the result can be converted to physical flux units if the input is flux-calibrated.
- Parameters:
wave_um (array_like) – Wavelength array in microns.
spec_ts (array_like) – 2D array of spectral time series with shape (n_times, n_wavelengths).
flux_calibrated (bool, optional) – If True, applies flux calibration to the output spectra. Default is False.
- Returns:
median_spectrum (ndarray) – The median stellar spectrum across the time series.
err_median_spectrum (ndarray) – The estimated uncertainties in each wavelength bin.
- stctm.exotune_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], Fscale_guess=1.0)
Generate prior bounds for model parameters based on default ranges, user-specified Gaussian priors, and optional log-space fitting options for specific parameters.
- Parameters:
param (dict) – Dictionary of initial/default parameter values (e.g., Tphot, logg_phot).
gaussparanames (list of str) – List of parameter names for which Gaussian priors are to be applied.
hyperp_gausspriors (list of list, optional) – Each entry should be [mean, std] for the corresponding parameter in gaussparanames. Used to narrow the prior range to within ±5σ around the mean.
fitLogfSpotFac (list of bool, optional) – Two-element list indicating whether to use log-uniform priors for ‘fspot’ and ‘ffac’, respectively.
hyperp_logpriors (list, optional) – Lower and upper bounds to apply when using log-space priors for ‘fspot’ or ‘ffac’.
T_grid (list of float) – Temperature grid defining the allowable range for temperature-related parameters (e.g., Tphot).
logg_grid (list of float, optional) – Surface gravity grid defining the bounds for logg-related parameters.
Fscale_guess (float, optional) – Initial guess for the flux scaling factor, used to set the bounds for ‘logFscale’.
- Returns:
Dictionary mapping each parameter name to a [lower_bound, upper_bound] list representing its prior range. For parameters fitted in log-space, the key is prefixed with ‘log’ followed by underscore.
- Return type:
dict
- stctm.exotune_utilities.get_scaling_guess(param, T_grid, logg_grid, model_wv, models_grid, spec, overwrite_param=True, wave_min_match_um=1.0, wave_max_match_um=2.0)
Estimate an initial flux scaling factor (Fscale) between an observed spectrum and a model spectrum by comparing their median flux values over a specified wavelength range.
- Parameters:
param (dict) – Dictionary of parameters (e.g., for model fitting). May be updated with ‘logFscale’ and ‘Fscale’.
T_grid (array-like) – Grid of effective temperatures used for selecting the closest model.
logg_grid (array-like) – Grid of surface gravities used for selecting the closest model.
model_wv (array-like) – Wavelength grid corresponding to the model spectra.
models_grid (ndarray) – Grid of model spectra to compare against the observed data.
spec (object) – Observed spectrum object. Must have attributes: wave, waveMin, waveMax, yval, and yerrUpp.
overwrite_param (bool, optional) – If True, updates param with the estimated Fscale value. Default is True.
wave_min_match_um (float, optional) – Lower bound (in microns) of the wavelength range used for matching spectra. Default is 1.0.
wave_max_match_um (float, optional) – Upper bound (in microns) of the wavelength range used for matching spectra. Default is 2.0.
- Returns:
Fscale_guess (float) – Estimated flux scaling factor based on the median ratio of observed to model fluxes.
model_int (array-like) – Model spectrum integrated over the observation bins.
- stctm.exotune_utilities.init_default_and_fitted_param(Tphot, met, logg_phot, fitspot=True, fitfac=True, fitThet=False, fitTphot=False, fitFscale=True, fitlogg_phot=False, fitlogg_het=False, fitLogfSpotFac=[0, 0], fiterrInfl=False, Fscale_guess=1, dlogg_het_guess=0.0)
Initialize default stellar parameters and define which are to be fitted.
- Parameters:
Tphot (float) – Photosphere temperature in Kelvin.
met (float) – Logarithmic stellar metallicity [dex].
logg_phot (float) – Logarithmic surface gravity of the stellar photosphere.
fitspot (bool, optional) – If True, include starspots in the model. Default is True.
fitfac (bool, optional) – If True, include faculae in the model. Default is True.
fitThet (bool, optional) – If True, fit the temperature differences of spots and faculae. Default is False.
fitTphot (bool, optional) – If True, fit the photospheric temperature. Default is False.
fitFscale (bool, optional) – If True, fit the flux scaling factor (logFscale). Default is True.
fitlogg_phot (bool, optional) – If True, fit the photospheric surface gravity (logg_phot). Default is False.
fitlogg_het (bool, optional) – If True, fit the difference in log(g) between photosphere and heterogeneities. Default is False.
fitLogfSpotFac (list of bool, optional) – Two-element list indicating whether to fit log10 of spot and facula covering fractions, respectively. Default is [0, 0].
fiterrInfl (bool, optional) – If True, fit an error inflation parameter (logErrInfl). Default is False.
Fscale_guess (float, optional) – Initial guess for the flux scaling factor. Default is 1.
dlogg_het_guess (float, optional) – Initial guess for the log(g) difference of heterogeneities. Default is 0.0.
- Returns:
param (dict) – Dictionary containing initialized model parameters and their default values.
fitparanames (list of str) – List of parameter names to be varied during fitting.
- stctm.exotune_utilities.init_default_and_fitted_param_fromDict(params, Fscale_guess=1, dlogg_het_guess=0.0)
Initialize default stellar parameters and define which are to be fitted, using a parameter dictionary input (e.g. parsed from an INI file).
- Parameters:
params (dict) – Dictionary containing model parameters and fit flags
Fscale_guess (float, optional) – Initial guess for the flux scaling factor. Default is 1.
dlogg_het_guess (float, optional) – Initial guess for the log(g) difference of heterogeneities. Default is 0.0.
- Returns:
param (dict) – Dictionary containing initialized model parameters and their default values.
fitparanames (list of str) – List of parameter names to be varied during fitting.
- stctm.exotune_utilities.initializer(lnprob, lnprob_args=(), lnprob_kwargs={})
Initializes the global FunctionCache with a function and its arguments.
- Parameters:
lnprob (callable) – The function to evaluate.
lnprob_args (tuple, optional) – Positional arguments for the function.
lnprob_kwargs (dict, optional) – Keyword arguments for the function.
- stctm.exotune_utilities.integ_model(lam_min, lam_max, wave, F)
Integrate a model over specified wavelength ranges.
Computes the average flux within multiple wavelength intervals by integrating the flux density and normalizing by the width of each interval.
Here simply a compatibility wrapper that defers to the other utilities function. :param lam_min: Array of lower bounds for the wavelength intervals. :type lam_min: array_like :param lam_max: Array of upper bounds for the wavelength intervals. :type lam_max: array_like :param wave: Wavelength array corresponding to the model flux values. :type wave: array_like :param F: Model flux values corresponding to each wavelength in wave. :type F: array_like
- Returns:
F_int – Array of average integrated fluxes over the specified wavelength ranges.
- Return type:
ndarray
- stctm.exotune_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 all model parameters, including both default (fixed) and fitted para.
fitparanames (list of str) – Names of the parameters in theta that are being optimized.
spec (tuple) – Observed spectrum as a tuple: (waveMin, waveMax, yval, yerrLow).
models_baseline (list of arrays) – Precomputed baseline model spectra (photosphere, spot, faculae) at fixed radius.
T_grid (array-like) – Grid of effective temperatures corresponding to the model grid.
logg_grid (array-like) – Grid of surface gravities corresponding to the model grid.
model_wv (array-like) – Wavelength grid of the model spectra.
models_grid (ndarray) – 3D grid of model spectra indexed by temperature and gravity (fixed radius).
- Returns:
lnlk (float) – Log-likelihood value computed from the squared residuals between observed and model fluxes.
model_int (array) – Integrated composite model spectrum matched to the observed wavelength bins.
- stctm.exotune_utilities.lnprior(theta, param, fitparanames, gaussparanames, hyperp_gausspriors, fitLogfSpotFac, hyperp_logpriors, T_grid, logg_grid, Fscale_guess)
Get log prior for a set of model parameters.
This function evaluates whether the given parameter vector theta falls within the allowed prior bounds (uniform or Gaussian priors) and applies additional constraints such as ensuring the sum of ‘fspot’ and ‘ffac’ does not exceed 1.
- Parameters:
theta (array-like) – Array of current values for the fitted model parameters
param (dict) – Dictionary of default parameters used to compute derived parameters. This will be updated with values from theta.
fitparanames (list of str) – Names of the parameters being fit.
gaussparanames (list of str) – Subset of fitparanames for which Gaussian priors should be applied.
hyperp_gausspriors (list of list) – List of [mean, std] values for each parameter in gaussparanames, defining the Gaussian priors.
fitLogfSpotFac (list of bool) – Two-element list indicating whether ‘fspot’ and ‘ffac’ are being fit in log-space.
hyperp_logpriors (list) – Lower and upper bounds for log-space priors on ‘fspot’ or ‘ffac’, if applicable.
T_grid (array-like) – Grid of allowed temperatures for model evaluation; used to constrain ‘Tphot’, ‘deltaTfac’, and ‘deltaTspot’.
logg_grid (array-like) – Grid of allowed surface gravities; used to constrain ‘loggphot’ and ‘dlogghet’.
Fscale_guess (float) – Initial estimate for the flux scaling factor, used to set bounds on ‘logFscale’.
- Returns:
Logarithm of the prior probability (ln prior). Returns -np.inf if any parameter falls outside its allowed prior range, or if the sum of ‘fspot’ and ‘ffac’ exceeds 1.
- Return type:
float
- stctm.exotune_utilities.lnprob(theta, spec, param, fitparanames, gaussparanames, hyperp_gausspriors, fitLogfSpotFac, hyperp_logpriors, models_baseline_fixR, T_grid, logg_grid, model_wv, models_grid_fixR, Fscale_guess)
Compute ln prob for a given parameter vector.
- Parameters:
theta (array-like) – Array of current values for the fitted model parameters
spec (StellSpec object) – Stellar spectrum to be fitted
param (dict) – Dictionary of all model parameter values, with defaults; updated with values from theta.
fitparanames (list of str) – List of parameter names being optimized (order must match theta).
gaussparanames (list of str) – Subset of fitparanames for which Gaussian priors are applied.
hyperp_gausspriors (list of list) – List of [mean, std] for each parameter in gaussparanames defining the Gaussian priors.
fitLogfSpotFac (list of bool) – Flags indicating whether to apply log-space priors to ‘fspot’ and ‘ffac’, respectively.
hyperp_logpriors (list) – Log-space prior bounds for ‘fspot’ or ‘ffac’, if applicable.
models_baseline_fixR (array-like) – Precomputed baseline model spectra (e.g., unspotted models) at fixed radius.
T_grid (array-like) – Temperature grid used to define valid parameter ranges.
logg_grid (array-like) – Surface gravity grid used to define valid parameter ranges.
model_wv (array-like) – Wavelength array corresponding to the model spectra.
models_grid_fixR (array-like) – Full grid of model spectra with fixed radius.
Fscale_guess (float) – Initial guess for the flux scaling factor, used for prior construction.
- Returns:
float : Log-posterior probability (log-prior + log-likelihood). Returns -np.inf if prior is invalid.
array : Model spectrum corresponding to the input parameters. Returned only if prior is valid.
- Return type:
tuple
- stctm.exotune_utilities.lnprob_cache(theta)
Evaluates the cached function with the provided input.
- Parameters:
theta (any) – The input to pass as the first argument to the cached function.
- Return type:
The result of evaluating the cached function.
- stctm.exotune_utilities.load_as_dict(path)
Load an INI or TOML config file into a uniform dictionary.
- Parameters:
path (str) – Path to the configuration file.
- Returns:
(format, dict) where format is “ini” or “toml”, and dict contains sections with keys/values.
- Return type:
tuple
- stctm.exotune_utilities.parse_all_input_exotune_iniFile(config_path)
Parse an INI or TOML configuration file and command-line style arguments into a parameter dictionary.
This function provides backward compatibility for INI files while supporting the newer TOML format. Command-line arguments override values from the config file.
- Parameters:
config_path (str) – Path to the configuration file (.ini or .toml).
- Returns:
- paramsdict
Dictionary of parameter names and values, normalized for downstream use.
- label_runstr
A label string describing the run, built from selected parameters.
- Return type:
tuple
- stctm.exotune_utilities.parse_gaussian_inputs(input_para)
Forwarder to the master implementation in stellar_retrieval_utilities.
- Parameters:
input_para (dict)
- Returns:
(gaussparanames
- Return type:
np.ndarray, hyperp_gausspriors: list[list[float]])
- stctm.exotune_utilities.parse_mask_ranges(v)
Normalize a mask specification into a list of ranges.
- Parameters:
v (str, list, or None) – Mask specification. Can be: - “” or None -> [] - “a_b|c_d” -> [[a, b], [c, d]] - [[a, b], [c, d]] -> returned as list of floats
- Returns:
A list of [min, max] float pairs.
- Return type:
list
- stctm.exotune_utilities.parse_range_pair(value, as_type=<class 'float'>)
Normalize a 2-value range into a list [min, max].
- Parameters:
value (str, list, tuple, or None) – The range to parse. Can be “a_b”, [a, b], (a, b), or None/””.
as_type (type, optional) – The type to cast values to (default: float).
- Returns:
A 2-element list [min, max] of the given type, or [] if empty.
- Return type:
list
- stctm.exotune_utilities.plot_corner(samples, plotparams, plot_datapoints=False, smooth=1.5, quantiles=[0.16, 0.5, 0.84], title_kwargs={'fontsize': 10}, hist_kwargs={'linewidth': 3}, rg=None, show_titles=True, levels=(0.393, 0.865, 0.989), **kwargs)
Generate a corner plot to visualize posterior distributions from MCMC samples.
This function wraps the corner.corner plotting and uses the master function from stellar_retrieval_utilities.py
- Parameters:
samples (ndarray) – MCMC samples array of shape (nsamples, nparameters).
plotparams (dict) –
- Dictionary containing plot settings. Must include:
”labels” : list of str, axis labels for each parameter
”hist_color” : str, color for the histograms and contour plots
plot_datapoints (bool, default=False) – Whether to overplot individual samples in the 2D contour plots.
smooth (float, default=1.5) – Smoothing parameter passed to corner.corner for KDE.
quantiles (list of float, default=[0.16, 0.5, 0.84]) – Quantiles to display as vertical lines on the 1D histograms.
title_kwargs (dict, default={'fontsize': 14}) – Keyword arguments for customizing title appearance in each subplot.
hist_kwargs (dict, default={"linewidth": 3}) – Keyword arguments for customizing the histogram appearance.
rg (list or tuple, optional) – Plotting range for each parameter.
show_titles (bool, default=True) – Whether to show titles with median and quantile values for each parameter.
levels (tuple of float, default=(0.393, 0.865, 0.989)) – Contour levels for 2D histograms, corresponding to 1, 2, and 3 sigma for a 2D Gaussian.
**kwargs (dict) – Additional keyword arguments passed to corner.corner.
- Returns:
fig – The matplotlib figure object containing the corner plot.
- Return type:
matplotlib.figure.Figure
- stctm.exotune_utilities.plot_custom_corner(samples, fitparanames, parabestfit, param, gaussparanames, hyperp_gausspriors, fitLogfSpotFac, hyperp_logpriors, T_grid, logg_grid)
Generate a customized corner plot with parameters ordered for clarity and axes ranges informed by priors.
- Parameters:
samples (ndarray) – Array of MCMC samples with shape (n_samples, n_parameters), post burn-in.
fitparanames (list of str) – Names of the fitted parameters in the order they appear in samples.
parabestfit (ndarray) – Best-fit values for the parameters.
param (dict) – Dictionary containing default parameter values, used for computing prior ranges.
gaussparanames (list of str) – Names of parameters with Gaussian priors.
hyperp_gausspriors (list of lists) – Hyperparameters defining the Gaussian priors for relevant parameters.
fitLogfSpotFac (list of bool) – Flag indicating whether to fit the log of fspot/ffac parameters.
hyperp_logpriors (dict) – Hyperparameters defining log-uniform priors for specific parameters.
T_grid (ndarray) – Grid of stellar effective temperatures used to inform priors.
logg_grid (ndarray) – Grid of stellar surface gravities used to inform priors.
- Returns:
fig – The figure object containing the customized corner plot.
- Return type:
matplotlib.figure.Figure
- stctm.exotune_utilities.plot_exotune_blobs(spec, oot_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)
oot_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:
ax – The axis object with the plot drawn on it.
- Return type:
matplotlib.axes.Axes
- stctm.exotune_utilities.plot_exotune_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 ExoTUNE model spectra with uncertainty intervals from MCMC samples.
Visualizes the model spectra generated from posterior samples of the fit parameters, including the maximum likelihood model and confidence intervals (1, 2, 3 sigma) derived from the sample distribution. It also optionally saves these results to a CSV file.
- Parameters:
spec (StellSpec object) – Observed spectrum object.
param (dict) – Dictionary of default model parameters (updated for each sample).
fitparanames (list of str) – Names of the fitted parameters.
ind_bestfit (int) – Index of the maximum likelihood sample within post_burnin_samples.
post_burnin_samples (pandas.DataFrame) – Flattened MCMC samples after burn-in.
T_grid (array-like) – Grid of temperatures used in the model.
logg_grid (array-like) – Grid of surface gravities used in the model.
modelgrid_wave (array-like) – Wavelength array for the spectra in the model grid.
grid_models_fixedresP (ndarray) – 2D array of model spectra at fixed resolution, indexed by (temperature, logg).
sample_spectra (ndarray, optional) – Precomputed model spectra for posterior samples. If None, they are computed.
modelgrid_resP (float, default=10000) – Resolving power of the model spectra.
target_resP (float, default=100) – Target resolving power for visualization and saving.
N_samp (int, default=1000) – Number of posterior samples to draw and compute spectra from.
ax (matplotlib.axes.Axes, optional) – Axis to plot on. If None, a new figure and axis are created.
bestfit_color (str, default='k') – Color for the maximum likelihood spectrum line.
color (str, default='b') – Color for uncertainty bands and median spectrum line.
plot3sig (bool, default=True) – Whether to plot the +/- 3 sigma envelope.
plot2sig (bool, default=True) – Whether to plot the +/- 2 sigma envelope.
plot1sig (bool, default=True) – Whether to plot the +/- 1 sigma envelope.
plotmedian (bool, default=True) – Whether to plot the median spectrum.
plotbestfit (bool, default=True) – Whether to plot the maximum likelihood spectrum.
legend_loc (int, default=1) – Location of the plot legend.
save_csv (bool, default=True) – Whether to save the resulting model spectra (median, percentile intervals) to a CSV file.
results_folder (str, optional) – Folder path where CSV will be saved if save_csv=True.
runname (str, optional) – Identifier to append to output filenames.
- Returns:
fig (matplotlib.figure.Figure or None) – The matplotlib figure object. None if ax is provided.
ax (matplotlib.axes.Axes) – The axis object with the plotted spectra.
sample_spectra (ndarray) – Array of model spectra generated from posterior samples.
- stctm.exotune_utilities.plot_maxlike_and_maxprob(spec, param, parabestfit, ind_maxprob, ind_bestfit, fitparanames, flat_st_ctm_models, pad=0.25)
Plot the best-fit stellar models for maximum likelihood and maximum posterior samples.
- Parameters:
spec (StellSpec object) – Observed spectrum object
param (dict) – Dictionary of default model parameters to be updated with best-fit values.
parabestfit (ndarray) – Array of parameter values corresponding to the best-fit model (typically max likelihood).
ind_maxprob (int) – Index of the sample with the highest posterior probability.
ind_bestfit (int) – Index of the sample with the maximum likelihood.
fitparanames (list of str) – Names of the parameters used in the fit; must match order of parabestfit.
flat_st_ctm_models (ndarray) – Array of model predictions corresponding to all samples.
pad (float, default=0.25) – Padding to apply on the x-axis when setting plot limits.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib figure object with the plotted spectrum and models.
ax (matplotlib.axes.Axes) – The axis object containing the plot.
- stctm.exotune_utilities.plot_median_spectrum_and_unc(wave_arr, median_spectrum, err_median_spectrum, label='Median from entire time series')
Plot median stellar spectrum with uncertainty shading.
- Parameters:
wave_arr (array_like) – Wavelength array in microns.
median_spectrum (array_like) – Median spectrum values corresponding to each wavelength.
err_median_spectrum (array_like) – Uncertainties associated with each value in the median spectrum.
label (str, optional) – Label for the spectrum in the plot legend. Default is “Median from entire time series”.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib figure object.
ax (matplotlib.axes._subplots.AxesSubplot) – The matplotlib axes object containing the plot.
- stctm.exotune_utilities.prep_spec_waveMasked(spec, params)
Preprocess a spectrum object by masking invalid or unwanted wavelength regions.
This function modifies a StellSpec-like spectrum object by: - Removing wavelengths beyond the red limit of the PHOENIX model grid. - Removing data points where the observed flux is NaN. - Applying custom wavelength range masks defined in the params dictionary. - Plotting the resulting masked spectrum with shaded regions indicating removed wavelength intervals.
- Parameters:
spec (psspec.StellSpec) – A StellSpec-like object containing spectral data and methods for masking.
params (dict) –
- Dictionary of parameters including:
”wave_range_mask”: list of lists, where each item defines a wavelength range to mask (e.g., [[1.2, 1.3], [2.8, 3.0]]).
- Returns:
spec (StellSpec object) – The updated spectrum object with masked data removed.
fig2 (matplotlib.figure.Figure) – The matplotlib figure showing the masked spectrum and shaded regions.
Notes
The wavelength red limit (5.39 µm) is hardcoded based on the PHOENIX model grid.
NaN flux values are automatically identified and removed.
The function assumes spec provides .wave, .yval, .remDataByIndex(), .waveMin, .waveMax, and .plot() attributes/methods.
- stctm.exotune_utilities.preprocess_gaussians(params)
Pre-normalize Gaussian prior fields so the sru.parse_gaussian_inputs() forwarder receives the shapes it expects.
- Parameters:
params (dict) – Parameter dictionary to be mutated in place.
- Returns:
Mutates ‘gaussparanames’ and ‘hyperp_gausspriors’ in params.
- Return type:
None
- stctm.exotune_utilities.read_in_2d_spec(path)
Read a 2D time-series spectrum from an HDF5 file.
This function reads an HDF5 file containing time-series spectral data (e.g., from a pipeline like Eureka!), extracts the 1D wavelength and time arrays, and reshapes the optimal extraction spectrum into a 2D array of shape (time, wavelength).
- Parameters:
path (str) – Path to the HDF5 file containing spectral time series data.
- Returns:
timeUnique (ndarray) – 1D array of unique time values.
waveUnique (ndarray) – 1D array of unique wavelength values.
optspec2D (ndarray) – 2D array of optimally extracted spectra with shape (n_times, n_wavelengths).
- stctm.exotune_utilities.samp2bestfit(samp)
Compute summary statistics and best-fit values from MCMC samples.
Calculates key quantiles (median, 1 and 2 sigma) and identifies the samples corresponding to the maximum posterior probability and maximum likelihood.
Wrapper around stellar_retrieval_utilities.samp2bestfit (identical behavior).
- Parameters:
samp (pandas.DataFrame) – DataFrame containing flattened MCMC samples, including at least the columns ‘lnprobability’ and ‘lnlike’, along with one column for each parameter.
- Returns:
bestfit (pandas.DataFrame) –
- DataFrame summarizing posterior statistics for each parameter. Includes:
50th percentile (median)
16th and 84th percentiles (for +/-1 sigma)
2.5th and 97.5th percentiles (for +/-2 sigma)
Parameter values at maximum likelihood (MaxLike)
Parameter values at maximum posterior probability (MaxProb)
Explicit +/-1 sigma and +/-2 sigma intervals based on the above quantiles
ind_bestfit (int) – Index of the sample with the maximum likelihood.
ind (int) – Index of the sample with the maximum posterior probability.
- stctm.exotune_utilities.save_bestfit_stats(spec, ind_bestfit, fitparanames, flat_oot_spec_models, results_folder, runname, save_fit=True)
Compute and optionally save summary statistics (red/chi2, BIC) for the best-fit model.
- Parameters:
spec (object) – Observed spectrum object, expected to contain attributes: yval (observed flux values) and yerrLow (associated uncertainties).
ind_bestfit (int) – Index of the best-fit model (typically from maximum likelihood).
fitparanames (list of str) – Names of the parameters used in the fit, used to compute degrees of freedom.
flat_oot_spec_models (ndarray) – Array of modeled spectra (post-burn-in), from which the best-fit model is selected.
results_folder (str) – Directory path where the output file should be saved.
runname (str) – Label for identifying this run; appended to output filenames.
save_fit (bool, default=True) – If True, saves the best-fit statistics to a CSV file.
- Returns:
Astropy Table containing the computed fit statistics.
Writes a CSV file if save_fit=True. Prints diagnostic info to console.
Output file (‘exotune_bestfit_stats_<runname>.csv’)
- stctm.exotune_utilities.save_mcmc_to_pandas(*args, **kwargs)
Save MCMC sampling results and extract best-fit parameters.
This function processes the MCMC sampler output by removing the burn-in phase, reshaping and storing the flattened samples as a Pandas DataFrame and an Astropy Table. It also computes and saves the best-fit parameters based on the maximum likelihood.
This is simply a wrapper around stellar_retrieval_utilities.save_mcmc_to_pandas
- Parameters:
results_folder (str) – Path to the directory where output files should be saved.
runname (str) – Identifier to append to output filenames for labeling different runs.
sampler (emcee.EnsembleSampler) – The MCMC sampler object containing the chains and log-probabilities.
burnin (int) – Number of initial steps (per walker) to discard as burn-in.
ndim (int) – Number of parameters in the fit.
fitparanames (list of str) – Names of the fitted parameters.
save_fit (bool) – If True, saves the flattened samples and best-fit parameters to CSV files. -> Writes two CSV files if save_fit=True: 1. Flattened sample chains with log-probabilities (exotune_pandas_<runname>.csv) 2. Best-fit parameter values (exotune_bestfit_<runname>.csv)
- Returns:
bestfit (pandas.DataFrame) – DataFrame containing best-fit values including maximum likelihood estimate.
ind_bestfit (int) – Index of the best-fit sample (based on median or quantiles).
ind_maxprob (int) – Index of the sample with the highest posterior probability.
parabestfit (ndarray) – Array of parameter values corresponding to the maximum likelihood sample.
samples (pandas.DataFrame) – Flattened MCMC samples after burn-in, with associated log-probabilities.
t_res (astropy.table.Table) – Astropy table version of the samples DataFrame.
- stctm.exotune_utilities.save_ref_files(this_dir, this_script, iniFile, utils_script, res_dir)
Save reference files used in a run to the results directory for reproducibility.
This function copies the main script, the INI configuration file, and a utility script into a specified results directory, renaming them with standard names.
Wrapper around sru.save_ref_files adapted to ExoTUNE’s naming conventions.
- Parameters:
this_dir (str) – Path to the directory where the current scripts and INI file are located.
this_script (str) – Filename of the main run script (e.g., ‘exotune_runscript.py’).
iniFile (str) – Filename of the INI configuration file used for the run.
utils_script (str) – Path to the utility script used by the main script (e.g., ‘exotune_utilities.py’).
res_dir (str) – Path to the directory where the reference copies will be saved.
- stctm.exotune_utilities.setAxesFontSize(ax, fontsize)
Wrapper around stellar_retrieval_utilities.setAxesFontSize to set font sizes for axis labels and ticks.
Set font size for all axis labels and tick labels of a matplotlib axis.
Updates the font size of the title, x-axis label, y-axis label, and all tick labels associated with the given axis.
- Parameters:
ax (matplotlib.axes.Axes) – The matplotlib axis object whose fonts will be updated.
fontsize (int or float) – Font size to apply to all axis text elements.
Notes
This function modifies the axis in-place and is adapted from auxbenneke/utilities.py.
- stctm.exotune_utilities.table_keys(name)
Get all table alias names given a section of the TOML file.
- Parameters:
name (str) – Section name (e.g., “saving options”).
- Returns:
All possible alias names for that table.
- Return type:
tuple
- stctm.exotune_utilities.wrap_text(text, nchar=60)
Splits a long string (text, str.) by inserting a line break every nchar (int.) characters, ideally breaking at spaces for better readability. :param text: The input string to be wrapped. :type text: str :param nchar: Maximum number of characters per line before inserting a line break. :type nchar: int, default=60
- Returns:
The input string with line breaks inserted for wrapping.
- Return type:
str
- stctm.exotune_utilities.xspeclog(ax, xlim=None, level=1, fmt='%2.1f')
Wrapper around stellar_retrieval_utilities.xspeclog to set logarithmic x-axis ticks Configure logarithmic x-axis ticks for spectrum plots.
- Parameters:
ax (matplotlib.axes.Axes) – The matplotlib axis object on which to set the log-scale x-axis ticks.
xlim (tuple of float, optional) – Optional (xmin, xmax) tuple to explicitly set the x-axis limits.
level (int or float, default=1. Preset level for tick density and appearance:) –
0.5 : Dense major ticks (0.2 to 6, step 0.2) and finer minor ticks (step 0.1)
- 1Standard major ticks at typical wavelengths (e.g., 1.0, 1.5, 2.0, …)
and minor ticks at 0.1 intervals
2 : Integer-based major ticks from 2 to 8, with no minor ticks
3 : Sparse major ticks with minor ticks at selected in-between values
4 : Very sparse major and minor ticks for compact plots
fmt (str, default="%2.1f") – Format string for major tick labels.
Notes
This function modifies the axis in-place and is adapted from auxbenneke/utilities.py.