API Reference

Public package interface for specRT.

class spec_rt.SpectraDecomposing(x, y, y_err, xemi, yemi, yemi_err)[source]

Bases: object

Legacy radiative-transfer decomposition workflow.

static F_test(x, y_0, y_fit1, y_fit2, sigma_rms, x_1, x_2)[source]

x_1,x_2: degree of freedom

Gaussian_fit()[source]

Run the full absorption plus emission decomposition workflow.

static calculate_fwhm(wavelength, intensity)[source]
static calculate_noise(y, yerr, n=1)[source]
static create_legacy_axes(*, figsize=(12, 8), dpi=300)

Create the four-panel subplot layout used by the original notebook.

fit_and_plot()[source]

Fit the spectra and draw the legacy four-panel diagnostic figure.

static fwhm_x_range(x, y)[source]
static gaussian_func(x, *params)[source]

Evaluate one Gaussian component via gaussFitSpec.

gaussian_func_multi(x, *gausf)[source]

Evaluate the sum of Gaussian components via gaussFitSpec.

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 be exp(-tau) and converts it to 1 - 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.

static parse_coords(coord_string)[source]

Convert a coordinate string in the format ‘JHHMMSS±DDMMSS’ to RA and Dec.

Parameters: coord_string (str): The coordinate string, e.g., ‘J053344-721624’.

Returns: tuple: RA (in decimal degrees), Dec (in decimal degrees)

static sigma1_data(x, rang=30)[source]
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_fwhm and max_fwhm when 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_centers value. This is only used when initial_centers is 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 as 1 - exp(-tau) or tau, where negative components are unphysical.

  • filter_components – If True, apply the weak-component filter after a manual initial_centers fit, 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 SpectrumFitResult containing the component table, model arrays, residuals, selected method, number of components, covariance, and fit statistics.

Raises:
  • ValueError – If input arrays have incompatible shapes, if method is not "bic" or "f_test", or if max_components is 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 be exp(-tau) and converts it to 1 - 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_model with a shaded one-sigma uncertainty band when spectrum_err is provided.

Parameters:
  • velocity – One-dimensional velocity grid.

  • spectrum – One-dimensional observed spectrum values.

  • spectrum_err – One-dimensional uncertainty values. Pass None to 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, call matplotlib.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) where axes contains 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 the gaussFitSpec.fitting.SpectrumFitResult returned by gaussFitSpec.fit_spectrum().

Parameters:
  • result – Fit result returned by gaussFitSpec.fit_spectrum().

  • path – Output CSV file path.

  • index – Passed to pandas.DataFrame.to_csv(). The default False avoids 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: object

Legacy radiative-transfer decomposition workflow.

static F_test(x, y_0, y_fit1, y_fit2, sigma_rms, x_1, x_2)[source]

x_1,x_2: degree of freedom

Gaussian_fit()[source]

Run the full absorption plus emission decomposition workflow.

static calculate_fwhm(wavelength, intensity)[source]
static calculate_noise(y, yerr, n=1)[source]
static create_legacy_axes(*, figsize=(12, 8), dpi=300)

Create the four-panel subplot layout used by the original notebook.

fit_and_plot()[source]

Fit the spectra and draw the legacy four-panel diagnostic figure.

static fwhm_x_range(x, y)[source]
static gaussian_func(x, *params)[source]

Evaluate one Gaussian component via gaussFitSpec.

gaussian_func_multi(x, *gausf)[source]

Evaluate the sum of Gaussian components via gaussFitSpec.

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 be exp(-tau) and converts it to 1 - 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.

static parse_coords(coord_string)[source]

Convert a coordinate string in the format ‘JHHMMSS±DDMMSS’ to RA and Dec.

Parameters: coord_string (str): The coordinate string, e.g., ‘J053344-721624’.

Returns: tuple: RA (in decimal degrees), Dec (in decimal degrees)

static sigma1_data(x, rang=30)[source]

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 be exp(-tau) and converts it to 1 - 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.

spec_rt.spectra_decomposing_plotting.create_legacy_axes(*, figsize=(12, 8), dpi=300)[source]

Create the four-panel subplot layout used by the original notebook.

spec_rt.spectra_decomposing_plotting.plot_fit_panels(model, *, ax, x, y, yerr, xemi, yemi, yemi_err, name, popt_ori, popt, Ts, gausf, funT, mean_Ts, sigma_meanTsf, nwarm, v_shift, F_values)[source]

Render the four-panel legacy diagnostic figure.