Skip to content

API reference

This page is generated from the source docstrings by mkdocstrings. It documents the public Python API; for the algorithms themselves see the catalogue.

Data types

spectro_kernel.types.spectrum.Spectrum1D dataclass

A one-dimensional spectrum: flux sampled over a wavelength axis.

Attributes:

Name Type Description
wavelength ndarray

Wavelength axis, conventionally in Ångström.

flux ndarray

Flux values, one per wavelength sample.

flux_unit str

Free-form label for the flux unit (e.g. "ADU", "erg/s/cm2/A").

wavelength_unit str

Label for the wavelength unit (default "Angstrom").

uncertainty ndarray | None

Optional 1-sigma flux uncertainty, same length as flux.

mask ndarray | None

Optional boolean array; True marks a sample to ignore.

meta dict[str, Any]

Free-form metadata (object name, instrument, dates, ...).

header dict[str, Any] | None

Raw FITS header as a plain dict, when the spectrum came from a file.

Arrays are treated as immutable. :meth:content_hash is memoised on the identity of the underlying ndarray objects, so mutating an array in place (spec.flux[i] = …) after the hash has been computed is unsupported — the cached digest would no longer match the content. Every catalogue algorithm derives new arrays (:meth:copy, :meth:with_flux, spec.flux = new_array); do the same in application code and the cache is always valid.

npix property

Number of samples in the spectrum.

wavelength_min property

Smallest wavelength value (nan for an empty spectrum).

wavelength_max property

Largest wavelength value (nan for an empty spectrum).

copy()

Return a deep copy that shares nothing mutable with the original.

with_flux(flux, *, flux_unit=None)

Return a copy with a new flux array (and optionally a new flux unit).

select_range(wmin, wmax)

Return the sub-spectrum with wmin <= wavelength <= wmax.

content_hash()

Return a stable SHA-256 hex digest of the spectrum's numeric content.

Covers wavelength, flux, uncertainty (when set), mask (when set) and flux_unit. The digest is memoised per array identity: a second call on the same arrays is O(1); replacing any array (what every algorithm does) recomputes it. In-place mutation is not detected — see the class docstring.

preview(n=50)

Return a small JSON-safe summary, suitable for an MCP tool response.

to_dict()

Return the full spectrum as JSON-serialisable lists.

spectro_kernel.types.context.WorkContext dataclass

Mutable container of typed-or-named results carried through a pipeline.

last_step property

The most recently recorded processing step, if any.

add_history(step)

Append a processing step to the audit trail.

copy()

Return a deep copy (copy-on-write friendly): algorithms can mutate freely.

hash_state()

Return a SHA-256 digest of the context's scientific content.

The history is intentionally excluded so that a re-run with identical inputs and parameters produces the same hash. Covered: spectrum, spectra, image, images, metrics, line_fits, embedding, plus — only when non-empty, so contexts without them keep their historical digests — extras (JSON-serialisable values, kernel types carrying a content_hash, and ndarrays; anything else is skipped), the periodograms / light_curves arrays and the exports bytes. figures and catalog_lookups are not hashed.

is_empty()

True when no scientific payload has been set yet.

summary()

Return a compact, JSON-serialisable description of what the context holds.

spectro_kernel.types.history.ProcessingStep dataclass

One recorded algorithm execution within a :class:WorkContext.

to_dict()

Return a JSON-serialisable representation of the step.

spectro_kernel.types.line.LineFitResult dataclass

The outcome of fitting a profile to a single spectral line.

Wavelengths are in Ångström, fluxes in the spectrum's own flux_unit.

sigma_angstrom property

Gaussian standard deviation derived from the FWHM.

is_emission property

True when the fitted amplitude is positive (line in emission).

to_dict()

Return a JSON-serialisable representation of the fit.

spectro_kernel.types.enums.AlgorithmCategory

Bases: StrEnum

Stable taxonomy for the algorithm catalogue.

As a :class:~enum.StrEnum, members are strings: values stay JSON-serialisable and callers can compare against plain strings (category == "continuum").

coerce(value) classmethod

Return an :class:AlgorithmCategory from itself or its string value.

The algorithm contract

spectro_kernel.base.BaseAlgorithm

Base class for every algorithm in the catalogue.

Subclasses set the class-level metadata and implement :meth:run. The registry decorator fills in :attr:name, :attr:category and :attr:version.

Class attributes

