casper.interface package#
Subpackages#
- casper.interface.gisic package
- Submodules
- casper.interface.gisic.norm_functions module
- casper.interface.gisic.normalize module
- casper.interface.gisic.segment module
- casper.interface.gisic.spectrum module
SpectrumSpectrum.add_continuum_point()Spectrum.assess_segment_variation()Spectrum.define_cont_points()Spectrum.generate_inflection_segments()Spectrum.generate_segments()Spectrum.get_continuum_points()Spectrum.normalize()Spectrum.remove_point()Spectrum.set_fluxpoints()Spectrum.set_segment_continuum()Spectrum.set_segment_midpoints()Spectrum.set_wavelength()Spectrum.spline_continuum()
- Module contents
Submodules#
casper.interface.EW module#
- casper.interface.EW.CAII_K12(wave: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], flux: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) float[source]#
Compute the equivalent width of the Ca II K12 absorption feature.
This function interpolates the inverted normalized flux (1 - flux) and integrates it over the wavelength range 3927.7 to 3939.7 Angstroms (KP K12 region) to estimate the equivalent width of the Ca II K line.
- Parameters:
wave (array_like) – Wavelength values of the spectrum (in Angstroms).
flux (array_like) – Normalized flux values corresponding to the wavelength array.
- Returns:
The equivalent width of the Ca II K absorption feature (within the K12 bounds), in Angstroms.
- Return type:
- casper.interface.EW.CAII_K18(wave: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], flux: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) float[source]#
Compute the equivalent width of the Ca II K absorption feature over the K18 region.
This function interpolates the inverted normalized flux (1 - flux) and integrates it over the wavelength range 3924.7 to 3942.7 Angstroms (KP K18 region) to estimate the equivalent width of the Ca II K line.
- Parameters:
wave (ArrayLike) – Wavelength values of the spectrum (in Angstroms).
flux (ArrayLike) – Normalized flux values corresponding to the wavelength array.
- Returns:
The equivalent width of the Ca II K absorption feature in the K18 region, in Angstroms.
- Return type:
- casper.interface.EW.CAII_K6(wave: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], flux: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) float[source]#
Compute the equivalent width of the Ca II K6 absorption feature.
This function interpolates the inverted normalized flux (1 - flux) and integrates it over the wavelength range 3930.7 to 3936.7 Angstroms (KP K6 bounds) to estimate the equivalent width of the Ca II K line.
- Parameters:
wave (array_like) – Wavelength values of the spectrum (in Angstroms).
flux (array_like) – Normalized flux values corresponding to the wavelength array.
- Returns:
The equivalent width of the Ca II K absorption feature (within K6 bounds), in Angstroms.
- Return type:
- casper.interface.EW.CAII_KP(wave: ndarray, flux: ndarray) float | float64[source]#
Compute the Ca II K-line strength index (KP) based on Beers et al. (1999).
This function evaluates K6, K12, and K18 bandpasses and returns the appropriate KP value according to Beers et al.’ decision tree.
- Parameters:
wave (np.ndarray) – Wavelength array of the spectrum.
flux (np.ndarray) – Normalized flux array corresponding to the wavelengths.
- Returns:
Ca II KP index value. Returns np.nan if selection logic fails.
- Return type:
- casper.interface.EW.GBAND_QUAD(wave: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], flux: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], bounds: tuple[float, float] = [4222.0, 4322.0]) tuple[float, float][source]#
Compute the equivalent width (EW) of the G-band (CH absorption lines) from a normalized spectrum.
This function integrates the area of absorption in the CH band region (G-band), defined by bounds, using a normalized flux. It also returns a correction factor (EW_subtract) in case the CH-band region is not fully normalized to 1.0. This correction is useful for estimating whether to use CH only mode or CH+C2 mode in stellar carbon abundance analysis.
- Parameters:
- Returns:
ew (float) – Equivalent width (EW) of the CH absorption feature.
EW_subtract (float) – Correction factor to account for improper normalization of the CH-band. If the peak flux in the band is below 1.0, this value will be non-zero.
- casper.interface.EW.get_KP_band(spectrum: Spectrum) Tuple[float, float][source]#
Return the Ca II K line wavelength range for chi-square fitting based on Beers (1999), using measurements K6, K12, and K18.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class with a ‘frame’ dictionary containing “wave” and “norm” arrays.
- Returns:
Wavelength bounds (min, max) from config.KP_BOUNDS.
- Return type:
Notes
If an unexpected condition occurs, np.nan is returned.
- casper.interface.EW.set_CH_procedure(spectrum: Spectrum) None[source]#
Set the carbon analysis mode for the given spectrum based on G-band strength.
This function measures the CH G-band equivalent width (CH_EW) using GBAND_QUAD. If a carbon mode is specified in spectrum.INPUT_CARBON_MODE, that mode is used. Otherwise, the function decides between “CH” and “CH+C2” based on the CH_EW threshold.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class containing a frame with “wave” and “norm”, and methods for setting G-band and carbon mode.
- Returns:
Modifies the spectrum in place.
- Return type:
None
casper.interface.MAD module#
- casper.interface.MAD.MAD(array: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) float[source]#
Compute the Median Absolute Deviation (MAD) of a numerical array.
MAD is a robust measure of statistical dispersion. It is calculated as the median of the absolute deviations from the median of the data.
- Parameters:
array (ArrayLike) – Input array of numerical values.
- Returns:
The median absolute deviation of the input array.
- Return type:
- casper.interface.MAD.S_MAD(array: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) float[source]#
Compute the scaled Median Absolute Deviation (S_MAD) as an estimator of standard deviation.
This scales the MAD by dividing by 0.6745, which makes it consistent with the standard deviation under a normal distribution.
- Parameters:
array (ArrayLike) – Input array of numerical values.
- Returns:
The scaled MAD, used as a robust estimate of standard deviation.
- Return type:
casper.interface.MCMC_interface module#
- casper.interface.MCMC_interface.chi_likelihood(theta: Tuple[float, ...], observed_spec_regions: Dict[str, DataFrame], synth_wave: ndarray, photo_teff: float, photo_teff_unc: float, SN_DICT: Dict[str, float], G_CLASS: str, bounds: Literal['default', 'final'] = 'default') float[source]#
Compute the log-likelihood of stellar model parameters given observed spectra.
This function compares interpolated synthetic spectra to observed spectral regions (e.g., Ca II and CH bands) using a chi-squared likelihood, combined with Gaussian priors on Teff and log-normal priors on inverse variance terms.
- Parameters:
theta (Tuple[float, ...]) – Tuple of model parameters: (Teff, [Fe/H], [C/Fe], XI_CA, XI_CH [, XI_C2]).
observed_spec_regions (Dict[str, pd.DataFrame]) – Dictionary of observed spectra with region names (“CA”, “CH”) as keys. Each DataFrame must contain “wave” and “norm” columns.
synth_wave (np.ndarray) – The wavelength grid for the synthetic model spectra.
photo_teff (float) – External photometric estimate of effective temperature.
photo_teff_unc (float) – Uncertainty in the photometric Teff estimate.
SN_DICT (Dict[str, Dict[str, float]]) – Dictionary mapping region names (“CA”, “CH”) to noise model parameters (each must contain “alpha” and “beta”).
G_CLASS (str) – Spectral class key used to select the interpolator model.
bounds (Literal["default", "final"], optional) – Specifies which set of parameter bounds to use. Default is “default”.
- Returns:
Log-likelihood value. Returns -np.inf if the interpolation fails or the likelihood evaluates to a non-finite value.
- Return type:
- casper.interface.MCMC_interface.chi_likelihood_C2(theta: Tuple[float, ...], observed_spec_regions: Dict[str, DataFrame], synth_wave: ndarray, photo_teff: float, photo_teff_unc: float, SN_DICT: Dict[str, Dict[str, float]], G_CLASS: str, bounds: Literal['default', 'final'] = 'default') float[source]#
Compute the log-likelihood including the C2 band when AC > 8.
This function extends chi_likelihood by incorporating the C2 band in addition to the Ca II and CH regions. It assumes the model includes an extra parameter (XI_C2) for the C2 noise level and balances the influence of CH and C2 via a 0.5 weighting factor.
- Parameters:
theta (Tuple[float, ...]) – Model parameters tuple: (Teff, [Fe/H], [C/Fe], XI_CA, XI_CH, XI_C2).
observed_spec_regions (Dict[str, pd.DataFrame]) – Dictionary of observed spectral regions (“CA”, “CH”, “C2”). Each DataFrame must contain “wave” and “norm” columns.
synth_wave (np.ndarray) – Wavelength grid for synthetic spectra.
photo_teff (float) – Photometric estimate of effective temperature.
photo_teff_unc (float) – Uncertainty in the photometric Teff estimate.
SN_DICT (Dict[str, Dict[str, float]]) – Mapping from region name to noise model parameters (“alpha” and “beta”).
G_CLASS (str) – Spectral class key for selecting the synthetic model interpolator.
bounds (Literal["default", "final"], optional) – Set of parameter bounds to use. Default is “default”.
- Returns:
Log-likelihood score incorporating Ca II, CH, and C2 bands. Returns -np.inf if interpolation fails or the result is not finite.
- Return type:
- casper.interface.MCMC_interface.chi_ll_refine(theta: Tuple[float, float], observed_spec_regions: Dict[str, DataFrame], synth_wave: ndarray, PARAMS: Dict[str, Tuple[float]], G_CLASS: str, bounds: Literal['default', 'final'] = 'default') float[source]#
Refined log-likelihood using fixed Teff and sigma values from earlier sampling.
This function refines the likelihood by evaluating only two parameters: [Fe/H] and [C/Fe], assuming Teff, XI_CA, and XI_CH have been fixed previously. Typically used after initial fitting, especially when the CH+C2 mode is active (e.g., AC > 8) and Teff/sigma values are considered well-constrained.
- Parameters:
theta (Tuple[float, float]) – Model parameters to refine: (Fe/H, [C/Fe]).
observed_spec_regions (Dict[str, pd.DataFrame]) – Dictionary of observed spectra by region (“CA”, “CH”). Each DataFrame must contain “wave” and “norm” columns.
synth_wave (np.ndarray) – The wavelength grid for the synthetic spectrum.
PARAMS (Dict[str, Tuple[float]]) – Dictionary of fixed values for Teff and sigma parameters. Required keys: “TEFF”, “XI_CA”, “XI_CH”.
G_CLASS (str) – Spectral class key used to select the interpolator.
bounds (Literal["default", "final"], optional) – Parameter bounds to apply. Default is “default”.
- Returns:
Log-likelihood score for the refined parameters. Returns -np.inf if interpolation fails or likelihood is not finite.
- Return type:
- casper.interface.MCMC_interface.chi_ll_refine_C2(theta: ndarray, observed_spec_regions: Dict[str, DataFrame], synth_wave: ndarray, PARAMS: Dict[str, ndarray], G_CLASS: str, bounds: str = 'default') float[source]#
Compute the log-likelihood (LL) score for observed vs. synthetic spectra using chi-squared loss across three molecular regions: Ca II, CH, and C₂.
- Parameters:
theta (np.ndarray) – MCMC parameter array where: - theta[0] = [Fe/H] metallicity - theta[1] = [C/Fe] carbon abundance
observed_spec_regions (dict) – Dictionary with keys “CA”, “CH”, and “C2”, each mapping to a DataFrame containing observed spectral data with columns “wave” and “norm”.
synth_wave (np.ndarray) – Wavelength grid for the synthetic spectra.
PARAMS (dict) – Dictionary of stellar parameters and inverse noise terms. Must contain: - “TEFF”: np.ndarray of effective temperature - “XI_CA”, “XI_CH”, “XI_C2”: np.ndarrays of inverse noise (1/SNR)
G_CLASS (str) – The stellar class used to identify the appropriate synthetic model.
bounds (str, optional) – Bound checking mode. Defaults to “default”.
- Returns:
The log-likelihood value. Returns -np.inf if synthetic flux generation fails or LL is non-finite.
- Return type:
- casper.interface.MCMC_interface.interp1d_synth_flux(synth_wave: ndarray, G_CLASS: str, teff: float, feh: float, carbon: float) Callable[[ndarray], ndarray] | None[source]#
Interpolate normalized synthetic flux at a given wavelength range.
This function retrieves synthetic flux values for given stellar parameters using a precomputed interpolator, normalizes them over a specified wavelength range, and returns a linear interpolating function for use in later modeling.
- Parameters:
synth_wave (np.ndarray) – The wavelength grid for the synthetic spectrum.
G_CLASS (str) – Spectral class key used to select the appropriate interpolator.
teff (float) – Effective temperature of the star.
feh (float) – Metallicity [Fe/H] of the star.
carbon (float) – Carbon abundance [C/Fe] of the star.
- Returns:
A 1D linear interpolating function over the synthetic spectrum, or None if the interpolated flux is not finite.
- Return type:
Callable[[np.ndarray], np.ndarray] | None
- casper.interface.MCMC_interface.kde_param(distribution: ndarray, x0: float) Dict[str, Any][source]#
Estimate the peak of a (possibly multimodal) distribution using KDE.
This function fits a kernel density estimation (KDE) model to the input distribution and then uses Powell’s optimization method to find the maximum of the estimated density.
- Parameters:
distribution (np.ndarray) – A 1D array representing the distribution to model.
x0 (float) – Initial guess for the peak location in the distribution.
- Returns:
A dictionary with: - “result”: The x-value where the KDE reaches its maximum (float). - “kde”: The fitted KDEUnivariate object.
- Return type:
Dict[str, Any]
- casper.interface.MCMC_interface.likelihood_params(theta: Tuple[float, ...], include_C2: bool = False) Tuple[float, ...][source]#
Extract model parameters from the input vector theta.
This function returns either 5 or 6 parameters depending on whether the CH+C2 mode is enabled. Parameters include stellar properties and inverse noise terms used in likelihood calculations.
- Parameters:
theta (Tuple[float, ...]) – A tuple containing model parameters in the following order: - Teff (effective temperature) - [Fe/H] (metallicity) - [C/Fe] (carbon abundance) - XI_CA (inverse noise variance for Ca II region) - XI_CH (inverse noise variance for CH region) - XI_C2 (optional; only included if include_C2=True)
include_C2 (bool, optional) – If True, the function extracts all 6 parameters, including XI_C2. If False, only the first 5 parameters are returned. Default is False.
- Returns:
A tuple of 5 or 6 float values depending on the include_C2 flag.
- Return type:
Tuple[float, …]
casper.interface.MLE_priors module#
- casper.interface.MLE_priors.default_feh_cfe_param_edges(feh: float, carbon: float) float[source]#
Apply hard bounds to [Fe/H] and [C/Fe] parameters using native grid limits.
- casper.interface.MLE_priors.default_param_edges(teff: float, feh: float, carbon: float, sigma_array: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) float[source]#
Apply hard bounds to Teff, [Fe/H], [C/Fe], and sigma parameters using native grid limits.
This function checks whether the input parameters fall within the predefined native bounds used by the MASTER grid. It also validates that all sigma values are within [0.0, 1.0].
- Parameters:
- Returns:
-np.inf if any parameter is out of bounds; otherwise 0.0 if all values are valid.
- Return type:
- casper.interface.MLE_priors.feh_cfe_param_edges(feh: float, carbon: float, mcmc_bounds: dict | None, bounds: str = 'default') float[source]#
Apply bounds to [Fe/H] and [C/Fe] based on MCMC or default limits.
If bounds is set to “final”, the function first checks against MCMC-provided parameter limits. Regardless of bounds mode, it falls back to checking hard-coded default limits.
- Parameters:
- Returns:
-np.inf if either parameter is out of bounds; otherwise 0.0.
- Return type:
- casper.interface.MLE_priors.ln_chi_square_sigma(obs: ndarray, model: ndarray, sigma: float) float[source]#
Compute the log-likelihood based on chi-squared with constant uncertainty (sigma).
- casper.interface.MLE_priors.param_edges(teff: float, feh: float, carbon: float, sigma_array: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], mcmc_bounds: dict | None = None, bounds: str = 'default') float[source]#
Apply parameter bounds based on search phase (“default” or “final”).
In the “final” phase, MCMC-specific bounds are applied to Teff, [Fe/H], and [C/Fe]. Regardless of phase, this function checks hard bounds on all parameters using default_param_edges, including sigma restrictions.
- Parameters:
teff (float) – Effective temperature to check.
feh (float) – Metallicity [Fe/H] to check.
carbon (float) – Carbon-to-iron ratio [C/Fe] to check.
sigma_array (ArrayLike) – Array of sigma values to validate (each must be in the range [0.0, 1.0]).
mcmc_bounds (dict, optional) – Dictionary of MCMC parameter bounds with keys “teff”, “feh”, and “cfe”, each mapping to a (min, max) tuple.
bounds ({"default", "final"}, optional) – Which bound strategy to use. If “final”, apply MCMC bounds before falling back to default grid and sigma bounds.
- Returns:
-np.inf if any parameter is out of bounds; otherwise 0.0 if all are valid.
- Return type:
- casper.interface.MLE_priors.sigma_lnprior(sigma: float, alpha_value: float, beta_value: float) float[source]#
Compute the log prior probability of sigma using the Beta distribution.
Uses the Beta PDF to estimate the prior probability of sigma, assuming sigma lies between 0 and 1 (or is normalized). This function returns the log of the probability, or negative infinity if the value is out of bounds or has zero probability.
- Parameters:
- Returns:
Log of the prior probability. Returns -inf if the probability is zero or invalid.
- Return type:
- casper.interface.MLE_priors.teff_lnprior(X: float, mean: float, sigma: float) float[source]#
Compute the logarithm of the Gaussian prior for effective temperature (Teff).
This represents the log prior probability of Teff assuming a normal distribution centered on the photometric Teff with a given uncertainty.
casper.interface.ac module#
- casper.interface.ac.ac(cfe: float, feh: float) float[source]#
Compute the absolute carbon abundance (A(C)) from [C/Fe] and [Fe/H].
This function adds the carbon-to-iron ratio ([C/Fe]), the metallicity ([Fe/H]), and the Asplund (2009) solar carbon abundance (8.43) to estimate the absolute carbon abundance A(C).
- casper.interface.ac.cfe(ac: float, feh: float) float[source]#
Calculate the carbon-to-iron abundance ratio ([C/Fe]) from absolute carbon abundance.
This function subtracts the Asplund (2009) solar carbon abundance (8.43) and the metallicity ([Fe/H]) from the absolute carbon abundance (A(C)) to estimate [C/Fe].
casper.interface.batch module#
- class casper.interface.batch.Batch(io_paths: dict[str, str] | str)[source]#
Bases:
objectInitialize the Batch object with input/output path configuration.
- Parameters:
io_paths (dict[str, str] | str) – Either a dict containing paths to spectra, parameter files, and output locations, or a path to a legacy Python file that defines those paths.
- archetype_classification() None[source]#
Perform archetype classification for all spectra in the batch.
This method computes the likelihood of each spectrum belonging to one of the three archetype gravity classes (GI, GII, GIII) by calling archetype_classify_MC() on each Spectrum object. It then generates and prints a table summarizing the results.
Output#
A printed likelihood table displaying likelihood scores for each gravity class per star.
A text file saved to disk with suffix “_archetype_likelihood_table.txt”.
Prints total time spent on classification.
Notes
Uses the precomputed LL_DICT for likelihood values.
Assumes that likelihoods for GI, GII, and GIII have been correctly computed and stored.
- build_frames(bounds: tuple = [3800.0, 5000.0]) None[source]#
Construct and trim data frames for each spectrum in the batch.
- For each Spectrum object:
Sets its internal frame using its current wavelength and flux data.
Trims the frame to the specified wavelength bounds.
- Parameters:
bounds (tuple, optional) – A (min, max) wavelength range to trim each spectrum to. Defaults to config.WAVE_BOUNDS.
- calibrate_temperatures(default: bool = True, teff_sigma: int = 250) None[source]#
Calibrate and assign effective temperatures (Teff) for each spectrum.
Uses photometric color indices (J-K and g-r) and gravity class to estimate Teff. If a hard-set Teff value is available, it overrides the photometric estimate.
- Parameters:
default (bool, optional) – Flag for default behavior (not currently used), by default True.
teff_sigma (int, optional) – Standard deviation to associate with temperature uncertainty, by default 250.
Effects (Side)
------------
estimates. (- Updates the TEMP_FRAME for each spectrum with multiple photometric Teff)
photometric). (- Sets the adopted temperature (hard or)
file. (- Writes a temperature summary table to an output)
- ebv_correction() None[source]#
Apply E(B-V) reddening correction to each spectrum’s photometric data.
Iterates through the parameter file and applies extinction correction to each corresponding spectrum in the batch using its row values.
- estimate_logg() None[source]#
Estimate surface gravity (log g) for each spectrum using coarse MCMC parameters.
For each spectrum: - Interpolates log g from temperature and metallicity using a gravity calibration. - Computes uncertainty using the standard deviation and MAD of the sampled distribution.
Output#
Updates each Spectrum object with logg and logg_err.
Prints log g and its uncertainty for each spectrum.
- estimate_sn() None[source]#
Estimate the signal-to-noise ratio (S/N) for each spectrum in the batch.
Applies the estimate_sn() method on each Spectrum object in the spectra_array. This method computes noise characteristics for relevant wavelength regions and stores the S/N statistics in each spectrum’s SN_DICT attribute.
Side Effects#
Updates each spectrum’s SN_DICT with estimated S/N values.
- generate_output_files() None[source]#
Generate and save output parameter files for all spectra.
This method: - Collects output parameter rows from each spectrum. - Saves the combined DataFrame as a .npy binary file in the NPSAVE_DIR. - Attempts to write the same DataFrame to a CSV file using the defined output name.
Output#
A .npy file for structured numpy access.
A .csv file for tabular review; backup is saved with “1” appended if the first fails.
- generate_output_spectra() None[source]#
Generate and save output spectral data for all spectra.
This method: - Collects processed spectral data rows from each spectrum. - Saves the combined DataFrame as a .npy binary file in the NPSAVE_DIR. - Attempts to write the same DataFrame to a CSV file using the defined output name.
Output#
A .npy file for structured numpy access.
A .csv file for tabular review; backup is saved with a suffix if the first attempt fails.
- generate_plots() None[source]#
Generate diagnostic and spectral plots for the batch.
This method produces: - Corner plots from MCMC posteriors for each spectrum. - Trace plots for MCMC chains to assess convergence. - Observed vs. synthetic spectral comparison plots.
Output#
Saves plots to output directory as defined in self.output_name.
- generate_synthetic() None[source]#
Generate synthetic spectra for each Spectrum object in the batch.
For each spectrum: - Uses interpolated model flux values based on MCMC-derived parameters. - Applies continuum normalization to the synthetic flux. - Sets the resulting synthetic spectrum on the Spectrum object.
Output#
Updates each Spectrum with a new synth_spectrum DataFrame.
Handles edge cases where interpolation fails due to invalid parameters.
- get_sn() None[source]#
Retrieve and save the signal-to-noise ratio (S/N) data for all spectra.
This method calls get_sn() on each Spectrum object to gather S/N information, concatenates the results into a single DataFrame, and writes it to a CSV file.
- Returns:
snr (pd.DataFrame) – signal to noise
Output
——
Saves a CSV file containing the S/N data to the specified output path.
Notes
If the first attempt to save fails (e.g., due to file permissions or naming issues), it attempts to save the file with an alternate name ending in “1_snr.csv”.
- load_params() None[source]#
Load stellar parameter file and process key metadata.
This method reads the CSV file at self.param_path and stores it in self.param_file. It ensures key columns like ‘sequence’, ‘mode’, ‘class’, and ‘carbon_mode’ are treated as strings, and stores the list of sequences for further use.
- Sets:
self.param_file (DataFrame): Parsed parameter table from CSV. self.sequence (List[str]): List of sequence identifiers from the parameter file.
- load_spectra() None[source]#
Load observed spectra based on filenames listed in the parameter file.
This method constructs the full path to each spectrum file listed in self.param_file[“filename”], reads the spectrum data (in either FITS or CSV format), and stores it as a list of Spectrum objects.
- Sets:
self.spectra_names (List[str]): List of filenames extracted from the parameter file. self.spectra_array (List[Spectrum]): List of Spectrum objects created from the input files. self.length (int): Number of loaded spectra.
- mcmc_determination() None[source]#
Run MCMC parameter estimation and KDE post-processing for each spectrum in the batch.
This method:
Prepares spectral regions needed for MCMC.
Performs a coarse MCMC run to estimate initial stellar parameters.
Applies KDE smoothing to the coarse MCMC results.
Performs a refined MCMC run based on the coarse outputs.
Applies KDE smoothing to the refined MCMC results.
- Return type:
None
Notes
Updates each Spectrum object in self.spectra_array with MCMC chains, best-fit values,
and KDE distributions. - Prints progress messages and total time taken.
- normalize(default: bool = True) None[source]#
Normalize all spectra in the batch using GISIC normalization.
- For each spectrum in the batch:
Applies GISIC normalization for multiple convolution sigma values.
Averages the continuum estimates and uses them to normalize the spectrum.
Clips normalized flux values to the range [0.0, 2.0] for stability.
Updates the spectrum with the computed normalized flux and continuum.
- Parameters:
default (bool, optional) – If True, performs standard GISIC normalization. Custom normalization is not yet implemented. Defaults to True.
- radial_correct() None[source]#
Apply radial velocity correction to each Spectrum object in the batch.
For each entry in the parameter file, retrieves the corresponding radial velocity (RV) and applies a wavelength shift to the associated Spectrum to correct for Doppler effects.
Prints the correction applied for each spectrum.
- Raises:
ValueError – If RV is missing or cannot be converted to float.
- set_KP_bounds() None[source]#
Set the Ca II K line passband (KP) wavelength bounds for each spectrum.
Uses the get_KP_band() function from the EW module to calculate KP boundaries and assigns them to each spectrum in the batch.
Side Effects#
Updates each spectrum’s KP_bounds attribute.
- set_carbon_mode() None[source]#
Set the carbon mode (“CH” or “CH+C2”) for each spectrum in the batch.
Uses the set_CH_procedure() function from the EW module to determine and assign the appropriate carbon classification mode based on CH band strength and noise characteristics.
Side Effects#
Updates each spectrum’s carbon_mode attribute.
- set_io_paths() None[source]#
Load and configure I/O paths from a parameter file.
This method reads a configuration dict (or legacy Python config file) and parses the paths for the parameter file, spectra directory, and output file.
Notes
This sets the following attributes:
- self.io_params (dict): Dictionary containing keys like ‘param_path’,
‘spectra_dir_path’, and ‘output_file_name’ loaded from the I/O parameter file.
self.param_path (str): Absolute path to the input parameter file.
self.spectra_path (str): Absolute path to the directory containing spectra files.
self.output_name (str): Full output file path including filename, saved under OUTPUT_DIR.
- set_mcmc_args() None[source]#
Build and set MCMC argument dictionaries for all spectra.
This method iterates over each Spectrum object in the batch and calls set_mcmc_args(), which prepares the required arguments for running MCMC parameter estimation.
Notes
MCMC arguments typically include spectral regions, synthetic wavelength grids, initial temperature estimates, and inverse S/N weights.
These are used later during coarse and refined MCMC runs.
- set_params() None[source]#
Assign input parameters from the parameter file to each Spectrum object in the batch.
Iterates over all rows in the loaded parameter DataFrame and sets key attributes on the corresponding Spectrum object, including stellar identifiers, observational class, carbon mode, MCMC iteration settings, and temperature constraints.
- Raises:
AssertionError – If a filename in the parameter file does not match the corresponding Spectrum.
casper.interface.config module#
casper.interface.interface_main module#
J Yoon 03/11/2022 To use multiprocessing module: Some builds of NumPy (including the version included with Anaconda) will automatically parallelize some operations using something like the MKL linear algebra. This can cause problems when used with the parallelization methods described here so it can be good to turn that off (by setting the environment variable OMP_NUM_THREADS=1, for example).
- casper.interface.interface_main.archetype_classify_MC(spectrum: Spectrum) None[source]#
Classify the archetype group (GI, GII, GIII) for a given spectrum using Monte Carlo simulation and log-likelihood comparison.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class with required attributes including: - teff_irfm and teff_irfm_err - normalized frame as a DataFrame with “wave” and “norm” - KP_bounds and SN_DICT - G_CLASS and MODE
Notes
This function: - Draws random temperature values from a normal distribution centered on teff_irfm - Uses those temperatures to synthesize spectra for GI, GII, and GIII groups - Computes log-likelihoods using CAII and CH regions - Selects the group with the highest median log-likelihood - Stores results in spectrum.LL_DICT and sets spectrum.ARCH_GROUP
- casper.interface.interface_main.estimate_logg(spectrum: Spectrum) None[source]#
Estimate and assign the surface gravity (logg) and its uncertainty for the input spectrum.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class containing MCMC parameters and samplers. Must include: - Gravity class - MCMC_COARSE and MCMC_REFINE parameter dictionaries - MCMC_COARSE_sampler - Burn-in discard value (mcmc_coarse_n_discard)
Notes
The logg value is interpolated using effective temperature and metallicity.
Uncertainty is computed using the scaled MAD from the MCMC COARSE samples.
Standard deviation and raw MAD are also printed for reference.
- casper.interface.interface_main.generate_kde_params(spectrum: Spectrum, mode: Literal['COARSE', 'REFINE'], n_thin: int = 1) None[source]#
Perform kernel density estimation (KDE) on the MCMC sampler chain to estimate parameter values and uncertainties for a given spectrum.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class containing MCMC sampler results and configuration data.
mode (Literal["COARSE", "REFINE"]) – Determines whether to use the coarse or refined MCMC sampler chain.
n_thin (int, optional) – Thinning factor for the MCMC chain. Default is 1 (no thinning).
- Return type:
None
Notes
For ndim == 2, this function estimates iron to hydrogen ratio and carbon to iron ratio.
For ndim == 5 or 6, it additionally estimates effective temperature and signal-to-noise terms.
The abundance of carbon (A(C)) is calculated from the iron and carbon ratios.
The KDE is reflected at the edges to reduce boundary artifacts.
Sets MCMC parameter estimates (e.g., effective temperature, iron to hydrogen ratio,carbon to iron ratio, signal-to-noise based uncertainty terms)
Sets KDE objects for each parameter to support probability density evaluation
- casper.interface.interface_main.generate_synthetic(spectrum: Spectrum) None[source]#
Generate and set the best synthetic spectrum for a star based on MCMC parameters.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class that must contain: - Gravity class - MCMC_COARSE[“TEFF”] value - MCMC_REFINE[“FEH”] and [“CFE”] values
Notes
This function: - Uses an interpolator to compute synthetic flux values - Normalizes the flux using a GISIC-based routine - Assigns the normalized synthetic spectrum to the spectrum object - Handles invalid or NaN flux cases gracefully by filling with NaNs
- casper.interface.interface_main.kde_param_reflection(distro: ndarray) Dict[str, Any][source]#
Estimate the peak of a potentially multimodal distribution using kernel density estimation (KDE) with reflective padding to reduce edge effects.
- Parameters:
distro (np.ndarray) – One-dimensional array representing the parameter distribution. Must contain numeric values.
- Returns:
A dictionary with the following keys: - “result”: The peak value (mode) estimated from the KDE with reflection. - “kde”: The KDE fit to the original distribution. - “kde_reflect”: A scaled interpolation function of the KDE fit to the reflected distribution.
- Return type:
Dict[str, Any]
Notes
This method reduces boundary bias by reflecting the distribution at its minimum and maximum.
The same bandwidth is used for both the original and reflected KDE.
The Powell optimization method is used to find the maximum of the reflected KDE.
- casper.interface.interface_main.mcmc_determination(spectrum: Spectrum, mode: str = 'COARSE', burnin_factor: int = 7) None[source]#
Run a Markov Chain Monte Carlo (MCMC) procedure to estimate stellar parameters using the input spectrum and configuration mode.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class that must contain: - Spectral regions - Photometric temperature and error - Signal-to-noise dictionary - Gravity class - Carbon mode - MCMC iteration count - Previously determined COARSE parameters (for REFINE mode)
mode (str, optional) – MCMC run mode, either “COARSE” or “REFINE”. Default is “COARSE”.
burnin_factor (int, optional) – Factor to multiply by the maximum autocorrelation time to determine the number of burn-in steps to discard. Default is 7.
Notes
The function performs the following: - Sets up initial parameters and arguments based on run mode - Uses multiprocessing to speed up MCMC sampling with emcee - Computes autocorrelation time to determine burn-in - Stores the MCMC sampler and related diagnostics back into the spectrum object
- casper.interface.interface_main.synth_normalize(spectrum: Spectrum, group: str, temp: float) ndarray[source]#
Normalize the synthetic flux for a given stellar spectrum.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – A spectrum object that includes gravity class (G_CLASS) and mode (MODE).
group (str) – Archetype group label (e.g., GI, GII, GIII).
temp (float) – Effective temperature in Kelvin.
- Returns:
Continuum-normalized synthetic flux array in the identification wavelength range defined by config.id_start_wave to config.id_end_wave.
- Return type:
np.ndarray
Notes
If the interpolated flux contains non-finite values, a warning is printed and nothing is returned.
casper.interface.io_paths module#
casper.interface.plot_functions module#
- casper.interface.plot_functions.plot_corner_array(spec_batch: Batch) None[source]#
Generate and save corner plots for all spectra in a batch.
This function loops through a batch of spectra, calls plot_single_corner on each, and saves all the resulting corner plots into a single PDF file.
- Parameters:
spec_batch (Batch) – An instance of the Batch class with the following attributes: - spectra_array : list of spectrum-like objects - output_name : str, base name for the output PDF
- Returns:
The function saves a PDF file named “<output_name>_corner.pdf” and does not return a value.
- Return type:
None
- casper.interface.plot_functions.plot_mcmc_trace_array(spec_batch: Batch) None[source]#
Generate and save MCMC trace plots for all spectra in a batch.
This function loops over each spectrum in the batch and uses plot_single_mcmc_trace() to create a trace plot showing how each parameter evolves over MCMC steps. All plots are saved into a single PDF file named “<output_name>_mcmc_trace.pdf”.
- Parameters:
spec_batch (Batch) – An instance of the Batch class with the following attributes: - spectra_array : list of spectrum-like objects - output_name : str, used as the base name for the output PDF
- Returns:
The function writes a PDF to disk but returns nothing.
- Return type:
None
- casper.interface.plot_functions.plot_single_corner(spectrum: Spectrum, io_path: str, n_thin: int = 1) Figure[source]#
Generate a corner plot for MCMC samples from a single spectrum object.
This function retrieves MCMC samples from the spectrum, applies thinning and burn-in, estimates parameter values using KDE, and visualizes the joint distributions and 1D marginals in a corner plot. It also overlays median values and KDEs, along with a LaTeX-formatted legend of key parameters.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class with the following: - MCMC_COARSE_sampler : the emcee sampler object with .get_chain() - get_sequence() : returns spectrum sequence ID - get_starname() : returns star name - mcmc_coarse_n_discard : number of burn-in steps to discard - INPUT_CARBON_MODE : string indicating carbon mode (e.g., “CH” or “CH+C2”) - get_output_row() : returns a DataFrame row containing derived parameters
io_path (str) – Output path used in the plot title or for labeling.
n_thin (int, optional) – Thinning factor for the MCMC chains. Default is 1 (no thinning).
- Returns:
The corner plot figure with parameter distributions and legend annotations.
- Return type:
matplotlib.figure.Figure
Notes
Ensure your matplotlib setup supports LaTeX. If there are issues rendering LaTeX, you may need to install a LaTeX distribution and/or adjust your matplotlib settings.
- casper.interface.plot_functions.plot_single_mcmc_trace(spectrum: Spectrum, n_thin: int = 1) Figure[source]#
Plot the MCMC trace (walkers over steps) for a single spectrum object.
This function visualizes the evolution of MCMC chains for each parameter in the COARSE (or fine) sampler. It adapts the labels and number of plots based on the number of parameters used during sampling (ndim).
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class with the following attributes and methods: - MCMC_COARSE_sampler: the emcee sampler object - get_sequence(): returns an identifier string for the spectrum - get_filename(): returns the source filename - get_MCMC_iterations(): returns total number of iterations - mcmc_coarse_tau: estimated autocorrelation time - mcmc_coarse_acc_frac: mean acceptance fraction - mcmc_coarse_n_discard: suggested burn-in index
n_thin (int, optional) – Thinning factor to reduce the number of MCMC samples plotted. Default is 1.
- Returns:
The matplotlib figure object containing the MCMC trace plots.
- Return type:
matplotlib.figure.Figure
- casper.interface.plot_functions.plot_spectra(spectra_batch: Batch) None[source]#
Generate and save a multi-panel PDF of spectral plots for each spectrum in a batch.
This function creates a multi-page PDF where each page displays several subplots showing the raw, normalized, and zoomed-in regions of each spectrum. For each spectrum, the following are plotted:
Raw flux with continuum overlay
Normalized spectrum
Zoomed-in views of Ca II, CH, and C₂ bands with error shading
Synthetic model overlay
- Parameters:
spectra_batch (Batch) –
- An instance of the Batch class containing:
spectra_array : list of individual spectrum-like objects
output_name : str, base name for the saved PDF file
length : int, total number of spectra in the batch
- Returns:
The function saves a PDF file to disk and does not return any value.
- Return type:
None
- casper.interface.plot_functions.produce_title(spectrum: Spectrum) str[source]#
Generate a formatted plot title string using spectrum metadata and MCMC results.
This function retrieves relevant stellar parameters from the spectrum object, including effective temperature, surface gravity, metallicity, carbon abundance, carbon mode, gravity class, and radial velocity. It then formats these values into a human-readable title suitable for plot labeling.
- Parameters:
spectrum (casper.interface.spectrum.Spectrum) – An instance of the Spectrum class that contains stellar metadata, MCMC-derived parameters, and classification information.
- Returns:
A formatted string representing the title for use in plots.
- Return type:
casper.interface.spectrum module#
- class casper.interface.spectrum.Spectrum(spec: Any, filename: str, is_fits: bool = True)[source]#
Bases:
objectInitialize a spectrum from either a FITS header/data object or a CSV-style DataFrame.
- Parameters:
spec (Any) – The spectrum input object. - If is_fits is True: spec should be a FITS object with accessible headers and data. - If is_fits is False: spec should be a pandas DataFrame with “wave” and “flux” columns.
filename (str) – The name of the input file, used for logging and reference.
is_fits (bool, optional) – Flag indicating whether the input is a FITS file. If False, CSV-style input is expected. Default is True.
- self.wavelength#
Computed wavelength array from FITS header or CSV column.
- Type:
np.ndarray
- self.original_wavelength#
Copy of the original wavelength array.
- Type:
np.ndarray
- self.flux#
Flux values corresponding to the wavelengths.
- Type:
np.ndarray
- self.segments#
Placeholder for segmented spectrum data (to be initialized later).
- Type:
None
- self.mad_global#
Placeholder for global median absolute deviation (optional post-processing).
- Type:
None
- ebv_correct(row: Series) None[source]#
Apply reddening correction (E(B-V)) to observed color indices using SFD extinction values.
This function updates self.PHOTO_0 with dereddened values for: - J-K - H-K - g-r
If E(B-V) > 0, the correction is applied using extinction coefficients from config.A_EBV. Otherwise, it assumes the values are already corrected.
- Parameters:
row (pd.Series) – A pandas row containing the observed color indices: - “J-K”, “H-K”, “g-r” and the reddening value: - “EBV_SFD”
Updates
-------
self.PHOTO_0 (dict) – A dictionary of dereddened color indices.
- estimate_sn() None[source]#
Estimate the signal-to-noise ratio (S/N) and inverse variance (XI) in sideband regions.
This function calculates median S/N and XI values, along with their robust spread (using MAD), for each spectral region defined in config.SIDEBANDS. It also derives shape parameters ‘alpha’ and ‘beta’ for modeling inverse noise variance as a beta distribution.
Conditions#
The function only evaluates bands if both sideband intervals fall within the wavelength coverage.
If a band is out of range, NaNs are stored in the result.
Updates#
- self.SN_DICTdict
A dictionary where each key (e.g., “CA”, “CH”) maps to a sub-dictionary containing: - SN_AVG: average signal-to-noise across both sidebands - SN_STD: robust standard deviation (MAD-based) of S/N - XI_AVG: average inverse S/N - XI_STD: robust std dev of inverse S/N - alpha: shape parameter for beta distribution modeling inverse S/N - beta: shape parameter for beta distribution modeling inverse S/N
- get_KP_bounds() tuple[float, float][source]#
Get the wavelength bounds used for the Ca II K line analysis (KP).
- get_MCMC_iterations() int[source]#
Retrieve the number of MCMC iterations.
- Returns:
The number of iterations used in the MCMC process.
- Return type:
- get_SN_dict() dict[source]#
Get the signal-to-noise (S/N) dictionary computed for spectral sidebands.
- Returns:
A dictionary containing S/N statistics for each spectral region (e.g., ‘CA’, ‘CH’, ‘C2’), including average S/N, standard deviation, average XI, XI standard deviation, and related parameters.
- Return type:
- get_arch_group() str[source]#
Get the archival group classification assigned to the star.
- Returns:
The group classification (e.g., “GI”, “GII”, or “GIII”) based on likelihood analysis.
- Return type:
- get_carbon_mode() str[source]#
Get the carbon analysis mode assigned to the spectrum.
- Returns:
The carbon mode used (e.g., “CH” or “CH+C2”).
- Return type:
- get_environ_mode() str[source]#
Get the galactic environment classification mode.
- Returns:
The galactic environment mode, either “UFD” (ultra-faint dwarf) or “HALO”.
- Return type:
- get_filename() str[source]#
Retrieve the object’s filename, padded for formatting.
- Returns:
The filename as a left-aligned string with a width of 20 characters.
- Return type:
- get_flux() ndarray[source]#
Get the observed flux array of the spectrum.
- Returns:
Array of observed flux values.
- Return type:
np.ndarray
- get_frame() DataFrame[source]#
Get the DataFrame containing the wavelength and flux data used for CASPER analysis.
- Returns:
DataFrame with “wave” and “flux” (and potentially other) columns.
- Return type:
pd.DataFrame
- get_frame_flux() Series[source]#
Get the flux values from the DataFrame used in CASPER analysis.
- Returns:
Series containing the flux values from the current frame.
- Return type:
pd.Series
- get_frame_norm() Series[source]#
Get the normalized flux values from the DataFrame used in CASPER analysis.
- Returns:
Series containing the normalized flux values from the frame.
- Return type:
pd.Series
- get_frame_wave() Series[source]#
Get the wavelength values from the DataFrame used in CASPER analysis.
- Returns:
Series containing the wavelength values from the current frame.
- Return type:
pd.Series
- get_gravity_class() str[source]#
Get the gravity classification of the star.
- Returns:
Gravity class label (e.g., “GIANT” or “DWARF”).
- Return type:
- get_kde_dict() dict | tuple[dict, dict][source]#
Retrieve the kernel density estimation (KDE) results used in MCMC analysis.
- get_mcmc_dict(mode: str = 'COARSE') dict | tuple[dict, dict] | float[source]#
Retrieve the MCMC results dictionary for the specified mode.
- Parameters:
mode (str, optional) – The mode of MCMC results to retrieve. Options are: - “COARSE”: Return only the coarse MCMC results. - “REFINE”: Return only the refined MCMC results. - “BOTH”: Return a tuple of (coarse, refined) MCMC results. Default is “COARSE”.
- Returns:
The requested MCMC results dictionary, a tuple of both, or np.nan if the mode is invalid.
- Return type:
- get_output_row() DataFrame[source]#
Generate a single-row DataFrame with the final stellar parameter outputs.
This method consolidates metadata, MCMC-derived parameters, observational data, and S/N statistics into a structured output format. Useful for analysis export and tracking parameter estimates across runs.
- Returns:
A DataFrame containing one row with: - Star identifiers, gravity and carbon classification - Effective temperature (from IRFM and MCMC) and uncertainties - Surface gravity, [Fe/H], [C/Fe], and A(C) with uncertainties - Radial velocity, observed and synthetic spectra - Signal-to-noise statistics for CA, CH, and optionally C2 regions
- Return type:
pd.DataFrame
- get_photo_temp() tuple[float, float][source]#
Get the photometric effective temperature and its associated uncertainty.
- get_rv() float[source]#
Get the radial velocity used for wavelength correction.
- Returns:
The radial velocity in km/s.
- Return type:
- get_sequence() str[source]#
Retrieve the object’s sequence identifier.
- Returns:
Sequence identifier as a string.
- Return type:
- get_sn() DataFrame[source]#
Compile a summary of signal-to-noise and inverse S/N statistics for key spectral bands.
- Returns:
A single-row DataFrame containing: - Sequence and filename - SN_AVG and SN_STD for CA and CH bands - XI_AVG and XI_STD for CA, CH, and C2 bands - XI_C2 and XI_C2_ERR if carbon mode is “CH+C2”
- Return type:
pd.DataFrame
- get_spectra_row() DataFrame[source]#
Retrieve observed and synthetic spectra as a single-row DataFrame.
This method returns the observed wavelength and normalized flux, along with the corresponding synthetic wavelength and normalized flux, all stored as lists within a single-row DataFrame.
- Returns:
A DataFrame with one row and four columns: - “OBSERVED_WAVE”: list of observed wavelengths - “OBSERVED_FLUX”: list of observed normalized flux values - “SYNTH_WAVE”: list of synthetic wavelengths - “SYNTHETIC_FLUX”: list of synthetic normalized flux values
- Return type:
pd.DataFrame
- get_starname() str[source]#
Retrieve the object’s star name, padded for formatting.
- Returns:
The star name as a left-aligned string with a width of 25 characters.
- Return type:
- get_wave() ndarray[source]#
Get the current wavelength array of the spectrum.
- Returns:
Array of wavelength values.
- Return type:
np.ndarray
- prepare_regions() None[source]#
Prepare wavelength regions for spectral analysis.
This method segments the spectrum into specific wavelength regions for calcium (CA), CH, and optionally C2 molecular bands based on the carbon_mode.
Regions are: - CA: Defined by self.KP_bounds - CH: 4222 angstrom to 4322 angstrom - C2: 4710 angstrom to 4750 angstrom (only if carbon_mode is “CH+C2”)
The resulting regions are stored in self.regions as a dictionary of DataFrames.
- print_KP_bounds() str[source]#
Return the Ca II K region wavelength bounds as a formatted string.
- Returns:
A string representation of the Ca II K region bounds, formatted as ‘lower_bound - upper_bound’.
- Return type:
- radial_correction(velocity: float = 0.0) None[source]#
Apply radial velocity correction to the wavelength array.
This function updates the object’s wavelength array by shifting it to the rest frame using the provided radial velocity.
- set_GBAND(input: float) None[source]#
Set the G-band equivalent width (EW) measurement.
- Parameters:
input (float) – The measured G-band equivalent width.
- Return type:
None
- set_KP_bounds(input_bounds: list[float]) None[source]#
Set the KP (Ca II K line) equivalent width integration bounds.
- set_carbon_mode(carbon_mode: str) None[source]#
Set the carbon mode used for the spectrum analysis.
- Parameters:
carbon_mode (str) – The carbon mode to be applied (e.g., “CH” or “CH+C2”).
- set_flux(input_flux: ndarray) None[source]#
Set the flux array for the spectrum.
- Parameters:
input_flux (np.ndarray) – Array of flux values corresponding to the spectrum’s wavelengths.
- Return type:
None
- set_frame(wave: ndarray, flux: ndarray) None[source]#
Set the spectral data frame with wavelength and flux.
- Parameters:
wave (np.ndarray) – Array of wavelength values.
flux (np.ndarray) – Array of corresponding flux values.
- Return type:
None
- set_frame_cont(input_cont: ndarray) None[source]#
Add or update the ‘cont’ column in the spectral data frame.
- Parameters:
input_cont (np.ndarray) – Array of continuum flux values to assign to the ‘cont’ column.
- Return type:
None
- set_frame_norm(input_norm: ndarray) None[source]#
Add or update the ‘norm’ column in the spectral data frame.
- Parameters:
input_norm (np.ndarray) – Array of normalized flux values to assign to the ‘norm’ column.
- Return type:
None
- set_group_ll(input_dict: Dict[str, Tuple[float, Any]]) None[source]#
Set the log-likelihood values and assign the most probable stellar group.
This function updates the internal LL dictionary, selects the group with the highest log-likelihood score, prints the result, and assigns the group label (GI, GII, or GIII) to the spectrum.
- Parameters:
input_dict (dict) – Dictionary mapping group names (e.g., “GI”, “GII”, “GIII”) to tuples containing log-likelihood values and associated data.
- set_kde_functions(input_dict: dict, mode: str) None[source]#
Set the kernel density estimation (KDE) results from MCMC output.
- Parameters:
- Raises:
ValueError – If the provided mode is not “COARSE” or “REFINE”.
- set_mcmc_args(input_dict: dict | None = None) None[source]#
Set the arguments used for the Markov Chain Monte Carlo (MCMC) procedure.
This method stores the MCMC-related arguments into the object’s mcmc_args attribute.
- Parameters:
input_dict (dict or None, optional) – A dictionary of MCMC arguments. If None, an empty dictionary is assigned.
- set_mcmc_results(input_dict: dict, mode: str) None[source]#
Set the results from the Markov Chain Monte Carlo (MCMC) runs.
Depending on the mode provided, stores the MCMC output into either the COARSE or REFINE attribute.
- set_norm(input_flux: ndarray) None[source]#
Set the normalized flux array for the spectrum.
- Parameters:
input_flux (np.ndarray) – Array of normalized flux values.
- Return type:
None
- set_params(SEQUENCE: str, STARNAME: str, CLASS: str, JK: float, MODE: str, INPUT_CARBON_MODE: str, iter: int, T_SIGMA: float, HARD_TEFF: float) None[source]#
Set the core stellar parameters and classification attributes for the spectrum.
- Parameters:
SEQUENCE (str) – Unique identifier for the spectrum in the sequence list.
STARNAME (str) – Identifier or name of the observed star.
CLASS (str) – Stellar gravity class. Must be either “GIANT” or “DWARF”.
JK (float) – J - K color index of the star.
MODE (str) – Galactic environment mode. Must be “UFD” (ultra-faint dwarf) or “HALO”.
INPUT_CARBON_MODE (str) – Initial carbon mode selection, e.g., “CH” or “CH+C2”.
iter (int) – Number of MCMC iterations to be run for fitting.
T_SIGMA (float) – Gaussian prior sigma on Teff.
HARD_TEFF (float) – Fixed Teff value if used as a hard prior.
- Raises:
AssertionError – If CLASS is not “GIANT” or “DWARF”, or if MODE is not “UFD” or “HALO”.
- set_sampler(input_sampler: object, mode: str = 'COARSE') None[source]#
Set the MCMC sampler object for a given sampling mode.
- set_synth_spectrum(synth: dict) None[source]#
Set the synthetic spectrum for the object.
- Parameters:
synth (dict) – Dictionary containing the synthetic spectrum data, typically with keys like “wave” and “norm” for wavelength and normalized flux arrays.
- Return type:
None
- set_temp_frame(TEMP_FRAME: DataFrame) None[source]#
Set the temperature frame for the spectrum.
This method assigns the given DataFrame of temperature estimates to the object’s TEMP_FRAME attribute.
- Parameters:
TEMP_FRAME (pandas.DataFrame) – A DataFrame containing temperature values from various calibration methods.
- set_temperature(input_temp: float, sigma: float) None[source]#
Set the effective temperature and its uncertainty.
This method assigns the input effective temperature and its corresponding uncertainty to the spectrum object.
- casper.interface.spectrum.obtain_flux(data)[source]#
Extract a 1D flux array from FITS-like input data with varying shapes.
If the input data is 1D, it is flattened and returned directly. If the data is multi-dimensional, the first row is selected and flattened.
- Parameters:
data (np.ndarray) – Input data array, typically from a FITS file.
- Returns:
A flattened 1D array representing the flux.
- Return type:
np.ndarray
casper.interface.synthetic_functions module#
- casper.interface.synthetic_functions.CAII_CH_CHI_LH(obs: DataFrame, synth: Dict[str, _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]], CA_BOUNDS: Tuple[float, float], CH_BOUNDS: Tuple[float, float], CA_XI: float, CH_XI: float) float[source]#
Calculate how well the synthetic spectrum matches the observed data in the Ca II and CH wavelength regions.
- Parameters:
obs (DataFrame) – Observed spectrum with “wave” and “norm” columns.
synth (dict) – Synthetic spectrum with: - “wave”: array of wavelengths - “norm”: array of normalized flux values
CA_BOUNDS (tuple) – Wavelength range for the Ca II region (min, max).
CH_BOUNDS (tuple) – Wavelength range for the CH region (min, max).
CA_XI (float) – Inverse signal-to-noise ratio (1 / SNR) for the Ca II region.
CH_XI (float) – Inverse signal-to-noise ratio (1 / SNR) for the CH region.
- Returns:
The total log-likelihood score for both regions. Higher values mean the synthetic model matches the data better.
- Return type:
- casper.interface.synthetic_functions.get_grav_interp()[source]#
Load and return the pre-computed surface-gravity interpolator.
This utility opens the pickled file that stores an isochrone-based interpolator for stellar surface gravity (log g) and returns the loaded object.
- Returns:
GRAV_INTERP – The surface-gravity interpolation object loaded from
interface/libraries/grav_interp.pkl.- Return type:
- casper.interface.synthetic_functions.get_interp()[source]#
Load and return the precomputed spectral interpolation library.
This function reads a pickled file containing a precomputed interpolator used for synthetic spectra at a resolution of R~2000. The interpolator is used to estimate model spectra at arbitrary stellar parameters.
- Returns:
INTERPOLATOR – The loaded interpolation object from the pickled file.
- Return type:
- casper.interface.synthetic_functions.ln_chi_square_sigma(flux: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], synth: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], xi: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) float[source]#
Calculate truncated log chi-square probability distribution function for an absorption feature.
The function allows evaluating how well the synthetic spectrum matches the observed one by comparing observed flux values to synthetic (model) flux values using a version of the chi-square formula. The uncertainty is based on the signal-to-noise ratio and is adjusted using the model flux.
- Parameters:
flux (array_like) – The observed flux values.
synth (array_like) – The synthetic (model) flux values, matched in wavelength to the observed flux.
xi (array_like or float) – The inverse signal-to-noise ratio (1 / SNR). This gets multiplied by the synthetic flux to get the uncertainty for each point.
- Returns:
A number that tells us how likely the model is to match the data. If the result is not valid (e.g., negative), it returns -infinity.
- Return type:
- casper.interface.synthetic_functions.normalize_synth_spectrum(synth_wave: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], synth_flux: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]) ndarray[source]#
Normalize a synthetic spectrum using GISIC continuum fitting.
This function applies the GISIC normalization algorithm across multiple sigma values (defined in the config) to generate continuum fits for a synthetic spectrum. The median of all continuum estimates is used to normalize the input flux.
- Parameters:
synth_wave (array_like) – Wavelength values of the synthetic spectrum.
synth_flux (array_like) – Corresponding flux values of the synthetic spectrum.
- Returns:
synth_norm – The continuum-normalized synthetic flux array. Flux values are scaled such that the continuum is near unity. Values below 0 or above 2 are clipped to 1.0 for stability.
- Return type:
ndarray
casper.interface.temp_calibrations module#
- casper.interface.temp_calibrations.Bergeat(JK: float) float[source]#
Estimate effective temperature using the Bergeat calibration.
This function calculates Teff using the $(J-K)_{0}$ color and [Fe/H], following the approach from Bergeat et al.
- Parameters:
JK (float) – The $(J-K)_{0}$ color index.
- Returns:
Effective temperature in Kelvin.
- Return type:
Notes
Based on the calibration from Bergeat et al. (2001), Eq.(19) and Table 5.
- casper.interface.temp_calibrations.Casagrande(JK: float, FEH: float = -2.5, CLASS: str | None = None) float[source]#
Estimate effective temperature using the Casagrande Calibration.
This function calculates stellar effective temperature (Teff) from the J-Ks color index and metallicity [Fe/H], using an empirical formula. It is valid for 0.07 ≤ JK ≤ 0.80.
- Parameters:
- Returns:
Effective temperature in Kelvin. Returns np.nan if JK is out of bounds.
- Return type:
Notes
Based on the calibration from [Casagrande et al. (2010)](https://ui.adsabs.harvard.edu/abs/2010A%26A…512A..54C/abstract). Reference: J-Ks in Table 4 and Eq. (3)
- casper.interface.temp_calibrations.Fukugita(gr: float) float[source]#
Estimate effective temperature from g-r color index using the Fukugita et al. (2011) relation.
- casper.interface.temp_calibrations.Hernandez(JK: float, FEH: float = -2.5, CLASS: str | None = None) float[source]#
Compute effective temperature (Teff) using the Hernandez Calibration.
This function estimates stellar effective temperature from the (J-Ks) color and metallicity [Fe/H], using separate calibrations for GIANT and DWARF stars.
- Parameters:
- Returns:
Effective temperature in Kelvin. Returns np.nan if JK is out of the valid range.
- Return type:
Notes
Based on the infrared flux method from [Hernandez et al. (2009)](https://ui.adsabs.harvard.edu/abs/2009A%26A…497..497G/abstract). Reference: J-Ks in Table 5 and Eq. (10)
- casper.interface.temp_calibrations.calibrate_temp_frame(JK: float, gr: float, FEH: float = -2.5, CLASS: str | None = None) DataFrame[source]#
Build a DataFrame of calibrated effective temperature estimates using multiple color indices.
This function runs various photometric temperature calibrations (Casagrande, Hernandez, Bergeat, Fukugita) depending on the availability of valid (finite) input values for J-Ks and g-r color indices. It then attempts to determine an adopted Teff value.
- Parameters:
- Returns:
A DataFrame containing the Teff estimates from each calibration and an additional row “ADOPTED” with the median effective temperature. If adoption fails, “ADOPTED” will be set to NaN.
- Return type:
pd.DataFrame
- casper.interface.temp_calibrations.determine_effective(TEMP_FRAME: DataFrame) DataFrame[source]#
Determine the adopted effective temperature from a table of temperature estimates.
This function: - Sorts the input DataFrame by the “VALUE” column - Filters out non-finite values - Selects the median finite value as the adopted effective temperature - Appends this value to the DataFrame with the index “ADOPTED”
- Parameters:
TEMP_FRAME (pd.DataFrame) – DataFrame containing a “VALUE” column with Teff estimates.
- Returns:
The original DataFrame with an additional row indexed as “ADOPTED”, containing the median finite temperature value.
- Return type:
pd.DataFrame
- Raises:
AssertionError – If the selected temperature value is not finite.