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

_fiber_l2_bundle(input_model, fiber)

Return (spec, err, dq, wave) for a fiber, or None if SPEC/WAVE missing.

Classes

StellarRVPrimitive([dataset, config, ...])

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: BasePrimitive

Cross-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 .mas or two-column center+weight tables; see line_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 from fit_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 in PARAMETERS.

Parameters:
  • suffix (str) – Default: "stellar_rv". Short label used by the framework for this primitive’s derived products, logging, and file naming together with output_dir.

  • algorithm (str) – Default: "ccf_line_mask". Must be a key of STELLAR_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"]). None uses get_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. None selects 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 for ccf_stellar_template. Passed to resolve_stellar_template_to_log_micron() with template_wavelength / template_flux when those are set.

  • template_wavelength (array-like or None) – Default: None. In-memory template wavelength grid (µm). Used with template_flux when you do not load from template_path.

  • template_flux (array-like or None) – Default: None. Template flux samples matching template_wavelength (same length).

  • mask_path (str or None) – Default: None. Path to a SPIROU .mas or KPF-style two-column mask file for ccf_line_mask (delta-line model). None resolves to the packaged lte049 ccfopt delta mask (see packaged_default_line_mask_path()) via resolve_mask_path() when you are not passing mask_wavelength / mask_weight.

  • mask_wavelength (array-like or None) – Default: None. In-memory mask rest wavelengths (µm) for ccf_line_mask. Must be paired with mask_weight; when both are set, mask_path is not required for loading.

  • mask_weight (array-like or None) – Default: None. Weights matching mask_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) (see combine_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 when ccf_input_velocity is set (prior gate used instead).

  • chunk_rv_prior_half_width_m_s (float or None) – Default: None. When ccf_input_velocity is set, keep only chunks with |RV − ccf_input_velocity| <= half_width before aggregation. None uses max(2000, 0.5 × v_half_window) m/s.

  • window_line_by_line (bool) – Default: True. Line-mask algorithm only (ccf_line_mask). Ignored for ccf_stellar_template (that path always chunks on window_size_um). When False, chunk boundaries follow window_size_um via ccf_order_n_chunks_for_span(). When True, each mask line defines its own wavelength chunk (Voronoi bins in observed λ at ccf_input_velocity, which must be finite — grid center). Spectral pixels per chunk use the intersection of that Voronoi interval with a symmetric window_size_um band; see build_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] at v_step_coarse. If None, a scout pass on the broad uniform grid estimates the peak, then the fiber is evaluated on a centered window (v_half_window at v_step_coarse).

  • v_half_window (float) – Default: 15000.0. Half-width (m/s) of the centered uniform velocity window (±this value around ccf_input_velocity or the auto-scout center).

  • ccf_zb (float) – Default: 0.0. Both algorithms: barycentric factor \(z_b\). For ccf_line_mask it enters \(\lambda_{\rm obs} = \lambda_{\rm rest}(1+v/c)/(1+z_b)\) (zb in run_ccf_line_mask_for_fiber() / rv_per_chunks_line_mask()). For ccf_stellar_template it applies the same multiplicative shift in \(\ln\lambda\) template evaluation as in _ccf_chunk_ccf_numba(). Set by the caller or pipeline (e.g. Stage2Pipeline populates this from BARYCORR BERV when not overridden).

  • ccf_min_good_pixels (int) – Default: 9. Both algorithms: minimum unmasked finite spectral pixels per wavelength chunk (chunking from window_size_um via ccf_order_n_chunks_for_span(), or from window_line_by_line Voronoi bins) required to form a CCF and fit an RV. For ccf_line_mask this is min_good_pixels in rv_per_chunks_line_mask(); for ccf_stellar_template it 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 to get_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 to run_ccf_line_mask_for_fiber() / chunk loops. None lets resolve_numba_threads() pick a host-appropriate count; 1 forces single-threaded, reproducible runs.

  • debug_ccf (bool) – Default: False. Extra logging and diagnostics. For ccf_stellar_template, forces the slower non-Numba CCF path instead of the parallel driver.

  • preview_write_png (bool) – Default: True. When save_preview is 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 when save_preview and preview_write_png are True (see stellar_rv_preview).

  • show_overlay_debug (bool) – Default: False. For ccf_line_mask, open mask-overlay debug HTML in a browser; for ccf_stellar_template, open template-overlay debug HTML. Meaning follows algorithm.

  • save_overlay_debug (bool) – Default: False. For ccf_line_mask, write mask-overlay HTML (_output["mask_overlay_debug"]); for ccf_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 (see STELLAR_RV_ALGORITHMS). The algorithm returns per-chunk arrays, aggregate RV, and optional per-chunk CCF supplement columns; this method writes RVCCF_FIB{fiber} (merged RV + CCF) and RVCCFAVG_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_mask this 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: mode is debug (Python masked_ccf_rv per chunk) or parallel (Numba). When want_preview is True, the parallel path reuses the flat CCF stack for the preview dict; debug + preview uses build_ccf_preview_dict() with kind="spectra_orders".

Parameters:
  • order_tasks (list of tuple) – (row_index, order_number) for each echelle row to process (already filtered by do_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). When ccf_center_m_s is set, v_step_m_s samples 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). When ccf_center_m_s is set, v_step_m_s samples 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). When ccf_center_m_s is set, v_step_m_s samples the centered window.

  • ccf_center_m_s – When ccf_center_m_s is not None, build a uniform window via build_centered_uniform_velocity_grid() (ccf_input_velocity, v_half_window, v_step_coarse on the primitive).

  • ccf_half_window_m_s – When ccf_center_m_s is not None, build a uniform window via build_centered_uniform_velocity_grid() (ccf_input_velocity, v_half_window, v_step_coarse on 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 into RVCCF_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.

fiber is accepted for API compatibility; all fibers share primitive.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_errs with combine_rvs_median_mad() (|Δ| <= outlier_sigma * max(MAD, σ_i)). Per-chunk rv_errs are scaled by rv_err_inflation only for IVW weights (default 3.5) so the mean is not dominated by underdispersed formal σ. The reported rv_std is \(\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 to MAD/√N. If the median formal σ is >10⁶× the inlier MAD (broken Hessian), IVW is discarded and MAD/√N is reported. Inflated IVW SE and empirical MAD/√N are returned as rv_std_internal and scatter_se for 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 rvs and positive rv_errs set the rejection center (sample median, or center_m_s when 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 σ_i are 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 aggregate rv_std is \(\max(\sigma_{\mathrm{IVW}},\,\mathrm{MAD}/\sqrt{N})\) of the inliers.

When chunk_rv_prior_m_s is finite, the gate keeps |RV − prior| <= half_width (default DEFAULT_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_s and 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.