astrocook.core.spectrum module#
- class astrocook.core.spectrum.TableAdapter(data_dict)[source]#
Bases:
objectAdapter to wrap the V2 .t dictionary and expose Astropy Table-like properties.
- class astrocook.core.spectrum.Spectrum(data: SpectrumData, history: list | None = None)[source]#
Bases:
CombineMixin,ContinuumMixin,ExpressionsMixin,FluxMixin,LinesMixinComposite container for spectral data and operations.
This class wraps the raw data (flux, wavelength, error) and provides immutable operations that return new
Spectruminstances. It serves as the primary data structure passed between Recipes and the GUI.- Parameters:
data (SpectrumData) – The core data container holding the Astropy Quantities.
history (list, optional) – A list of strings describing the modification history of this spectrum.
- __init__(data: SpectrumData, history: list | None = None)[source]#
- resolution() ndarray[source]#
Resolving power R of each pixel, from the
resolcolumn.The single source of the resolution (#526). The unit of the column decides how it is read: dimensionless for R, a velocity for the FWHM.
- Returns:
R for each pixel; NaN where it is not known (all NaN if the spectrum has no resolution).
- Return type:
np.ndarray
- property x: Quantity#
The wavelength (or velocity) array.
- property xmin: Quantity#
The lower bound of the wavelength bins.
- property xmax: Quantity#
The upper bound of the wavelength bins.
- property y: Quantity#
The flux density array.
- property dy: Quantity#
The flux error (1-sigma) array.
- property cont: Quantity | None#
Returns the ‘cont’ auxiliary column as an Astropy Quantity, or None if the column does not exist.
- property norm: Quantity | None#
Returns the normalization vector (Continuum * Telluric).
Logic:
If cont exists: - Returns cont * telluric (if the
telluriccolumn exists andthe flux is not already corrected: the flag
TELLURIC_CORRECTEDof the metadata,core/telluric.py).Returns cont (otherwise).
If cont is missing: - Returns 1.0 (if flux median is ~1, assuming pre-normalized). - Returns None (if flux is physical, signaling need for continuum fitting).
- property model: Quantity | None#
Returns the ‘model’ auxiliary column as an Astropy Quantity, or None if the column does not exist.
- property meta: Dict[str, Any]#
A dictionary of metadata (header keywords, redshifts, etc.).
- property t: TableAdapter#
Replaces the raw table/dictionary access. Returns a TableAdapter instance to simulate an Astropy Table (V1) for compatibility with GUI/V1 logic (like gui_table.py).
- Type:
Adapter
- has_aux_column(name: str) bool[source]#
Check if an auxiliary column exists.
- Parameters:
name (str) – The name of the column to check (e.g.,
'cont').- Returns:
Trueif the column is present in the auxiliary data,Falseotherwise.- Return type:
bool
- columns_in_range(names: List[str], x_min: float | None = None, x_max: float | None = None, max_points: int | None = None) Dict[str, Any][source]#
The values of some columns in a range of x, to read them (phase 6-ter, PR 3: the MCP server, or a script).
A range of more than
max_pointspixels is averaged in blocks ofceil(n / max_points)pixels: the columns whose name starts withd(errors) as the error of the mean, the others as the mean. This is for reading only: the spectrum is not rebinned (that is Rebin).- Parameters:
names (list of str) – The columns (the axis is always given: under the name asked for it,
λif it was not asked). The names of the GUI are the names of the core columns (λ,λmin,λmax,F,dF); those of the data (x,xmin,xmax,y,dy) andlamare accepted, and the values are given under the name asked (F120; phase 6-quater, PR 8).x_min (float, optional) – The range, in the unit of x; None: the start (end) of the spectrum.
x_max (float, optional) – The range, in the unit of x; None: the start (end) of the spectrum.
max_points (int, optional) – The largest number of points; None: every pixel.
- Returns:
columns(name -> ndarray),units(name -> str),axis(the name under which the axis is given),n_pixels(pixels in the range),binned_by.- Return type:
dict
- Raises:
KeyError – If a column does not exist (the message lists those that do).
ValueError – If the range is empty or outside the spectrum.
- get_column(name: str) Quantity | None[source]#
Get an auxiliary column as an Astropy Quantity.
- Parameters:
name (str) – The name of the auxiliary column to retrieve (e.g.,
'cont').- Returns:
The column data with units, or
Noneif the column does not exist.- Return type:
astropy.units.Quantity or None
- with_properties(z_em: float, resol: float = 0.0, object_name: str | None = None, overwrite_resol_col: bool = False) Spectrum[source]#
Return a NEW Spectrum instance with updated properties.
- Parameters:
z_em (float) – The emission redshift.
resol (float, optional) – Resolving power R;
0.0(the default) leaves the resolution unchanged.object_name (str, optional) – The object name (header keyword).
overwrite_resol_col (bool, optional) – If
True, aresolcolumn that varies with wavelength is replaced by a flat one atresol. IfFalse(the default, #526) it is kept, andresolonly replaces a flat column or creates a missing one.
- Returns:
A new instance with updated metadata.
- Return type:
- sanitize_legacy_tellurics() Spectrum[source]#
Patches legacy spectra where ‘cont’ included tellurics and ‘cont_no_telluric’ stored the intrinsic continuum.
Logic:
If ‘cont_no_telluric’ exists: - Overwrite ‘cont’ with ‘cont_no_telluric’ (Intrinsic). - Remove ‘cont_no_telluric’.
Returns a new Spectrum instance (or self if no changes needed).
- update_column(name: str, values: ndarray, unit: Unit | None = None, description: str = '') Spectrum[source]#
Return a NEW Spectrum instance with the specified column updated or added.
Handles both core columns (y, dy) and auxiliary columns (cont, model, etc.).
- Parameters:
name (str) – Name of the column to update (e.g.,
'cont','model').values (np.ndarray) – The numerical data for the column.
unit (astropy.units.Unit, optional) – The physical unit. If None, inherits from existing column or defaults to flux unit.
description (str, optional) – Description of the column content.
- Returns:
A new instance with the updated column data.
- Return type:
- remove_meta_keys(keys: List[str]) Spectrum[source]#
Remove specified keys from the metadata dictionary.
Returns a new Spectrum instance with the specified metadata keys removed. This is commonly used to clean up temporary large objects (like JSON mapping dictionaries) before saving the session to disk.
- Parameters:
keys (list of str) – A list of metadata keys to remove.
- Returns:
A new instance with the cleaned metadata.
- Return type:
- apply_expression(target_col: str, expression: str, extra_vars: Dict[str, ndarray] | None = None) Self#
Apply a numerical expression to columns and return a new spectrum.
- Parameters:
target_col (str) – The name of the column to create or overwrite.
expression (str) – A NumExpr-compatible string (e.g.
"y / cont").extra_vars (dict, optional) – Additional variables to pass to the evaluation context.
- Returns:
A new instance with the computed column.
- Return type:
- calc_intersection_expression(others_specs: List[Spectrum], z_target: float, trans_self: str, trans_others: List[str], window_kms: float) str | None#
Calculate the wavelength expression for the velocity intersection of spectra.
Determines the wavelength range where this spectrum and a list of others overlap in velocity space, relative to specific transitions.
- Parameters:
others_specs (list of Spectrum) – List of other spectra to intersect with.
z_target (float) – Target redshift for the velocity conversion.
trans_self (str) – Transition name for the current spectrum (e.g.,
'Ly_a').trans_others (list of str) – List of transition names for the other spectra, corresponding to
others_specs.window_kms (float) – Symmetric velocity window width in km/s.
- Returns:
A boolean expression string (e.g.,
"(x > 400.0) & (x < 500.0)") defining the intersection, orNoneif no overlap exists.- Return type:
str or None
- calculate_running_std(input_col: str, output_col: str, window_pix: int) Self#
Calculate a running RMS on a column and save it as a new column.
- Parameters:
input_col (str) – Name of the column to calculate statistics on (e.g.,
'y').output_col (str) – Name of the output column (e.g.,
'running_std').window_pix (int) – Width of the window in pixels.
- Returns:
A new instance with the added RMS column.
- Return type:
- calibrate(magnitudes: str) Self#
Calibrate (and warp) the flux to match target photometric magnitudes.
- Parameters:
magnitudes (str) – Comma-separated pairs of
Filter=Mag(e.g.,"SDSS_g=17.5, SDSS_r=17.0").- Returns:
A new instance with calibrated flux.
- Return type:
- coadd(others: List[Spectrum], xstart: Quantity | None, xend: Quantity | None, dx: Quantity, kappa: float | None = 5.0, equalize_order: int = 0) Self#
Co-add this spectrum with a list of other spectra onto a new common grid.
Handles scaling, unit conversion, “drizzle” rebinning, and converts the result back to the original wavelength unit.
- Parameters:
others (list of Spectrum) – List of spectra to add.
xstart (Quantity, optional) – Bounds of the new grid.
xend (Quantity, optional) – Bounds of the new grid.
dx (Quantity) – Step size of the new grid.
kappa (float, optional) – Sigma clipping threshold. Defaults to
5.0.equalize_order (int, optional) – Polynomial order for flux scaling (-1=Off, 0=Scalar). Defaults to
0.
- Returns:
The resulting co-added spectrum.
- Return type:
- detect_absorptions(mask_col: str = 'abs_mask', min_pix: int = 3) Self#
Detect absorption regions based on a boolean mask.
Groups adjacent pixels marked as ‘absorbed’ into discrete regions.
- detect_doublet_z(other_spec: Spectrum, trans_self: str, trans_other: str) float#
Find the redshift of maximum coincidence between this spectrum and another.
Calculates the cross-correlation (product of absorption depths) to align two spectra covering different lines of a doublet.
- Parameters:
other_spec (Spectrum) – The other spectrum object.
trans_self (str) – Transition in this spectrum (e.g.,
'OVI_1031').trans_other (str) – Transition in the other spectrum (e.g.,
'OVI_1037').continuum (The depths are those of the flux normalized by the)
:param (
norm): :type (norm): before phase 6-quater, PR 10 they were1 - y, :param right only for a flux already normalized (F145).:- Returns:
The detected redshift.
- Return type:
float
- Raises:
ValueError – If a spectrum has no continuum and its flux is not normalized, or the two transitions cover no redshift in common (0.0 was returned, as if it were a redshift, until phase 6-quater, PR 10).
- equalize_to_reference(reference_spec: Spectrum, order: int = 0) Self#
Scale this spectrum’s flux to match a reference spectrum.
Computes a scaling polynomial by comparing the flux of this spectrum to a reference spectrum, and applies this scaling to all flux-like columns (y, dy, cont, model).
- Parameters:
- Returns:
A new instance with scaled flux, in the unit of this spectrum.
- Return type:
Notes
The two spectra are compared in the units of this one (F138, phase 6-quater, PR 9): the axis of the reference converted to the unit of this axis, its flux to the unit of this flux when they are of one kind. Before, the values were compared as they were, so a reference with the axis in Å against this one in nm had no overlap (no scaling), and one per Å against this one per nm gave a flux off by their ratio. A flux of another kind (arbitrary, against a physical one) is compared by its values: the scaling calibrates it, and the recipe declares the unit. Nothing is converted when the units are the same.
- find_absorbed(smooth_len_lya: Quantity, smooth_len_out: Quantity, kappa: float, template: bool) Self#
Identify absorbed regions using V1 logic.
- Parameters:
smooth_len_lya (Quantity) – Smoothing length for the Ly-alpha forest.
smooth_len_out (Quantity) – Smoothing length outside the forest.
kappa (float) – Sigma clipping threshold.
template (bool) – Use PCA template (Not Implemented).
- Returns:
A new instance with the
abs_maskcolumn added/updated.- Return type:
- fit_continuum(fudge: float | str, smooth_std_kms: float, mask_col: str = 'abs_mask', renorm_model: bool = False, template: bool = False) Self#
Fit a continuum to the unabsorbed regions.
Orchestrates: Interpolate -> Auto-Fudge -> Smooth -> Renormalize Model.
- Parameters:
fudge (float or str) – Fudge factor. Can be a float or
'auto'. With'auto'the factor is computed from the residuals of the unabsorbed pixels around the interpolated continuum, which passes through those pixels: it is 1 by construction. In V1 the automatic fudge corrected the running mean from which V1 builds the continuum; V2 interpolates instead, so there is nothing to correct (findings register F3, accepted). The bias of the final smoothing is not corrected.smooth_std_kms (float) – Smoothing width for the continuum spline in km/s.
mask_col (str, optional) – Name of the mask column to use. Defaults to
'abs_mask'.renorm_model (bool, optional) – If True, re-normalizes the ‘model’ column to the new continuum.
template (bool, optional) – If True, uses a QSO template to trace Lyman-alpha emission.
- Returns:
A new instance with the
contcolumn added/updated.- Return type:
- fit_powerlaw(regions_str: str, kappa: float = 3.0) Self#
Fit a power-law continuum to specified rest-frame regions.
- get_region_bounds(region: str) Tuple[Quantity, Quantity]#
Get observed wavelength bounds for a standard spectral region.
Calculates the observed wavelength range for a preset region (e.g., Ly-alpha forest) based on the object’s emission redshift.
- Parameters:
region (str) – The region identifier. Supported presets: -
'lya_forest': Ly-beta to Ly-alpha. -'all_ly_forest': Ly-limit to Ly-alpha. -'red_side': Redward of Ly-alpha.- Returns:
A tuple
(obs_min, obs_max)as Astropy Quantities.- Return type:
tuple
- Raises:
ValueError – If
z_emis 0.0 or the region preset is unknown.
- get_resampled_column(col_name: str, target_x_grid: ndarray, fill_value: float = nan) ndarray#
Lightweight API to interpolate a single column onto a new x-grid.
- Parameters:
col_name (str) – Name of the column to interpolate.
target_x_grid (np.ndarray) – Target grid in nanometers.
fill_value (float, optional) – Value to fill outside the interpolation range. Defaults to
NaN.
- Returns:
Interpolated values.
- Return type:
np.ndarray
- get_velocity_bounds(z_target: float, trans: str) tuple#
Calculate the min/max velocity coverage of this spectrum relative to a target.
- Parameters:
z_target (float) – The target redshift.
trans (str) – Transition name (e.g.,
'Ly_a').
- Returns:
(min_velocity, max_velocity) in km/s. Returns
(-inf, inf)if invalid.- Return type:
tuple
- identify_lines(multiplet_list: List[str], mask_col: str = 'abs_mask', min_pix_region: int = 3, merge_dv: float = 10.0, score_threshold: float = 0.5, bypass_scoring: bool = False, debug_rating: bool = False, z_em_margin_kms: float = 3000.0) Self#
Identify absorption lines by correlating regions with multiplet templates.
Uses a de-blending strategy to separate merged features. A doublet gives one candidate system per absorption component, from its stronger line, and no candidate lies beyond
z_emby more thanz_em_margin_kms(by defaultZ_EM_MARGIN_KMS, 3000 km/s; a parameter since phase 6-bis, PR 6b).- Parameters:
multiplet_list (list of str) – List of multiplets to search for.
mask_col (str, optional) – Name of the mask column.
min_pix_region (int, optional) – Minimum pixels for a region.
merge_dv (float, optional) – Velocity threshold for merging regions (km/s).
score_threshold (float, optional) – R^2 score threshold for identification.
bypass_scoring (bool, optional) – Accept all candidates if True.
debug_rating (bool, optional) – Show debug plots if True.
z_em_margin_kms (float, optional) – How far beyond
z_ema candidate system can lie (km/s): the associated absorbers and the uncertainty ofz_em(F55).
- Returns:
A new instance with the
abs_idscolumn and identification metadata.- Return type:
- mask_expression(target_col: str, expression: str, extra_vars: Dict[str, ndarray] | None = None) Self#
Mask a column based on a boolean expression (sets values to NaN).
- mask_region(mask_col: str, obs_min: Quantity, obs_max: Quantity) Self#
Update a mask column, setting it to False outside the specified bounds.
- Parameters:
mask_col (str) – Name of the mask column.
obs_min (Quantity) – Minimum observed wavelength.
obs_max (Quantity) – Maximum observed wavelength.
- Returns:
A new instance with the updated mask.
- Return type:
- prepare_expression_context(expression: str, other_specs: Dict[str, Spectrum]) Tuple[str, Dict[str, ndarray]]#
Prepare context for cross-spectrum arithmetic expressions.
Parses an expression for aliases (e.g.,
"s1.F"), resolves them against provided spectrum objects, and resamples their data onto the current spectrum’s grid.- Parameters:
expression (str) – The raw expression string (e.g.,
"F - s1.F").other_specs (dict) – A dictionary mapping alias names to
Spectrumobjects.
- Returns:
A tuple containing: 1. final_expr (str): The processed expression with safe variable names. 2. extra_vars (dict): A dictionary mapping variable names to resampled numpy arrays.
- Return type:
tuple
- rebin(xstart: Quantity | None, xend: Quantity | None, dx: Quantity, kappa: float | None, filling: float) Self#
Rebin the spectrum to a new uniform grid.
- Parameters:
xstart (Quantity, optional) – Start wavelength. If None, uses data minimum.
xend (Quantity, optional) – End wavelength. If None, uses data maximum.
dx (Quantity) – Step size (bin width). Can be wavelength or velocity.
kappa (float, optional) – Sigma clipping threshold for rejecting outliers in bins.
filling (float) – Value to fill gaps (default: NaN).
- Returns:
A new instance with the rebinned data.
- Return type:
- remove_columns(col_names: List[str]) Spectrum[source]#
Return a NEW Spectrum with specified auxiliary columns removed.
- Parameters:
col_names (list of str) – Names of the columns to delete.
- Returns:
A new instance with the columns removed.
- Return type:
- resample_on_grid(target_grid_spec: Spectrum, fill_value: float = nan) Self#
Resample this spectrum onto the exact wavelength grid of another spectrum.
- scale_flux(scale_factor: float | ndarray) Self#
Scale the flux (y, dy) and the flux auxiliary columns (cont, model, cont_pl).
- Parameters:
scale_factor (float or np.ndarray) – Multiplicative factor.
- Returns:
A new instance with scaled flux.
- Return type:
- smooth(sigma_kms: float) Self#
Apply Gaussian smoothing to the flux (y, dy), the flux auxiliary columns (cont, model, cont_pl) and the transmission (telluric).
- Parameters:
sigma_kms (float) – Standard deviation of the Gaussian kernel in km/s.
- Returns:
A new instance with smoothed columns.
- Return type:
- smooth_column(target_col: str, sigma_kms: float, renorm_model: bool = False) Self#
Apply Gaussian smoothing to a single target column.
- Parameters:
target_col (str) – Name of the column to smooth.
sigma_kms (float) – Standard deviation of the Gaussian kernel in km/s.
renorm_model (bool, optional) – If True and
target_colis'cont', the'model'column will be re-normalized.
- Returns:
A new instance with the smoothed column.
- Return type:
- split(expression: str, extra_vars: Dict[str, ndarray] | None = None) Self#
Split the spectrum based on a boolean expression.
- stitch(other_specs: List[Spectrum], sort: bool = True) Self#
Merge this spectrum with a list of other spectra.
Concatenates x, y, dy, and all auxiliary columns.
- update_continuum_from_knots(knots_x: List[float], knots_y: List[float], renorm_model: bool = True) Self#
Update the continuum using a Cubic Spline through provided knots.
- with_flux_unit(unit: UnitBase) Self#
Declare the unit of the flux, without converting the values (phase 6-quater, PR 8-bis;
y_convertconverts).The unit is given to
y,dy, the flux columns (cont,model,cont_pl) in the unit of the flux or without one, and the other columns in the unit of the flux when this is not dimensionless (a dimensionless quality flag is not a flux).- Parameters:
unit (astropy.units.Unit) – The unit of the flux, e.g.
erg/(Angstrom s cm2)orarb_flux.- Returns:
A new instance with the same values and the unit declared.
- Return type:
- with_telluric_corrected(corrected: bool) Self#
Declare whether the flux is already corrected for the tellurics (phase 7-ter, T1): the flag
TELLURIC_CORRECTEDof the metadata, kept in the archive. With it the normalization (norm) is the continuum alone; without it, the continuum times thetelluriccolumn, when there is one (core/telluric.py).- Parameters:
corrected (bool) – True if the flux is already corrected.
- Returns:
A new instance with the flag set; the values unchanged.
- Return type:
- merge_column(col_name: str, other_values: ndarray) Spectrum[source]#
Merge new values into an existing column.
Strategy: Use new value if it’s non-zero, otherwise keep old value.
- Parameters:
col_name (str) – Name of the column.
other_values (np.ndarray) – Array of new values.
- Returns:
A new instance with merged data.
- Return type:
- update_model(model_flux: ndarray) Spectrum[source]#
Update the ‘model’ auxiliary column with new flux values.
- Parameters:
model_flux (np.ndarray) – The new model flux array.
- Returns:
A new instance with the updated model.
- Return type:
- x_convert(z_ref: float, xunit: Unit) Spectrum[source]#
Convert the X-axis units and return a NEW Spectrum instance.
- Parameters:
z_ref (float) – Reference redshift for velocity conversion.
xunit (astropy.units.Unit) – Target unit (e.g.,
nm,km/s).
- Returns:
A new instance with the converted X-axis.
- Return type: