API Reference
Public API
Lightweight 1D Gaussian spectral decomposition.
The public API is intentionally small. Most users will read a three-column
spectrum table with read_spectrum(), fit it with fit_spectrum(),
save the returned component table, and optionally create a diagnostic plot with
plot_fit().
- class gaussFitSpec.SpectrumFitResult(components, best_model, individual_components, residual, method, n_components, fit_statistics, covariance=None, parameters=None)[source]
Result returned by
fit_spectrum().The object stores both the human-readable component table and the arrays needed for downstream analysis or plotting.
- Parameters:
components (DataFrame)
best_model (ndarray)
individual_components (ndarray)
residual (ndarray)
method (str)
n_components (int)
fit_statistics (dict)
covariance (ndarray | None)
parameters (ndarray | None)
- components
Table with one row per fitted Gaussian component. The columns are
name,component_index,amplitude,amplitude_err,velocity,velocity_err,fwhm, andfwhm_err.- Type:
pandas.core.frame.DataFrame
- best_model
Total fitted model evaluated at the input velocity values.
- Type:
numpy.ndarray
- individual_components
Two-dimensional array with shape
(n_components, n_velocity)containing each Gaussian component.- Type:
numpy.ndarray
- residual
Difference between the input spectrum and
best_model.- Type:
numpy.ndarray
- method
Model-selection method used for the fit, either
"bic"or"f_test".- Type:
str
- n_components
Number of Gaussian components selected.
- Type:
int
- fit_statistics
Dictionary containing goodness-of-fit values such as
chi2,reduced_chi2,aic,bic,rss, andn_parameters. F-test fits also includef_valueandf_test_pvaluewhen applicable.- Type:
dict
- covariance
Covariance matrix returned by
scipy.optimize.curve_fit. This isNoneonly if no usable covariance is available.- Type:
numpy.ndarray | None
- parameters
Raw fitted parameters in repeating
amplitude, velocity, sigmaorder.- Type:
numpy.ndarray | None
- gaussFitSpec.fit_spectrum(velocity, spectrum, spectrum_err=None, *, name='spectra1', method='bic', max_components=8, f_test_alpha=0.05, min_fwhm=None, max_fwhm=None, initial_centers=None, fixed_n_components=None, bic_weight=10.0, verbose=False)[source]
Fit a 1D spectrum with multiple Gaussian components.
The fitter builds candidate models sequentially, using peaks in the spectrum or residuals as initial guesses. Gaussian amplitudes may be positive or negative, component centers are bounded by the input velocity range, and widths are constrained by
min_fwhmandmax_fwhmwhen provided.- Parameters:
velocity – One-dimensional velocity grid.
spectrum – One-dimensional spectrum values sampled on
velocity.spectrum_err – One-dimensional uncertainty values. If
None, a single noise level is estimated from the spectrum and used for all points.name – Name stored in the output component table. The default is
"spectra1".method – Model-selection method. Use
"bic"for Bayesian information criterion selection or"f_test"for the approximate sequential F-test.max_components – Maximum number of Gaussian components to try when selecting a model automatically.
f_test_alpha – Significance threshold used by
method="f_test". Additional components are accepted when the approximate F-test p-value is below this value.min_fwhm – Optional minimum allowed full width at half maximum.
max_fwhm – Optional maximum allowed full width at half maximum.
initial_centers – Optional iterable of component centers. When provided, the fitter uses these centers as the initial model instead of automatic model selection.
fixed_n_components – Optional fixed number of components to fit. When provided, automatic model selection is skipped.
bic_weight – Minimum BIC improvement required before accepting an additional Gaussian component when
method="bic". This also controls the extra penalty term applied to weak components, matching the behavior of the reference fitting script.verbose – If
True, print per-iteration progress messages during sequential model selection. For BIC fits this includes the BIC value and number of Gaussian components tried.
- Returns:
A
SpectrumFitResultcontaining the component table, model arrays, residuals, selected method, number of components, covariance, and fit statistics.- Raises:
ValueError – If input arrays have incompatible shapes, if
methodis not"bic"or"f_test", or ifmax_componentsis less than one.RuntimeError – If no candidate Gaussian model can be fitted.
Example
from gaussFitSpec import fit_spectrum, read_spectrum velocity, spectrum, spectrum_err = read_spectrum("examples/example_spectra.txt") result = fit_spectrum(velocity, spectrum, spectrum_err, method="bic") print(result.components)
- gaussFitSpec.plot_fit(velocity, spectrum, spectrum_err, result, *, output_file=None, show=False, figure=None, axes=None)[source]
Create a diagnostic plot for a fitted spectrum.
The figure contains an upper panel with the observed spectrum, optional error bars, the total fitted model, and individual Gaussian components. A lower panel shows the residual
spectrum - result.best_modelwith a shaded one-sigma uncertainty band whenspectrum_erris provided.- Parameters:
velocity – One-dimensional velocity grid.
spectrum – One-dimensional observed spectrum values.
spectrum_err – One-dimensional uncertainty values. Pass
Noneto omit error bars and the residual uncertainty band.result – Fit result returned by
gaussFitSpec.fit_spectrum().output_file – Optional path where the figure should be saved. Parent directories are created automatically.
show – If
True, callmatplotlib.pyplot.show()before returning.figure – Optional Matplotlib figure to draw into. If supplied without compatible axes, the figure is cleared and rebuilt.
axes – Optional pair of Matplotlib axes
(ax_main, ax_residual).
- Returns:
A tuple
(figure, axes)whereaxescontains the main spectrum axis and the residual axis.
Example
from gaussFitSpec import plot_fit plot_fit( velocity, spectrum, spectrum_err, result, output_file="examples/example_fit.png", )
- gaussFitSpec.read_spectrum(path)[source]
Read a plain table containing one 1D spectrum.
The input file must contain exactly three numerical columns in this order: velocity, spectrum, and spectrum uncertainty. Both whitespace-separated and comma-separated files are accepted, and lines beginning with
#are ignored.- Parameters:
path – Path to a
.txt,.dat,.csv, or similar plain text table.- Returns:
A tuple
(velocity, spectrum, spectrum_err)of NumPy arrays.- Raises:
ValueError – If the file does not contain exactly three columns or if any value cannot be converted to a floating-point number.
Example
from gaussFitSpec import read_spectrum velocity, spectrum, spectrum_err = read_spectrum("examples/example_spectra.txt")
- gaussFitSpec.save_components_csv(result, path, index=False)[source]
Save the fitted Gaussian component table to CSV.
This is a small convenience wrapper around
result.components.to_csv(...). It accepts thegaussFitSpec.fitting.SpectrumFitResultreturned bygaussFitSpec.fit_spectrum().- Parameters:
result – Fit result returned by
gaussFitSpec.fit_spectrum().path – Output CSV file path.
index – Passed to
pandas.DataFrame.to_csv(). The defaultFalseavoids writing the DataFrame index.
Example
from gaussFitSpec import save_components_csv save_components_csv(result, "examples/example_components.csv")
Fitting
Core multi-Gaussian fitting routines.
- class gaussFitSpec.fitting.SpectrumFitResult(components, best_model, individual_components, residual, method, n_components, fit_statistics, covariance=None, parameters=None)[source]
Result returned by
fit_spectrum().The object stores both the human-readable component table and the arrays needed for downstream analysis or plotting.
- Parameters:
components (DataFrame)
best_model (ndarray)
individual_components (ndarray)
residual (ndarray)
method (str)
n_components (int)
fit_statistics (dict)
covariance (ndarray | None)
parameters (ndarray | None)
- components
Table with one row per fitted Gaussian component. The columns are
name,component_index,amplitude,amplitude_err,velocity,velocity_err,fwhm, andfwhm_err.- Type:
pandas.core.frame.DataFrame
- best_model
Total fitted model evaluated at the input velocity values.
- Type:
numpy.ndarray
- individual_components
Two-dimensional array with shape
(n_components, n_velocity)containing each Gaussian component.- Type:
numpy.ndarray
- residual
Difference between the input spectrum and
best_model.- Type:
numpy.ndarray
- method
Model-selection method used for the fit, either
"bic"or"f_test".- Type:
str
- n_components
Number of Gaussian components selected.
- Type:
int
- fit_statistics
Dictionary containing goodness-of-fit values such as
chi2,reduced_chi2,aic,bic,rss, andn_parameters. F-test fits also includef_valueandf_test_pvaluewhen applicable.- Type:
dict
- covariance
Covariance matrix returned by
scipy.optimize.curve_fit. This isNoneonly if no usable covariance is available.- Type:
numpy.ndarray | None
- parameters
Raw fitted parameters in repeating
amplitude, velocity, sigmaorder.- Type:
numpy.ndarray | None
- gaussFitSpec.fitting.fit_spectrum(velocity, spectrum, spectrum_err=None, *, name='spectra1', method='bic', max_components=8, f_test_alpha=0.05, min_fwhm=None, max_fwhm=None, initial_centers=None, fixed_n_components=None, bic_weight=10.0, verbose=False)[source]
Fit a 1D spectrum with multiple Gaussian components.
The fitter builds candidate models sequentially, using peaks in the spectrum or residuals as initial guesses. Gaussian amplitudes may be positive or negative, component centers are bounded by the input velocity range, and widths are constrained by
min_fwhmandmax_fwhmwhen provided.- Parameters:
velocity – One-dimensional velocity grid.
spectrum – One-dimensional spectrum values sampled on
velocity.spectrum_err – One-dimensional uncertainty values. If
None, a single noise level is estimated from the spectrum and used for all points.name – Name stored in the output component table. The default is
"spectra1".method – Model-selection method. Use
"bic"for Bayesian information criterion selection or"f_test"for the approximate sequential F-test.max_components – Maximum number of Gaussian components to try when selecting a model automatically.
f_test_alpha – Significance threshold used by
method="f_test". Additional components are accepted when the approximate F-test p-value is below this value.min_fwhm – Optional minimum allowed full width at half maximum.
max_fwhm – Optional maximum allowed full width at half maximum.
initial_centers – Optional iterable of component centers. When provided, the fitter uses these centers as the initial model instead of automatic model selection.
fixed_n_components – Optional fixed number of components to fit. When provided, automatic model selection is skipped.
bic_weight – Minimum BIC improvement required before accepting an additional Gaussian component when
method="bic". This also controls the extra penalty term applied to weak components, matching the behavior of the reference fitting script.verbose – If
True, print per-iteration progress messages during sequential model selection. For BIC fits this includes the BIC value and number of Gaussian components tried.
- Returns:
A
SpectrumFitResultcontaining the component table, model arrays, residuals, selected method, number of components, covariance, and fit statistics.- Raises:
ValueError – If input arrays have incompatible shapes, if
methodis not"bic"or"f_test", or ifmax_componentsis less than one.RuntimeError – If no candidate Gaussian model can be fitted.
Example
from gaussFitSpec import fit_spectrum, read_spectrum velocity, spectrum, spectrum_err = read_spectrum("examples/example_spectra.txt") result = fit_spectrum(velocity, spectrum, spectrum_err, method="bic") print(result.components)
I/O
Input and output helpers for gaussFitSpec.
- gaussFitSpec.io.read_spectrum(path)[source]
Read a plain table containing one 1D spectrum.
The input file must contain exactly three numerical columns in this order: velocity, spectrum, and spectrum uncertainty. Both whitespace-separated and comma-separated files are accepted, and lines beginning with
#are ignored.- Parameters:
path – Path to a
.txt,.dat,.csv, or similar plain text table.- Returns:
A tuple
(velocity, spectrum, spectrum_err)of NumPy arrays.- Raises:
ValueError – If the file does not contain exactly three columns or if any value cannot be converted to a floating-point number.
Example
from gaussFitSpec import read_spectrum velocity, spectrum, spectrum_err = read_spectrum("examples/example_spectra.txt")
- gaussFitSpec.io.save_components_csv(result, path, index=False)[source]
Save the fitted Gaussian component table to CSV.
This is a small convenience wrapper around
result.components.to_csv(...). It accepts thegaussFitSpec.fitting.SpectrumFitResultreturned bygaussFitSpec.fit_spectrum().- Parameters:
result – Fit result returned by
gaussFitSpec.fit_spectrum().path – Output CSV file path.
index – Passed to
pandas.DataFrame.to_csv(). The defaultFalseavoids writing the DataFrame index.
Example
from gaussFitSpec import save_components_csv save_components_csv(result, "examples/example_components.csv")
Plotting
Plotting helpers for gaussFitSpec.
- gaussFitSpec.plotting.plot_fit(velocity, spectrum, spectrum_err, result, *, output_file=None, show=False, figure=None, axes=None)[source]
Create a diagnostic plot for a fitted spectrum.
The figure contains an upper panel with the observed spectrum, optional error bars, the total fitted model, and individual Gaussian components. A lower panel shows the residual
spectrum - result.best_modelwith a shaded one-sigma uncertainty band whenspectrum_erris provided.- Parameters:
velocity – One-dimensional velocity grid.
spectrum – One-dimensional observed spectrum values.
spectrum_err – One-dimensional uncertainty values. Pass
Noneto omit error bars and the residual uncertainty band.result – Fit result returned by
gaussFitSpec.fit_spectrum().output_file – Optional path where the figure should be saved. Parent directories are created automatically.
show – If
True, callmatplotlib.pyplot.show()before returning.figure – Optional Matplotlib figure to draw into. If supplied without compatible axes, the figure is cleared and rebuilt.
axes – Optional pair of Matplotlib axes
(ax_main, ax_residual).
- Returns:
A tuple
(figure, axes)whereaxescontains the main spectrum axis and the residual axis.
Example
from gaussFitSpec import plot_fit plot_fit( velocity, spectrum, spectrum_err, result, output_file="examples/example_fit.png", )