hispecdrp.primitives.stellar_rv.stellar_rv_primitive
Stellar radial-velocity primitive (template and mask-line CCF).
Algorithm overview and references live in docs/source/algorithms/stellar_rv.rst.
Functions
|
Return (spec, err, dq, wave) for a fiber, or None if SPEC/WAVE missing. |
Classes
|
Cross-correlate L2 spectra against a template or a line mask to measure RV. |
- class StellarRVPrimitive(dataset=None, config=None, context=None, log_config=None, parent=None, **kwargs)[source]
Bases:
BasePrimitiveCross-correlate L2 spectra against a template or a line mask to measure RV.
Algorithms
ccf_line_mask(default) — mask-shifted CCF using a line mask (SPIROU.masor two-column center+weight tables; seeline_mask_utils). Per-chunk CCFs use Numba Lanczos / linear spectrum sampling (rv_per_chunks_line_mask()/mask_ccf_pixel_interp_order; default Lanczos-3); final RVs are Gaussian centroids fromfit_ccf_rv().ccf_stellar_template— weighted CCF in \(\ln\lambda\) against a stellar template; per-chunk RVs; median/MAD rejection; inverse-variance mean (ccf_utils).
All constructor arguments list their default from
PARAMETERS; override per run as needed. Order matches the grouped layout inPARAMETERS.- Parameters:
suffix (str) – Default:
"stellar_rv". Short label used by the framework for this primitive’s derived products, logging, and file naming together withoutput_dir.algorithm (str) – Default:
"ccf_line_mask". Must be a key ofSTELLAR_RV_ALGORITHMS. Chooses_run_algorithm_ccf_line_mask(line-mask CCF, no PHOENIX template) or_run_algorithm_ccf_stellar_template(log-λ template CCF).do_fibers (sequence of str or None) – Default:
None. Which fiber indices to process (e.g.["1","2"]).Noneusesget_do_traces()/ recipe defaults for the input model.do_orders (sequence of int or None) – Default:
None. Echelle order numbers (not row indices) to include.Noneselects all orders handled by the same L2 helper as sibling primitives (subject to config / model).template_path (str or None) – Default:
None. Path to a stellar template spectrum on disk forccf_stellar_template. Passed toresolve_stellar_template_to_log_micron()withtemplate_wavelength/template_fluxwhen those are set.template_wavelength (array-like or None) – Default:
None. In-memory template wavelength grid (µm). Used withtemplate_fluxwhen you do not load fromtemplate_path.template_flux (array-like or None) – Default:
None. Template flux samples matchingtemplate_wavelength(same length).mask_path (str or None) – Default:
None. Path to a SPIROU.masor KPF-style two-column mask file forccf_line_mask(delta-line model).Noneresolves to the packaged lte049 ccfopt delta mask (seepackaged_default_line_mask_path()) viaresolve_mask_path()when you are not passingmask_wavelength/mask_weight.mask_wavelength (array-like or None) – Default:
None. In-memory mask rest wavelengths (µm) forccf_line_mask. Must be paired withmask_weight; when both are set,mask_pathis not required for loading.mask_weight (array-like or None) – Default:
None. Weights matchingmask_wavelength(same length).mask_ccf_pixel_interp_order (int) – Default:
3. Mask algorithm only: Lanczos parameter a (1= linear;3= Lanczos-3 windowed-sinc in pixel-index space) for sampling flux and the per-pixel gate onto Doppler-shifted mask-line wavelengths in_calc_mask_ccf_chunks_numba(). Values are clamped to[1, ccf_utils.MAX_MASK_CCF_PIXEL_INTERP_ORDER]. Values greater than 1 use Lanczos-a (not historical Lagrange polynomials).window_size_um (float) – Default:
0.25. Approximate wavelength span (µm) of each chunk along an order: spectra are split into contiguous bins of roughly this width for per-chunk RVs (template algorithm) or mask CCF chunking (mask algorithm).outlier_sigma (float) – Default:
3.0. Multiplier for error-aware chunk rejection before the inverse-variance weighted mean: keep chunks with|RV − center| <= outlier_sigma * max(MAD, σ_i)(seecombine_stellar_rv_chunk_estimates()).chunk_rv_max_abs_m_s (float) – Default:
120000.0(120 km s−1). Per-chunk RVs with|RV|above this limit are excluded before aggregation (coarse-grid CCF alias peaks). Set very large to disable. Ignored whenccf_input_velocityis set (prior gate used instead).chunk_rv_prior_half_width_m_s (float or None) – Default:
None. Whenccf_input_velocityis set, keep only chunks with|RV − ccf_input_velocity| <= half_widthbefore aggregation.Noneusesmax(2000, 0.5 × v_half_window)m/s.window_line_by_line (bool) – Default:
True. Line-mask algorithm only (ccf_line_mask). Ignored forccf_stellar_template(that path always chunks onwindow_size_um). WhenFalse, chunk boundaries followwindow_size_umviaccf_order_n_chunks_for_span(). WhenTrue, each mask line defines its own wavelength chunk (Voronoi bins in observed λ atccf_input_velocity, which must be finite — grid center). Spectral pixels per chunk use the intersection of that Voronoi interval with a symmetricwindow_size_umband; seebuild_line_mask_chunk_wavelength_intervals_line_by_line().v_min_coarse (float or None) – Default:
None. Broad uniform CCF lower bound (m/s) when no center is set (scout / full-range search).None→V_MIN_DEFAULT_M_S.v_max_coarse (float or None) – Default:
None. Broad uniform CCF upper bound (m/s).None→V_MAX_DEFAULT_M_S.v_step_coarse (float or None) – Default:
25.0. Uniform velocity sampling (m/s) for both the broad and centered grids.None→V_STEP_DEFAULT_M_S.ccf_input_velocity (float or None) – Default:
None. If set (m/s), the CCF uses a uniform window centered here:[ccf_input_velocity − v_half_window, ccf_input_velocity + v_half_window]atv_step_coarse. IfNone, a scout pass on the broad uniform grid estimates the peak, then the fiber is evaluated on a centered window (v_half_windowatv_step_coarse).v_half_window (float) – Default:
15000.0. Half-width (m/s) of the centered uniform velocity window (±this value aroundccf_input_velocityor the auto-scout center).ccf_zb (float) – Default:
0.0. Both algorithms: barycentric factor \(z_b\). Forccf_line_maskit enters \(\lambda_{\rm obs} = \lambda_{\rm rest}(1+v/c)/(1+z_b)\) (zbinrun_ccf_line_mask_for_fiber()/rv_per_chunks_line_mask()). Forccf_stellar_templateit applies the same multiplicative shift in \(\ln\lambda\) template evaluation as in_ccf_chunk_ccf_numba(). Set by the caller or pipeline (e.g.Stage2Pipelinepopulates this fromBARYCORRBERVwhen not overridden).ccf_min_good_pixels (int) – Default:
9. Both algorithms: minimum unmasked finite spectral pixels per wavelength chunk (chunking fromwindow_size_umviaccf_order_n_chunks_for_span(), or fromwindow_line_by_lineVoronoi bins) required to form a CCF and fit an RV. Forccf_line_maskthis ismin_good_pixelsinrv_per_chunks_line_mask(); forccf_stellar_templateit gates the Numba per-chunk CCF and the Python per-chunk fit. Overlay debug HTML uses the same threshold for chunk inclusion.output_model (str) – Default:
"L2Model". Datamodel type name passed toget_output_model()when cloning the input to attach RVCCF tables.max_cores (int or None) – Default:
None. Upper bound on parallel Numba threads: template path uses it for echelle-order parallelism; mask path passes it torun_ccf_line_mask_for_fiber()/ chunk loops.Noneletsresolve_numba_threads()pick a host-appropriate count;1forces single-threaded, reproducible runs.debug_ccf (bool) – Default:
False. Extra logging and diagnostics. Forccf_stellar_template, forces the slower non-Numba CCF path instead of the parallel driver.preview_write_png (bool) – Default:
True. Whensave_previewis True, also write a stacked Kaleido PNG alongside the HTML preview. Set False for large line-mask runs (many CCF slots) where PNG export can take minutes or hang in headless Chrome.preview_png_scale (float) – Default:
2.0. Pixel scale multiplier for Kaleido PNG exports whensave_previewandpreview_write_pngare True (seestellar_rv_preview).show_overlay_debug (bool) – Default:
False. Forccf_line_mask, open mask-overlay debug HTML in a browser; forccf_stellar_template, open template-overlay debug HTML. Meaning followsalgorithm.save_overlay_debug (bool) – Default:
False. Forccf_line_mask, write mask-overlay HTML (_output["mask_overlay_debug"]); forccf_stellar_template, write template-overlay HTML (_output["template_overlay_debug"]).
- _combine_chunk_rvs(all_rvs, all_rv_errs, *, fiber)[source]
Robust per-fiber aggregate from chunk RV arrays (sanity gate + MAD + weighted mean).
Returns
(inlier_mask, rv_mean_m_s, rv_std_m_s).
- _create_preview()[source]
- static _get_spectrograph(input_model)[source]
Return spectrograph name from model metadata.
- Parameters:
input_model (DataModel) – Input data model with meta.spectrograph.
- Returns:
str – “BSPEC” or “RSPEC” if present in metadata; otherwise “BSPEC”.
- _process_fiber(input_model, output_model, fiber, spectrograph, do_orders, order_vec, template_ln, template_flux)[source]
Run the configured stellar RV algorithm for one fiber and write RVCCF/RVCCFAVG.
Dispatches to the algorithm named in
self.algorithm(seeSTELLAR_RV_ALGORITHMS). The algorithm returns per-chunk arrays, aggregate RV, and optional per-chunk CCF supplement columns; this method writesRVCCF_FIB{fiber}(merged RV + CCF) andRVCCFAVG_FIB{fiber}to the output model.- Parameters:
input_model (DataModel) – Open L2 (or compatible) model with per-fiber
SPEC_FIB*/WAVE_FIB*(and optional ERR/DQ). Used to read science data for the chosen fiber.output_model (DataModel) – Cloned L2 output; receives Astropy tables on attributes
rvccf_fib*/rvccfavg_fib*(framework naming).fiber (str) – Fiber id string, e.g.
"1", matching attribute suffixes_FIB1.spectrograph (str) –
"BSPEC"or"RSPEC"from metadata; stored in RV tables for downstream.do_orders (list of int) – Echelle order numbers to include in the CCF (subset of
order_vec).order_vec (list of int) – Map from echelle row index to physical order number (one entry per spectral row).
template_ln (np.ndarray) – Natural log of template wavelength in microns; used by template algorithm. For
ccf_line_maskthis is an empty placeholder array.template_flux (np.ndarray) – Template flux aligned with
template_ln; empty for mask-only algorithm.
- _process_fiber_orders(order_tasks, wave, spec, err, dq, do_not_use, template_ln, template_flux, fiber, *, mode, max_cores=None, want_preview=False, v_min_m_s=-500000.0, v_max_m_s=500000.0, v_step_m_s=50.0, ccf_center_m_s=None, ccf_half_window_m_s=20000.0)[source]
Single driver for per-order chunk RVs:
modeisdebug(Pythonmasked_ccf_rvper chunk) orparallel(Numba). Whenwant_previewis True, the parallel path reuses the flat CCF stack for the preview dict; debug + preview usesbuild_ccf_preview_dict()withkind="spectra_orders".- Parameters:
order_tasks (list of tuple) –
(row_index, order_number)for each echelle row to process (already filtered bydo_orders).wave (np.ndarray) – 2D echelle data for the fiber: wavelength, flux, error, and DQ (same shape).
spec (np.ndarray) – 2D echelle data for the fiber: wavelength, flux, error, and DQ (same shape).
err (np.ndarray) – 2D echelle data for the fiber: wavelength, flux, error, and DQ (same shape).
dq (np.ndarray) – 2D echelle data for the fiber: wavelength, flux, error, and DQ (same shape).
do_not_use (int) – DQ bitmask for pixels to exclude from CCF (typically
DQ_FLAGS["DO_NOT_USE"]).template_ln (np.ndarray) – Template in log(µm) and flux for CCF (same length).
template_flux (np.ndarray) – Template in log(µm) and flux for CCF (same length).
fiber (str) – Fiber id for logging.
mode (str) –
"debug"(verbose diagnostics) or"parallel"(Numba).max_cores (int or None, optional) – Effective thread count for parallel mode (already resolved/capped).
want_preview (bool, optional) – Whether to build the mean + per-order CCF preview structure for Plotly.
v_min_m_s (float, optional) – Uniform CCF velocity axis (m/s): broad search from the primitive’s
v_min_coarse/v_max_coarse/v_step_coarse(after defaults). Whenccf_center_m_sis set,v_step_m_ssamples the centered window.v_max_m_s (float, optional) – Uniform CCF velocity axis (m/s): broad search from the primitive’s
v_min_coarse/v_max_coarse/v_step_coarse(after defaults). Whenccf_center_m_sis set,v_step_m_ssamples the centered window.v_step_m_s (float, optional) – Uniform CCF velocity axis (m/s): broad search from the primitive’s
v_min_coarse/v_max_coarse/v_step_coarse(after defaults). Whenccf_center_m_sis set,v_step_m_ssamples the centered window.ccf_center_m_s – When
ccf_center_m_sis notNone, build a uniform window viabuild_centered_uniform_velocity_grid()(ccf_input_velocity,v_half_window,v_step_coarseon the primitive).ccf_half_window_m_s – When
ccf_center_m_sis notNone, build a uniform window viabuild_centered_uniform_velocity_grid()(ccf_input_velocity,v_half_window,v_step_coarseon the primitive).
- Returns:
tuple –
(all_rvs, all_rv_errs, all_wavelengths, all_orders, preview_detail, rvccf_chunk_supplement)— lists of per-chunk quantities (same length), optional preview dict, and optional CCF supplement table (merged intoRVCCF_FIB*by_write_rv_tables).
- _resolve_chunk_rv_prior_half_width_m_s()[source]
Half-width (m/s) for prior-gated chunk aggregation when a CCF center is set.
- _run_algorithm_ccf_line_mask(input_model, output_model, fiber, spectrograph, do_orders, order_vec, template_ln, template_flux)[source]
Line-mask CCF (SPIROU/KPF-inspired) + Gaussian RV fit.
Minimal delegation to
run_ccf_line_mask_for_fiber().
- _run_algorithm_ccf_stellar_template(input_model, output_model, fiber, spectrograph, do_orders, order_vec, template_ln, template_flux)[source]
Stellar-template cross-correlation + median/MAD + inverse-variance weighted mean.
Cross-correlates the stellar template spectrum to the input spectrum in log(wavelength), producing per-chunk RVs (debug Python or Numba-parallel). Chunk RVs are combined with median/MAD outlier rejection and a weighted mean; CCF curves may be stored for the preview. Returns the standard 6-tuple for _write_rv_tables.
- Returns:
all_wavelengths (np.ndarray) – Chunk center wavelengths (µm).
all_rvs (np.ndarray) – Per-chunk RV (m/s).
all_rv_errs (np.ndarray) – Per-chunk RV uncertainty (m/s).
inlier (np.ndarray) – Boolean mask of chunks used for the aggregate.
rv_mean (float) – Aggregated RV (m/s).
rv_std (float) – Uncertainty of the aggregated RV (m/s).
- _write_rv_tables(output_model, fiber, spectrograph, wavelengths, rvs, rv_errs, rv_agg, rv_agg_err, inlier=None, orders=None, *, rvccf_chunk_supplement=None)[source]
Write RVCCF_FIB{fiber} (per-chunk RV plus optional CCF columns) and RVCCFAVG_FIB{fiber}.
Creates table extensions on the output L2 model with per-chunk RVs and the aggregated RV (mean and std). All velocities are in m/s.
- Parameters:
output_model (DataModel) – L2 output model to update.
fiber (str) – Fiber number (e.g. “1”).
spectrograph (str) – “BSPEC” or “RSPEC”.
wavelengths (np.ndarray) – Chunk center wavelengths (µm).
rvs (np.ndarray) – Per-chunk radial velocity (m/s).
rv_errs (np.ndarray) – Per-chunk RV uncertainty (m/s).
rv_agg (float) – Aggregated RV (e.g. weighted mean) in m/s.
rv_agg_err (float) – Uncertainty of the aggregated RV in m/s.
inlier (np.ndarray, optional) – Boolean mask of chunks used for the aggregate; used for table only.
orders (np.ndarray, optional) – Echelle order number per chunk (same length as
rvs). -1 if unknown.
- static resolve_ccf_zb_for_fiber(primitive, input_model, fiber)[source]
Return the uniform CCF \(z_b\) for previews and overlays.
fiberis accepted for API compatibility; all fibers shareprimitive.ccf_zb.
- combine_rv_estimates_median_mad_weighted(rvs, rv_errs, outlier_sigma=4.0, *, center_m_s=None, rv_err_inflation=3.5)[source]
Error-aware robust rejection, inverse-variance mean, and IVW uncertainty.
Outlier rejection uses the uninflated per-chunk
rv_errswithcombine_rvs_median_mad()(|Δ| <= outlier_sigma * max(MAD, σ_i)). Per-chunkrv_errsare scaled byrv_err_inflationonly for IVW weights (default 3.5) so the mean is not dominated by underdispersed formal σ. The reportedrv_stdis \(\max(\sigma_{\mathrm{IVW}},\,\mathrm{MAD}/\sqrt{N})\) of the inliers: photon-weighted IVW when it is honest, and the empirical line scatter when formal σ are optimistic or systematics dominate. As per-chunk σ → 0 (infinite S/N), this converges toMAD/√N. If the median formal σ is >10⁶× the inlier MAD (broken Hessian), IVW is discarded andMAD/√Nis reported. Inflated IVW SE and empiricalMAD/√Nare returned asrv_std_internalandscatter_sefor diagnostics.
- combine_rvs_median_mad(rvs, rv_errs, outlier_sigma=4.0, *, center_m_s=None)[source]
Error-aware robust outlier mask on per-chunk RVs.
Chunks with finite
rvsand positiverv_errsset the rejection center (sample median, orcenter_m_swhen finite) and the ensemble MAD. A chunk is kept when|RV − center| <= outlier_sigma * max(MAD, σ_i)so points that agree within the MAD are never rejected, while points that are both outside the MAD envelope and inconsistent with their own formal
σ_iare rejected. Invalid chunks are marked not inlier.
- combine_stellar_rv_chunk_estimates(rvs, rv_errs, outlier_sigma=4.0, *, chunk_rv_max_abs_m_s=120000.0, chunk_rv_prior_m_s=None, chunk_rv_prior_half_width_m_s=None, median_fallback_sigma=3.0)[source]
Aggregate per-chunk RVs for
StellarRVPrimitive.Applies a sanity gate, error-aware MAD rejection (
|Δ| <= outlier_sigma * max(MAD, σ_i)), and inverse-variance weighting (combine_rv_estimates_median_mad_weighted()). The reported aggregaterv_stdis \(\max(\sigma_{\mathrm{IVW}},\,\mathrm{MAD}/\sqrt{N})\) of the inliers.When
chunk_rv_prior_m_sis finite, the gate keeps|RV − prior| <= half_width(defaultDEFAULT_CHUNK_RV_PRIOR_HALF_WIDTH_M_S) and MAD rejection is anchored to the prior. Otherwise the gate uses|RV| <= chunk_rv_max_abs_m_sand the sample median anchors MAD rejection.When the weighted mean disagrees with the inlier median by more than
median_fallback_sigma × MAD, the median is used for the aggregate RV (guards against alias peaks with underestimated formal errors on coarse CCF grids); the reported uncertainty remains the IVW SE.
- weighted_mean_rv(rvs, rv_errs, inlier)[source]
Inverse-variance weighted mean RV and error on the mean.