API Reference
Public package interface for specRT.
- class spec_rt.SpectraDecomposing(x, y, y_err, xemi, yemi, yemi_err)[source]
Bases:
objectLegacy radiative-transfer decomposition workflow.
- static create_legacy_axes(*, figsize=(12, 8), dpi=300)
Create the four-panel subplot layout used by the original notebook.
- static load_six_column_spectrum(path, *, absorption_format='transmission')
Load the six-column example table used by the original notebook.
- Parameters:
path – Text file containing six columns in the order absorption velocity, absorption spectrum, absorption error, emission velocity, emission spectrum, emission error.
absorption_format –
"transmission"expects the second column to beexp(-tau)and converts it to1 - exp(-tau). Use"one_minus_exp_tau"to keep the column unchanged.
- Returns:
A tuple
(x, y, yerr, xemi, yemi, yemi_err)with non-finite emission rows removed.
- spec_rt.create_legacy_axes(*, figsize=(12, 8), dpi=300)[source]
Create the four-panel subplot layout used by the original notebook.
- spec_rt.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, initial_center_window=None, fixed_n_components=None, bic_weight=10.0, positive_amplitudes=False, filter_components=False, 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 by default, 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.
initial_center_window – Optional maximum absolute distance each fitted center may move from its corresponding
initial_centersvalue. This is only used wheninitial_centersis provided.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.positive_amplitudes – If
True, constrain Gaussian amplitudes to be non-negative. Use this for absorption spectra represented as1 - exp(-tau)or tau, where negative components are unphysical.filter_components – If
True, apply the weak-component filter after a manualinitial_centersfit, matching the automatic BIC cleanup.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)
- spec_rt.load_six_column_spectrum(path, *, absorption_format='transmission')[source]
Load the six-column example table used by the original notebook.
- Parameters:
path – Text file containing six columns in the order absorption velocity, absorption spectrum, absorption error, emission velocity, emission spectrum, emission error.
absorption_format –
"transmission"expects the second column to beexp(-tau)and converts it to1 - exp(-tau). Use"one_minus_exp_tau"to keep the column unchanged.
- Returns:
A tuple
(x, y, yerr, xemi, yemi, yemi_err)with non-finite emission rows removed.
- spec_rt.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", )
- spec_rt.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")
- spec_rt.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")
- spec_rt.sd
alias of
SpectraDecomposing
- spec_rt.validate_absorption_input(y, yerr, *, edge_fraction=0.1, sigma_limit=3.0)[source]
Validate that the absorption input behaves like
1 - exp(-tau).The function checks that the edge channels stay close to a zero baseline within a configurable number of noise sigma.
- Returns:
A dictionary with the measured baseline mean, baseline scatter, and reference noise level.
- class spec_rt.spectra_decomposing.SpectraDecomposing(x, y, y_err, xemi, yemi, yemi_err)[source]
Bases:
objectLegacy radiative-transfer decomposition workflow.
- static create_legacy_axes(*, figsize=(12, 8), dpi=300)
Create the four-panel subplot layout used by the original notebook.
- static load_six_column_spectrum(path, *, absorption_format='transmission')
Load the six-column example table used by the original notebook.
- Parameters:
path – Text file containing six columns in the order absorption velocity, absorption spectrum, absorption error, emission velocity, emission spectrum, emission error.
absorption_format –
"transmission"expects the second column to beexp(-tau)and converts it to1 - exp(-tau). Use"one_minus_exp_tau"to keep the column unchanged.
- Returns:
A tuple
(x, y, yerr, xemi, yemi, yemi_err)with non-finite emission rows removed.
Input/output helpers for the radiative-transfer workflow.
- spec_rt.spectra_decomposing_io.load_six_column_spectrum(path, *, absorption_format='transmission')[source]
Load the six-column example table used by the original notebook.
- Parameters:
path – Text file containing six columns in the order absorption velocity, absorption spectrum, absorption error, emission velocity, emission spectrum, emission error.
absorption_format –
"transmission"expects the second column to beexp(-tau)and converts it to1 - exp(-tau). Use"one_minus_exp_tau"to keep the column unchanged.
- Returns:
A tuple
(x, y, yerr, xemi, yemi, yemi_err)with non-finite emission rows removed.
- spec_rt.spectra_decomposing_io.validate_absorption_input(y, yerr, *, edge_fraction=0.1, sigma_limit=3.0)[source]
Validate that the absorption input behaves like
1 - exp(-tau).The function checks that the edge channels stay close to a zero baseline within a configurable number of noise sigma.
- Returns:
A dictionary with the measured baseline mean, baseline scatter, and reference noise level.
- spec_rt.spectra_decomposing_io.write_table_outputs(model, *, name, popt, pcov, gausf, funT, xemi, Or, fit_e, mean_Ts, sigma_meanTsf, v_shift, F_values)[source]
Persist the CSV outputs produced by the legacy workflow.
Plotting helpers for the radiative-transfer workflow.