Fitting Interface#

class jaxqsofit.JAXQSOFit(config)[source]#

Bases: object

Config-first spectral fitting interface for quasar spectra.

Parameters:

config (jaxqsofit.config.FitConfig)

__init__(config)[source]#

Initialize a config-first JAXQSOFit spectral fitter.

Parameters:

config (object) – config value.

property numpyro_samples#

Posterior samples mirrored from the internal posterior state.

property pred_out#

Posterior predictive outputs mirrored from the internal posterior state.

property pred_bands#

Posterior uncertainty bands mirrored from the internal posterior state.

property fig#

Main fitted-spectrum figure mirrored from the internal posterior state.

property trace_fig#

Trace figure mirrored from the internal posterior state.

property corner_fig#

Corner figure mirrored from the internal posterior state.

classmethod from_arrays(*, lam, flux, err=None, mask=None, z=0.0, ra=None, dec=None, filename=None, output_path=None, resolving_power=None, apply_instrumental_resolution=False, psf_mags=None, psf_mag_errs=None, psf_bands=None)[source]#

Build a config-first fitter from raw arrays.

Parameters:
  • lam (array-like) – Observed-frame wavelength array in Angstrom.

  • flux (array-like) – Observed spectral flux-density array.

  • err (array-like or float, optional) – Flux-density uncertainty. If omitted, a small positive uncertainty is supplied by the downstream data preparation.

  • mask (array-like of bool, optional) – Pixel keep-mask. True includes a pixel and False rejects it.

  • z (float, optional) – Source redshift.

  • ra (float, optional) – Sky coordinates in degrees, used for Milky Way dereddening when enabled.

  • dec (float, optional) – Sky coordinates in degrees, used for Milky Way dereddening when enabled.

  • filename (str, optional) – Object name and default output basename.

  • output_path (str or pathlib.Path, optional) – Directory for saved figures and posterior bundles.

  • resolving_power (float, optional) – Effective resolving power used to downweight oversampled spectral likelihoods.

  • apply_instrumental_resolution (bool, optional) – If True, include the Gaussian instrumental LSF in the forward model. Requires a positive resolving_power. Defaults to False.

  • psf_mags (array-like, optional) – PSF-aperture magnitudes and uncertainties used for spectral recalibration.

  • psf_mag_errs (array-like, optional) – PSF-aperture magnitudes and uncertainties used for spectral recalibration.

  • psf_bands (sequence of str, optional) – Filter names corresponding to psf_mags.

save_posterior_bundle(save_name=None, save_path=None, *, _state=None)[source]#

Persist posterior samples plus minimal metadata for compact reloads.

Parameters:
  • save_name (object) – save_name value.

  • save_path (object) – save_path value.

  • _state (object) – _state value.

save(path=None, *, save_name=None, _state=None)[source]#

Persist posterior samples and fit metadata to a compact bundle.

Parameters:
  • path (object) – path value.

  • save_name (object) – save_name value.

  • _state (object) – _state value.

classmethod load_from_samples(filename=None, output_path=None, save_name=None, plot_fig=True, plot_diagnostics=True, kwargs_plot=None, diagnostics_kwargs=None)[source]#

Load a compressed HDF5 posterior bundle and return a JAXQSOFit object.

Parameters:
  • filename (object) – filename value.

  • output_path (object) – output_path value.

  • save_name (object) – save_name value.

  • plot_fig (object) – plot_fig value.

  • plot_diagnostics (object) – plot_diagnostics value.

  • kwargs_plot (object) – kwargs_plot value.

  • diagnostics_kwargs (object) – diagnostics_kwargs value.

classmethod load(filename=None, output_path=None, save_name=None, plot_fig=True, plot_diagnostics=True, kwargs_plot=None, diagnostics_kwargs=None)#

Load a compressed HDF5 posterior bundle and return a JAXQSOFit object.

Parameters:
  • filename (object) – filename value.

  • output_path (object) – output_path value.

  • save_name (object) – save_name value.

  • plot_fig (object) – plot_fig value.

  • plot_diagnostics (object) – plot_diagnostics value.

  • kwargs_plot (object) – kwargs_plot value.

  • diagnostics_kwargs (object) – diagnostics_kwargs value.

classmethod load_result(*args, **kwargs)[source]#

