Reference
API reference
All public names in gspice.__all__ are documented below except the submodule gspice.legacy, which has its own page.
Models and fitting
Section titled “Models and fitting”Fit a model of the spectra.
gspice.Model
Section titled “gspice.Model”class gspice.Model( mean: ArrayLike, cov: Iterable[ArrayLike | LowRank], n_train: Iterable[int | np.integer[Any]], *, edges: Iterable[float | np.floating[Any] | np.integer[Any]] = (), center: float | np.floating[Any] | np.integer[Any] | None = None, noise: bool | np.bool_ = False, weighted: bool | np.bool_ = False, blocks: Blocks | None = None,)Fitted Gaussian model of spectra on a common pixel grid.
A spectrum in S/N bin has the working vector
in scaled units. Let be the
flux of the spectrum with its bad pixels interpolated. Let be the square
root of the mean inverse variance of its good pixels (see scale).
Then for a constant
center, and otherwise.
A noise-aware model (noise=True) has one bin and works in flux units.
Spectrum has
where cov[0] is the covariance of the noise-free flux. is
at the good pixels and at the bad pixels
of the spectrum. The constructor checks only the diagonal of cov[0].
Prediction rejects a that is not positive definite where it factors
. The prior factors only at the target pixels.
The constructor takes the attributes below as array_like values, iterables and numpy
scalars. It stores them as the types given here, with read-only float64 copies of
the arrays and new LowRank covariances. The attributes after n_train are
keyword-only. The constructor does not check that a covariance is positive definite,
which costs . Two models are equal only if they are the same
object.
A model computes the precision matrix of a bin at its first use and keeps it.
It also keeps the guard weights of the latest nguard of each bin (see
pixelwise). Each matrix takes bytes, 46 MB at
npix 2400, also for a LowRank covariance. Pickle, copy and deepcopy start without
them.
Attributes:
- mean (ndarray, shape (nbin, npix)) – The vector
mean[b]of each of the nbin S/N bins (scaled; flux for a noise-aware model), subtracted to give , over the npix pixels. Finite; nbin and npix are 1 or more. - cov (tuple of ndarray, each shape (npix, npix), or LowRank) – The covariance of in each bin (scaled²), or of the noise-free flux of
a noise-aware model (flux²). Either nbin finite, exactly symmetric matrices
with a positive diagonal, or nbin
LowRankcovariances of npix pixels with positivediag. All bins hold one kind. A noise-aware model allows a diagonal ≥ 0, or aLowRankwithdiag≥ 0. A positive semi-definitecov[0]makes every positive definite. - n_train (tuple of int) – The number of training spectra in each bin (nbin integers ≥ 1).
- edges (tuple of float) – The nbin − 1 interior S/N edges between the bins: finite and strictly
increasing. Spectrum with the signal-to-noise ratio
(see
snr) is in the binnp.searchsorted(edges, snr_s, side="right"). - center (float or None) – None for a mean-centered model, or the constant center (flux). None for a noise-aware model.
- noise (bool) – True for a noise-aware model, which has one bin and
centerNone. - weighted (bool) – True if the model was fitted with positive weights that are not all equal in a bin.
- blocks (Blocks or None) – The blocks and thresholds of
fit_blocks, with a row of thresholds for each bin and every block within the npix pixels. None for a model without them.
Raises:
- TypeError – If a field has a type or dtype that is not allowed above. The message starts with the name of the field.
- ValueError – If a field has a shape or a value that is not allowed above. The message starts with the name of the field.
gspice.LowRank
Section titled “gspice.LowRank”class gspice.LowRank(vectors: ArrayLike, values: ArrayLike, diag: ArrayLike)Low-rank plus diagonal covariance.
fit with rank=K returns a Model with a LowRank covariance. A model computes
its precision matrix by the Woodbury identity, without forming . It rejects
the covariance where , with
Here are the variances of , and . bounds both the condition number of scaled to unit diagonal and . The constructor takes array_like values and stores read-only float64 copies. Two LowRank are equal only if they are the same object.
Attributes:
- vectors (ndarray, shape (npix, K)) – The columns of , for npix ≥ 1 pixels: finite.
fitreturns orthonormal columns (unit-free), in decreasing order ofvalues. - values (ndarray, shape (K,)) – The variance of each column (scaled²; flux² for a noise-aware model): finite and positive.
- diag (ndarray, shape (npix,)) – The diagonal term (scaled²; flux² for a noise-aware model): finite and 0 or
more.
Modelrequires positive values, except for a noise-aware model.
Raises:
- TypeError – If a field has a dtype that is not integer or floating. The message starts with the name of the field.
- ValueError – If a field has a shape or a value that is not allowed above. The message starts with the name of the field.
gspice.Blocks
Section titled “gspice.Blocks”class gspice.Blocks( starts: ArrayLike, width: int | np.integer[Any], nguard: int | np.integer[Any], thresholds: ArrayLike,)Geometry of the block scan and threshold of each block, from fit_blocks.
Block holds the pixels starts[j] to starts[j] + width - 1.
Its statistic of fit_blocks compares the block with its
prediction from the pixels farther than nguard from it. thresholds[b, j] is
the threshold of for the spectra of S/N bin .
The constructor takes array_like values, of an integer dtype for starts, and
numpy scalars. It stores them as the types given here, with read-only copies of the
arrays. Two Blocks are equal only if they are the same object.
Attributes:
- starts (ndarray of int64, shape (nblock,)) – The first pixel of each of the nblock ≥ 1 blocks: 0 or more, and strictly increasing.
- width (int) – The number of pixels per block, ; 1 or more.
- nguard (int) – The half-width of the guard window around each block (pixels); from 0 to
, so that
savecan write it. - thresholds (ndarray, shape (nbin, nblock)) – The threshold of of each bin and block (unit-free): finite and positive.
Raises:
- TypeError – If a field has a type or dtype that is not allowed above. The message starts with the name of the field.
- ValueError – If a field has a shape or a value that is not allowed above. The message starts with the name of the field.
gspice.fit
Section titled “gspice.fit”gspice.fit( flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, nsigma: Sequence[float | np.floating[Any] | np.integer[Any]] | NDArray[np.integer[Any] | np.floating[Any]] = (20.0, 8.0, 6.0), maxbadpix: int | np.integer[Any] = 64, nguard: int | np.integer[Any] = 20, cumulative: bool | np.bool_ = True, center: float | np.floating[Any] | np.integer[Any] | None = None, weights: ArrayLike | None = None, rank: int | np.integer[Any] | None = None, noise: bool | np.bool_ = False, snr_bins: int | np.integer[Any] | Iterable[float | np.floating[Any] | np.integer[Any]] | None = None, progress: Callable[[str, int, int], object] | None = None,) -> tuple[Model, NDArray[np.bool_]]Fit a model to training spectra with iterative outlier clipping (paper Alg. 4).
The bad pixels are (mask != 0) | (ivar == 0), and fit never reads flux or
ivar there. fit uses a spectrum unless it has more than maxbadpix bad
pixels, has the weight 0, or a pass mask or the final mask covers it completely.
counts the spectra of a fit. A fit on a mask interpolates the pixels in
it, and scales each spectrum by over the pixels outside it (see
scale). It then estimates
where , and
. With unit weights, is the column mean and the
divisor is . With a constant center , ,
and
. With rank=K, the covariance is
the LowRank .
Here are the leading eigenpairs of , and
, so that
and have the same diagonal.
Pass of the = len(nsigma) passes fits on its mask
with unit weights and the rank, and flags : each pixel,
interpolated ones included, whose in-sample of pixelwise with
nguard exceeds nsigma[n - 1], and its two neighbors. holds the
bad pixels.
- With
cumulative=True(paper Alg. 4), , and the final mask is . - With
cumulative=False(2022), , and the final mask is . nsigma=()fits on the mask of the bad pixels, without clipping.
The final fit uses the final mask and the weights . Without rank, fit
logs a warning on the "gspice" logger for each pass whose threshold exceeds the
in-sample ceiling of of an outlier in a spectrum of typical leverage.
With noise=True, the passes clip as above. The final fit then estimates the
covariance of the noise-free flux, in flux units. Let be 1 at the
pixels outside the final mask and 0 elsewhere, and . Then
is unbiased element by element under these conditions:
- The spectra are independent, with a common mean and signal covariance.
- The noise has zero mean and the variance . It is uncorrelated between pixels and with the signal.
- The masks, weights and ivar do not depend on the flux. The outlier flags of the final mask break this condition.
The model holds and
, with
its eigendecomposition. This cov[0] is
biased upward. With rank=K, cov[0] is the LowRank
.
Here are the leading eigenpairs of ,
and . So
and have the same diagonal.
With snr_bins, spectrum goes to the S/N bin
np.searchsorted(edges, snr_s, side="right"), with from
snr on flux, ivar and mask. Each bin runs the passes and the final fit
above on its own spectra. Bin of the model thus equals a fit on the
spectra of bin alone, with their own clipping, , and
. Each bin clips with its own . So the in-sample ceiling of
falls in small bins, and they flag fewer outliers.
With cumulative=False, fit equals gspice.legacy.covar_iter_mask: the
covariance to rounding, and the mask exactly. This holds under these conditions:
nguardis 20,center,weights,rankandsnr_binsare None, andnoiseis False.fluxis float64, andivar == 0only at pixels inmask.nsigmais not empty.- No lies within the error of the 2022 Schur updates of a threshold.
- No pass mask or final mask covers completely a spectrum with at most
maxbadpixbad pixels. - fit raises no error.
Parameters:
- flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale, except that fit drops a spectrum without a good pixel. - nsigma (sequence of float or ndarray, shape (N,), optional) – The threshold on of each clipping pass, in order; finite and positive.
- maxbadpix (int, optional) – The largest number of bad pixels of a used spectrum; 0 or more.
- nguard (int, optional) – The half-width of the guard window of z (pixels); 0 or more.
- cumulative (bool, optional) – Whether each pass keeps the flags of every earlier pass (paper Alg. 4), or only those of the pass before it (2022).
- center (float, optional) – The constant center (flux); finite. None: a mean-centered model.
- weights (array_like, shape (nspec,), optional) – The weights of the final fit, of an integer or floating dtype; finite and 0 or more. None: equal weights.
- rank (int, optional) – The rank of a low-rank model, used by every pass; from 1 to npix −
- None: a dense model.
- noise (bool, optional) – If True, fit a noise-aware model (see
Model). It needscenterandsnr_binsNone. - snr_bins (int or sequence of float, optional) – The S/N bins. Either their number , 1 or more, with the interior edges
at the quantiles (
np.quantile, linear) of of the spectra that fit uses. These spectra have at mostmaxbadpixbad pixels, a positive weight and a good pixel. Or the interior edges, finite and strictly increasing. None: one bin. - progress (callable, optional) –
progress(stage, done, total), called after each chunk of spectra of each pass and of the final fit. Its arguments are the stage"fit", the number of spectra of that fit done, and their total . With S/N bins, each fit of a bin counts the spectra of that bin.
Returns:
- model (Model) – The model, with the edges, the of each bin in
n_train, and the center.weightedis True if the weights of the spectra of a bin in the final fit are not all equal. The covariances areLowRankwithrank=K. The model holds its precision matrices (seeModel), except a noise-aware model, whose prediction forms one per spectrum. For a noise-aware model,weightedis True if the weights are not all equal, whatever . - mask (ndarray of bool, shape (nspec, npix)) – The final mask, and True at every pixel of a spectrum that fit does not use.
Raises:
-
TypeError – If an argument has a type or a dtype that is not allowed above.
-
ValueError – If an argument has a shape or a value that is not allowed above. If a fit, of a bin with
snr_bins, lacks the spectra that it needs:- For a dense model, if it is mean-centered, and for a constant center. Also a good pixel in one of them at every pixel.
- With
rank=K, if it is mean-centered, and for a constant center, for of rank or more.
With
rank=K, also if or a . Ifnoiseis True with a center orsnr_bins. Withnoise=True, the passes need the spectra above. The final fit raises instead if fewer than two spectra are good at a pixel, or if a denominator of is 0 or negative. Withrank=K, it also raises if for . With two spectra at each pixel, a denominator is 0 or negative where no spectrum is good at both pixels of a pair. Rounding near 0 can also make it 0 or negative. The message names the pass or the final fit, the bin and its edges, and the counts. It also names the first such pixels or pairs of pixels, or . fit checks the counts of every bin before any bin clips. -
numpy.linalg.LinAlgError – If a covariance has a variance of 0, or fails the check of its precision matrix. The check fails if the matrix is not positive definite. It also fails if the reciprocal condition number of the covariance, scaled to unit diagonal, is below . This can happen for close to npix. With
rank=K, the check fails if ofLowRankis above . Clipping checks only ifnguard < npix - 1. The message names the pass or the final fit, the bin and . It also names the pixel of variance 0, the reciprocal condition number below , or . Withnoise=True, only for the clipping covariances.
Notes
Cost:
- Per pass and bin, with the of the bin: about flops for the covariance, and for its precision matrix. The guard weights cost , and z costs . Here .
- The final fit: about flops per bin.
- With nbin above 1, the S/N sorts the npix values of each spectrum once.
- With
rank=K, each fit adds the leading eigenpairs of . Where , Lanczos costs about flops per product with . Otherwise they cost about flops, more than the of a dense . then costs about flops. - Each fit holds the working vectors of its spectra, bytes.
- With
noise=True, the final fit costs about flops for , and . It also costs a full eigendecomposition of an npix × npix matrix, also withrank=K. It holds a few arrays of one chunk ofmax(1, 2**24 // npix)spectra instead of the working vectors.
gspice.fit_blocks
Section titled “gspice.fit_blocks”gspice.fit_blocks( model: Model, flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, width: int | np.integer[Any] = 150, stride: int | np.integer[Any] = 75, nguard: int | np.integer[Any] = 20, percentile: float | np.floating[Any] | np.integer[Any] = 99.9, progress: Callable[[str, int, int], object] | None = None,) -> ModelReturn the model with block thresholds from clean spectra.
Block holds the width pixels from starts[j]. The starts are 0,
stride, 2 stride and so on, up to npix − width. If the last of them is
smaller than npix − width, the start npix − width follows. The defaults
give 31 blocks at npix 2400. fit_blocks first replaces the bad pixels by their
conditional mean, as infill does. It does not detect outliers by z.
Take a spectrum in S/N bin , with the working vector of its
infilled flux (see Model) and the inverse of cov[b]. Let
be a block, the pixels within nguard of , clipped at the
ends, and the pixels outside . Then
where and are the conditional mean
and covariance of given . The guard pixels
are thus marginalized. Where covers all pixels,
and are those of the prior, 0 and cov[b] at
, computed without .
thresholds[b, j] is np.percentile (linear) of of block
, at = percentile, over the spectra of bin
. A block without an artifact then exceeds its threshold with the
probability
if is an integer. Otherwise the probability is at most this
value, for a density that falls beyond the threshold. For , it is
0.20% at and 0.12% at . repair also infills the
pixels that z flags, which lowers this rate. Use clean held-out spectra.
For a noise-aware model, is in flux units. The covariance of
each spectrum (see Model) then replaces cov[b] in its infill and its blocks.
Parameters:
- model (Model) – The model.
- flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale, with the npix ofmodel. Clean spectra, with at least spectra in each bin such that . The check reads as the decimalFraction(str(p)): 1000 spectra at . - width (int, optional) – The number of pixels per block, ; from 1 to npix.
- stride (int, optional) – The distance between the starts of consecutive blocks (pixels); 1 or more.
- nguard (int, optional) – The half-width of the guard window around each block (pixels); from 0 to
, as for
Blocks. - percentile (float, optional) – The percentile of the thresholds; .
- progress (callable, optional) –
progress(stage, done, total), called after each chunk of spectra, with the stage"fit_blocks", the number of spectra done and their total. For a noise-aware model, a chunk is one spectrum.
Returns:
- Model – A new model, equal to
modelexcept forblocks: aBlocksthat holds the starts, width, nguard and thresholds.
Raises:
- TypeError – If
modelis not a Model, orwidth,strideornguardis not an integer. Ifpercentileis not a real number, orprogressis not callable or None. Ifflux,ivarormaskhas a dtype thatscaledoes not allow. - ValueError – If
flux,ivarormaskhas a shape or a value thatscaledoes not allow. Iffluxhas another npix thanmodel, or a spectrum has no good pixel. Ifwidth,stride,nguardorpercentileis outside its range. If a bin has fewer spectra than needs; the message names the bin and its count. If a threshold is not finite or is 0, as for spectra equal to their conditional mean. - numpy.linalg.LinAlgError – If the covariance of a bin fails the check of its precision matrix, as in
pixelwise, and the of a block does not cover all pixels. If of a block is not positive definite. Ifcov[b]at fails that check, for a block whose covers all pixels. Also as ininfill, for the bad pixels. The message names the bin, and the block or the row of a pattern. For a noise-aware model, as ininfill, with in place ofcov[b].
Notes
Cost:
- flops for at the first use of a bin, then flops per bin and block.
- About flops per spectrum, plus the
infillof the bad pixels, of the mean only. - The factors of all bins take bytes
during the scan: 8.8 MB per bin at npix 2400 with the defaults, and 649 MB at
stride=1. - Beyond the inputs, and their float64 copies if they are long double, fit_blocks
holds a bool array of the input shape. It also holds the of the
spectra of one bin (nblock float64 per spectrum), and a few float64 arrays of one
chunk of
max(1, 2**24 // npix)spectra. - The new model shares the arrays of
model, its precision matrices and its guard weights (seeModel). - Unless every block covers all pixels with its guard, a noise-aware model forms
and the factors of the blocks for each spectrum. takes
flops for a dense
cov[0], or for aLowRankof rank . Otherwise the infill of the bad pixels forms no , and costs as ininfill.
Prediction
Section titled “Prediction”Predict pixels from other pixels.
gspice.Prediction
Section titled “gspice.Prediction”class gspice.Prediction( flux: NDArray[np.float64], var: NDArray[np.float64], z: NDArray[np.float64],)The prediction of each pixel of a set of spectra, from pixelwise.
The arrays that pixelwise returns are read-only.
Attributes:
- flux (ndarray, shape (nspec, npix)) – The prediction of each pixel (flux).
- var (ndarray, shape (nspec, npix)) – The conditional variance of each pixel (flux²), which includes the noise.
With
inflate=True, it is multiplied by . - z (ndarray, shape (nspec, npix)) – at good pixels, with the input flux, and NaN at bad pixels (unit-free).
gspice.Repaired
Section titled “gspice.Repaired”class gspice.Repaired( flux: NDArray[np.float64], var: NDArray[np.float64], replaced: NDArray[np.bool_], ignored: NDArray[np.bool_], chi2: NDArray[np.float64], dof: NDArray[np.int64], fs: NDArray[np.float64], draws: NDArray[np.float64] | None, blocks: NDArray[np.bool_] | None = None, _covariances: _Covariances | None = None,)Spectra whose replaced pixels hold their conditional mean, from infill.
repair also returns one. The arrays that infill and repair return are
read-only. With covariance=True, covariance(s) gives the conditional
covariance of the replaced pixels of spectrum s.
Attributes:
- flux (ndarray, shape (nspec, npix)) – The conditional mean at the replaced pixels, and the input flux elsewhere (flux).
- var (ndarray, shape (nspec, npix)) – The conditional variance at the replaced pixels, which includes the noise.
With
inflate=True, it is multiplied by . 1/ivar at the other good pixels, and inf at the other bad pixels (flux²). - replaced (ndarray of bool, shape (nspec, npix)) – The replaced pixels .
- ignored (ndarray of bool, shape (nspec, npix)) – The pixels that are neither conditioned on nor replaced, .
- chi2 (ndarray, shape (nspec,)) – over the replaced pixels that
are good in the input (unit-free). is their input values minus the
conditional mean. is their conditional covariance, which
inflate=Truemultiplies by . 0 wheredofis 0. - dof (ndarray of int64, shape (nspec,)) – The number of replaced pixels that are good in the input.
- fs (ndarray, shape (nspec,)) – of
finite_sample_factor(unit-free), divided by withinflate=True. is then_trainof the bin of the spectrum, and the number of its conditioning pixels. NaN wheredofis 0 or . 1 for a model with a constant center, weights, aLowRankcovariance or noise, for which no factor is derived. Take the other models, and replace and ignore masks that do not depend on the data. Thenchi2 / (dof * fs)has the mean 1 for held-out Gaussian spectra, with or withoutinflate. - draws (ndarray, shape (nspec, npix), or None) – A draw from the conditional distribution at the replaced pixels, with the
covariance of
covariance, and the input flux elsewhere (flux). None if the call ran withoutrng. - blocks (ndarray of bool, shape (nspec, nblock), or None) – The blocks of
model.blocksthat the block pass ofrepairflagged in each spectrum. None for a result ofinfill, or ofrepairwithblockwise=False.
covariance
Section titled “covariance”covariance(s: int | np.integer[Any]) -> tuple[NDArray[np.int64], NDArray[np.float64]]Return the conditional covariance of the replaced pixels of spectrum s.
Parameters:
- s (int) – The row of the spectrum; from 0 to nspec − 1.
Returns:
- pixels (ndarray of int64, shape (m,)) – The replaced pixels of spectrum
s, in increasing order. - cov (ndarray, shape (m, m)) – Their conditional covariance (flux²), multiplied by
with
inflate=True. Its diagonal isvar[s, pixels].
Raises:
- TypeError – If
sis not an integer. - ValueError – If the call ran without
covariance=True, orsis outside 0 to nspec − 1.
gspice.pixelwise
Section titled “gspice.pixelwise”gspice.pixelwise( model: Model, flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, nguard: int | np.integer[Any] = 20, inflate: bool | np.bool_ = False, progress: Callable[[str, int, int], object] | None = None,) -> PredictionPredict each pixel from all pixels farther than nguard from it (paper Alg. 3).
Take pixel of a spectrum in S/N bin , with its working
vector (see Model) and the inverse of cov[b].
Let , and let hold the
pixels outside . Then
Prediction.flux and Prediction.var are this mean and variance in flux units,
as unscale returns them. Bad pixels enter as interpolated values. Their z is NaN,
and var omits the error of those values. Next to a run of 60 bad pixels at the
correlation length 20, the measured was 0.65 to 2.45,
depending on the noise level.
A bad pixel farther than nguard from takes its value from the nearest
good pixels. So a good pixel within nguard of can enter the prediction
of . Next to a run of bad pixels longer than nguard, itself
can also enter it. nguard >= npix - 1 gives the prior.
For a noise-aware model, is in flux units, and is the inverse of
the covariance of the spectrum (see Model). pixelwise forms
for each spectrum. Where , it
computes the mean as . This is equal in exact
arithmetic, but the values in cancel only to rounding.
Parameters:
- model (Model) – The model.
- flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale, with the npix ofmodel. - nguard (int, optional) – The half-width of the guard window (pixels); 0 or more.
- inflate (bool, optional) – If True, multiply
varby offinite_sample_factor. is then_trainof the bin of the spectrum. is the number of conditioning pixels of each pixel, which is larger near the ends, where is clipped. then has the mean 1 for held-out Gaussian spectra. It needs a dense, mean-centered, unweighted scaled model. - progress (callable, optional) –
progress(stage, done, total), called after each chunk of spectra, with the stage"pixelwise", the number of spectra done and their total. For a noise-aware model, a chunk is one spectrum.
Returns:
- Prediction – The prediction, in flux units.
Raises:
- TypeError – If
modelis not a Model,nguardis not an integer,inflateis not a bool, orprogressis not callable or None. Ifflux,ivarormaskhas a dtype thatscaledoes not allow. - ValueError – If
flux,ivarormaskhas a shape or a value thatscaledoes not allow. Iffluxhas another npix thanmodel,nguardis negative, or a spectrum has no good pixel. Ifinflateis True andmodelhas a constant center, weights, aLowRankcovariance or noise. Ifinflateis True and at a pixel of a bin with spectra, where is not defined; the message names and . - numpy.linalg.LinAlgError – If
nguard < npix - 1and the covariance of a bin with spectra fails the check of its precision matrix. The check fails if the matrix is not positive definite, or if the reciprocal condition number of the covariance, scaled to unit diagonal, is below . It also fails if of aLowRankcovariance is above . The message names the bin, or for a noise-aware model the row whose fails.
Notes
Cost:
- flops for at the first use of a bin, or
for a
LowRankof rank . - About flops for the guard
weights, at the first use of a bin and after each change of
nguard, with . - Then flops per spectrum.
- The model keeps and the guard weights (see
Model). - A noise-aware model costs per spectrum, and keeps none. Where , it costs about flops for its guard windows and for the mean, instead of the guard weights.
gspice.infill
Section titled “gspice.infill”gspice.infill( model: Model, flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, replace: ArrayLike | None = None, ignore: ArrayLike | None = None, inflate: bool | np.bool_ = False, covariance: bool | np.bool_ = False, rng: np.random.Generator | None = None, progress: Callable[[str, int, int], object] | None = None,) -> RepairedReplace pixels by their Gaussian conditional mean given the conditioning pixels.
Take a spectrum in S/N bin , with its working vector (see
Model) and the inverse of cov[b]. Let be the pixels of
replace | ignore | bad, with the bad pixels (mask != 0) | (ivar == 0).
The other pixels are the conditioning pixels. Then
Repaired.flux is this mean at the replaced pixels = replace, in
flux units as unscale returns it, and the input flux elsewhere. The pixels of
outside keep their input value, and the result reports them as
ignored. A pixel in both replace and ignore is replaced. Values in
never enter the mean, so an outlier there cannot change it. chi2 compares the
input values at , the replaced pixels that are
good in the input, with their conditional distribution.
Where covers all pixels, the result is the prior
, which infill computes from cov[b] without
. For a noise-aware model, is in flux units, and the
of the spectrum (see Model) replaces cov[b]. Each spectrum then has its own
and pattern.
With rng, Repaired.draws holds the draw of
, in flux units like the mean. Here is the mean at
, , and holds the
normals of the spectrum at .
Spectra of one S/N bin with equal , and form a pattern.
The spectra of a pattern in one chunk of max(1, 2**24 // npix) rows share one
factorization of . To infill with another model the pixels that a
result r replaced and ignored, pass replace=r.replaced and
ignore=r.ignored.
Parameters:
- model (Model) – The model.
- flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale, with the npix ofmodel. - replace (array_like of bool, shape (nspec, npix) or (npix,), optional) – The pixels to replace, . An (npix,) mask applies to every spectrum, for example to predict a range of pixels. None: the bad pixels.
- ignore (array_like of bool, shape (nspec, npix) or (npix,), optional) – Pixels that are neither conditioned on nor replaced, unless they are in
replace, such as a guard around a range of pixels. None: no pixels. - inflate (bool, optional) – If True, multiply
varand the covariance at the replaced pixels by offinite_sample_factor. is then_trainof the bin of the spectrum, and the number of its conditioning pixels. Also dividechi2by the factor, and multiply the deviation of each draw from the mean by its square root. Then, for held-out Gaussian spectra, take any fixed linear combination of the replaced pixels. Its squared residual, divided by its variance from the covariance, has the mean 1. It needs a dense, mean-centered, unweighted scaled model. - covariance (bool, optional) – If True, keep the conditional covariance of each pattern for
Repaired.covariance. - rng (numpy.random.Generator, optional) – If given, the source of
Repaired.draws. infill drawsrng.standard_normal((n, npix))for each chunk of rows, in row order, and nothing else. Each spectrum uses its row of these normals. Calls on consecutive slices with one generator give the draws of one call, to rounding. Draws widen the errors of measurements made on them;varandcovariancegive the uncertainty of the replaced pixels. None: no draws. - progress (callable, optional) –
progress(stage, done, total), called after each chunk of spectra, with the stage"infill", the number of spectra done and their total. For a noise-aware model, a chunk is one spectrum.
Returns:
- Repaired – The infilled spectra, in flux units.
Raises:
-
TypeError – If
modelis not a Model, orinflateorcovarianceis not a bool. Ifrngis neither None nor a numpy.random.Generator, orprogressis not callable or None. Ifflux,ivarormaskhas a dtype thatscaledoes not allow, orreplaceorignoreis not of a bool dtype. -
ValueError – If
flux,ivarormaskhas a shape or a value thatscaledoes not allow. Iffluxhas another npix thanmodel, or a spectrum has no good pixel. Ifreplaceorignorehas another shape than (nspec, npix) or (npix,). Ifinflateis True andmodelhas a constant center, weights, aLowRankcovariance or noise. Ifinflateis True and for a spectrum with a pixel to replace, where is not defined; the message names and . -
numpy.linalg.LinAlgError – If the covariance of a bin fails the check of its precision matrix, as in
pixelwise, where a spectrum of the bin has a pixel to replace and does not cover all its pixels. If of a pattern is not positive definite. For a pattern whose covers all pixels, ifcov[b]at fails that check, or ifrngis given andcov[b]at is not positive definite. The message names the bin, and for a pattern its first spectrum.For a noise-aware model, replaces
cov[b]. A that fails the check of its precision matrix raises with its row in the message. ALowRankcov[0]forms no precision matrix. Its raises where , with, and of . It also raises where the factor of fails, or the factor of its conditional covariance at (at without
rng). The message names its row. accepts every that the check ofLowRankaccepts. It also accepts some with up to , whichpixelwiseandrepairstill reject.
Notes
Cost:
- flops for at the first use of a bin, or
for a
LowRankof rank . - Per pattern and chunk, flops, and more
with
covariance=True. - Per spectrum, flops, or where is one run.
- Without
rng, some patterns share one factor: patterns of a chunk with one bin and one , and short of all pixels. Let be the pixels in the of all of them. For each pattern, let be the pixels of its outside . Let be the pixels of in the of another of them but not in its own. The patterns share the factor under three conditions. Each has , and . The shared factor costs fewer flops than their own factors, or than the mean from . - These patterns together cost flops, and
more with
covariance=True. Let be the pixels in the of any of them. Each of these patterns costs flops, and more withcovariance=True. Each of their spectra costs flops. An (npix,) mask on spectra with a few bad pixels of their own is such a case. - The model keeps (see
Model). - With
covariance=True, the result keeps bytes per pattern and chunk. - With
rng, each spectrum costs npix normals and flops more. Where covers all pixels, it costs flops more instead. Each pattern and chunk then also costs flops for the factor ofcov[b]at , which aLowRankforms at flops. - A noise-aware model forms for each spectrum with a pixel to replace,
and every spectrum is its own pattern. Where is also short of all
pixels, a dense
cov[0]forms no . Per spectrum, it costs flops for the Cholesky factor of , before the pattern costs above. From this factor, and cost about flops, with the first pixel of . - A
LowRankcov[0]of rank forms no . Per spectrum, it costs flops for its system, and for the mean andvar.chi2costs . Withrng,chi2and the draws cost instead.
Repair
Section titled “Repair”Detect artifacts, and replace the flagged pixels and the bad pixels.
gspice.repair
Section titled “gspice.repair”gspice.repair( model: Model, flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, nguard: int | np.integer[Any] = 20, nsigma_replace: float | np.floating[Any] | np.integer[Any] = 10.0, nsigma_ignore: float | np.floating[Any] | np.integer[Any] = 5.0, dilate: int | np.integer[Any] = 1, blockwise: bool | np.bool_ = True, runlength: int | np.integer[Any] | None = 5, halfwidth: int | np.integer[Any] = 150, minfrac: float | np.floating[Any] | np.integer[Any] = 0.5, count_on: Literal['all', 'flagged'] = 'all', inflate: bool | np.bool_ = False, covariance: bool | np.bool_ = False, rng: np.random.Generator | None = None, progress: Callable[[str, int, int], object] | None = None,) -> RepairedDetect artifacts, and replace the flagged pixels and the bad pixels.
Take a spectrum with the working vector (see Model) and the bad pixels
(mask != 0) | (ivar == 0). For a vector , let
at every pixel, its interpolated bad
pixels included. Here and are the mean and variance
of pixelwise with nguard for a vector , and
is the z of pixelwise. Let
be the pixels within of a pixel of along the spectrum, with
= dilate. Let be nsigma_replace and
be nsigma_ignore. A conditional mean is that of infill. The steps, in this
order, are:
-
, and .
-
If
blockwise: let be with its values at replaced by their conditional mean given the other pixels. Take the blocks ofmodel.blocksthat are not flagged, and the ratio . Here is that offit_blocks, and is the S/N bin of the spectrum. While the largest ratio exceeds 1, the block of that ratio is flagged, and its pixels join . then becomes with its values at replaced by their conditional mean given the other pixels. A block is flagged at most once, so there are at most nblock rounds. Withoutblockwise, is empty. -
Let be with its values at replaced by their conditional mean given the pixels outside . Let . Then
and .
-
If
runlengthis not None, step 4 widens . Every run of at leastrunlengthconsecutive pixels of the counting set adds the pixels withinhalfwidthof the run to , minus . Step 4 adds no pixel to a spectrum if fewer than pixels outside and would then remain. is forcount_on="all". For"flagged", holds and the pixels outside bad with . -
The result is that of
infillwithreplace=M,ignore=I, andinflate,covarianceandrng, bit for bit, plus the flagged blocks. A dense noise-aware model can form in steps 1 to 4, for guard windows or blocks short of all pixels. Step 5 then conditions on that , whereinfilluses the Cholesky factor of . The two then agree to rounding.
Nothing limits the replaced set. Since and depend on the data,
does not hold for Repaired.chi2 (see finite_sample_factor). For a
noise-aware model, is in flux units, and the of the spectrum
(see Model) replaces cov[b] in every step. repair then runs the five steps one
spectrum at a time, with one for all of them.
Parameters:
- model (Model) – The model; with
blockwise=True, one with blocks fromfit_blocks. - flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale, with the npix ofmodel. - nguard (int, optional) – The half-width of the guard window of z (pixels); 0 or more.
- nsigma_replace (float, optional) – The threshold of for replacing a pixel; finite and positive.
- nsigma_ignore (float, optional) – The threshold of for ignoring a pixel; finite,
positive and at most
nsigma_replace. - dilate (int, optional) – The number of pixels by which dil widens the flags of z on each side; 0 or more. Paper Fig. 8 uses 2.
- blockwise (bool, optional) – If True, run the block pass of step 2.
- runlength (int or None, optional) – The shortest run of that widens (pixels); 1 or more. None skips step 4.
- halfwidth (int, optional) – The number of pixels on each side of a run that join ; 0 or more.
- minfrac (float, optional) – The fraction of npix that step 4 leaves to condition on; from 0 to 1.
- count_on ({“all”, “flagged”}, optional) – The counting set of step 4.
- inflate, covariance (bool, optional) – As in
infill, for step 5.inflateneeds a dense, mean-centered, unweighted scaled model. - rng (numpy.random.Generator, optional) – As in
infill, for step 5: the source ofRepaired.draws. None: no draws. - progress (callable, optional) –
progress(stage, done, total), called with the stage"repair", the number of spectra done and their total. repair calls it after each chunk of spectra of steps 1 to 4, and again after each chunk of step 5. A noise-aware model runs the five steps on chunks of one spectrum, and reports after its steps 1 to 4 and after its step 5.
Returns:
- Repaired – The repaired spectra, in flux units, with
replacedandignored.blocksholds the flagged blocks of each spectrum, or None ifblockwiseis False.
Raises:
- TypeError – If
modelis not a Model, ornguard,dilate,runlengthorhalfwidthis not an integer (or None forrunlength). Ifnsigma_replace,nsigma_ignoreorminfracis not a real number, orblockwise,inflateorcovarianceis not a bool. Ifrngis neither None nor a numpy.random.Generator, orprogressis not callable or None. Ifflux,ivarormaskhas a dtype thatscaledoes not allow. - ValueError – If
flux,ivarormaskhas a shape or a value thatscaledoes not allow. Iffluxhas another npix thanmodel, or a spectrum has no good pixel. If an argument is outside its range above,count_onis neither"all"nor"flagged", orblockwiseis True andmodelhas no blocks. Ifinflateis True andmodelhas a constant center, weights, aLowRankcovariance or noise. Ifinflateis True and, before step 5, for a spectrum with a replaced pixel, with ; the message names and . - numpy.linalg.LinAlgError – If the covariance of a bin with spectra fails the check of its precision matrix,
as in
pixelwise. repair checks the of every bin with spectra before any spectrum, also fornguard >= npix - 1, wherepixelwisecomputes no . As infit_blocksfor the blocks of a bin with spectra, withblockwise=True. As ininfillfor a conditional mean. The message names the bin, and the block or the row. For a noise-aware model, as ininfill, with in place ofcov[b], checked for each spectrum where a step factors .
Notes
Cost:
- flops for at the first use of a bin, and the
guard weights as in
pixelwise. - With
blockwise=True, flops per block and bin with spectra, with the block and its guard. - Per spectrum, flops for the two pixelwise passes, and about flops per scan of its blocks.
- Per spectrum, one scan and one infill per flagged block, and two infills as in
infill. These two are the infill of step 5, and that of step 2, whose last gives , or withoutblockwisethat of step 3. All infills except that of step 5 compute only the mean, from where . - repair holds
replacedandignoredof all spectra, and a few arrays of one chunk. - A noise-aware model costs, for each spectrum, , its guard windows as in
pixelwise, and its block factors. takes flops for a densecov[0], or for aLowRankof rank . The infills of aLowRankcov[0]do not use , and cost as ininfill.
Diagnostics
Section titled “Diagnostics”Check that the predicted uncertainties are calibrated.
gspice.Calibration
Section titled “gspice.Calibration”class gspice.Calibration(z2: ArrayLike, n: ArrayLike, fs: ArrayLike)Held-out whitened residuals, from calibration or another held-out result.
Row is a spectrum, and column is one prediction of n[s, j]
of its pixels. z2[s, j] is , with the
residuals of these pixels from their conditional mean and their full
conditional covariance. fs[s, j] is its finite-sample factor, such as
of finite_sample_factor. For held-out Gaussian spectra and pixel sets
that do not depend on the data, z2 / (n * fs) then has the mean 1. The methods
use only the entries with n > 0 and finite z2 and fs.
Calibration(z2=r.chi2[:, None], n=r.dof[:, None], fs=r.fs[:, None]) holds the
result r of infill on held-out spectra, with replace and ignore masks that do
not depend on the data. Calibration(z2=p.z**2, n=1, fs=1) holds the result p
of pixelwise with inflate=True.
The constructor takes array_like values, and broadcasts n and fs to the
shape of z2. It stores read-only copies: z2 and fs as float64, and n
as int64. Two calibrations are equal only if they are the same object. Pickle, copy
and deepcopy check the fields again.
Attributes:
- z2 (ndarray, shape (nspec, ncol)) – of each prediction (unit-free): finite and 0 or more, or NaN.
- n (ndarray of int64, shape (nspec, ncol)) – The number of predicted pixels: from 0 to .
- fs (ndarray, shape (nspec, ncol)) – The finite-sample factor of each prediction (unit-free): finite and positive, or NaN.
Raises:
- TypeError – If
z2orfsdoes not have an integer or floating dtype, orndoes not have an integer dtype; bool is neither. The message starts with the name of the field. - ValueError – If
z2is not 2-D, ornorfsdoes not broadcast to the shape ofz2. If a field has a value that is not allowed above. The message starts with the name of the field.
ratio(where: ArrayLike | None = None) -> tuple[NDArray[np.float64], NDArray[np.float64]]Mean of z2 / (n * fs) in each column, and its standard error.
Take the entries of column that the methods use, in the
spectra of where. mean[j] is the mean of their z2 / (n * fs), and
, with std their standard
deviation with the divisor . For held-out spectra, sem is
conditional on the fitted model. It falls with the number of held-out spectra,
but the spread across training sets does not.
Parameters:
- where (array_like of bool, shape (nspec,), optional) – The spectra to use. None: all.
Returns:
- mean (ndarray, shape (ncol,)) – The mean (unit-free); NaN where .
- sem (ndarray, shape (ncol,)) – Its standard error (unit-free); NaN where .
Raises:
- TypeError – If
wheredoes not have a bool dtype. - ValueError – If
wherehas another shape than (nspec,).
tail( q: float | np.floating[Any] | np.integer[Any] = 0.99, where: ArrayLike | None = None,) -> NDArray[np.float64]Fraction of each column with z2 / fs above a quantile.
Take the entries of column that the methods use, in the
spectra of where. The result is the fraction of them with z2 / fs above
. is the distribution function
with the n of the entry as its degrees of freedom. For held-out Gaussian
spectra, the fraction approaches only for .
It is 1.37% at for .
Parameters:
- q (float, optional) – The quantile; .
- where (array_like of bool, shape (nspec,), optional) – The spectra to use. None: all.
Returns:
- ndarray, shape (ncol,) – The fraction (unit-free); NaN where .
Raises:
- TypeError – If
qis not a real number, orwheredoes not have a bool dtype. - ValueError – If
qis not strictly between 0 and 1, orwherehas another shape than (nspec,).
qq( i: int | np.integer[Any] = 0, where: ArrayLike | None = None,) -> tuple[NDArray[np.float64], NDArray[np.float64]]Normal scores of column i against , for a QQ plot.
Take the entries of column i that the methods use, in the spectra
of where. expected holds for
, with the standard normal distribution
function. observed holds the sorted scores
. is the
distribution function with the n of the entry as its degrees
of freedom. A score is where . It is
elsewhere, from the survival function, so that both
tails keep their precision. A score is where z2 is 0, and
where the survival function underflows to 0. For held-out
Gaussian spectra, observed approaches expected under the condition of
tail.
Parameters:
- i (int, optional) – The column; from 0 to ncol − 1.
- where (array_like of bool, shape (nspec,), optional) – The spectra to use. None: all.
Returns:
- expected (ndarray, shape (m,)) – The normal scores of the plotting positions, in increasing order.
- observed (ndarray, shape (m,)) – The scores of the entries, in increasing order.
Raises:
- TypeError – If
iis not an integer, orwheredoes not have a bool dtype. - ValueError – If
iis outside 0 to ncol − 1, orwherehas another shape than (nspec,).
gspice.calibration
Section titled “gspice.calibration”gspice.calibration( model: Model, flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, sizes: Iterable[int | np.integer[Any]] | None = None, layout: Literal['run', 'scattered'] = 'run', rng: np.random.Generator, progress: Callable[[str, int, int], object] | None = None,) -> CalibrationHeld-out whitened residuals for masks drawn independently of the data.
For each spectrum and each size of sizes, calibration draws a set
of good pixels. It computes, as infill with replace=M
does,
with the input values at minus their conditional mean given
the pixels outside , and their full
conditional covariance. It also computes of
finite_sample_factor, NaN where it is not defined. is the n_train
of the bin of the spectrum. The factor is 1 where no factor is derived (see
Repaired.fs). For held-out Gaussian spectra of a model with a derived factor,
then has the mean 1. For a noise-aware model, the covariance
is the of the spectrum (see Model).
Rank the good pixels of a spectrum from 0 to in increasing
order. With layout="run", holds those of ranks start to
start + n - 1, with start = rng.integers(m - n + 1).
With layout="scattered", holds those of ranks
rng.choice(m, n, replace=False). rng draws these spectrum by spectrum in row
order, and size by size within a spectrum. It draws nothing else, so the masks do
not depend on the chunking. A spectrum with draws nothing for that
size. Its entry there has n 0 and z2 NaN.
Parameters:
- model (Model) – The model.
- flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale, with the npix ofmodel. - sizes (iterable of int, optional) – The sizes , one column of the result each, in this order; 1 or more.
None: the sizes 1, 4, 16, 64, 256 and 1024 that are not above half the median
number of good pixels per spectrum (
np.median). Without a spectrum, all six. A spectrum with fewer good pixels than a size hasn0 there, so the spectra of a column can differ between sizes.Calibrationmethods withwhere=(result.n > 0).all(axis=1)compare all sizes on the same spectra. - layout ({“run”, “scattered”}, optional) – Whether is a run of good pixels, or good pixels scattered at random.
- rng (numpy.random.Generator) – The source of the masks, as above.
- progress (callable, optional) –
progress(stage, done, total), called after each chunk of spectra, with the stage"calibration", the number of spectra done and their total. For a noise-aware model, a chunk is one spectrum.
Returns:
- Calibration –
z2,nandfsof each spectrum (row) and size (column).
Raises:
- TypeError – If
modelis not a Model, orsizesis neither None nor an iterable of integers. Ifrngis not a numpy.random.Generator, orprogressis not callable or None. Ifflux,ivarormaskhas a dtype thatscaledoes not allow. - ValueError – If
flux,ivarormaskhas a shape or a value thatscaledoes not allow. Iffluxhas another npix thanmodel, or a spectrum has no good pixel. Ifsizesis empty or holds an integer below 1, orlayoutis neither"run"nor"scattered". Ifsizesis None and the median number of good pixels per spectrum is below 2. - numpy.linalg.LinAlgError – Before the first chunk, if the covariance of a bin fails its check, for a bin
with a spectrum that has more good pixels than the smallest size. For a
noise-aware model, the check is at the spectrum. Otherwise as in
infillwithreplace=M.
Notes
Cost:
- For each size, flops for at the first use of a bin.
- Then flops per pattern of a chunk of
max(1, 2**24 // npix)spectra, or where covers all pixels. A spectrum has at most one pattern per size. - Per spectrum, flops, or where is one run.
- The masks of a chunk take up to bytes.
- A noise-aware model costs per spectrum and size as in
infill, with . A densecov[0]factors once per spectrum for all sizes.
gspice.finite_sample_factor
Section titled “gspice.finite_sample_factor”gspice.finite_sample_factor( n_train: int | np.integer[Any], n_cond: int | np.integer[Any], n_pred: int | np.integer[Any] = 1,) -> floatgspice.finite_sample_factor( n_train: ArrayLike, n_cond: ArrayLike, n_pred: ArrayLike = 1,) -> float | NDArray[np.float64]Held-out calibration factor for Gaussian data.
Take a held-out spectrum, predicted at pixels from conditioning pixels. The prediction uses the mean and the covariance (divisor ) of unweighted training spectra. Let be the residual of the pixels from their conditional mean, and their full conditional covariance. Then has the mean
The factor is exact for independent Gaussian working vectors and pixel sets that do not depend on the data. Pixels that are neither conditioned on nor predicted, such as a guard window or ignored pixels, do not count in . does not hold for data that are not Gaussian, such as scaled spectra with a spread of S/N. The arguments broadcast. The arithmetic is float64, which holds each count exactly.
Parameters:
- n_train (array_like of int) – , the number of training spectra; from 1 to .
- n_cond (array_like of int) – , the number of conditioning pixels; from 0 to .
- n_pred (array_like of int, optional) – , the number of predicted pixels; from 1 to .
Returns:
- float or ndarray – (unit-free): a float if the arguments are scalars, and otherwise a float64 array of their broadcast shape.
Raises:
- TypeError – If an argument does not have an integer dtype; bool is not one.
- ValueError – If an argument is outside its range, the arguments do not broadcast, or . The message names the arguments and the first such entry.
gspice.noise_audit
Section titled “gspice.noise_audit”gspice.noise_audit( model: Model, flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, nguard: int | np.integer[Any] = 20, progress: Callable[[str, int, int], object] | None = None,) -> NDArray[np.float64]Ratio of the residual scatter to the reported noise at each pixel.
Let be the flux and its prediction by pixelwise with
nguard, in flux units. Then
where the mean runs over the spectra whose pixel is good (see
scale). Let be the noise-free flux. Let be the mean of
, which is 1 where
ivar is right, and the mean of
. Then
if does not depend on the noise of . That holds
for held-out spectra, with mask and ivar independent of the noise, and noise
that is uncorrelated beyond nguard. It fails where the interpolation of a bad
pixel carries , or a pixel within nguard of , into
(see pixelwise). With several S/N bins, also
enters the median S/N that picks the bin of .
holds the astrophysical error, the noise propagated from the
conditioning pixels, and the estimation error of model.
So where the identity holds, and grows
with S/N. Next to a run of bad pixels longer than nguard, can
fall below . A scaled model absorbs into its covariance an
that its training spectra share, so the z of pixelwise is blind to
it. is not.
Parameters:
- model (Model) – The model.
- flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale, with the npix ofmodel. - nguard (int, optional) – The half-width of the guard window of
pixelwise(pixels); 0 or more. - progress (callable, optional) –
progress(stage, done, total), called after each chunk of spectra, with the stage"noise_audit", the number of spectra done and their total. For a noise-aware model, a chunk is one spectrum.
Returns:
- ndarray, shape (npix,) – (unit-free); NaN at the pixels where no spectrum is good.
Raises:
- TypeError – If
modelis not a Model,nguardis not an integer, orprogressis not callable or None. Ifflux,ivarormaskhas a dtype thatscaledoes not allow. - ValueError – If
flux,ivarormaskhas a shape or a value thatscaledoes not allow. Iffluxhas another npix thanmodel,nguardis negative, or a spectrum has no good pixel. - numpy.linalg.LinAlgError – As in
pixelwise.
Notes
Cost: that of pixelwise. Beyond the inputs, and their float64 copies if they are
long double, noise_audit holds a bool array of the input shape. It also holds a few
float64 arrays of one chunk of max(1, 2**24 // npix) spectra.
Scaling
Section titled “Scaling”Scale spectra before fitting, and undo the scaling.
gspice.scale
Section titled “gspice.scale”gspice.scale( flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None, *, center: float | np.floating[Any] | np.integer[Any] = 0.0, refmean: ArrayLike | None = None,) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]Scale spectra to unit mean noise.
The bad pixels are (mask != 0) | (ivar == 0), and scale never reads flux or
ivar there. It checks and computes the float64 values of the inputs. A long
double beyond the float64 range is not finite, and one that rounds to 0 in float64
is 0. is flux[s] cast to float64, then linearly interpolated
over its bad pixels, and held constant beyond its first and last good pixels.
is the square root of the mean of over its good
pixels. With float64 flux, scale(flux, ivar, mask) equals the 2022
gspice.legacy.standard_scale with the mask (mask != 0) | (ivar == 0), to
rounding.
Parameters:
- flux (array_like, shape (nspec, npix)) – Flux, of an integer or floating dtype; finite at good pixels.
- ivar (array_like, shape (nspec, npix)) – Inverse variance (flux⁻²), of an integer or floating dtype; finite and 0 or
more at pixels not in
mask. - mask (array_like, shape (nspec, npix), optional) – A nonzero value marks a pixel in
mask; of a bool, integer or floating dtype. None: no pixel is inmask. - center (float, optional) – A constant subtracted before scaling (flux).
- refmean (array_like, shape (npix,), optional) – The mean subtracted after scaling (scaled); finite. None: the column mean of , which needs at least one spectrum. For held-out spectra, pass the model mean of their S/N bin: their own mean breaks the finite-sample factor .
Returns:
- X (ndarray, shape (nspec, npix)) – The scaled spectra (scaled).
- refscale (ndarray, shape (nspec,)) – (flux⁻¹).
- refmean (ndarray, shape (npix,)) – The subtracted mean (scaled); a copy if
refmeanis given.
Raises:
- TypeError – If an argument has a dtype or a type that is not allowed above.
- ValueError – If an argument has a shape or a value that is not allowed above, or a spectrum has no good pixel.
gspice.unscale
Section titled “gspice.unscale”gspice.unscale( x: ArrayLike, refscale: ArrayLike, refmean: ArrayLike, *, center: float | np.floating[Any] | np.integer[Any] = 0.0, var: ArrayLike | None = None,) -> tuple[NDArray[np.float64], NDArray[np.float64] | None]Invert scale, for values and their variances.
It computes with the float64 values of the inputs, as scale does.
Parameters:
- x (array_like, shape (nspec, n)) – Values at pixels (scaled), of an integer or floating dtype.
- refscale (array_like, shape (nspec,)) – of
scale(flux⁻¹); finite and positive. - refmean (array_like, shape (n,)) – The mean that
scalesubtracted at these pixels (scaled); finite. - center (float, optional) – The
centerofscale(flux). - var (array_like, shape (n,) or (nspec, n), optional) – Variances of
x(scaled²), of an integer or floating dtype; 0 or more.
Returns:
- f (ndarray, shape (nspec, n)) – Flux.
- var_f (ndarray, shape (nspec, n), or None) – Variances of
f(flux²); None ifvaris None.
Raises:
- TypeError – If an argument has a dtype or a type that is not allowed above.
- ValueError – If an argument has a shape or a value that is not allowed above.
gspice.snr
Section titled “gspice.snr”gspice.snr( flux: ArrayLike, ivar: ArrayLike, mask: ArrayLike | None = None,) -> NDArray[np.float64]Median signal-to-noise ratio over the good pixels of each spectrum.
The ratio at a pixel is . The bad pixels
are (mask != 0) | (ivar == 0), and snr never reads flux or ivar there.
The products are computed in float64.
Parameters:
- flux, ivar, mask (array_like, shape (nspec, npix)) – As in
scale.
Returns:
- ndarray, shape (nspec,) – Signal-to-noise ratio (unit-free).
Raises:
- TypeError – If an argument has a dtype that
scaledoes not allow. - ValueError – If an argument has a shape or a value that
scaledoes not allow, or a spectrum has no good pixel.
Simulation
Section titled “Simulation”Make synthetic spectra for tests and examples.
gspice.Simulation
Section titled “gspice.Simulation”class gspice.Simulation( flux: NDArray[np.float64], ivar: NDArray[np.float64], truth: NDArray[np.float64], artifacts: NDArray[np.bool_], snr: NDArray[np.float64], labels: NDArray[np.int64],)Synthetic spectra from simulate, with their noise-free flux and artifacts.
The arrays that simulate returns are read-only.
Attributes:
- flux (ndarray, shape (nspec, npix)) – The flux, with noise and artifacts (flux).
- ivar (ndarray, shape (nspec, npix)) – The inverse variance of the noise, (flux⁻²).
- truth (ndarray, shape (nspec, npix)) – The noise-free flux without artifacts (flux).
- artifacts (ndarray of bool, shape (nspec, npix)) – The pixels that an injected artifact covers.
- snr (ndarray, shape (nspec,)) – The continuum signal-to-noise ratio that each spectrum was drawn with (unit-free).
- labels (ndarray of int64, shape (nspec,)) – The population of each spectrum: 0, or 1 for the giants.
gspice.simulate
Section titled “gspice.simulate”gspice.simulate( nspec: int | np.integer[Any], npix: int | np.integer[Any] = 500, *, rng: np.random.Generator, artifacts: float | np.floating[Any] | np.integer[Any] = 0.0, gaussian: bool | np.bool_ = False,) -> SimulationSynthetic continuum-normalized spectra for tests and examples (no network).
Each spectrum has the continuum 1 and absorption lines at evenly spaced centers. Line has a Gaussian profile , with a standard deviation from 1.5 to 4 pixels. The lines depend only on npix. Two latent parameters set the depths. A spectrum is in population 1, the giants, with the probability 0.3, and then has . Otherwise . Line has the depth
with from 0.1 to 0.6 its depth at , and . The depths are thus correlated, in (0, 0.95), and not Gaussian. Then , in (0, 1]. The continuum S/N has the density on [30, 400]. The noise is Gaussian with .
With gaussian=True, with
. Here is the truth of population 0 at
, and the columns of are its derivatives there.
Every spectrum has the label 0 and the S/N 50, and .
So ivar is equal for all spectra. Without artifacts,
, and the
scaled spectra (see scale) are exactly Gaussian. truth can then leave (0, 1].
round(artifacts * nspec) spectra (half to even), chosen at random, get one
artifact each. Its type is drawn uniformly from three:
- A cosmic ray adds to each of 1 to 3 adjacent pixels, with log-uniform on [5, 50].
- A bad column sets the flux of 5 to 20 adjacent pixels to 2.
- A shifted segment of 200 to 600 adjacent pixels has the flux plus the noise. The shift is from 0.5 to 3 pixels, of either sign. truth is interpolated linearly, and held constant beyond its ends.
An artifact covers at most npix − 1 pixels, or 1 if npix is 1. Its start is drawn
uniformly from the starts where it fits. For one state of rng, every value of
artifacts gives the same ivar, truth, snr and labels. It also
gives the same flux outside the pixels in Simulation.artifacts.
Parameters:
- nspec (int) – The number of spectra; 0 or more.
- npix (int, optional) – The number of pixels; 1 or more.
- rng (numpy.random.Generator) – The source of all randomness. With the same libraries and thread settings, the same state gives the same result bit for bit.
- artifacts (float, optional) – The fraction of spectra with an artifact; from 0 to 1.
- gaussian (bool, optional) – Draw exactly Gaussian spectra, as above.
Returns:
- Simulation – The spectra.
Raises:
- TypeError – If an argument has a type that is not allowed above.
- ValueError – If an argument has a value that is not allowed above.
Notes
Cost: time and memory, plus the nline
profiles of npix values each. With gaussian=False, the line sum adds
flops.
Input and output
Section titled “Input and output”Write a model to a file, and read it back.
gspice.save
Section titled “gspice.save”gspice.save( model: Model, path: str | bytes | os.PathLike[str] | os.PathLike[bytes],) -> NoneWrite model to the .npz file path.
The archive is not compressed. It holds these arrays:
schema(the integer 1),gspice_version,mean,n_train,edges,center(NaN if None) andweighted. For a noise-aware model, alsonoise(True).- For the covariance of each bin ,
cov{b}, orvectors{b},values{b}anddiag{b}for the fields of aLowRank. - If
model.blocksis not None,block_starts,block_width,block_nguardandblock_thresholdsfor its fields.
load reads it.
Parameters:
- model (Model) – The model to write.
- path (str or path-like) – The file to write, with any suffix: save adds none. An existing file is replaced.
Raises:
- TypeError – If
modelis not a Model, orpathis not a str or path-like. - OSError – If the file cannot be written.
gspice.load
Section titled “gspice.load”gspice.load(path: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> ModelRead a model written by save.
Parameters:
- path (str or path-like) – A file written by
save.
Returns:
- Model – The model.
Raises:
- ValueError – If the file is not a zip archive, or is a damaged one. If it has no
schema, or a schema other than the 0-d integer 1. If it lacks one of the arraysschema,mean,n_train,edges,centerandweighted. If it holds some but not all of the four block arrays, orvectors{b}withoutvalues{b}ordiag{b}. If it holds an array thatsavedoes not write. The message namespath. Also ifModel,LowRankorBlocksrejects a field, for example a count of covariances other than the number of bins. The message then names the field. - TypeError – If
pathis not a str or path-like, or ifModel,LowRankorBlocksrejects a field. - OSError – If the file cannot be read, and for some damaged archives.