pca2d-preclean

Two frames, one fit · SPIRou, NIRPS, HARPS, HARPS-N, ESPRESSO

← Home

RADIAL VELOCITY PRECLEANING

Two frames,
one fit

A spectrum holds two things that do not move together: the star, which shifts with the barycentric velocity, and the sky above the telescope, which does not. pca2d-preclean fits both at once and writes back spectra with the Earth's share removed, before LBL or any other code measures a velocity.

What it is, and how the pieces fit

One command reads a campaign of spectra, builds a cube, fits it, and writes corrected files that any velocity code can read. The whole chain is five stages (cube, fit, correct, figures, lbl), and each one can be run alone. Since October 2026 the same code also runs inside LBL: one PCA2D key in an LBL wrap file corrects the spectra before the velocities are measured (below).

The idea is simple enough to state in one line: over a campaign, the same wavelength sample is seen at many different barycentric velocities. Anything that keeps its place in the observer's frame while the star slides past it is not the star. Give the fit one block of components that sits still in the star's frame and another that sits still in the Earth's, and the two separate themselves.

The demonstration target throughout this page is TOI-2120, an M dwarf observed with SPIRou: 321 exposures, a wide BERV span, and deep water bands crossing the stellar lines.

The idea, step by step

A water band through a whole campaign, decomposed step by step: the high pass, the reconstruction, and each block removed in turn.
All 316 exposures of TOI-2120 around 1267 nm, each row one exposure, ordered by BERV, in the star's rest frame. Panel 1 is the high-passed data: vertical structure belongs to the star, and the slanted ridges are the atmosphere walking across it as the barycentric velocity changes. Panel 3 is what a corrected file holds, the observer block removed: the slants are gone, the vertical lines untouched, and the window scatter falls from 0.0740 to 0.0490. Panel 5 is what nothing accounted for, 0.0419, close to the photon noise. The bottom panel is five of those rows back in flux, before and after.

What a corrected file holds

The corrected spectrum compared with panel three of the report.
A corrected file holds exactly what panel 3 of the report shows, sample for sample, on its own original wavelength grid: nothing is smoothed or interpolated on the way out. What it does not hold is every sample: the yellow is what the fit gave no weight, and it is written as NaN rather than guessed at. That is the method's real cost, and it is not small (see below).

The model behind it

Let \(y(\lambda, t)\) be the high-passed log flux of the exposure taken at time \(t\), sampled on a common log-wavelength grid. The model writes it as the sum of two blocks, one anchored in each frame:

\[ y(\lambda, t)\;=\;\underbrace{\bar{S}(\lambda\,\mathcal{D}_t) \;+\;\sum_{i=1}^{n_\star} a_i(t)\,P_i(\lambda\,\mathcal{D}_t)}_{\textstyle\text{the star's frame}} \;+\;\underbrace{\sum_{j=1}^{n_\oplus} b_j(t)\,Q_j(\lambda)}_{\textstyle\text{the Earth's frame}} \;+\;\varepsilon(\lambda, t) \]

The Doppler factor is always the relativistic one, never the first-order approximation:

\[ \mathcal{D}_t \;=\; \sqrt{\frac{1 + v_t/c}{1 - v_t/c}}, \qquad v_t \;=\; v_{\mathrm{sys}} - v_{\mathrm{berv}}(t) \]

On a log-wavelength grid this is a pure translation by \(\operatorname{artanh}(v_t/c)\) divided by the grid step, which is why the grid is logarithmic in the first place. At a 30 km/s BERV the first-order form is off by \(\tfrac{1}{2}(v/c)^2 \approx\) 1.5 m/s, which is the whole scale of the measurement.

The full derivation, the weights, and how the two bases are built →

What the coefficients do in time

The fitted amplitudes of each component against time.
Every component's fitted amplitude, exposure by exposure, with the nightly means ringed. The left column is the star-anchored block, the right the Earth-anchored one, and each panel is labelled with the share of weighted variance it carries: \(b_1\) alone accounts for 17.2 %, against 3.4 % for the stellar component and 1.0 % each for \(b_2\) and \(b_3\).