Load a posterior bundle and wrap it in a FitResult.

Parameters:
  • *args (tuple) – Additional positional arguments.

  • **kwargs (dict) – Additional keyword arguments.

Return type:

FitResult

fit(*, verbose=True, kwargs_plot=None, **kwargs)[source]#

Run preprocessing, inference, persistence, and plotting.

The public API is configuration-first: construct JAXQSOFit with a jaxqsofit.config.FitConfig, then call fit(). Model choices, preprocessing, inference settings, output behavior, PSF recalibration data, and priors all live on the config object.

Parameters:
  • verbose (bool, optional) – Verbose optimizer output where applicable.

  • kwargs_plot (dict or None, optional) – Extra keyword arguments passed to plot_fig().

  • **kwargs – Removed legacy fit keyword arguments. Passing any value here raises a configuration-first error message with the corresponding config field when one exists.

Returns:

Result object exposing samples, medians, persistence, and plotting helpers while the fitter keeps mirrored posterior state.

Return type:

FitResult

run_fsps_numpyro_fit(num_warmup=500, num_samples=1000, num_chains=1, target_accept_prob=0.9, dense_mass=False, max_tree_depth=8, warmup_max_tree_depth=None, age_grid_gyr=(0.1, 0.3, 1.0, 3.0, 10.0), logzsol_grid=(-1.0, -0.5, 0.0, 0.2), prior_config=None, dsps_ssp_fn='tempdata.h5', use_lines=True, decompose_host=True, fit_pl=True, fit_fe=True, fit_bc=True, fit_poly=False, fit_reddening=False, fit_poly_order=2, psf_mags=None, psf_mag_errs=None, psf_filter_curves=None, use_psf_phot=False, custom_components=None, custom_line_components=None, init_values=None, random_seed=0)[source]#

Fit the full model using NUTS MCMC and store posterior summaries.

Parameters:
  • num_warmup (int, optional) – MCMC warmup and posterior sample counts.

  • num_samples (int, optional) – MCMC warmup and posterior sample counts.

  • num_chains (int, optional) – Number of MCMC chains.

  • target_accept_prob (float, optional) – Target acceptance probability for NUTS.

  • dense_mass (bool, optional) – If True, use one global dense mass matrix. The default False uses compact dense emission-line blocks unless disabled in prior_config.

  • max_tree_depth (int, optional) – Maximum NUTS tree depth.

  • warmup_max_tree_depth (int or None, optional) – Warmup-only tree-depth limit. Retained draws continue to use max_tree_depth so adaptation can explore longer trajectories without silently increasing the production cost ceiling.

  • age_grid_gyr (sequence of float, optional) – SSP age grid in Gyr.

  • logzsol_grid (sequence of float, optional) – SSP metallicity grid in log(Z/Zsun).

  • prior_config (dict or None, optional) – Prior/config dictionary for model blocks.

  • dsps_ssp_fn (str, optional) – DSPS SSP template HDF5 path.

  • use_lines (bool, optional) – Component toggles for model blocks.

  • decompose_host (bool, optional) – Component toggles for model blocks.

  • fit_pl (bool, optional) – Component toggles for model blocks.

  • fit_fe (bool, optional) – Component toggles for model blocks.

  • fit_bc (bool, optional) – Component toggles for model blocks.

  • fit_poly (bool, optional) – Component toggles for model blocks.

  • fit_reddening (bool, optional) – Component toggles for model blocks.

  • fit_poly_order (int, optional) – Polynomial order for the multiplicative continuum tilt.

  • init_values (dict or None, optional) – Optional initial values for init_to_value.

  • psf_mags (object) – psf_mags value.

  • psf_mag_errs (object) – psf_mag_errs value.

  • psf_filter_curves (object) – psf_filter_curves value.

  • use_psf_phot (object) – use_psf_phot value.

  • custom_components (object) – custom_components value.

  • custom_line_components (object) – custom_line_components value.

run_fsps_optax_fit(num_steps=2000, learning_rate=1e-2, age_grid_gyr=(0.1, 0.3, 1.0, 3.0, 10.0), logzsol_grid=(-1.0, -0.5, 0.0, 0.2), prior_config=None, dsps_ssp_fn='tempdata.h5', use_lines=True, decompose_host=True, fit_pl=True, fit_fe=True, fit_bc=True, fit_poly=False, fit_reddening=False, fit_poly_order=2, psf_mags=None, psf_mag_errs=None, psf_filter_curves=None, use_psf_phot=False, custom_components=None, custom_line_components=None, plot_init=False, random_seed=0)[source]#