name: Registry name (snake_case). Set by @register_algorithm. version: Algorithm version (SemVer). Set by @register_algorithm. category: An :class:AlgorithmCategory. description: One-line summary. Defaults to the docstring's first line. long_description: Optional detailed explanation, references, caveats. default_params: Every accepted parameter mapped to its default value. required_params: Parameter names that must be supplied (non-None) by the caller. param_descriptions: Per-parameter human-readable help. input_requirements: WorkContext attributes that must be populated before running. output_produces: WorkContext paths the algorithm populates (documentation only). backend: The library this algorithm leans on — "astropy", "specutils", "astroquery", "scipy", "plotly" or "numpy". astropy / specutils / astroquery mean a domain-standard implementation is wrapped; scipy / numpy mean the method is implemented here on top of general numerical primitives. This makes provenance auditable. references: Literature citations for the method or the wrapped implementation.

run(ctx, params)

Perform the work. params is already merged with defaults and validated.

Read inputs from ctx, write outputs back into ctx, and return an :class:AlgorithmOutput summary. Subclasses must override this.

merge_params(params)

Return default_params overlaid with params; reject unknown keys.

validate_params(params)

Raise :class:InvalidParameterError if a required parameter is missing.

check_inputs(ctx)

Raise :class:InputRequirementError if a required context input is absent.

execute(ctx, params=None)

Validate, run, time, and record one execution against ctx.

Always returns an :class:AlgorithmOutput — exceptions raised inside :meth:run are caught, converted to a failed result, and recorded in the context's history. Use :func:spectro_kernel.registry.run_algorithm if you prefer exceptions to propagate.

metadata()

Return this algorithm's catalogue entry as a JSON-serialisable dict.

spectro_kernel.base.AlgorithmOutput dataclass

The structured result of one algorithm execution.

An algorithm's real payload (a normalised spectrum, a fitted line, ...) is written into the :class:WorkContext. This object carries the summary: success flag, scalar metrics, small JSON-safe artifacts, and any error message.

ok(*, metrics=None, artifacts=None, message=None) classmethod

Build a successful result.

fail(error) classmethod

Build a failed result carrying error.

to_dict()

Return a JSON-serialisable representation.

The registry

spectro_kernel.registry

The algorithm registry — the discoverable catalogue at the heart of the kernel.

An algorithm registers itself with the :func:register_algorithm decorator. Humans discover the catalogue through :func:list_algorithms / :func:describe_algorithm, the CLI does the same, and the MCP server turns each entry into a tool. One registry, three front-ends, identical contents.

register_algorithm(name=None, *, category=None, version=None)

Class decorator that adds an algorithm to the registry.

Usage::

@register_algorithm("snr_der", category=AlgorithmCategory.QUALITY, version="1.0.0")
class SnrDer(BaseAlgorithm):
    ...

name, category and version may also be set as class attributes; the decorator arguments win when both are present. Re-registering the same class is a no-op (so module re-imports are harmless); registering a different class under an existing name raises :class:DuplicateAlgorithmError.

list_algorithms(category=None)

List catalogue entries, optionally filtered by category, sorted by name.

list_categories()

Return the sorted list of categories that currently have at least one algorithm.

get_algorithm(name)

Return the algorithm class registered under name.

create_algorithm(name)

Return a fresh algorithm instance registered under name.

describe_algorithm(name)

Return the full catalogue entry for name as a JSON-serialisable dict.

has_algorithm(name)

Return whether an algorithm is registered under name.

run_algorithm(name, ctx, params=None, *, raise_on_error=True)

Resolve, instantiate and execute name against ctx in one call.

This is the convenience entry point used by the CLI and the MCP server. By default a failed run raises :class:~spectro_kernel.errors.SpectroKernelError; pass raise_on_error=False to receive the failed :class:AlgorithmOutput instead.

Pipelines

spectro_kernel.pipeline.Pipeline

An ordered, named sequence of algorithm steps.

execute(ctx=None, *, stop_on_error=True)

Run every step against ctx (a fresh context is created when omitted).

Steps run in declared order unless any of them carries depends_on, in which case the pipeline is treated as a DAG and executed in topological order. With stop_on_error (the default) execution halts at the first failed step; otherwise it runs every step and reports overall success as the AND of all.

describe()

Return a JSON-serialisable description of the pipeline definition.

spectro_kernel.pipeline.PipelineBuilder

Fluent builder for :class:Pipeline objects.

named(name, *, description='', version='')

Set the pipeline name (and optionally description/version).

add(algorithm, *, label='', depends_on=None, **params)

Append a step running algorithm with keyword params.

Pass depends_on=["other_label"] to declare a non-linear dependency — any step with depends_on switches the pipeline to topological-order execution.

add_step(step)

Append a pre-built :class:PipelineStep.

from_config(config)

Populate the builder from a preset-style config dict.

Expected shape::