And where there is little to remove

The same decomposition at 1669 nm, in the methane band.
The same decomposition at 1669 nm, in the methane band. The contamination is far weaker here, and the correction is correspondingly small: the window scatter goes from 0.0470 to 0.0455, a 3 % improvement, against 34 % in the water band above. The fit does not invent a correction where there is nothing to correct, which matters as much as removing one where there is.

And what they follow

Rank correlation of each coefficient against the ancillary quantities.
Rank correlation of each coefficient against every quantity the headers carry. On TOI-2120 nothing follows the airmass: the Earth components track the clock (+0.805) and the throughput instead, and one of them tracks the BERV at −0.737, which is the component to watch.

The high pass, and why it is taken against a template

Before any of this, the continuum and the blaze have to go. A Savitzky-Golay filter does that, but a filter run over a whole spectrum is dragged downward by every deep line, so the smooth curve it returns is not the continuum, it is the continuum minus a fraction of the line.

That bias would be harmless if it were the same every night. It is not. When a telluric line sweeps across the core of a stellar line with the BERV, the pixels it saturates are blanked, and the hole moves. The filter then decrouches differently from one exposure to the next, and leaves behind a residual that tracks the BERV without being stellar.

A synthetic deep line with a moving mask, filtered both ways.
A controlled experiment: the spectrum is held exactly fixed and only the ten-pixel mask moves across the line core, as the BERV would move it. Top: the line and the mask at three positions. Bottom: one continuum pixel's high-passed value against where the mask sits. The ordinary filter wanders by a factor of 7.6 more than the template-based one, for an input that never changed.
Telluric depth at the line core, BERV −25 km/s
3 %
Same line, BERV −5 km/s
89 %
Scatter from the moving mask, ordinary filter
0.00230
Same, filtered against a template
0.00030

Measured on HD 69830 at 688.85 nm, and on a synthetic line whose spectrum is held fixed while only the ten-pixel mask moves. Since 2026-10-16 the high pass is therefore taken on the residual to a median template, built in the star's frame and brought back to each exposure's own frame. No line is masked, and nothing enters or leaves the mask as the BERV changes.

Why the two forms are not algebraically the same, and what the change bought →

What it is worth, measured

On TOI-2120 (321 SPIRou exposures, a 37.9 km/s barycentric span, deep water bands across the stellar lines) the nightly velocity scatter drops by a factor of 3.4 on the 80 epochs the two series share:

LBL on the delivered spectra
47.98 m/s
After precleaning
14.20 m/s
Paired gain, bootstrap 16–84 %
3.14–3.65×
What it costs: samples kept
73 → 49 %
Reduced χ², 158.7 → 9.5
16.6×

That is the favourable case. The harder test is the optical, where the tellurics have already been cleaned once: three HARPS campaigns, each measured three ways on the same exposures and in a single instrument mode. rms is the plain dispersion, MAD the robust one; they differ when a correction straightens the tails while leaving the core alone.

StarPipelinerms (m/s)MAD (m/s)Error bar
HD 10700
G8V, 86 epochs
ESO DRS, CCF2.161.690.34
LBL, telluric-cleaned2.191.750.38
+ pca2d-preclean2.071.570.49
HD 69830
K0V, 150 epochs
ESO DRS, CCF3.713.570.34
LBL, telluric-cleaned3.733.490.36
+ pca2d-preclean3.503.290.50
GJ 581
M3V, 116 epochs
ESO DRS, CCF9.8311.681.37
LBL, telluric-cleaned9.6212.060.84
+ pca2d-preclean9.0610.760.91

GJ 581's CCF row excludes three exposures where the DRS fails outright, returning −591 to −655 m/s where LBL finds −3 to +12; with them the CCF rms is 97.8 m/s. pca2d-preclean is the only one of the three to beat the CCF on all three stars, and the gain is in the tails: it straightens the worst exposures more than it improves the median one.

The full results, the component diagnostics, and the cases where it makes things worse →

Velocities, before and after

LBL velocities from the delivered spectra and from the corrected ones.
The same exposures measured twice: once from the delivered spectra, once from the corrected ones. Both series come from the run's own LBL stage, so nothing here is a reprocessing of someone else's numbers.

A bias that follows the BERV, and what removing it looks like

This is the measurement the whole method exists for. Plot each exposure's velocity residual against \(V_{\mathrm{tot}} = v_{\mathrm{rad}} - \mathrm{BERV}\), the velocity at which the star sits relative to the telluric rest frame. Near zero, every stellar line is sitting on top of the atmospheric line that contaminates it; far from zero, they have walked apart. Anything that peaks at \(V_{\mathrm{tot}} = 0\) is therefore not stellar.

TOI-2120 velocity residual against the total barycentric velocity, before and after precleaning, with the fitted bias and its envelope.
TOI-2120. Top left, as delivered: a spike of 144.8 m/s at \(V_{\mathrm{tot}} = 0\), 4.3 km/s wide, detected at 15.8 σ (\(\Delta\mathrm{BIC} = +416\)). Top right, after precleaning: nothing left to detect, 1.4 σ, with a 95 % upper limit on any remaining peak. The jitter halves at the same time, from 23.5 to 11.7 m/s. Bottom: both fits with their 1σ envelopes, over the binned medians.
Bias at \(V_{\mathrm{tot}}=0\), delivered
144.8 m/s
Significance, delivered
15.8 σ
After precleaning
1.4 σ
Jitter, before → after
23.5 → 11.7

A spike at \(V_{\mathrm{tot}} = 0\) that is 4.3 km/s wide is about the width of a telluric line convolved with the instrumental profile, which is what it should be if the atmosphere is what makes it. The bias amplitude and its width are strongly anticorrelated in the posterior (\(r = -0.93\)), so the two are not independently constrained: the figure beside it shows that posterior in full.

Five spectrographs, one pipeline

The reader is picked from INSTRUME in the files themselves, never chosen by hand, and each spectrograph's settings live in one block of config.yaml.

Near-infrared
SPIRou · NIRPS
Optical
HARPS · HARPS-N · ESPRESSO

The optical spectrographs need one step the infrared ones do not: their spectra arrive with the tellurics still in them, so LBL's telluric cleaning runs first and pca2d fits the residuals of that cleaning. In the infrared, APERO has already done it.

How that cleaning is done, and the two things that had to change in it →

One trap worth stating: on HARPS the delivered wavelength grid is already barycentric, so the instrument's own BERV reads zero. Left alone, the two frames of the fit would collapse into one and the correction would make things worse: it took the rms from 11.2 to 51.6 m/s before this was caught. input.to_observer undoes the barycentric correction on the way in so that the two frames stay distinct.

Where it runs: inside LBL

The algorithm is a module of LBL, lbl.pca2d, on LBL's lbl-pca2d branch, and LBL alone runs it: no window, no other package. When the run parameters of an ordinary wrap file carry a PCA2D dict, lbl_wrap measures the object as delivered, corrects it, measures the corrected spectra as an object of their own, and writes one report. Without the key nothing of it is even imported, and LBL runs exactly as before.

from lbl.recipes import lbl_wrap rparams = dict(INSTRUMENT='NIRPS_HE', DATA_SOURCE='CADC', DATA_DIR='/data/nirps/lbl', DATA_TYPES=['SCIENCE'], OBJECT_SCIENCE=['TOI756'], OBJECT_COMPARISON=['TOI756'], OBJECT_TEFF=[3300], RUN_LBL_TEMPLATE=True, RUN_LBL_MASK=True, RUN_LBL_COMPUTE=True, RUN_LBL_COMPILE=True) rparams['PCA2D'] = dict(n_star=1, n_earth=3) # the nominal set lbl_wrap.main(rparams)

And what it leaves in LBL's tree:

DATA_DIR/science/TOI756/ read, never written DATA_DIR/science/TOI756_pca2d/ the corrected spectra, same names, same format DATA_DIR/pca2d/TOI756/1-3/ the fit, the figures, the report DATA_DIR/lblrdb/lbl_TOI756_pca2d_TOI756_pca2d.rdb the velocities DATA_DIR/reports/TOI756_pca2d_TOI756_pca2d.pdf the report

The report is the pca2d report followed by LBL's: the star as SIMBAD describes it, the delivered and corrected velocities on the exposures they share with what got better and what got worse, the river plots of the correction step by step in each window, the components, their coefficients in time and against everything they could follow, their periodograms, every setting that ran, and then LBL's series, false inclusion probabilities and indicators. A commented example wrap file, with what the precleaning does, is lbl/doc/example_wrap_pca2d.py in the branch.

With LBL's telluric cleaning on, which is the path for the optical spectrographs, the precleaning runs after it, on <object>_tc, and writes <object>_tc_pca2d. Any key of the configuration can go in the dict, by a short name (nsig_cut=0), as 'section.key' or as a dict per section; an unknown key stops the run before anything is read. name='x' keeps a variant beside the nominal as <object>_pca2d_x, and joint=True fits every object of the wrap against one observer basis. A correction already on disk with the same settings is not made again; a different one moves the previous one, and every LBL product made from it, aside rather than mixing them.

The window is only a front end to this. Same objects, same choices, same log; what it runs is that same kind of wrap file, DATA_DIR/run_<object>_pca2d.py, one dict with its PCA2D key, left there to be read and run again by hand.

Checked on SIPS J1259-4336 (NIRPS HE, 51 exposures). Through the window, the wrap file and LBL, and again from a plain wrap file with no window, the corrected velocities equal those of the standalone pipeline to 1.6×10-6 m/s, and the delivered ones are identical. The corrected flux agrees to one unit in the last place of a 32-bit float: LBL's environment does its linear algebra with Apple's Accelerate, the standalone one with a generic BLAS.
Two branches, not merged yet. main of pca2d-preclean still holds the standalone pipeline with its own copy of the engine; the version described here is on the branches below.

Install it

Two branches, one environment: LBL first, from its lbl-pca2d branch, then this package, from its lbl-wrapper branch, in the same environment.

git clone -b lbl-pca2d https://github.com/njcuk9999/lbl.git lbl-rapide conda create -n lbl-rapide python=3.12 conda activate lbl-rapide pip install -e ./lbl-rapide git clone -b lbl-wrapper https://github.com/eartigau/pca2d_preclean.git pip install -e ./pca2d_preclean

The first half alone is enough: any LBL wrap file with a PCA2D key does everything, report included, and lbl_pca2d is the command line. The second half adds the window, and no computation. LBL pins its dependencies exactly (python 3.12, numpy 2.3.3, scipy 1.17.0, astropy 7.2.0), and pip installs them with it.

BranchWhat it is
lbl-pca2dnjcuk9999/lbl LBL with the precleaning inside: use this one
test-speed-260918-110104njcuk9999/lbl LBL's speed branch, without pca2d
lbl-wrappereartigau/pca2d_preclean the window, which writes the wrap file: only for the window
maineartigau/pca2d_preclean the standalone pipeline, until the merge

Run it

python my_lbl_wrap.py

Without the window: any LBL wrap file with rparams['PCA2D'] = dict(n_star=1, n_earth=3).

pca2d-gui

The window: tick the objects, choose the counts, Run. It writes the wrap file and runs it with LBL.

lbl_pca2d --object TOI2120 \ --n-star 1 --n-earth 3

The command line, for research runs side by side under their own names: the same code, lbl.pca2d. --n-star and --n-earth are how many components each block gets; everything else comes from config.yaml, and the resolved settings are written beside the outputs so a run can always be read back.

What comes out

A run leaves a folder named for the object and the component counts. Inside: the corrected spectra on their original grids, the fitted components, a CSV of every coefficient, and a PDF report of around thirty pages: the river plots above, the coefficients in time, the correlations, and, when LBL ran, the velocities and their periodograms.

LBL itself now writes a second report per run, in <DATA_DIR>/reports: a summary table with the code version it used, the velocity series, the velocities coloured by BERV, the periodogram beside the spectral window, the false inclusion probability both plain and outlier-aware, and the telluric correction on the best, median and worst exposure of the campaign.