Fit a MAP approximation using staged SVI with an Optax optimizer.

Parameters:
  • num_steps (int, optional) – Total SVI steps across all stages.

  • learning_rate (float, optional) – Adam learning rate.

  • age_grid_gyr (sequence of float, optional) – SSP age grid in Gyr.

  • logzsol_grid (sequence of float, optional) – SSP metallicity grid in log(Z/Zsun).

  • prior_config (dict or None, optional) – Prior/config dictionary for model blocks.

  • dsps_ssp_fn (str, optional) – DSPS SSP template HDF5 path.

  • use_lines (bool, optional) – Component toggles for model blocks.

  • decompose_host (bool, optional) – Component toggles for model blocks.

  • fit_pl (bool, optional) – Component toggles for model blocks.

  • fit_fe (bool, optional) – Component toggles for model blocks.

  • fit_bc (bool, optional) – Component toggles for model blocks.

  • fit_poly (bool, optional) – Component toggles for model blocks.

  • fit_reddening (bool, optional) – Component toggles for model blocks.

  • fit_poly_order (int, optional) – Polynomial order for the multiplicative continuum tilt.

  • plot_init (bool, optional) – If True, plot and store the stage-1 continuum/host warm-start model before starting the full model stage.

  • psf_mags (object) – psf_mags value.

  • psf_mag_errs (object) – psf_mag_errs value.

  • psf_filter_curves (object) – psf_filter_curves value.

  • use_psf_phot (object) – use_psf_phot value.

  • custom_components (object) – custom_components value.

  • custom_line_components (object) – custom_line_components value.

run_fsps_optax_nuts_fit(optax_steps=2000, optax_learning_rate=1e-2, num_warmup=500, num_samples=1000, num_chains=1, target_accept_prob=0.9, dense_mass=False, max_tree_depth=8, warmup_max_tree_depth=None, age_grid_gyr=(0.1, 0.3, 1.0, 3.0, 10.0), logzsol_grid=(-1.0, -0.5, 0.0, 0.2), prior_config=None, dsps_ssp_fn='tempdata.h5', use_lines=True, decompose_host=True, fit_pl=True, fit_fe=True, fit_bc=True, fit_poly=False, fit_reddening=False, fit_poly_order=2, psf_mags=None, psf_mag_errs=None, psf_filter_curves=None, use_psf_phot=False, custom_components=None, custom_line_components=None, plot_init=False, random_seed=0)[source]#

Warm-start with Optax MAP, then run NUTS as final inference.

Parameters:
  • optax_steps (int, optional) – Number of SVI/Optax warm-start steps.

  • optax_learning_rate (float, optional) – Learning rate for SVI warm-start.

  • num_warmup (int, optional) – NUTS warmup and posterior sample counts.

  • num_samples (int, optional) – NUTS warmup and posterior sample counts.

  • num_chains (int, optional) – Number of MCMC chains.

  • target_accept_prob (float, optional) – Target acceptance probability for NUTS.

  • dense_mass (bool, optional) – If True, use one global dense mass matrix. The default False uses compact dense emission-line blocks unless disabled in prior_config.

  • max_tree_depth (int, optional) – Maximum NUTS tree depth.

  • warmup_max_tree_depth (int or None, optional) – Warmup-only tree-depth limit passed to NumPyro.

  • age_grid_gyr (sequence of float, optional) – SSP age grid in Gyr.

  • logzsol_grid (sequence of float, optional) – SSP metallicity grid in log(Z/Zsun).

  • prior_config (dict or None, optional) – Prior/config dictionary for model blocks.

  • dsps_ssp_fn (str, optional) – DSPS SSP template HDF5 path.

  • use_lines (bool, optional) – Component toggles for model blocks.

  • decompose_host (bool, optional) – Component toggles for model blocks.

  • fit_pl (bool, optional) – Component toggles for model blocks.

  • fit_fe (bool, optional) – Component toggles for model blocks.

  • fit_bc (bool, optional) – Component toggles for model blocks.

  • fit_poly (bool, optional) – Component toggles for model blocks.

  • fit_reddening (bool, optional) – Component toggles for model blocks.

  • fit_poly_order (int, optional) – Polynomial order for the multiplicative continuum tilt.

  • plot_init (bool, optional) – If True, plot and store the stage-1 Optax warm-start model before starting the full Optax stage and NUTS.

  • psf_mags (object) – psf_mags value.

  • psf_mag_errs (object) – psf_mag_errs value.

  • psf_filter_curves (object) – psf_filter_curves value.

  • use_psf_phot (object) – use_psf_phot value.

  • custom_components (object) – custom_components value.

  • custom_line_components (object) – custom_line_components value.

