Skip to content

Model Components

Building blocks for spectrospatial models. Combine them inside your own Equinox module and wrap it with build_model.

Parameters

spectracles.Parameter

Bases: Module

A parameter in a statistical model, which may be fixed or free, and may have a prior.

A free parameter is inferred (and needs a prior for that). A fixed one (fixed=True) keeps its value, but can be freed again, e.g. by set_fixed_status or a schedule. For constants that should never be freed, use Known.

The prior is a static field: it is part of the model's structure, not an array leaf, so it is never optimised and never mistaken for a shared array.

debug_repr()

Return the full equinox-style repr for debugging.

spectracles.ConstrainedParameter

Bases: Module

A parameter in a statistical model, which may be fixed or free, with lower and/or upper bounds. Can be an array, but all entries must share the same bounds.

debug_repr()

Return the full equinox-style repr for debugging.

spectracles.Known

Bases: Parameter

A constant of the problem, such as a rest wavelength: never inferred or optimised.

Unlike a fixed Parameter, it can never be freed, it is left out of parameter summaries and path listings by default (show_knowns=True), and set refuses to change it unless given allow_set_knowns=True.

Kernels

Kernels define the power spectrum of a FourierGP. A subclass only needs to implement feature_weights(freqs), returning sqrt(P(k)) on the mode grid.

spectracles.Kernel

Bases: Module

Base class for kernels. Subclasses declare whatever hyperparameter fields they need. The only contract is feature_weights(freqs) -> sqrt(P(k)) on the mode grid.

Kernels can also give their continuous form, which the discretisation diagnostic compares the field against: spectral_density(k), the 2D spectral density normalised so that its integral over k is the variance, and covariance(r). Both raise NotImplementedError unless a kernel defines them.

spectral_density(k)

The 2D spectral density S(|k|), with integral over k equal to k(0).

covariance(r)

The covariance k(r) at separation r.

spectracles.Matern12

Bases: Kernel

spectracles.Matern32

Bases: Kernel

spectracles.Matern52

Bases: Kernel

spectracles.SquaredExponential

Bases: Kernel

spectracles.model.kernels.LogLogLinear

Bases: Kernel

Log-log-linear CFM kernel: log-amplitude PSD is linear in log(k).

feature_weights(freqs) = exp(m_0 + m_s * log(k)) with DC (k=0) forced to zero so the fluctuation field has zero mean by construction. The field's spatial mean should be provided separately via FourierGP(..., mean=...).

m_s is the spectral index; m_0 the log-amplitude. For negative m_s (the physically common regime) the continuous PSD is IR-divergent, which is why the DC term must be handled as a separate Parameter outside the PSD.

Spatial Models

spectracles.SpatialModel

Bases: Module

spectracles.Domain dataclass

The square region the data cover, in the data's own units (e.g. arcsec).

A FourierGP given a domain works in those units: its length scale is in the same units as the coordinates, and it represents the field on a periodic box made of the domain plus a margin of padding on each side. Several GPs can share one domain and still choose their own padding.

Parameters:

Name Type Description Default
centre tuple[float, float]

The centre (x, y) of the region.

required
extent float

The side of the square region.

required

Attributes:

Name Type Description
centre tuple[float, float]

The centre, as a tuple of floats.

extent float

The side of the square, as a float.

from_points(x, y) classmethod

The smallest square containing the points: centred on their bounding box, with the longer side of the box as its extent.

grid(shape, padding=0.0)

A regular grid of points over the domain, e.g. to map a field after fitting.

With padding=0.0 (the default) the grid spans the data region, which is inside the periodic box of every GP on this domain. To span one GP's whole box, pass its padding, e.g. domain.grid((200, 200), padding=gp.padding).

Parameters:

Name Type Description Default
shape tuple[int, int]

(n, m): n points along x and m along y, edges included.

required
padding float

How far past the domain to extend on each side, as a fraction of the extent.

0.0

Returns:

Type Description
SpatialDataGeneric

The points, flattened. Values evaluated on them reshape to (n, m),

SpatialDataGeneric

as do the grid's own x and y (e.g. for pcolormesh):

grid = domain.grid((200, 200)) flux_map = field(grid).reshape(200, 200) x, y = grid.x.reshape(200, 200), grid.y.reshape(200, 200)

box_size(padding)

The side of the periodic box: the extent plus padding × extent on each side.

spectracles.FourierGP

Bases: SpatialModel

A Gaussian-process field, represented by Fourier modes on a periodic box.

With a domain, coordinates and length scales are in the domain's units (e.g. arcsec), and the field lives on a periodic box of the domain plus padding × extent on each side. The modes and padding are then chosen for you, so that the field matches its kernel to tol over the range of length scales it can take (by default, its prior's 1% to 99% quantiles):

FourierGP(kernel, domain=domain)
FourierGP(kernel, domain=domain, tol=1e-4, length_scale=(30.0, 300.0))
FourierGP(kernel, domain=domain, n_modes=(301, 301), padding=0.15)  # by hand

Without a domain, coordinates must already lie in [-π, π], the length scale is in those units, and n_modes is needed.

A field can have a mean, a Parameter added to the GP, and a link that transforms the result, e.g. for a positive line flux:

FourierGP(kernel, domain=domain, mean=Parameter(prior=Normal(0.0, 1.0)), link="exp")

With a mean, the GP's own constant (k = 0) mode is dropped, so the mean alone sets the field's average over the box; the kernel's variance is still the field's pointwise variance.

Parameters:

Name Type Description Default
kernel Kernel

The kernel, e.g. Matern32(length_scale, variance).

required
n_modes tuple[int, int] | None

Modes in each direction, two positive odd integers. Chosen from tol if not given (needs a domain).

None
domain Domain | None

The region the data cover, in the data's units.