{"name": ..., "description": ..., "version": ...,
 "steps": [{"algorithm": "snr_der", "params": {...}, "name": "..."}, ...]}

from_preset(name)

Populate the builder from a named YAML preset.

build(*, validate=True)

Return the assembled :class:Pipeline.

With validate (the default) every referenced algorithm must already exist in the registry, so typos fail fast at build time rather than mid-run.

spectro_kernel.pipeline.PipelineResult dataclass

The outcome of executing a pipeline.

history property

The processing steps recorded on the context (the full audit trail).

to_dict()

Return a JSON-serialisable summary of the run.

Input / output

spectro_kernel.io

Pure, multi-source spectrum I/O.

These functions stand on their own — import and use them directly — and are also wrapped by the read_fits / read_ascii_spectrum / export_* algorithms so the same readers serve the library, the CLI and the MCP server.

read_fits(source, *, allow_remote=True, timeout=60.0, max_bytes=1 << 30, url_validator=None)

Read a 1D spectrum from a FITS file (local path or http(s) URL).

Supports both the WCS-array layout (1D flux + CRVAL1/CDELT1/CRPIX1) and the binary-table layout (explicit wavelength and flux columns).

Remote sources are downloaded with a timeout and a max_bytes ceiling. The library applies no SSRF policy by default — that decision belongs to the caller (see the module docstring). A backend exposing user-supplied URLs should pass spectro_kernel.url_safety.validate_safe_url as url_validator; with a validator set, HTTP redirects are refused too. allow_remote=False guarantees the call never touches the network.

Raises:

Type Description
IOReadError

if the source cannot be read or no spectral data is found.

URLNotAllowedError

(or whatever url_validator raises) when the validator refuses the URL or a redirect is encountered.

write_fits(spectrum, path)

Write spectrum to a FITS file and return the path written.

A linearly-sampled wavelength axis is stored as a 1D image with a WCS header; an irregular axis is stored as a binary table with explicit columns.

Raises:

Type Description
IOWriteError

if the file cannot be written.

read_ascii_spectrum(source, *, delimiter=None, flux_unit='ADU')

Read a spectrum from a two- or three-column text file.

The first numeric column is wavelength (Ångström), the second flux, an optional third column the flux uncertainty. A non-numeric first line is treated as a header and skipped. The delimiter is auto-detected (comma, semicolon, tab or whitespace) unless given explicitly.

Raises:

Type Description
IOReadError

if the file is missing or has fewer than two numeric columns.

write_ascii_spectrum(spectrum, path, *, delimiter=',', header=True)

Write spectrum to a delimited text file and return the path written.

Raises:

Type Description
IOWriteError

if the file cannot be written.

read_votable_spectrum(source)

Read a 1D spectrum from a VOTable file.

The first table is used; wavelength and flux columns are matched by name.

Raises:

Type Description
IOReadError

if the file is missing or has no recognisable spectral columns.

write_votable_spectrum(spectrum, path)

Write spectrum to a VOTable file and return the path written.

Raises:

Type Description
IOWriteError

if the file cannot be written.

Presets

spectro_kernel.presets

YAML pipeline presets — reproducible, versionable analysis recipes.

load_preset(name)

Return the parsed config dict for preset name.

name may be a bundled preset name (matched against the name field or the file stem) or a path to a .yaml/.yml file.

Raises:

Type Description
PresetNotFoundError

if no matching preset can be found.

list_presets()

Return a summary of every bundled preset, sorted by name.

Errors

spectro_kernel.errors

Public exception hierarchy for spectro-kernel.

Everything raised intentionally by the kernel derives from :class:SpectroKernelError, so callers (apps, the CLI, the MCP server) can catch a single base class.

SpectroKernelError

Bases: Exception

Base class for all spectro-kernel errors.

AlgorithmNotFoundError

Bases: SpectroKernelError, KeyError

Raised when an algorithm name is not present in the registry.

DuplicateAlgorithmError

Bases: SpectroKernelError

Raised when two algorithms try to register under the same name.

PresetNotFoundError

Bases: SpectroKernelError, KeyError

Raised when a preset name cannot be resolved.

InvalidParameterError

Bases: SpectroKernelError, ValueError

Raised when an algorithm receives an invalid or missing parameter.

InputRequirementError

Bases: SpectroKernelError

Raised when a WorkContext is missing an input an algorithm requires.

IOReadError

Bases: SpectroKernelError

Raised when a spectrum or image cannot be read from a source.

IOWriteError

Bases: SpectroKernelError

Raised when a result cannot be written to a destination.

PipelineError

Bases: SpectroKernelError

Raised when a pipeline fails to build or to execute.