reconstruct_posterior_spectrum(wave_out=None, wave_min=2500.0, wave_max=None, n_draws=None, return_components=True, _state=None)[source]#

Rebuild posterior component draws on a requested rest-frame grid.

Parameters:
  • wave_out (array-like or None, optional) – Explicit rest-frame wavelength grid. If None, build a grid from min(wave_min, self.wave.min()) to wave_max or self.wave.max() using the median native wavelength spacing.

  • wave_min (float or None, optional) – Bounds for the auto-generated grid when wave_out is None.

  • wave_max (float or None, optional) – Bounds for the auto-generated grid when wave_out is None.

  • n_draws (int or None, optional) – If provided, use at most the first n_draws posterior samples.

  • return_components (bool, optional) – If True, include per-component draws and medians in the return value. This includes any fitted custom components.

  • _state (object) – _state value.

component_fraction_at_wave(component='host', wave0=2500.0, reference='continuum', reconstruct=False, n_draws=None)[source]#

Return component/reference flux fraction at a requested wavelength.

Parameters:
  • component (str, optional) – Component names. Supported reconstructed names are host, PL, Fe_uv, Fe_op, Balmer_cont, and continuum. Any fitted custom component names are also accepted.

  • reference (str, optional) – Component names. Supported reconstructed names are host, PL, Fe_uv, Fe_op, Balmer_cont, and continuum. Any fitted custom component names are also accepted.

  • wave0 (float, optional) – Rest-frame wavelength in Angstrom.

  • reconstruct (bool, optional) – If True, rebuild posterior components on a grid that reaches wave0. Returns (median, err) from the posterior draws.

  • n_draws (int or None, optional) – Maximum number of posterior draws to use in the reconstruction.

balnicity_index(component_names=None, line_center=1549.06, vmin=3000.0, vmax=25000.0, min_width=2000.0, depth_threshold=0.1, include_line_emission=True, return_details=False)[source]#

Return a simple BALnicity-style index from the summed fitted BAL model.

The BAL model is defined as the sum of selected negative custom components, typically names beginning with bal_. The reference model is the BAL-free AGN continuum, optionally plus the fitted emission-line model. The returned BI uses the standard-style integrand 1 - f_norm / 0.9 over contiguous troughs at least min_width wide and deeper than depth_threshold.

Parameters:
  • component_names (object) – component_names value.

  • line_center (object) – line_center value.

  • vmin (object) – vmin value.

  • vmax (object) – vmax value.

  • min_width (object) – min_width value.

  • depth_threshold (object) – depth_threshold value.

  • include_line_emission (object) – include_line_emission value.

  • return_details (object) – return_details value.

line_profile_from_components(line_key)[source]#

Build a line-only profile from posterior-median component profiles.

Parameters:

line_key (str) – Line-name prefix (for example 'Hb_br').

Return type:

ndarray

line_profile_from_draw(draw_index, line_key)[source]#

Build a line-only profile for one posterior draw index.

Parameters:
  • draw_index (int) – Posterior draw index.

  • line_key (str) – Line-name prefix (for example 'Hb_br').

Return type:

ndarray

line_props(profile, wave=None)[source]#

Return (fwhm_kms, integrated_area) from a line profile.

Parameters:
  • profile (ndarray) – Line profile values.

  • wave (ndarray or None, optional) – Wavelength array. If None, self.wave is used.

Return type:

tuple[float, float]

line_props_from_profile(wave, profile)[source]#

Compatibility wrapper for line_props().

Parameters:
  • wave (ndarray) – Wavelength array.

  • profile (ndarray) – Line profile values.