None
padding float | None

The margin on each side of the domain, as a fraction of its extent. Chosen from tol if not given, or 0.15 when n_modes is.

None
tol float | None

The accuracy the modes and padding are chosen for (1e-3 by default): the truncation error at the shortest length scale and the aliasing error at the longest (see spectracles.discretisation).

None
length_scale float | tuple[float, float] | None

The range (shortest, longest) of length scales to choose for, or a single value; the prior's quantiles by default.

None
quantiles tuple[float, float]

The prior quantiles that give the default range.

(0.01, 0.99)
mean Parameter | None

A Parameter added to the GP before the link. None (default) means no mean: a zero-mean stationary GP.

None
link str

"identity" (default), "exp" (positive, log-normal) or "softplus" (lower + softplus, positive and close to linear when large).

'identity'
lower float

The lower bound for link="softplus".

0.0
coefficients Parameter | None

The (whitened) Fourier coefficients; a standard-normal prior by default.

None
zeromode Parameter | None

Deprecated name for mean.

None
nufft_tol float

The relative accuracy of the non-uniform FFT.

DEFAULT_NUFFT_TOL

Attributes:

Name Type Description
design tuple[float, float, float] | None

(tol, shortest, longest length scale) the modes and padding were chosen for, or None if they were given by hand.

zeromode property

Deprecated name for mean.

feature_weights()

The square root of each mode's power: the kernel's, without the k = 0 mode when the field has a mean (rescaled so the variance is unchanged).

spectracles.FieldFromRatio

Bases: SpatialModel

A field given as a base field times a ratio: base(x) × 10^log10_ratio(x).

Useful when a line's ratio to another line is the quantity of interest, e.g. [N II]/Hα. The ratio is modelled through its base-10 log, so it is positive; give log10_ratio a mean to set the typical ratio:

halpha = FourierGP(k1, domain=d, mean=Parameter(prior=Normal(0, 1)), link="exp")
log10_ratio = FourierGP(k2, domain=d, mean=Parameter(prior=Normal(-0.5, 0.5)))
nii = FieldFromRatio(base=halpha, log10_ratio=log10_ratio)

Parameters:

Name Type Description Default
base SpatialModel

The field the ratio is taken relative to.

required
log10_ratio SpatialModel

The base-10 log of the ratio, as a field.

required

ratio(data)

The ratio, 10^log10_ratio(x).

spectracles.FieldPlusScatter

Bases: SpatialModel

A field plus a separate value for each spaxel: field(x) + scatter[spaxel].

For a quantity that is mostly continuous across the sky, with some spaxel-to-spaxel scatter the field can't follow.

Parameters:

Name Type Description Default
field SpatialModel

The continuous part.

required
scatter PerSpaxel

The per-spaxel part, e.g. PerSpaxel(n, Parameter(dims=n, prior=Normal(0.0, 0.05))).

required

spectracles.model.spatial.FourierBasis

Bases: SpatialModel

A spatial model using a fixed Fourier basis with learnable coefficients.

Note that this is different to a FourierGP, which uses a kernel to regularise the coefficients.

spectracles.model.spatial.MultiFourierGP

Bases: SpatialModel

A collection of independent FourierGPs grouped to better batch through fiNUFFT calls. Requires that all component GPs use the same number of modes, but can use different kernels.

Not available yet: instantiating it raises NotImplementedError. It holds its kernels in a list, which built models will support from 1.1. The aim is faster models with several fields on GPU, since such fields usually share one frequency grid and can go through one batched NUFFT.

spectracles.PerSpaxel

Bases: SpatialModel

spectracles.model.spatial.PerIFU

Bases: SpatialModel

spectracles.model.spatial.PerTile

Bases: SpatialModel

spectracles.model.spatial.PerIFUAndTile

Bases: SpatialModel

spectracles.model.spatial.PerTilePinned

Bases: SpatialModel

Spectral Models

spectracles.SpectralSpatialModel

Bases: Module

spectracles.Constant

spectracles.WindowConstant

spectracles.Gaussian

Data

SpatialData is the base class for the points a spatial model is evaluated at. Subclass it to carry extra per-point fields your models need.

spectracles.SpatialData

Bases: Module

Base class for the spatial data that spatial models are evaluated at.

Subclasses must provide x, y (sky coordinates in model units) and idx (each point's index, e.g. its spaxel), all flat arrays. Declare them with field(converter=convert_to_flat_array) to flatten inputs, and add any other per-point fields a model needs:

class MySpatialData(SpatialData):
    x: Array = field(converter=convert_to_flat_array)
    y: Array = field(converter=convert_to_flat_array)
    idx: Array = field(converter=convert_to_flat_array)
    exposure_idx: Array = field(converter=convert_to_flat_array)

spectracles.SpatialDataGeneric

Bases: SpatialData

spectracles.SpatialDataLVM

Bases: SpatialData

Saving and Loading

spectracles.save_model(model, file, overwrite=False, **dump_kwargs)

Save a model to a file.

Parameters:

Name Type Description Default
model ShareModule

The model to save.

required
file Path

The file to save the model to.

required
overwrite bool

Whether to overwrite the file if it exists. Defaults to False.

False
**dump_kwargs Any

Additional arguments to pass to dill.dump.

{}

Raises:

Type Description
FileExistsError

If the file already exists and overwrite is False.

TypeError

If the model is not of type ShareModule.

Exception

If there is a warning when saving the model.

spectracles.load_model(file, **load_kwargs)

Load a model from a file.

Parameters:

Name Type Description Default
file Path

The file to load the model from.

required
**load_kwargs Any

Additional arguments to pass to dill.load.

{}

Returns:

Name Type Description
ShareModule ShareModule

The loaded model.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

TypeError

If the loaded model is not of type ShareModule.