kinextract.run_spectral_fit

kinextract.run_spectral_fit(cfg: FitConfig, gal_file: str | None = None, *, gal_errors=None, write_outputs: bool | None = None, output_prefix: str | None = None) dict[source]

Run the full non-parametric LOSVD spectral fit end-to-end.

This is the primary public entry point of kinextract. Given a FitConfig and a galaxy spectrum, it: loads and prepares the spectrum and stellar template library into a FitState (make_fit_state()); builds an initial non-parametric guess for the LOSVD and template weights (build_initial_guess_nonparam()); runs a bound-constrained MAP optimisation (fit_state_map_with_optional_clean()) over that same flat parameter vector, with optional automatic regularisation (xlam) selection and sigma-clipping as configured – or, when cfg.fit_continuum=True (or cfg.joint_prenorm=True), dispatches to kinextract.joint’s continuum-cofit engine instead; and finally computes summary statistics and (by default) writes the standard fitlov/ascii/rms/template output files. It supports both notebook usage (set cfg.gal_file and call run_spectral_fit(cfg)) and command-line/scripted usage (pass gal_file explicitly, overriding cfg).

The non-joint MAP path (cfg.fit_continuum=False and cfg.joint_prenorm=False) self-corrects the wing-tapered smoothness penalty’s v_center (recentered on a cross-correlation velocity estimate) and sigl0 (fixed-point iteration toward the recovered sigma) via _fit_map_sigl0_recenter(), mirroring kinextract.joint.fit_joint_auto_xlam_sigl0()’s validated approach – see its docstring for the rationale. A zero-centered/fixed-sigl0 default would cause a large, spurious V/sigma discrepancy against the joint path on otherwise-matched settings, so both paths self-correct the same way. Both corrections are controlled by cfg.joint_recenter_v/cfg.joint_n_sigl0_iter/cfg.joint_sigl0_tol (shared fields with the joint path). A full-posterior (NUTS/HMC) alternative to this MAP point estimate is available via kinextract.bayesian.fit_state_bayesian() for users who want a sampled posterior instead; call it directly in place of this function if you need distributional uncertainty from a single fit rather than (or in addition to) the bootstrap error estimators in kinextract.errors. It is not the default because a comprehensive recovery-accuracy comparison found the MAP point estimate matches or exceeds the posterior mean’s LOSVD-shape recovery across tested instruments and LOSVD shapes, at a small fraction of the runtime – consistent with the original Fortran implementation this package is a port of, which also uses MAP + Monte Carlo resampling rather than full posterior sampling.

For characterizing recovery bias for a specific target’s instrument/ S-N/template configuration – e.g. near the instrumental resolution limit, where any point estimator has some residual bias – see kinextract.validation.assess_recovery_bias(), which runs matched mock simulations and reports (and optionally corrects for) the empirical bias directly, rather than relying on generic multi-instrument numbers.

Parameters:
  • cfg (FitConfig) – Configuration object specifying the wavelength/redshift window, kinematic grid, regularisation, cleaning, and continuum-cofit settings for the fit. In notebook usage, you may set cfg.gal_file directly and call run_spectral_fit(cfg).

  • gal_file (str, optional) – Spectrum file path. If supplied, this overrides cfg.gal_file (and cfg is updated in place to match, for later introspection). Useful for command-line/batch usage where the same cfg is reused across many spectra.

  • gal_errors (array-like or float, optional) – Per-pixel error estimates to use instead of the errors read from the spectrum file. Accepts a 1-D array the same length as the full spectrum (before wavelength-range selection) or a scalar float for uniform errors. When provided, this overrides both the file errors and the use_spectrum_errors setting in cfg.

  • write_outputs (bool, optional) – If True, write fitlov/ascii/rms/template output files to cfg.outdir. If False, skip writing files and return the equivalent model products purely in memory (useful for notebook-driven exploration or bootstrap workers where per-replicate file I/O would be wasteful). Defaults to cfg.write_outputs (which itself defaults to False) when not given explicitly, so this can be set once per FitConfig instead of on every call; pass an explicit True/False here to override the config for a single call.

  • output_prefix (str, optional) – Prefix for output files. If None, inferred from gal_file via infer_output_prefix().

Returns:

Dictionary with keys:

"state"

The fully-populated FitState for this fit (velocity grid, data, best-fit LOSVD context, etc.).

"template_files"

List of stellar template file paths used in the fit.

"result"

The scipy.optimize.OptimizeResult from the final MAP optimisation.

"a_map"

Best-fit flat parameter vector (ndarray).

"f_map"

Best-fit objective value (float).

"outputs"

Dictionary of derived model products: the model spectrum ("gp"), recovered LOSVD ("b"), template weights ("w" and fractional "wfrac"), weighted template spectrum ("tt"), continuum parameters ("coff", "coff2", "A"), fit RMS ("rms", "nrms"), the co-fit continuum ("continuum"), and, when write_outputs is True, the paths of the files written ("paths").

"chi2"

Final chi-squared over good pixels (float; see _chi2_stats()).

"ngood"

Number of good (fitted, unmasked) pixels (int).

"prefix"

Output file prefix used (or that would have been used).

"gal_file"

Input spectrum file path actually used for this fit.

Return type:

dict

Examples

>>> from kinextract import FitConfig, run_spectral_fit
>>> cfg = FitConfig(gal_file="bin0105.spec", template_list_file="Tlist",
...                 zgal=0.0016, wavefitmin=8400, wavefitmax=8800)
>>> fit = run_spectral_fit(cfg)
>>> fit["chi2"]