Return type:

tuple[float, float]

save_result(conti_result, conti_result_type, conti_result_name, line_result, line_result_type, line_result_name, save_fits_name)[source]#

Write continuum+line summary table to a pandas CSV file.

Parameters:
  • conti_result (ndarray) – Continuum and line result values.

  • line_result (ndarray) – Continuum and line result values.

  • conti_result_type (ndarray) – Legacy dtype tags (stored but not enforced).

  • line_result_type (ndarray) – Legacy dtype tags (stored but not enforced).

  • conti_result_name (ndarray) – Column names for continuum and line outputs.

  • line_result_name (ndarray) – Column names for continuum and line outputs.

  • save_fits_name (str) – Output basename for CSV.

plot_trace(param_names=None, max_vector_elems=2, save_fig_path=None, save_fig_name=None, show_plot=False)[source]#

Plot posterior trace series for selected parameters.

Parameters:
  • param_names (list[str] | str | None, optional) – Parameter selector. Use 'all' to include all posterior keys.

  • max_vector_elems (int or None, optional) – Maximum number of vector elements to expand per key.

  • save_fig_path (str or None, optional) – Output directory when saving figures. If None, uses self.output_path or the current directory.

  • save_fig_name (str or None, optional) – Output filename override.

  • show_plot (bool, optional) – If True, display the figure interactively with plt.show().

plot_corner(param_names=None, max_vector_elems=2, bins=30, max_points=5000, save_fig_path=None, save_fig_name=None, show_plot=False)[source]#

Plot posterior projections with corner.corner.

Parameters:
  • param_names (list[str] | str | None, optional) – Parameter selector. Use 'all' to include all posterior keys.

  • max_vector_elems (int or None, optional) – Maximum number of vector elements to expand per key.

  • bins (int, optional) – Histogram bin count.

  • max_points (int, optional) – Maximum posterior draws to plot.

  • save_fig_path (str or None, optional) – Output directory when saving figures. If None, uses self.output_path or the current directory.

  • save_fig_name (str or None, optional) – Output filename override.

  • show_plot (bool, optional) – If True, display the figure interactively with plt.show().

Notes

Parameters containing non-finite values or no posterior variation are omitted because they do not define meaningful corner-plot ranges.

plot_mcmc_diagnostics(do_trace=True, do_corner=True, param_names=None, max_vector_elems=2, corner_bins=30, corner_max_points=2000, save_fig_path=None, show_plot=False)[source]#

Plot trace and/or corner diagnostics in a single convenience call.

Parameters:
  • do_trace (bool, optional) – If True, render the trace plot.

  • do_corner (bool, optional) – If True, render the corner plot.

  • param_names (list[str] | str | None, optional) – Parameter selector shared by both plots. Use 'all' to include all posterior keys.

  • max_vector_elems (int or None, optional) – Maximum number of vector elements to expand per key.

  • corner_bins (int, optional) – Histogram bin count for the corner plot.

  • corner_max_points (int, optional) – Maximum posterior draws to use in the corner plot.

  • save_fig_path (str or None, optional) – Output directory when saving figures. If None, uses self.output_path or the current directory.

  • show_plot (bool, optional) – If True, display each enabled figure interactively with plt.show().

plot_spectrum(**kwargs)[source]#

Plot the fitted spectrum, model components, and residuals.

Parameters:

**kwargs – Keyword arguments forwarded to plot_fig().

plot_fig(save_fig_path=None, broad_fwhm=1200, plot_legend=True, ylims=None, plot_residual=True, show_title=True, plot_1sigma=True, sigma_alpha=0.12, show_plot=True, plot_psf_space=False, plot_intrinsic_powerlaw=False)[source]#

Plot data, model components, line decomposition, and residuals.

