sheap.Sheapectral.Sheapectral module
Main sheap Interface
Provides the Sheapectral class, the high-level entry point for loading, correcting, fitting, and analyzing AGN spectra with sheap.
Contents
Spectral I/O: load spectra from arrays or files.
Corrections: apply Galactic extinction and redshift corrections.
Modeling: build complex spectral regions via SheapModelBuilder.
Fitting: run JAX-based optimization with SheapModelFitting.
Posterior Sampling: estimate parameters using single, pseudo-MC, MC, or MCMC.
Persistence: save/load full state with pickle.
Visualization: quicklook plotting and model visualization with SheapPlot.
Notes
Input spectra are expected in shape (n_objects, 3[,4], n_pixels), with channels = (wavelength, flux, error[, wdisp]).
Velocity resolution (FWHM) is computed from dispersion when available.
Main workflow:
sheap = Sheapectral("spectrum.fits", z=0.5, coords=(l, b)) sheap.makemodel(6500, 6600, n_narrow=1, n_broad=2) sheap.fitmodel() sheap.posteriors(sampling_method="montecarlo")
Results are stored in self.result (SheapResult).
- class Sheapectral(spectra, z=None, coords=None, ebv=None, names=None, extinction_correction='pending', redshift_correction='pending', **kwargs)[source]
Bases:
objectMain interface class for loading, correcting, fitting, and analyzing AGN spectra.
This class handles: - Spectral I/O and validation - Extinction and redshift correction - Spectral region definition and model building - JAX-based optimization and uncertainty estimation - Posterior sampling using Monte Carlo or MCMC - Saving/loading results from pickle - Quick visualization and result summaries
- Parameters:
spectra (str or jnp.ndarray) – Input spectra. If a string, it should be a path to a file readable by np.loadtxt. Expected shape after parsing: (n_objects, 3[, or 4], n_pixels).
z (float or jnp.ndarray, optional) – Redshift(s) for each spectrum. Scalar or 1D array of shape (n_objects,).
coords (jnp.ndarray, optional) – Galactic coordinates (l, b) for extinction correction, shape (n_objects, 2).
ebv (jnp.ndarray, optional) – E(B-V) values. If not provided, estimated from coords using the SFD map.
names (list of str, optional) – Object names. Defaults to stringified index if not given.
extinction_correction ({'pending', 'done'}, optional) – Whether to apply extinction correction during initialization.
redshift_correction ({'pending', 'done'}, optional) – Whether to apply redshift correction during initialization.
**kwargs – Additional arguments passed to underlying utilities.
- spectra
3D array with shape (n_objects, 3, n_pixels) [wavelength, flux, error].
- Type:
jnp.ndarray
- wdisp
Wavelength dispersion (if available) per pixel.
- Type:
jnp.ndarray or None
- fwhm_lambda
Instrumental resolution in Angstroms, if wdisp provided.
- Type:
jnp.ndarray
- fwhm_kms
Instrumental resolution in km/s.
- Type:
jnp.ndarray
- result
#TODO maybe change this name Output of the fitting routine, including parameters and metadata.
- Type:
- modelbuild
Configuration used to build the model region.
- Type:
- makemodel(xmin, xmax, n_narrow=1, n_broad=1, \*\*kwargs)[source]
Create a model from line and continuum definitions.
- Parameters:
limits (tuple)
n_narrow (int)
n_broad (int)
- fitmodel(...)[source]
Perform spectral model fitting using the configured model.
- Parameters:
profile (str)
penalty_weight (float)
curvature_weight (float)
smoothness_weight (float)
max_weight (float)
- estimate_posteriors(...)[source]
Estimate posterior distributions using MC or MCMC or just give and estimation of the params.
- Parameters:
num_samples (int)
key_seed (int)
- save_to_pickle(filepath)[source]
Save object state to a pickle file.
- Parameters:
filepath (str | Path)
- from_pickle(filepath)[source]
Load a Sheapectral instance from a saved pickle.
- Parameters:
filepath (str | Path)
- Return type:
- result_panda(n)[source]
Return a Pandas DataFrame of the fit parameters for object n.
- Parameters:
n (int)
param_filter (str | None)
regex (bool)
case (bool)
- Return type:
pd.DataFrame
- quicklook(idx, ax=None, xlim=None, ylim=None)[source]
Plot flux + error for spectrum idx.
- Parameters:
idx (int)
- modelplot()
Return or initialize plotting interface (SheapPlot).
- sheap_set_up()[source]
Ensure spectra have leading object axis, record shape and NaN mask.
- Parameters:
None
- Return type:
None
- makemodel(limits=None, n_narrow=1, n_broad=1, group_method=True, add_balmer_continuum=True, add_balmerhighorder_continuum=True, **kwargs)[source]
Initialize a SheapModelBuilder for later fitting.
- Parameters:
limits (tuple xmin,xmax)
n_narrow (int, optional) – Number of narrow components per line.
n_broad (int, optional) – Number of broad components per line.
**kwargs – Additional SheapModelBuilder options.
- Return type:
None
- fitmodel(run_fit=True, list_num_steps=None, list_learning_rate=None, covariance_error=False, profile='gaussian', add_penalty_function=False, method='adam', penalty_weight=0.0, curvature_weight=0.0, smoothness_weight=0.0, max_weight=0.0, limits_overrides={})[source]
Execute fitting of the prepared region on the spectra.
- Parameters:
list_num_steps (list of int, optional) – Maximum optimization steps per routine stage.
run_uncertainty_params (bool, optional) – Whether to compute parameter uncertainties.
profile (str, optional) – Line profile type for fitting.
list_learning_rate (list of float, optional) – Learning rates for each stage.
run_fit (bool, optional) – If False, construct the SheapModelFitting object without fitting.
add_penalty_function (bool, optional) – If True, include host-model penalty.
penalty_weight (float)
curvature_weight (float)
smoothness_weight (float)
max_weight (float)
- Raises:
RuntimeError – If makemodel() was not called first.
- Return type:
None
- estimate_posteriors(sampling_method='single', num_samples=50, key_seed=0, summarize=False, overwrite=False, num_warmup=500, n_random=1000, frac_box_sigma=0.02, k_sigma=0.3, only_sheaproducts=False, **kwargs)[source]
Estimate or sample posterior distributions of fit parameters.
- Parameters:
sampling_method ({'single', 'pseudomontecarlo', 'mcmc',"montecarlo"}) – Sampling algorithm to use.
num_samples (int, optional) – Number of samples to draw.
key_seed (int, optional) – Random seed for reproducibility.
summarize (bool, optional) – If True, compute summary statistics.
overwrite (bool, optional) – If True, rerun even if posterior exists.
num_warmup (int, optional) – Warm-up steps for MCMC.
n_random (int, optional) – Number of initial random positions for MCMC.
extra_products (bool, optional) – Return additional diagnostics.
- Returns:
Posterior object or results dictionary.
- Return type:
ParameterEstimation or dict
- Raises:
RuntimeError – If fit has not been run (self.result missing).
- classmethod from_pickle(filepath)[source]
Load a saved Sheapectral instance from a pickle file.
- Parameters:
filepath (str or Path) – Path to the pickle file created by save_to_pickle().
- Returns:
Restored object with loaded spectra and results.
- Return type:
- save_to_pickle(filepath)[source]
Save the current object state to a pickle file (.pkl).
- Parameters:
filepath (str or Path) – Destination path for the pickle.
- Return type:
None
- profile_functions_from_region_list()[source]
Recreate profile functions for each region component.
- Returns:
Profile model functions.
- Return type:
list of callables
- property modelplot
Get or initialize the SheapPlot plotting interface. TODO modelplot or plotter?
- Returns:
Plotting backend for spectra and fit results.
- Return type:
- Raises:
RuntimeError – If no fit result exists.
- result_panda(n, param_filter=None, regex=False, case=True)[source]
#TODO update this part to be able to show the actual name of the parameter lets say line with 0,1,2,3,4 is easier for code reason but for visualitation could be messy #TODO say if the paramters are at scale or not. Return a pandas DataFrame of fit parameters for a given spectrum.
- Parameters:
n (int) – Index of the spectrum object.
param_filter (str, optional) – If provided, return only rows whose parameter name matches this pattern. Uses pandas .str.contains, so it can be a substring or a regex (see regex and case).
regex (bool, default False) – If True, param_filter is interpreted as a regular expression.
case (bool, default True) – If False, ignore case when matching param_filter.
- Returns:
Index: parameter name. Columns: [‘value’, ‘error’, ‘max_constraint’,
’init_value’, ‘min_constraint’].
- Return type:
pandas.DataFrame
- quicklook(idx, ax=None, xlim=None, ylim=None, add_text=True, figsize=(15, 5))[source]
Produce a quick errorbar plot of flux vs. wavelength.
- Parameters:
idx (int) – Spectrum index to plot.
ax (matplotlib.axes.Axes, optional) – Axes to plot into (creates new if None).
xlim (tuple, optional) – X-axis limits as (xmin, xmax).
ylim (tuple, optional) – Y-axis limits as (ymin, ymax).
- Returns:
The axes containing the plot.
- Return type:
matplotlib.axes.Axes
- property plot_redshift_signal2noise_distribution
- property plot_chi2