astrocook.fitting.voigt_fitter module#
- astrocook.fitting.voigt_fitter.TAU_CUT = 1e-06#
A line is evaluated only where its optical depth exceeds this (#526)
- astrocook.fitting.voigt_fitter.COMPONENT_FLAGS = ('z_at_window', 'logN_at_lower_bound', 'logN_at_upper_bound', 'b_at_lower_bound', 'b_at_upper_bound', 'nan_errors')#
Flags that a fit leaves on the components it fits (#517), in ComponentData.flags: a free parameter ended at a bound of the fit (within AT_BOUND_RTOL of the width of its range), or the uncertainties could not be computed. The upper bounds of the fit are those of the constraint model (logN 23, b 300 km/s) or the tighter max_logN and max_b of the automatic pipelines (19, 50 km/s); the z bound is the window of the fit. A parameter at a bound has an unreliable value and error.
- astrocook.fitting.voigt_fitter.voigt_optical_depth(wave_grid_ang: ndarray, lambda_0: ndarray, f_val: ndarray, gamma: ndarray, z: ndarray, N_col: ndarray, b_kms: ndarray) ndarray[source]#
Optical depth of M Voigt lines on N samples, summed: the physics of the fitter, used also by the profiles of the System Inspector.
Input arrays (lambda_0, z, etc.) must be shape (M,). wave_grid_ang must be shape (N,). Returns summed tau array of shape (N,).
- exception astrocook.fitting.voigt_fitter.NoPixelsToFit[source]#
Bases:
ValueErrorNo valid pixel is around the components to fit: their lines fall outside the spectrum, or on pixels that cannot be used (F111, phase 6-ter, PR 7-quater). A
ValueError: the recipes report it as a fit that could not be done.- __init__(*args, **kwargs)#
- add_note(object, /)#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback(object, /)#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class astrocook.fitting.voigt_fitter.VoigtFitter(spectrum: Spectrum, system_list: SystemList, check_stop=None)[source]#
Bases:
objectEngine for fitting Voigt profiles to spectral data.
This class orchestrates the optimization process. It handles:
Resolution Logic: determining effective resolution (R or FWHM) from columns or metadata.
Dynamic Masking: identifying relevant pixels for the fit to speed up computation.
Optimization: utilizing
scipy.optimize.least_squaresto minimize residuals.Vectorization: calculating optical depths for multiple lines simultaneously.
- Parameters:
spectrum (Spectrum) – The spectral data to fit. Must have a valid normalization (continuum) or be pre-normalized.
system_list (SystemList) – The list of absorption components to model.
- __init__(spectrum: Spectrum, system_list: SystemList, check_stop=None)[source]#
- evaluate_uncertainties(z_window_kms: float = 20.0) SystemList[source]#
Recompute the uncertainties of the active components at their current values, without fitting.
Used at the end of the automatic pipelines:
refit_allfits each group while its neighbours still have their initial values, so the chi2 of that fit is not the chi2 of the final model (issue #534). One numerical Jacobian is computed at the current parameters.- Returns:
A new system list with
dz,dlogN,db,dbtur(of the free parameters) andchi2of the active components updated.- Return type:
- prepare_fit_context(z_window_kms: float = 20.0) Tuple[ndarray, ndarray][source]#
Prepares the internal state for fitting (masks, background, vectorized data).
- Returns:
(lower_bounds, upper_bounds) for the free parameters.
- Return type:
tuple
- get_fit_context_data() Dict[str, Any][source]#
Retrieve all internal data required for external likelihood calculations.
Extracts the sliced arrays, fit masks, and the model computation function used by the frequentist fitter, allowing external engines (like Bayesian samplers) to evaluate the exact same physical model. Must be called after
prepare_fit_context().- Returns:
A dictionary containing: -
'x': The wavelength grid array. -'y': The normalized flux array. -'dy': The normalized flux error array. -'mask': The boolean fit mask array. -'compute_model': A callable function that takes a free parameter vector and returns the normalized model array.- Return type:
dict
- fit(max_nfev: int = 2000, method: str = 'trf', z_window_kms: float = 20.0, verbose: int = 0, b_max: float | None = None, logN_max: float | None = None) Tuple[SystemList, ndarray, Any][source]#
Execute the Voigt profile optimization.
Performs a least-squares fit of the active components to the spectrum. Includes automatic spatial pre-filtering (fitting only pixels near the lines) and vectorized optical depth calculation.
- Parameters:
max_nfev (int, optional) – Maximum number of function evaluations for the optimizer. Defaults to
2000.method (str, optional) – Optimization method (e.g.,
'trf','lm'). Defaults to'trf'.z_window_kms (float, optional) – Velocity window (km/s) around component centers to include in the fit mask. Defaults to
20.0.verbose (int, optional) – Verbosity level for
scipy.optimize.least_squares. Defaults to0.b_max (float, optional) – Upper bound (km/s) on the free b parameters, tighter than the physical limit of the constraint model (300 km/s). Used by the automatic pipelines to keep the components from broadening into their neighbours; components that end at this bound may be broader and can be refitted without it. Defaults to
None(no extra bound).logN_max (float, optional) – Upper bound on the free logN parameters, tighter than the physical limit of the constraint model (23). Used by the automatic pipelines (19): in saturated troughs a single component can otherwise fill the trough with its damping wings and run away to logN 20-23 (findings register F62). Defaults to
None(no extra bound).
- Returns:
A tuple containing:
new_system_list (
SystemList): A new system list containing the optimized parameter values and errors.final_model_flux (np.ndarray): The full model flux array (physical units), evaluated on the entire grid.
res (OptimizeResult): The raw result object from
scipy.optimize.
- Return type:
tuple
- chi2_on_fit_pixels(model_flux: ndarray) Tuple[float, int][source]#
The chi2 of a model flux (in the units of
fit()andcompute_model_flux(), on the whole spectrum) on the pixels of the last fit, and their number: two models compared on the same pixels (metals_auto, F111).
- compute_model_flux() Tuple[ndarray, ndarray][source]#
Compute the model flux for the current parameters.
Calculates the Voigt profile model based on the current state of the system list, without performing any fitting/optimization.
- Returns:
A tuple containing: 1. wavelength (np.ndarray): The wavelength grid in Angstroms. 2. model_flux (np.ndarray): The computed model flux (physical units).
- Return type:
tuple