Parameters:
  • save_fig_path (str or None, optional) – Output directory when saving figures. If None, uses self.output_path or the current directory.

  • broad_fwhm (float, optional) – Reserved broad-line threshold kept for compatibility.

  • plot_legend (bool, optional) – If True, draw a legend.

  • ylims (tuple[float, float] or None, optional) – Optional y-axis limits for the spectrum panel.

  • plot_residual (bool, optional) – If True, draw the residual panel below the spectrum.

  • show_title (bool, optional) – Reserved title toggle kept for compatibility.

  • plot_1sigma (bool, optional) – If True, draw 16th-84th percentile posterior bands where available.

  • sigma_alpha (float, optional) – Alpha transparency for posterior uncertainty bands.

  • show_plot (bool, optional) – If True, call plt.show().

  • plot_psf_space (bool, optional) – If True, plot the PSF-space model/components instead of the fiber-scale model/components.

  • plot_intrinsic_powerlaw (bool, optional) – If True, overlay the intrinsic AGN power law before tilt and edge corrections.

class jaxqsofit.FitResult(fitter, samples, median, method, summary=None, path=None, figure=None, _state=None)[source]#

Bases: object

High-level result object returned by jaxqsofit fits.

Parameters:
  • fitter (Any)

  • samples (Mapping[str, Any] | None)

  • median (Mapping[str, Any])

  • method (str)

  • summary (Mapping[str, Any] | None)

  • path (Path | None)

  • figure (Any)

  • _state (_PosteriorState | None)

fitter: Any#
samples: Mapping[str, Any] | None#
median: Mapping[str, Any]#
method: str#
summary: Mapping[str, Any] | None = None#
path: Path | None = None#
figure: Any = None#
property spectrum: SpectralResult#

Typed spectral results on the fitted rest-frame wavelength grid.

predict(**kwargs)[source]#

Reconstruct posterior spectral components for this fit.

Parameters:

**kwargs (dict) – Keyword arguments passed to jaxqsofit.JAXQSOFit.reconstruct_posterior_spectrum(), such as wavelength-grid overrides or posterior draw selection options.

Return type:

PredictionResult

save(path=None, **kwargs)[source]#

Save the result with the fitter’s native persistence format.

Parameters:
  • path (str or pathlib.Path, optional) – Destination path for the posterior bundle. If omitted, the fitter’s configured output path and object name are used.

  • **kwargs (dict) – Additional persistence options forwarded to the fitter’s native save method.

Return type:

Path

plot_corner(**kwargs)[source]#

Plot posterior samples with the fitter’s corner-plot helper.

Parameters:

**kwargs (dict) – Keyword arguments passed to jaxqsofit.JAXQSOFit.plot_corner(), such as parameter selection, labels, output path, and display options.

plot_trace(**kwargs)[source]#

Plot posterior samples with the fitter’s trace-plot helper.

Parameters:

**kwargs (dict) – Keyword arguments passed to jaxqsofit.JAXQSOFit.plot_trace(), such as parameter selection, output path, and display options.

__init__(fitter, samples, median, method, summary=None, path=None, figure=None, _state=None)#
Parameters:
  • fitter (Any)

  • samples (Mapping[str, Any] | None)

  • median (Mapping[str, Any])

  • method (str)

  • summary (Mapping[str, Any] | None)

  • path (Path | None)

  • figure (Any)

  • _state (_PosteriorState | None)

Return type:

None

class jaxqsofit.PredictionResult(data, fitter)[source]#

Bases: object

Dict-like posterior prediction or reconstruction result.

Parameters:
  • data (Mapping[str, Any])

  • fitter (Any)

data: Mapping[str, Any]#
fitter: Any#
property spectrum: SpectralResult#

Typed, unit-explicit spectral posterior results.

property median: dict[str, Any]#

Median predictive values over the leading posterior axis.

keys()[source]#
items()[source]#
get(key, default=None)[source]#

get helper.

Parameters:
  • key (object) – key value.

  • default (object) – default value.

Return type:

Any

__init__(data, fitter)#
Parameters:
  • data (Mapping[str, Any])

  • fitter (Any)

Return type:

None

jaxqsofit.load_from_samples(output_path=None, save_name=None, plot_fig=True, plot_diagnostics=True, kwargs_plot=None, diagnostics_kwargs=None)#

Load a compressed HDF5 posterior bundle and return a JAXQSOFit object.

Parameters:
  • filename (object) – filename value.

  • output_path (object) – output_path value.

  • save_name (object) – save_name value.

  • plot_fig (object) – plot_fig value.

  • plot_diagnostics (object) – plot_diagnostics value.

  • kwargs_plot (object) – kwargs_plot value.

  • diagnostics_kwargs (object) – diagnostics_kwargs value.