hispecdrp.primitives.utils.ccf.ccf_utils

Cross-correlation (CCF) and radial-velocity utilities.

The canonical overview of the CCF algorithms and conventions lives in the documentation: docs/source/algorithms/ccf.rst.

Functions

_bootstrap_gaussian_rv_std_m_s(gx_km, gy0, ...)

Scatter of the fitted Gaussian mean (m/s) when each CCF sample is perturbed by its reported σ (i.i.d.); ignores bin-to-bin correlation.

_calc_mask_ccf_chunks_numba(left_edges_2d, ...)

Chunk-batched mask CCF(v) with parallelism over chunks.

_ccf_chunk_ccf_numba(ln_lam, spec, spec_err, ...)

Weighted cross-correlation CCF(v) for one chunk.

_ccf_chunk_ccf_numba_vgrid(ln_lam, spec, ...)

Same as _ccf_chunk_ccf_numba() but samples at arbitrary v_grid (m/s).

_ccf_fit_debug_jsonable(v)

Reduce fit_ccf_rv debug context values to JSON-friendly types.

_ccf_gaussian_amp_floor_free_baseline_scaled(...)

Positive lower bound on Gaussian amplitude (LevMar scaled gy units) when the compound model is Gaussian1D + Const1D with free Const1D: otherwise the fitter can drive Gaussian amplitude to exactly zero and absorb the line in the constant (χ² degeneracy), yielding flat preview Gaussians.

_ccf_preview_finalize_n_workers(n_slots)

Worker count for parallel Gaussian + refine in finalize_ccf_preview_dict().

_ccf_rv_from_ccf(v_grid, ccf, v_step, n_good)

Gaussian fit to CCF for final RV; else grid peak / HWHM.

_ccf_rv_numba_err_floor(vs)

Match _ccf_rv_err_numeric_floor() (m/s); sub-grid σ_RV allowed.

_ccf_weighted_covariance_scan(ln_lam, spec, ...)

Python CCF(v); same statistic as _ccf_chunk_ccf_numba (fallback when Numba off).

_fit_ccf_preview_slot_worker(sl, vs, *[, ...])

One slot: fit_ccf_rv() with CCF_PREVIEW_SLOT_FIT_CONFIG, then bisector RV for pipeline/preview metadata (_refine_ccf_rv_bisector_after_gaussian_fit()).

_fit_ccf_preview_slots_line_mask_numba(...)

Batch Gaussian fits for mask-line preview slots (same Numba path as RVCCF).

_fit_ccf_rv_line_mask_stored_negated_via_numba(...)

Mask-line stored CCF rows: use the same Numba centroid as the RVCCF pipeline.

_fractional_pixel_index(xq, x, n)

Continuous pixel index for xq on sorted abscissae x[:n].

_gaussian_ccf_model(v, amplitude, v0, sigma, ...)

_gaussian_preview_params_from_peak_up_ccf(...)

Build params / diagnostics for mask-line preview overlays when RV comes from fit_ccf_rv_rows_numba().

_lagrange_stencil_index_and_weights(xq, x, ...)

Interpolation weights on the same stencil as _poly_interp_sorted_1d().

_lanczos_kernel(x, a)

Lanczos-a kernel: sinc(x) sinc(x/a) for |x|<a, else 0.

_levmar_ccf_y_scale(gy)

Multiplicative scale so gy * scale has max absolute value ≈ 1.

_levmar_lsq_fit(ft, init, *args, **kwargs)

Run LevMarLSQFitter.

_line_mask_ccf_fit_free_baseline_requested(*, ...)

True when fit_ccf_rv() should treat the CCF constant term as an LM parameter.

_line_mask_peak_index_integral_and_prominence(ys, ...)

Choose among strict local maxima of the smoothed CCF using integrated excess (sum of positive deviation from the global median in a wide window) times sqrt(prominence + 1).

_linear_interp_sorted_1d(xq, x, y, n)

Linear interpolation on sorted x[:n] (ascending); clamps outside range.

_ln_lam(wave)

Natural log of wavelength (micron → log micron).

_masked_ccf_rv_core(wave, spec, spec_err, ...)

Single CCF build + fit; optionally build diagnostics dict (no duplicate CCF work).

_nan_stderr_of_mean_axis0(stacked_sigma, ...)

Standard error of nanmean(stacked_ccf, axis=0) when each row is an independent estimate with 1σ stacked_sigma[i, :] at each velocity.

_nanmean_axis0_ignore_empty_columns(arr)

Column-wise mean of finite values (axis 0).

_nanmedian_numba_1d(x)

_normalized_sinc(x)

sin(πx)/(πx) with sinc(0)=1.

_poly_interp_sorted_1d(xq, x, y, n, order)

Interpolate y at xq on sorted x[:n] (ascending).

_poly_interp_sorted_1d_value_and_flux_variance(xq, ...)

Interpolate y at xq plus propagated variance from pixel σ.

_process_all_orders_ccf_numba(wave_2d, ...)

Parallel per-order CCF fill: writes all_ccf[chunk, :], all_n_good[chunk], all_wl[chunk].

_process_all_orders_ccf_numba_vgrid(wave_2d, ...)

Same as _process_all_orders_ccf_numba() but with an explicit v_grid (m/s).

_process_all_orders_rvs_numba_single_grid(...)

Single uniform velocity grid: Numba CCF fill + per-chunk Gaussian RV.

_process_all_orders_rvs_numba_single_vgrid(...)

Explicit v_grid (uniform centered or custom): Numba CCF fill + per-chunk Gaussian RV.

_rv_err_slope_propagation_m_s(v_m_s, y_ccf, ...)

Diagonal error propagation σ_RV ≈ σ_y / |d(CCF)/dv| (m/s), v in m/s.

_rv_from_ccf_line_mask_numba_single(...)

Fast Numba seed RV from mask-line CCF (discrete peak + heuristic σ).

_rv_from_ccf_line_mask_peak_index_numba(...)

Peak index used by _rv_from_ccf_line_mask_numba_single() for LSTSQ / fallback paths.

_rv_from_ccf_line_mask_rows_numba(...)

_smooth_uniform5_numba(y, n)

5-point moving average; non-finite samples excluded from each local mean.

_subsample_velocity_ccf_for_gaussian_fit(vm, ...)

Uniform stride subsample along velocity when the grid is very long (line-mask broad scans).

assemble_rvccf_fib_table(rvs, rv_errs, ...)

Full per-chunk RVCCF_FIB* table: RV metrics plus optional CCF supplement columns.

build_ccf_preview_dict(kind, order_tasks, ...)

Build the stellar-RV CCF preview JSON-like structure for Plotly (per-order slots, mean CCF, Gaussian).

build_centered_uniform_velocity_grid(...)

Uniform CCF velocity samples on [center − half_width, center + half_width].

build_line_mask_chunk_wavelength_intervals_line_by_line(...)

Build observed-wavelength chunks with one mask line per chunk (Voronoi cells in λ).

build_rvccf_chunk_supplement(*, chunk_id, ...)

Supplement table with raw CCF(v) per chunk (columns merged into RVCCF_FIB*).

ccf_order_n_chunks_for_span(span_um, window_um)

Number of equal-wavelength segments for one echelle order given a target chunk width.

clip_gaussian_plot_velocity_range_m_s(...[, ...])

Bound [lo_m_s, hi_m_s] for evaluating a Gaussian CCF model.

continuum_normalize(flux[, wavelength, ...])

Divide flux by an estimated continuum (median filter and/or polynomial).

count_mask_lines_in_observed_wavelength_interval(...)

Count mask line segments with positive weight whose observed λ lies in [wl_lo_um, wl_hi_um].

doppler_paint_lagrange(wave_obs_um, ...[, ...])

Resample a rest-frame spectrum onto an observed wavelength grid via Lanczos.

doppler_paint_lanczos(wave_obs_um, ...[, ...])

Resample a rest-frame spectrum onto an observed wavelength grid via Lanczos.

dv_per_pixel_m_s(wl_um)

Rough echelle resolving element per detector pixel in velocity units (m/s).

estimate_ccf_uncertainty_highpass_residual(ccf, *)

Estimate a single CCF uncertainty σ (same units as ccf): Savitzky–Golay low-pass smooth, subtract to form a high-frequency residual, then take the RMS of successive differences in that residual (pixel-to-pixel scale).

finalize_ccf_preview_dict(order_slots, ...)

Build the _ccf_preview_by_fiber structure from per-order CCF 2-D arrays.

fit_ccf_rv(v_grid_m_s, ccf, v_step_m_s[, ...])

Fit a Gaussian plus constant baseline to a precomputed CCF and return RV ± error in m s⁻¹.

flat_chunk_echelle_orders(order_tasks, ...)

Echelle order number for each flattened chunk index (same packing as process_orders_rvs_numba_parallel()).

flat_chunk_wl_lo_hi(wave_2d, order_indices, ...)

Wavelength bounds per flattened chunk index (matches Numba chunking in _process_all_orders_ccf_numba()).

line_mask_chunk_restrict_velocity_range_m_s(...)

Velocity bounds for restrict_mask_to_chunk() on one line-window chunk.

line_mask_line_window_velocity_half_width_m_s(...)

Effective half-width (m/s) for a uniform centered CCF grid in line-window mode.

line_mask_n_chunks_for_order_line_by_line(...)

Return n_chunk for one order under build_line_mask_chunk_wavelength_intervals_line_by_line().

mask_line_window_spectrum_band_um(...[, rel_pad])

Observed-frame µm interval for spectrum + mask-CCF pixels in line-window line-mask.

masked_ccf_rv(wave, spec, spec_err, mask, ...)

Radial velocity from a single masked spectrum via log-λ CCF and Gaussian peak fit.

median_pixel_dv_m_s(wave_um)

Median detector-pixel velocity width (m/s) from a 1-D wavelength row.

prepare_template_for_doppler_paint(...[, ...])

Densify a rest-frame spectrum for doppler_paint_lanczos().

process_all_orders_rvs_numba(wave_2d, ...[, ...])

High-throughput per-chunk RVs: Numba CCF grid, then SciPy Gaussian per chunk.

process_one_order_rvs(wave, spec, spec_err, ...)

One echelle order: clip template, optional continuum norm, chunk RVs.

process_orders_rvs_numba_parallel(wave_2d, ...)

Stellar-RV fast path: many orders × wavelength chunks in one call.

run_ccf_line_mask_for_fiber(*, input_model, ...)

Run line-mask CCF RV for one fiber (StellarRVPrimitive(algorithm="ccf_line_mask")).

rv_per_chunks(wave, spec, spec_err, mask, ...)

Split one echelle spectrum into wavelength chunks; one RV per chunk.

rv_per_chunks_line_mask(wave_um, spec, ...)

Compute per-chunk RVs and optional CCF stacks for one echelle order.

template_min_resolution_for_doppler_paint(...)

Minimum template resolving power R = lambda / dlambda for Doppler paint.

validate_line_mask_line_window_chunking_config(*, ...)

Validate window_line_by_line against algorithm and ccf_input_velocity.

Classes

CCFFitConfig([pass1_half_width_km_s, ...])

Tunables for fit_ccf_rv() two-pass Gaussian + constant fits to \(\mathrm{CCF}(v)\).

class CCFBisectorConfig(rv_percentile_lo=10.0, rv_percentile_hi=90.0, rv_n_percentile_cuts=31, rv_percentile_step=5.0, bis_top_lo=60.0, bis_top_hi=90.0, bis_bottom_lo=10.0, bis_bottom_hi=40.0, core_weight_sigma_percentile=25.0, rv_err_core_percentile=50.0, rv_err_bootstrap_samples=0, rv_err_bootstrap_seed=None, min_cuts=5, min_peak_contrast_sigma=5.0, rv_err_min_vstep_fraction=0.15)[source]

Bases: object

Tunables for fit_ccf_rv_bisector() (traditional CCF bisector RV).

Follows the NEID-DRP bisector construction (percentile cuts through the CCF in velocity space; see NEID algorithms § CCF Bisector Calculation). Radial velocity and its uncertainty are a weighted mean of bisector midpoints \((v_\mathrm{left}+v_\mathrm{right})/2\) at multiple depth percentiles: with per-cut midpoint uncertainties \(e_i\) and weights \(w_i\),

\[\hat{v} = \frac{\sum_i w_i v_i}{\sum_i w_i},\qquad \sigma_{\hat{v}} = \frac{\sum_i w_i e_i}{\sum_i w_i}.\]

(The uncertainty is the weighted average of the cut uncertainties, not an independent-measurement reduction of those errors.) Cut weights are the core performance weight only; per-cut \(e_i\) comes from CCF-error propagation when informative, otherwise from the smooth-profile discretization estimate.

bis_bottom_hi = 40.0

Bottom section high for BIS.

bis_bottom_lo = 10.0

Bottom section low for BIS, NEID default 10–40%.

bis_top_hi = 90.0

Top section high for BIS.

bis_top_lo = 60.0

Top section low for bisector inverse slope (BIS), NEID default 60–90%.

core_weight_sigma_percentile = 25.0

Gaussian performance weight on percentile cuts (core emphasis).

min_cuts = 5

Minimum successful bisector cuts required for a valid RV.

min_peak_contrast_sigma = 5.0

Minimum peak amplitude (above baseline) in units of robust wing noise.

rv_err_bootstrap_samples = 0
rv_err_bootstrap_seed = None
rv_err_core_percentile = 50.0

Representative “core” cut percentile for diagnostics / preview labeling.

rv_err_min_vstep_fraction = 0.15

Floor rv_err to this fraction of the minimum positive velocity spacing.

rv_n_percentile_cuts = 31

Fixed number of evenly spaced percentile cuts (overrides rv_percentile_step when >= 2).

rv_percentile_hi = 90.0

Percentile range high (0–100) for bisector midpoints in the RV estimate.

rv_percentile_lo = 10.0

Percentile range low (0–100) for bisector midpoints in the RV estimate.

rv_percentile_step = 5.0

Step between percentile cuts when rv_n_percentile_cuts < 2.

class CCFFitConfig(pass1_half_width_km_s=800.0, pass2_half_width_km_s=120.0, initial_stddev_km_s=5.0, min_points=5, emission_strength_ratio=1.02, cal_mask_methods=frozenset({'etalon', 'lfc', 'thar'}), levmar_maxiter=1500, sigma_clip_unclipped_prefit_passes=2, sigma_clip_enable=True, sigma_clip_max_iter=10, sigma_clip_n_sigma=4.0, sigma_clip_n_sigma_relaxed=6.0, sigma_clip_relax_first_clip_iters=3, sigma_clip_min_keep_frac=0.3, rv_err_cov_combine='max', rv_err_bootstrap_samples=0, rv_err_bootstrap_seed=None)[source]

Bases: object

Tunables for fit_ccf_rv() two-pass Gaussian + constant fits to \(\mathrm{CCF}(v)\).

Velocity windows in the first and second pass are expressed in km s:sup:`−1` (*_km_s fields); RV results from fit_ccf_rv() are still returned in m s:sup:`−1`.

cal_mask_methods = frozenset({'etalon', 'lfc', 'thar'})
emission_strength_ratio = 1.02
initial_stddev_km_s = 5.0
levmar_maxiter = 1500
min_points = 5
pass1_half_width_km_s = 800.0
pass2_half_width_km_s = 120.0
rv_err_bootstrap_samples = 0
rv_err_bootstrap_seed = None
rv_err_cov_combine = 'max'
sigma_clip_enable = True
sigma_clip_max_iter = 10
sigma_clip_min_keep_frac = 0.3
sigma_clip_n_sigma = 4.0
sigma_clip_n_sigma_relaxed = 6.0
sigma_clip_relax_first_clip_iters = 3
sigma_clip_unclipped_prefit_passes = 2
class MaskLines(mask_style, line_center, line_left_edge, line_right_edge, line_width, weight, metadata=<factory>)[source]

Bases: object

Tabulated CCF line mask (delta zero-width lines or tophat finite segments).

delta — two on-disk columns (vacuum line-center nm, weight): line_left_edge, line_right_edge, and line_center coincide; line_width is 0. tophat — ≥3 columns (vacuum segment start nm, end nm, weight): line_center is the segment midpoint; line_width = line_right_edge - line_left_edge.

Wavelengths are vacuum; internal arrays use microns (nm÷1000 on read/write for .mas). Use load() and save() for disk I/O with # HISPEC_DRP_MASK_META JSON (read_mask_generation_meta()).

CCF hot paths use line_lambda_um (centers, µm) and weight.

classmethod _from_mas_path(mask_file)[source]
classmethod _from_two_column_path(mask_file)[source]
classmethod empty_like_style(mask_style, *, metadata=None)[source]

Zero-line mask preserving mask_style (e.g. after wavelength restriction).

classmethod from_delta_centers_um(line_lambda_um, weight, *, metadata=None)[source]

Build a delta mask: zero width at each center (µm).

classmethod from_kpf_segment_edges_um(lo_um, hi_um, weight, *, metadata=None)[source]

Deprecated alias for from_tophat_segment_edges_um().

classmethod from_tophat_segment_edges_um(lo_um, hi_um, weight, *, metadata=None)[source]

Build a tophat (finite-width) mask from rest segment bounds in µm.

property line_lambda_um

Rest line centers in µm (line_center in µm).

classmethod load(path)[source]

Load a mask from disk: .mas (vacuum nm on disk → µm) or two-column text (.txt / .dat / .csv; wavelength column Å/nm/µm via median heuristic). Other extensions try .mas parsing first, then two-column.

metadata_dict()[source]

Shallow copy of metadata for inspection or JSON serialization.

save(output_path=None, *, masks_directory=None, basename=None)[source]

Write this mask to a .mas file.

On-disk layout: delta → vacuum line-center (nm), weight; tophat → vacuum segment start (nm), end (nm), weight. One # HISPEC_DRP_MASK_META JSON line (read_mask_generation_meta()).

When output_path is None, writes {masks_directory}/{basename}.{mask_style}.mas with basename from metadata["template_path"] when set, else "mask". masks_directory defaults to package_data_masks_dir().

_bootstrap_gaussian_rv_std_m_s(gx_km, gy0, ge, *, seed_mean_km, seed_std_km, profile, n_samples, rng, maxiter=400, free_baseline=False, ccf_line_mask_stored_negated=None)[source]

Scatter of the fitted Gaussian mean (m/s) when each CCF sample is perturbed by its reported σ (i.i.d.); ignores bin-to-bin correlation. Uses weighted LM like the main fit.

_calc_mask_ccf_chunks_numba(left_edges_2d, right_edges_2d, s_use_2d, e_use_2d, sn_2d, n_pix_arr, v_grid_m_s, zb, line_lambda_rest_2d, line_left_rest_2d, line_right_rest_2d, line_w_2d, n_line_arr, compute_line_std, pixel_interp_order, tophat_segment_samples)[source]

Chunk-batched mask CCF(v) with parallelism over chunks.

Delta-line model: each mask line is a rest wavelength \(\lambda_{\rm rest}\). At trial velocity \(v\), the observed wavelength is \(\lambda_{\rm obs} = \lambda_{\rm rest}\,(1+v/c)/(1+z_b)\).

Tophat segment model (finite width): each mask entry has rest edges \([\lambda_{\rm lo},\lambda_{\rm hi}]\). At trial velocity the observed segment is shifted by the same factor as above. The segment’s contribution is approximated by averaging \(F\cdot\mathrm{SN}\) over tophat_segment_samples uniformly spaced points inside the shifted segment.

For each velocity, let \(x_j = F_j\,\mathrm{SN}_j\) at each contributing line (interpolated on pixel centers). Accumulate \(\sum_j w_j x_j\) and \(\sum_j w_j x_j^2\) over lines whose shifted \(\lambda_{\rm obs}\) lies in the chunk with finite \(F\) and \(\mathrm{SN}\). The CCF is the weighted mean \(\mathrm{CCF}(v)=\sum_j w_j x_j\,/\,\sum_j w_j\).

Flux errors: e_use_2d holds per-pixel flux \(\sigma\) on the chunk grid. The mask statistic is linear in pixel values \(G_m\) (Lanczos / linear interpolation of flux per line, \(\mathrm{SN}_j\) treated as exact on the stencil): \(C = \sum_m c_m G_m\) with \(c_m = \sum_j (w_j/W)\,\mathrm{SN}_j\,L^{(j)}_{m}\) where \(W=\sum_j w_j\) and \(L^{(j)}_{m}\) is the interpolator weight of pixel \(m\) for line \(j\) (zero outside that line’s stencil). Under independent pixel noise, \(\sigma_{\mathrm{meas}}^2 = \sum_m c_m^2 \sigma_m^2\). This co-adds lines that share stencil pixels and replaces the earlier \(\sum_j w_j^2\mathrm{Var}(F_j)/W^2\) independent-line sum, which inflated \(\sigma_{\mathrm{meas}}\) when many lines reused the same pixels.

The systematic / excess line-to-line component is the usual weighted dispersion of \(x_j\) about \(C\):

\[\sigma_{\mathrm{line}}^2 = \max\left(0,\; \frac{\sum_j w_j x_j^2}{\sum_j w_j} - C^2\right)\,.\]

When compute_line_std is True, the second output is the flux-propagated measurement uncertainty \(\sigma_{\mathrm{meas}}\) (independent pixel noise through the interpolator stencil). A line-to-line flux scatter \(\sigma_{\mathrm{line}}\) is still accumulated internally but is not added in quadrature: that term is a depth-dispersion floor, not jitter on the CCF centroid, and would freeze \(\sigma_\mu\) at the LSF width even at infinite S/N.

The third output stores the same \(\sigma_{\mathrm{meas}}\) (nan when unavailable).

Input arrays are padded to fixed widths; n_pix_arr and n_line_arr give valid lengths for each chunk row.

_ccf_background_sigma_clipped_median(y, *, n_sigma=3.0, max_iter=8, min_keep=5)[source]

Iterative sigma-clipped median — robust CCF continuum / background level.

_ccf_chunk_ccf_numba(ln_lam, spec, spec_err, good, template_ln, template_flux, v_min, v_max, v_step, ccf_out, min_good_pixels, zb)[source]

Weighted cross-correlation CCF(v) for one chunk. Writes ccf_out (length n_vel); returns count of good spectral pixels (for error scaling).

_ccf_chunk_ccf_numba_vgrid(ln_lam, spec, spec_err, good, template_ln, template_flux, v_grid, ccf_out, min_good_pixels, zb)[source]

Same as _ccf_chunk_ccf_numba() but samples at arbitrary v_grid (m/s).

_ccf_fit_debug_jsonable(v)[source]

Reduce fit_ccf_rv debug context values to JSON-friendly types.

_ccf_gaussian_amp_floor_free_baseline_scaled(gy_det, ys, *, frac_of_span=0.005, frac_of_peak=0.05, abs_scaled_floor=0.0)[source]

Positive lower bound on Gaussian amplitude (LevMar scaled gy units) when the compound model is Gaussian1D + Const1D with free Const1D: otherwise the fitter can drive Gaussian amplitude to exactly zero and absorb the line in the constant (χ² degeneracy), yielding flat preview Gaussians.

Uses both a fraction of the detrended peak-to-valley span and a fraction of the positive peak above the median-detrended baseline: span alone can be noise-dominated on narrow mask-CCF grids, leaving a tiny floor that still allows an effectively flat Gaussian.

Optional abs_scaled_floor (same units as scaled gy) forces a minimum when peak-derived floors would otherwise be numerically negligible.

_ccf_preview_finalize_n_workers(n_slots)[source]

Worker count for parallel Gaussian + refine in finalize_ccf_preview_dict().

Set HISPEC_DRP_CCF_PREVIEW_SLOT_THREADS to a positive int to cap workers; 1 forces sequential (legacy behavior). Unset or invalid: min(n_slots, cpu_count).

_ccf_rv_err_numeric_floor(v_step_m_s)[source]

Minimum positive RV uncertainty (m/s) for numerical stability only.

_ccf_rv_from_ccf(v_grid, ccf, v_step, n_good, vel_span_m_s_per_pixel=None, *, min_good_pixels=10, ccf_bisector_config=None)[source]

Gaussian fit to CCF for final RV; else grid peak / HWHM.

ccf_bisector_config is retained for API compatibility. Bisector refine is not used for the reported RV.

_ccf_rv_numba_err_floor(vs)[source]

Match _ccf_rv_err_numeric_floor() (m/s); sub-grid σ_RV allowed.

_ccf_weighted_covariance_scan(ln_lam, spec, spec_err, good, template_ln, template_flux, v_grid, zb=0.0)[source]

Python CCF(v); same statistic as _ccf_chunk_ccf_numba (fallback when Numba off).

_fit_ccf_preview_slot_worker(sl, vs, *, ccf_line_mask_stored_negated=None, line_mask_line_window_by_line=None, line_mask_gaussian_seed_mean_m_s=None, ccf_bisector_config=None)[source]

One slot: fit_ccf_rv() with CCF_PREVIEW_SLOT_FIT_CONFIG, then bisector RV for pipeline/preview metadata (_refine_ccf_rv_bisector_after_gaussian_fit()). Thread-safe (no shared mutable state).

_fit_ccf_preview_slots_line_mask_numba(slots, v_step, *, line_mask_gaussian_seed_mean_m_s=None, config=None)[source]

Batch Gaussian fits for mask-line preview slots (same Numba path as RVCCF).

Avoids calling fit_ccf_rv_rows_numba() from multiple threads inside finalize_ccf_preview_dict() (Numba workqueue is not thread-safe).

_fit_ccf_rv_line_mask_stored_negated_via_numba(v_grid_m_s, ccf, v_step_m_s, n_good, *, return_params, ccf_err, config, gaussian_seed_mean_m_s)[source]

Mask-line stored CCF rows: use the same Numba centroid as the RVCCF pipeline.

_fractional_pixel_index(xq, x, n)[source]

Continuous pixel index for xq on sorted abscissae x[:n].

Linear in wavelength between neighboring samples (handles mildly irregular BSPEC WAVE spacing while applying the band-limited kernel in pixel index).

_gaussian_ccf_model(v, amplitude, v0, sigma, baseline)[source]
_gaussian_preview_params_from_peak_up_ccf(v_grid_m_s, ccf_peak_up, rv_m_s, rv_err_m_s, *, fit_ok, config=None, gaussian_seed_mean_m_s=None)[source]

Build params / diagnostics for mask-line preview overlays when RV comes from fit_ccf_rv_rows_numba().

_lagrange_stencil_index_and_weights(xq, x, n, order, out_L)[source]

Interpolation weights on the same stencil as _poly_interp_sorted_1d().

Despite the historical name, weights are linear (order==1) or renormalized Lanczos-a (a=order). Writes out_L[0:k] and returns (s, k) for pixel indices s … s+k-1. Clamped endpoints use a one-point stencil with L[0]=1. Returns (-1, 0) if invalid.

_lanczos_kernel(x, a)[source]

Lanczos-a kernel: sinc(x) sinc(x/a) for |x|<a, else 0.

_levmar_ccf_y_scale(gy)[source]

Multiplicative scale so gy * scale has max absolute value ≈ 1.

scipy.optimize.leastsq (used by Astropy LevMarLSQFitter) reports ierr outside {1,…,4} when the problem is poorly scaled (common for mask-CCF amplitudes ~1e-18), which triggers AstropyUserWarning: The fit may be unsuccessful. Scaling y (and inverse-variance weights consistently) preserves Gaussian mean and stddev in velocity while improving conditioning.

_levmar_lsq_fit(ft, init, *args, **kwargs)[source]

Run LevMarLSQFitter.

Ill-conditioned fits can make scipy.optimize.leastsq overflow when forming cov_x; downstream code already rejects non-physical covariances via _lm.

_line_mask_ccf_fit_free_baseline_requested(*, fit_ccf_baseline_free, line_mask_line_window_by_line, ccf_line_mask_stored_negated=None)[source]

True when fit_ccf_rv() should treat the CCF constant term as an LM parameter.

For line-mask line-by-line chunking (window_line_by_line), the velocity span is often only a few km s−1 wide, so a robust median baseline estimated from essentially the entire profile is a poor substitute for wings; fitting Const1D jointly with the Gaussian avoids that bias.

For ccf_line_mask_stored_negated=True (line-mask / ccf_line_mask stored CCF rows), the baseline is not a free LM parameter: a free Gaussian1D + Const1D is χ²-degenerate (Gaussian amplitude collapses toward zero and the line is absorbed by the constant), which breaks Plotly Gaussian overlays. Pass half-width caps still apply when ccf_line_mask_stored_negated is true (see fit_ccf_rv()), so fixed sigma-clipped baselines remain local to the fit window.

_line_mask_peak_index_integral_and_prominence(ys, n, prom_half_width, integral_half_width)[source]

Choose among strict local maxima of the smoothed CCF using integrated excess (sum of positive deviation from the global median in a wide window) times sqrt(prominence + 1).

Pure prominence favors narrow spikes (large drop to a nearby valley). The physical stellar-RV peak from thousands of mask lines is broad; its prominence can be modest while the integrated contrast in ±~20–40 km/s is large. Combining integral × √prominence prefers that coherent peak over spurious narrow maxima (e.g. grid artifacts near unrelated velocities).

_linear_interp_sorted_1d(xq, x, y, n)[source]

Linear interpolation on sorted x[:n] (ascending); clamps outside range.

_ln_lam(wave)[source]

Natural log of wavelength (micron → log micron). Internal helper.

_make_velocity_grid(v_min, v_max, v_step)[source]

Uniform RV trial grid in m/s (matches Numba chunk CCF grid spacing).

_masked_ccf_rv_core(wave, spec, spec_err, mask, template_ln, template_flux, v_min, v_max, v_step, *, diagnostics, v_grid=None, zb=0.0, min_good_pixels=10)[source]

Single CCF build + fit; optionally build diagnostics dict (no duplicate CCF work).

Returns:

rv, rv_err, v_grid, ccf, diagnostics_or_none

_nan_stderr_of_mean_axis0(stacked_sigma, stacked_ccf)[source]

Standard error of nanmean(stacked_ccf, axis=0) when each row is an independent estimate with 1σ stacked_sigma[i, :] at each velocity.

Uses \(\sigma_{\mu,j}=\sqrt{\sum_i \sigma_{ij}^2}\,/\,n_j\) where the sum and \(n_j\) use the same rows as the column-wise mean (finite stacked_ccf; only rows with finite nonnegative stacked_sigma contribute to the sum of variances). This matches the scale of the mean CCF; using sqrt(mean(σ²)) instead would track a typical single-row σ and overstate uncertainty on the mean by ~ \(\sqrt{n}\) when rows are similar.

_nanmean_axis0_ignore_empty_columns(arr)[source]

Column-wise mean of finite values (axis 0). Columns with no finite entries are NaN.

Stacked CCF arrays often have velocity bins where every chunk row is NaN; np.nanmean(..., axis=0) then emits RuntimeWarning: Mean of empty slice once per such column. This implementation matches nanmean for mixed finite/NaN columns but avoids that warning.

_nanmedian_numba_1d(x)[source]
_normalized_sinc(x)[source]

sin(πx)/(πx) with sinc(0)=1.

_poly_interp_sorted_1d(xq, x, y, n, order)[source]

Interpolate y at xq on sorted x[:n] (ascending).

  • order == 1 — linear between bracketing samples (fast / robust).

  • order >= 2 — Lanczos-a windowed-sinc in pixel-index space with a = order (science default a = 3). Clamps outside [x[0], x[n-1]]. Near edges the truncated kernel is renormalized.

_poly_interp_sorted_1d_value_and_flux_variance(xq, x, y, e_sig, n, order)[source]

Interpolate y at xq plus propagated variance from pixel σ.

Same stencil / weights as _poly_interp_sorted_1d() (linear or Lanczos-a). Returns (ŷ, \sum_m w_m^2 e_sig[m]^2) with renormalized weights near edges. Edge clamps return the endpoint sample and its e_sig^2. Returns (nan, nan) if any stencil e_sig is non-finite or non-positive.

_process_all_orders_ccf_numba(wave_2d, spec_2d, spec_err_2d, dq_2d, do_not_use, template_ln, template_flux, window_size_um, order_indices, n_chunks_per_order, chunk_start, v_min, v_max, v_step, n_vel, all_ccf, all_n_good, all_wl, min_good_pixels, zb)[source]

Parallel per-order CCF fill: writes all_ccf[chunk, :], all_n_good[chunk], all_wl[chunk]. RV fit in Python via fit_ccf_rv().

_process_all_orders_ccf_numba_vgrid(wave_2d, spec_2d, spec_err_2d, dq_2d, do_not_use, template_ln, template_flux, window_size_um, order_indices, n_chunks_per_order, chunk_start, v_grid, n_vel, all_ccf, all_n_good, all_wl, min_good_pixels, zb)[source]

Same as _process_all_orders_ccf_numba() but with an explicit v_grid (m/s).

_process_all_orders_rvs_numba_single_grid(wave_2d, spec_2d, spec_err_2d, dq_2d, do_not_use, template_ln, template_flux, window_size_um, order_indices, n_chunks_per_order, chunk_start, v_min, v_max, v_step, *, return_ccf=False, numba_threads=None, min_good_pixels=10, zb=0.0)[source]

Single uniform velocity grid: Numba CCF fill + per-chunk Gaussian RV.

_process_all_orders_rvs_numba_single_vgrid(wave_2d, spec_2d, spec_err_2d, dq_2d, do_not_use, template_ln, template_flux, window_size_um, order_indices, n_chunks_per_order, chunk_start, v_grid, *, return_ccf=False, numba_threads=None, min_good_pixels=10, zb=0.0)[source]

Explicit v_grid (uniform centered or custom): Numba CCF fill + per-chunk Gaussian RV.

_refine_ccf_rv_bisector_after_gaussian_fit(v_grid_m_s, ccf, vstep, *, ccf_err=None, config=None, gaussian_seed_mean_m_s=None)[source]

Bisector RV after fit_ccf_rv() (NEID-style weighted percentile cuts).

Pass gaussian_seed_mean_m_s (Gaussian CCF center) so the bisector peak is taken near that velocity rather than a global argmax that can lock onto a window edge.

Returns (None, None, diag) when bisector fitting fails; diag may still carry ok=False and cut metadata for previews.

_rv_err_slope_propagation_m_s(v_m_s, y_ccf, sigma_ccf)[source]

Diagonal error propagation σ_RV ≈ σ_y / |d(CCF)/dv| (m/s), v in m/s.

Uses a robust high-percentile of |dCCF/dv| in the central part of the window so a single noisy bin does not dominate. When sigma_ccf is missing, uses mad_std of y_ccf as a noise scale. The result is not clipped to an arbitrary upper bound; very large values indicate a near-flat CCF or tiny |dCCF/dv|.

_rv_from_ccf_line_mask_numba_single(v_grid_m_s, ccf_raw, n_good, i_peak_prior)[source]

Fast Numba seed RV from mask-line CCF (discrete peak + heuristic σ).

Convention is fixed by algorithm, not inferred from each CCF shape: the mask weights target absorption lines, so the weight-normalized statistic is minimized near the correct Doppler shift. We always work in -CCF (search maxima), and flipped is always 1 so returned/preview CCF rows are negated consistently.

ccf_raw is the weight-normalized mask CCF row from _calc_mask_ccf_chunks_numba().

This estimate is only a fallback when the Gaussian CCF fit does not succeed; the pipeline final RV is the Gaussian centroid from fit_ccf_rv().

_rv_from_ccf_line_mask_peak_index_numba(v_grid_m_s, ccf_raw, i_peak_prior)[source]

Peak index used by _rv_from_ccf_line_mask_numba_single() for LSTSQ / fallback paths.

Returns -1 if the grid is invalid or no usable peak is found before edge handling.

_rv_from_ccf_line_mask_rows_numba(v_grid_m_s, ccf_rows, n_good_arr, out_rv, out_rv_err, out_flip, i_peak_prior)[source]
_smooth_uniform5_numba(y, n)[source]

5-point moving average; non-finite samples excluded from each local mean.

_subsample_velocity_ccf_for_gaussian_fit(vm, y, y_err_ok, v_step_m_s, max_samples)[source]

Uniform stride subsample along velocity when the grid is very long (line-mask broad scans).

Preserves ordering; scales v_step_m_s by the stride so error heuristics stay consistent with the effective sample spacing.

assemble_rvccf_fib_table(rvs, rv_errs, wavelengths, orders, inlier, *, supplement=None)[source]

Full per-chunk RVCCF_FIB* table: RV metrics plus optional CCF supplement columns.

When supplement is None or has length 0, CCF rows are empty arrays (RVCCF_CCF_ELEM_DTYPE), N_GOOD is -1, and velocity metadata is NaN / N_VEL 0.

build_ccf_preview_dict(kind, order_tasks, v_min, v_max, v_step, *, order_indices=None, n_chunks_per_order=None, chunk_start=None, all_ccf=None, v_grid=None, wave_2d=None, wave=None, spec=None, err=None, dq=None, do_not_use=None, template_ln=None, template_flux=None, window_size_um=None)[source]

Build the stellar-RV CCF preview JSON-like structure for Plotly (per-order slots, mean CCF, Gaussian).

Parameters:
  • kind ({'numba_flat', 'spectra_orders'}) –

    Which construction path to use:

    • numba_flat — consume flattened Numba outputs from process_orders_rvs_numba_parallel() with return_ccf=True (all_ccf, chunk_start, n_chunks_per_order, order_indices, v_grid, wave_2d).

    • spectra_orders — run rv_per_chunks() per order in pure Python (slower; useful when debugging or avoiding the Numba stack).

  • order_tasks (list of tuple) – (order_row_index, echelle_order_number) for each order included in the preview.

  • v_min (float) – CCF velocity grid bounds and step (m/s) used for logging and passed through to finalize_ccf_preview_dict() for axis metadata and Gaussian reference curves.

  • v_max (float) – CCF velocity grid bounds and step (m/s) used for logging and passed through to finalize_ccf_preview_dict() for axis metadata and Gaussian reference curves.

  • v_step (float) – CCF velocity grid bounds and step (m/s) used for logging and passed through to finalize_ccf_preview_dict() for axis metadata and Gaussian reference curves.

  • order_indices (ndarray, optional) – Required for kind='numba_flat'. Layout matches process_orders_rvs_numba_parallel(): chunk_start indexes into the flattened all_ccf rows per order block.

  • n_chunks_per_order (ndarray, optional) – Required for kind='numba_flat'. Layout matches process_orders_rvs_numba_parallel(): chunk_start indexes into the flattened all_ccf rows per order block.

  • chunk_start (ndarray, optional) – Required for kind='numba_flat'. Layout matches process_orders_rvs_numba_parallel(): chunk_start indexes into the flattened all_ccf rows per order block.

  • all_ccf (ndarray, optional) – 2-D array of CCF rows (chunks × velocity), required for numba_flat.

  • v_grid (ndarray, optional) – 1-D velocity samples (m/s), required for numba_flat.

  • wave_2d (ndarray, optional) – Shape (n_orders, n_pix) wavelength grid (µm); required for numba_flat to annotate wavelength span per order slot.

  • wave (ndarray, optional) – Required for spectra_orders: 2-D extracted-order arrays (same axis 0 as order_tasks row indices).

  • spec (ndarray, optional) – Required for spectra_orders: 2-D extracted-order arrays (same axis 0 as order_tasks row indices).

  • err (ndarray, optional) – Required for spectra_orders: 2-D extracted-order arrays (same axis 0 as order_tasks row indices).

  • dq (ndarray, optional) – Required for spectra_orders: 2-D extracted-order arrays (same axis 0 as order_tasks row indices).

  • do_not_use (int or None, optional) – DQ bitmask; pixels with (dq & do_not_use) != 0 are treated as bad for masking.

  • template_ln (ndarray, optional) – Full template in ln(micron) and flux for spectra_orders.

  • template_flux (ndarray, optional) – Full template in ln(micron) and flux for spectra_orders.

  • window_size_um (float or None, optional) – Chunk width (µm) for rv_per_chunks() in spectra_orders mode.

Returns:

dict or None – Structure consumed by hispecdrp.primitives.stellar_rv.previews.stellar_rv_preview (order slots + aggregated rows + fit metadata), or None if there is nothing to plot (no valid orders, empty CCF, or length mismatch between orders).

Raises:

ValueError – If required arguments for the selected kind are missing, or kind is unknown.

build_centered_uniform_velocity_grid(center_m_s, half_width_m_s, step_m_s)[source]

Uniform CCF velocity samples on [center − half_width, center + half_width].

Spacing is constant (step_m_s) across the whole window.

build_line_mask_chunk_wavelength_intervals_line_by_line(wave_um, mask_lines, *, v_center_m_s, zb, min_good_pixels=10)[source]

Build observed-wavelength chunks with one mask line per chunk (Voronoi cells in λ).

Mask rest wavelengths are mapped to the observed frame at v_center_m_s (same as doppler_shift_from_barycenter()). Distinct observed positions are sorted; each line defines one chunk whose wavelength window is the largest interval that (i) contains that predicted line λ, (ii) does not overlap neighboring chunks, and (iii) stays inside the pixel wavelength support [w_min, w_max] of wave_um. Neighbor boundaries are midpoints between adjacent predicted line wavelengths (1-D Voronoi cells). Spectrum outside the union of chunks is not analyzed.

Chunk center wavelengths are each line’s predicted observed λ.

The interval [wl_lo_um, wl_hi_um] is a 1-D Voronoi cell between neighbor lines (midpoint boundaries). It is not generally symmetric about the line’s predicted λ unless neighbor spacings happen to match.

Parameters:
  • wave_um – 1-D wavelength samples (µm) for the order.

  • mask_lines – Mask lines for the run.

  • v_center_m_s – Typically ccf_input_velocity (m/s).

  • zb – Barycentric factor for the Doppler mapping.

  • min_good_pixels – Reserved for future filtering when a chunk would contain too few spectral samples.

Returns:

wl_lo_um, wl_hi_um, chunk_center_wavelength_um (np.ndarray) – Per-chunk bounds (µm) and chunk-center wavelengths (µm). Chunk wavelength half-open convention in rv_per_chunks_line_mask() matches the last chunk inclusive on the right.

build_rvccf_chunk_supplement(*, chunk_id, n_good, v_min, v_max, v_step, ccf_2d, bis=None, bis_err=None)[source]

Supplement table with raw CCF(v) per chunk (columns merged into RVCCF_FIB*).

Parameters:
  • ccf_2d (np.ndarray) – Shape (n_chunk, n_vel); row i is the CCF for chunk i.

  • bis (np.ndarray or None) – Optional per-chunk Queloz BIS and uncertainty (m/s). When omitted, columns are filled with NaN.

  • bis_err (np.ndarray or None) – Optional per-chunk Queloz BIS and uncertainty (m/s). When omitted, columns are filled with NaN.

calc_bisector_inverse_slope(vel_grid, ccf, ccf_err=None, n_levels=100, quant_shallow=(0.1, 0.4), quant_core=(0.6, 0.9))[source]

Bisector Inverse Slope (BIS) of a CCF, after Queloz et al. (2001).

Thin wrapper over the njit core (_calc_bis). ccf_err is optional: it is used only to propagate the velocity uncertainties, never the velocity values themselves. When ccf_err is None the bisector velocities are computed normally and all three error outputs (bis_err, shallow_err, core_err) are returned as NaN, since there is no uncertainty information to propagate.

See _calc_bis for the full parameter and algorithm description. In brief, the bisector midpoints are averaged over two depth-fraction windows measured from the continuum toward the extremum (orientation-invariant for both absorption dips and emission peaks):

BIS = v_shallow - v_core

with shallow near the continuum and core near the core.

Parameters:
  • vel_grid (ndarray) – Velocity grid (ascending) and CCF values.

  • ccf (ndarray) – Velocity grid (ascending) and CCF values.

  • ccf_err (ndarray | None) – 1-sigma uncertainties on ccf. Optional; if None, the error outputs are NaN.

  • n_levels (int) – Number of evenly spaced depth levels sampled across the 0-1 range.

  • quant_shallow (tuple[float, float] | None) – Lower/upper depth fractions (0-1, measured from the continuum) bounding the shallow (near-continuum) region used for v_shallow. Defaults to (0.10, 0.40).

  • quant_core (tuple[float, float]) – Lower/upper depth fractions (0-1, measured from the continuum) bounding the core (near-core) region used for v_core. Defaults to (0.6, 0.90).

Returns:
  • bis (float) – The bisector inverse slope (v_shallow - v_core). NaN if not measurable.

  • bis_err (float) – Propagated 1-sigma uncertainty on bis (quadrature sum of shallow_err and core_err). NaN if not measurable or if ccf_err was None.

  • v_shallow (float) – Mean bisector velocity over the shallow (near-continuum) region.

  • shallow_err (float) – 1-sigma uncertainty on v_shallow. NaN if not measurable or if ccf_err was None.

  • v_core (float) – Mean bisector velocity over the core (near-core) region.

  • core_err (float) – 1-sigma uncertainty on v_core. NaN if not measurable or if ccf_err was None.

  • levels, bis_curve (ndarray) – Depth fractions and bisector velocities at each successfully bracketed level, sampled across the full 0-1 depth range. Paired element-for- element.

ccf_order_n_chunks_for_span(span_um, window_um)[source]

Number of equal-wavelength segments for one echelle order given a target chunk width.

If the order span does not exceed window_um, returns 1 (one chunk = full order). Otherwise returns ceil(span_um / window_um) so each segment has width span_um / n_chunks, which is at most window_um.

Used for mask-line CCF chunking (rv_per_chunks_line_mask()), template rv_per_chunks(), and Numba order layouts so chunk counts follow a single rule.

See also

build_line_mask_chunk_wavelength_intervals_line_by_line() — alternate chunking for ccf_line_mask when window_line_by_line is true (see rv_per_chunks_line_mask()).

clip_gaussian_plot_velocity_range_m_s(lo_m_s, hi_m_s, *, v_grid_min_m_s=None, v_grid_max_m_s=None, v_samples_m_s=None)[source]

Bound [lo_m_s, hi_m_s] for evaluating a Gaussian CCF model.

The returned interval is the intersection of [lo_m_s, hi_m_s] with the span of the CCF velocity axis (v_grid_* or v_samples_m_s), further clipped to the module absolute limits V_MIN_DEFAULT_M_S … V_MAX_DEFAULT_M_S (m/s), matching the broad CCF grid used in resolve_ccf_broad_grid_m_s() and related paths.

continuum_normalize(flux, wavelength=None, lowpass_window=None, poly_order=None)[source]

Divide flux by an estimated continuum (median filter and/or polynomial).

Used optionally before CCF in process_one_order_rvs() so line depths are less sensitive to slow spectral slope.

Parameters:
  • flux (np.ndarray) – 1-D flux.

  • wavelength (np.ndarray or None, optional) – Abscissa for polynomial continuum; if None, pixel index is used.

  • lowpass_window (int or None, optional) – Odd median-filter window; even values are incremented. None skips filtering.

  • poly_order (int or None, optional) – If set, fit continuum as a polynomial of this order (after median step if any).

Returns:

np.ndarray – flux / continuum, same shape as flux.

Notes

If both lowpass_window and poly_order are None, returns flux unchanged.

count_mask_lines_in_observed_wavelength_interval(mask_lines, *, wl_lo_um, wl_hi_um, v_center_m_s, zb)[source]

Count mask line segments with positive weight whose observed λ lies in [wl_lo_um, wl_hi_um].

Uses the same Doppler mapping as doppler_shift_from_barycenter() at v_center_m_s.

doppler_paint_lagrange(wave_obs_um, wave_rest_um, flux_rest, rv_m_s, *, zb=0.0, order=3, prepare_for_obs_grid=None, prepare_samples_per_pixel=8.0)

Resample a rest-frame spectrum onto an observed wavelength grid via Lanczos.

Uses the same Numba kernel as the science ccf_line_mask sampler (_poly_interp_sorted_1d() / mask_ccf_pixel_interp_order). At injected radial velocity rv_m_s and barycentric factor zb,

\[F_{\rm obs}(\lambda) = F_{\rm rest}\!\left( \lambda\,\frac{1+z_b}{1+v/c} \right)\]

which is the inverse of the mask Doppler map \(\lambda_{\rm obs}=\lambda_{\rm rest}(1+v/c)/(1+z_b)\).

Parameters:
  • wave_obs_um – Observed wavelengths (um).

  • wave_rest_um – Rest-frame knots (um) and fluxes; wave_rest_um must be strictly ascending.

  • flux_rest – Rest-frame knots (um) and fluxes; wave_rest_um must be strictly ascending.

  • rv_m_s – Injected stellar RV (m/s).

  • zb – Barycentric redshift factor (same convention as the mask CCF).

  • order – Lanczos parameter a (default 3 = Lanczos-3), matching mask_ccf_pixel_interp_order. 1 selects linear interpolation. Clamped to [1, MAX_MASK_CCF_PIXEL_INTERP_ORDER].

  • prepare_for_obs_grid – When set to the target observed wavelength grid (um), densify wave_rest_um / flux_rest first via prepare_template_for_doppler_paint() so the template has enough knots per BSPEC pixel for cm/s Doppler shifts. Omit for mask-CCF sub-pixel sampling on an already-discretized L2 spectrum.

  • prepare_samples_per_pixel – Passed to prepare_template_for_doppler_paint() when prepare_for_obs_grid is set (default 8).

Returns:

np.ndarray – Flux on wave_obs_um (float64).

See also

prepare_template_for_doppler_paint()

Instrument-linked template densification before paint.

doppler_paint_cubic_spline()

Alternate not-a-knot cubic paint (not the science/CCF-matching path).

doppler_paint_lanczos(wave_obs_um, wave_rest_um, flux_rest, rv_m_s, *, zb=0.0, order=3, prepare_for_obs_grid=None, prepare_samples_per_pixel=8.0)[source]

Resample a rest-frame spectrum onto an observed wavelength grid via Lanczos.

Uses the same Numba kernel as the science ccf_line_mask sampler (_poly_interp_sorted_1d() / mask_ccf_pixel_interp_order). At injected radial velocity rv_m_s and barycentric factor zb,

\[F_{\rm obs}(\lambda) = F_{\rm rest}\!\left( \lambda\,\frac{1+z_b}{1+v/c} \right)\]

which is the inverse of the mask Doppler map \(\lambda_{\rm obs}=\lambda_{\rm rest}(1+v/c)/(1+z_b)\).

Parameters:
  • wave_obs_um – Observed wavelengths (um).

  • wave_rest_um – Rest-frame knots (um) and fluxes; wave_rest_um must be strictly ascending.

  • flux_rest – Rest-frame knots (um) and fluxes; wave_rest_um must be strictly ascending.

  • rv_m_s – Injected stellar RV (m/s).

  • zb – Barycentric redshift factor (same convention as the mask CCF).

  • order – Lanczos parameter a (default 3 = Lanczos-3), matching mask_ccf_pixel_interp_order. 1 selects linear interpolation. Clamped to [1, MAX_MASK_CCF_PIXEL_INTERP_ORDER].

  • prepare_for_obs_grid – When set to the target observed wavelength grid (um), densify wave_rest_um / flux_rest first via prepare_template_for_doppler_paint() so the template has enough knots per BSPEC pixel for cm/s Doppler shifts. Omit for mask-CCF sub-pixel sampling on an already-discretized L2 spectrum.

  • prepare_samples_per_pixel – Passed to prepare_template_for_doppler_paint() when prepare_for_obs_grid is set (default 8).

Returns:

np.ndarray – Flux on wave_obs_um (float64).

See also

prepare_template_for_doppler_paint()

Instrument-linked template densification before paint.

doppler_paint_cubic_spline()

Alternate not-a-knot cubic paint (not the science/CCF-matching path).

doppler_shift_from_barycenter(wave, vel, zb)[source]

Map rest-frame wavelength(s) to the observed frame at trial velocity vel.

Applies \(\lambda_{\rm obs} = \lambda_{\rm rest} (1 + v/c) / (1 + z_b)\).

wave must be a 1-D float64 array. Non-finite zb or 1 + z_b = 0 are treated as z_b = 0. The element loop uses prange so callers can compose this inside other parallel Numba kernels.

dv_per_pixel_m_s(wl_um)[source]

Rough echelle resolving element per detector pixel in velocity units (m/s).

Uses the HISPEC-style mapping order ≈ 147 / λ (µm) and n_pix = 4096 so Δv ≈ c / (order · n_pix). This is a diagnostic scale for CCF sampling and error heuristics, not a physical FWHM.

With \(\Delta v = c\,(\Delta\lambda/\lambda)\), center wavelength \(\lambda \approx 147/\,{\rm order}\) µm, and pixel width \(\Delta\lambda \approx (147/{\rm order}^2)/4096\) µm, this gives \(\Delta v = c / ({\rm order}\cdot4096)\) m/s. Typical L2 scales: BSPEC (orders ~110–148) ~494–665 m/s per pixel; RSPEC (orders ~60–97) ~755–1220 m/s per pixel.

Parameters:

wl_um (float) – Wavelength in micron (positive, finite).

Returns:

float – Δv per pixel (m/s), or NaN if wl_um is non-finite or non-positive.

effective_ccf_v_step_for_fit(v_grid)[source]

Finest positive velocity spacing (m/s) on v_grid for CCF RV fits.

estimate_ccf_uncertainty_highpass_residual(ccf, *, lowpass_window=51, savgol_polyorder=3)[source]

Estimate a single CCF uncertainty σ (same units as ccf): Savitzky–Golay low-pass smooth, subtract to form a high-frequency residual, then take the RMS of successive differences in that residual (pixel-to-pixel scale).

Line-mask CCF path (run_ccf_line_mask_for_fiber(); ccf_line_mask primitive): this is the primary model for ccf_err on the per-order mean CCF (uniform array filled with sigma), and for the stacked rows passed into finalize_ccf_preview_dict() (replacing the former per-chunk weighted SD + stderr-of-mean combination).

Parameters:
  • ccf (ndarray) – CCF samples (same shape as used for Gaussian fitting).

  • lowpass_window (int) – Savitzky–Golay window length (forced odd); capped to array length. Larger ⇒ stronger low-pass (more large-scale structure removed from the residual).

  • savgol_polyorder (int) – Savitzky–Golay polynomial order (must be < window_length).

Returns:
  • sigma (float) – Scalar σ applied uniformly at each velocity bin when building ccf_err for fit_ccf_rv().

  • ccf_lowpass (ndarray) – Low-pass (smooth) component of ccf.

  • residual (ndarray) – ccf - ccf_lowpass (high-pass remainder).

finalize_ccf_preview_dict(order_slots, all_ccf_rows, v_grid, v_min, v_max, v_step, all_ccf_err_rows=None, *, ccf_line_mask_stored_negated=None, line_mask_line_window_by_line=None, line_mask_gaussian_seed_mean_m_s=None)[source]

Build the _ccf_preview_by_fiber structure from per-order CCF 2-D arrays.

order_slots entries are typically one slot per line-mask chunk (or one per echelle order when a row is a single chunk); this prepends the global mean slot (mean over all stacked chunk rows in all_ccf_rows).

When all_ccf_err_rows is provided (one stacked array per order, aligned with all_ccf_rows), the mean slot gets ccf_err = standard error of the column-wise mean CCF (sqrt(sum σ²)/n, not sqrt(mean(σ²))) and fit_ccf_rv() uses them as inverse-variance weights.

Parameters:
  • ccf_line_mask_stored_negated (bool or None, optional) – When not None, forwarded to each slot’s fit_ccf_rv() call and copied to the returned dict as "ccf_line_mask_stored_negated" (mask-line preview only).

  • line_mask_line_window_by_line (bool or None, optional) – Forwarded to fit_ccf_rv() (see _line_mask_ccf_fit_free_baseline_requested()).

  • line_mask_gaussian_seed_mean_m_s (float or None, optional) – When set (typically ccf_input_velocity / grid center), passed to fit_ccf_rv() as gaussian_seed_mean_m_s for mask-line stored CCFs so the discrete peak seed is taken near the search center instead of a global maximum on a nearly flat curve.

fit_ccf_rv(v_grid_m_s, ccf, v_step_m_s, n_good=None, return_params=False, *, ccf_err=None, mask_method=None, config=None, vel_span_m_s_per_pixel=None, two_pass=True, max_velocity_samples=8192, ccf_line_mask_stored_negated=None, fit_ccf_baseline_free=None, line_mask_line_window_by_line=None, gaussian_seed_mean_m_s=None)[source]

Fit a Gaussian plus constant baseline to a precomputed CCF and return RV ± error in m s⁻¹.

Uses a robust emission/absorption profile guess, Gaussian1D plus Const1D on the CCF in a sliding velocity window (values are scaled to ~unit magnitude before LM; RV parameters are unchanged). By default the constant baseline is fixed to _ccf_background_sigma_clipped_median() of the CCF samples in each fit window (not a free LM parameter). When fit_ccf_baseline_free=True, or when line_mask_line_window_by_line is true (narrow line-mask line-by-line grids) and ccf_line_mask_stored_negated is not true, the baseline is a free Const1D term fit jointly with the Gaussian, and pass half-widths are capped to a fraction of the available velocity span so the fit is not dominated by an artificial “global median” baseline across the whole short profile. The same half-width caps apply when ccf_line_mask_stored_negated is true (mask-line CCF), so fixed-baseline fits on short grids do not inherit multi-hundred-km pass windows. One or two Levenberg–Marquardt passes each use a wide velocity window (see CCFFitConfig) to stabilize the Gaussian amplitude and width. Within each window the fitter runs unclipped χ² passes on the full sample (repeated LM with levmar_maxiter), then sigma-clipping refinement with relaxed thresholds on the first clipping rounds. Formal uncertainty may use a KPF-inspired ccf_error scaling when plausible, else covariance from the fitter, else a σ/√n fallback.

Parameters:
  • v_grid_m_s (np.ndarray) – Velocity samples (m s⁻¹), usually sorted (uniform broad or centered window).

  • ccf (np.ndarray) – CCF values on the same grid.

  • v_step_m_s (float) – Effective finest velocity spacing (m s⁻¹) for plausibility checks and n_sp scaling — typically effective_ccf_v_step_for_fit() on v_grid_m_s.

  • n_good (int or None, optional) – Number of good spectral pixels in the chunk (for fallback error scaling).

  • return_params (bool, optional) – If True, return (rv, rv_err, params_dict, diag_dict); else (rv, rv_err).

  • mask_method (str or None, optional) – If in CCFFitConfig.cal_mask_methods, use absorption-style calibration peak logic.

  • config (CCFFitConfig or None, optional) – Override fit windows and thresholds.

  • vel_span_m_s_per_pixel (float or None, optional) – Spectral sampling scale passed into error heuristics.

  • two_pass (bool, optional) – If True (default), run a second fit narrowed around the first mean.

  • max_velocity_samples (int or None, optional) – When the input grid has more than this many finite samples, apply uniform stride subsampling for the Gaussian fit only (default 8192). Set None to always use the full grid. Does not change stored CCF arrays elsewhere — only speeds LM fitting on very long line-mask broad scans.

  • ccf_err (np.ndarray or None, optional) – Per-sample CCF uncertainty (same shape as ccf). When finite and predominantly positive, Levenberg–Marquardt fits use weights = 1/ccf_err² on the raw CCF samples in each pass window.

  • ccf_line_mask_stored_negated (bool or None, optional) – When not None, recorded in the diagnostics dict (when return_params is True) as "ccf_line_mask_stored_negated". Use True for mask-line CCF rows produced by rv_per_chunks_line_mask() / run_ccf_line_mask_for_fiber() (stored convention: negated from the raw weighted mask statistic so the peak is near the true RV). When True, the fitter does not use the data-driven emission/absorption heuristic: it assumes a peak-up line (positive Gaussian1D amplitude in scaled units, seed at the discrete maximum) and sets Gaussian1D.amplitude lower bound to 0 so LM cannot flip to a spurious negative-lobe solution on flat mask CCFs. None (default) omits the key — caller convention unknown.

  • fit_ccf_baseline_free (bool or None, optional) – When True, fit the CCF constant baseline in LM (do not fix Const1D). When None (default), use _line_mask_ccf_fit_free_baseline_requested() with line_mask_line_window_by_line to decide.

  • line_mask_line_window_by_line (bool or None, optional) – Line-mask line-by-line chunking flag (same meaning as window_line_by_line on the primitive). When fit_ccf_baseline_free is None and this is true, free-baseline mode is enabled automatically unless ccf_line_mask_stored_negated is true (see _line_mask_ccf_fit_free_baseline_requested()).

  • gaussian_seed_mean_m_s (float or None, optional) – When ccf_line_mask_stored_negated is true and this lies on the velocity grid, the discrete peak seed uses argmax(CCF) restricted to samples within a local window around this value (typically ccf_input_velocity), instead of the global maximum on the full grid. That avoids spurious seeds on stacked mean CCFs and aligns pass-1 with the injected search center.

Returns:

tuple – If return_params is False: (rv_ms, rv_err_ms). If True: (rv_ms, rv_err_ms, params, diag) with fitted Gaussian parameters and diagnostic metadata.

Notes

Design parallels public KPF PRV CCF-fitting ideas; see module References. When both the gradient-based CCF error and the Levenberg–Marquardt covariance on the Gaussian mean pass plausibility checks, CCFFitConfig field rv_err_cov_combine chooses ``min`` (historic) or ``max`` (more conservative; default).

Optional parametric bootstrap (rv_err_bootstrap_samples > 0): repeatedly add i.i.d. N(0, ccf_err) noise to the final-window CCF samples, refit the weighted Gaussian, and take the sample standard deviation of fitted means (m/s). The reported rv_err is at least that bootstrap scatter when bootstrap runs (still diagonal / uncorrelated noise; see Notes).

Self-consistency of ``ccf_err`` → ``rv_err`` (what is *not* done).

  • ccf_err is used only as diagonal inverse-variance weights 1/σ² on the raw CCF samples inside each fit window (Gaussian + constant model). For the line-mask primitive (ccf_line_mask), those σ come from the weighted SD of per-line \(F\,\mathrm{SN}\) about the chunk CCF, then combined across chunks as a standard error of the mean; this is not a full propagation from pixel flux errors, and bin-to-bin correlations in \(v\) are ignored.

  • The Levenberg–Marquardt covariance on the Gaussian mean (when returned by Astropy) is a local linearization error for the weighted nonlinear fit; it does not add systematic terms from model mismatch (true line profile ≠ Gaussian).

  • The gradient-based _gradient_ccf_err_km branch uses gradients of the raw CCF (√|CCF| scaling) and does not use ccf_err. It returns 0 if any CCF sample in the fit window is negative, so for strongly absorption-shaped curves the gradient branch may be inactive and rv_err relies on covariance or fallbacks. With rv_err_cov_combine="min", ``min(gradient, cov)`` can still yield an optimistically small rv_err; default "max" is more conservative.

  • If the LM Gaussian width collapses toward zero, the formal covariance on the mean can reach ~1e-16 m/s while still passing _ok_err; such fits set diag["lm_gaussian_width_plausible"]=False, drop the covariance branch, and combine rv_err with _rv_err_slope_propagation_m_s() (CCF + ccf_err) and a widened σ/√n fallback using v_step.

  • When the LevMar covariance is used for rv_err, slope propagation is still computed for diag["rv_err_slope_propagation_m_s"] but is not forced as a minimum on rv_err (no 200 km/s-style floor from max(rv_err, σ_slope)).

fit_ccf_rv_bisector(v_grid_m_s, ccf, v_step_m_s, *, ccf_err=None, config=None, return_diagnostics=False, gaussian_seed_mean_m_s=None)[source]

Radial velocity (m/s) from a traditional CCF bisector analysis.

At each depth percentile between baseline and peak, finds the left and right wing velocities where the CCF crosses that flux level and takes their midpoint. The RV estimate and its uncertainty are a performance-weighted mean of midpoints over config.rv_percentile_lo … config.rv_percentile_hi, with Gaussian weight emphasizing the CCF core (50% depth). The reported σ is the weighted average of per-cut midpoint uncertainties (\(\sum_i w_i e_i\,/\,\sum_i w_i\)), not an independent-cut \(1/\sqrt{N}\) reduction.

Also computes bisector inverse slope (BIS) following NEID-DRP: average midpoints in the top (60–90%) minus bottom (10–40%) sections, with the same weighted-mean uncertainty on each section.

Parameters:
  • v_grid_m_s (np.ndarray) – Velocity samples (m/s), need not be uniform.

  • ccf (np.ndarray) – CCF values on the same grid.

  • v_step_m_s (float) – Effective finest velocity spacing (m/s) for uncertainty floors; use effective_ccf_v_step_for_fit() on v_grid_m_s.

  • ccf_err (np.ndarray or None, optional) – Per-sample CCF uncertainty for wing-crossing error propagation.

  • config (CCFBisectorConfig or None, optional) – Bisector percentile ranges and weighting.

  • return_diagnostics (bool, optional) – If True, return (rv, rv_err, diag) with per-cut midpoints, BIS, etc.

  • gaussian_seed_mean_m_s (float or None, optional) – When set (typically the Gaussian CCF fit center), the bisector peak index is the sample nearest this velocity (with a small local refine). Do not re-search argmax(|CCF − baseline|) over a multi-km/s window: a global contrast search can lock onto a window edge when the core has near-zero contrast relative to an unweighted continuum.

Returns:
  • rv_m_s, rv_err_m_s (float) – Weighted bisector RV and combined uncertainty (m/s).

  • diag (dict, optional) – Present when return_diagnostics=True.

fit_ccf_rv_rows_numba(v_grid_m_s, ccf_rows, *, ccf_err_rows=None, gaussian_seed_mean_m_s=None, pass1_half_width_m_s=800000.0, pass2_half_width_m_s=120000.0, initial_stddev_m_s=5000.0, levmar_maxiter=450, min_points=5, max_cores=None, pix_size_m_s=None)[source]

Parallel Gaussian centroids for peak-up CCF rows.

Parameters:
  • v_grid_m_s – Shared velocity grid (m s⁻¹), shape (n_v,).

  • ccf_rows – CCF values, shape (n_chunk, n_v), peak-up (absorption as positive lobe).

  • ccf_err_rows – Optional per-sample σ, same shape as ccf_rows.

  • gaussian_seed_mean_m_s – Optional discrete-peak seed center (m s⁻¹).

  • pix_size_m_s – Detector pixel width in velocity (m s⁻¹). When set, σ_μ is inflated by √nsp with nsp = max(pix_size / Δv_grid, 1) so oversampled CCF bins that share pixels are not treated as independent.

  • max_cores – Numba thread cap for prange.

Returns:

rv, rv_err, ok – Arrays length n_chunk (ok is int64 0/1).

flat_chunk_echelle_orders(order_tasks, chunk_start, n_flat)[source]

Echelle order number for each flattened chunk index (same packing as process_orders_rvs_numba_parallel()).

chunk_start[j] is the global flat index of the first chunk of order_tasks[j] ((order_row_index, echelle_order_number)).

Parameters:
  • order_tasks (list of tuple) – (order_row_index, echelle_order_number) in the same order as used to build chunk_start and n_chunks_per_order.

  • chunk_start (np.ndarray) – Cumulative start index of each order’s chunks in the flattened all_rvs layout.

  • n_flat (int) – Total number of chunk slots (rows) in the flattened arrays.

Returns:

np.ndarray – dtype int64, length n_flat. For each flat chunk index i, the echelle order number of the order that owns that chunk, or -1 where i is out of range.

flat_chunk_wl_lo_hi(wave_2d, order_indices, n_chunks_per_order, chunk_start, total_chunks)[source]

Wavelength bounds per flattened chunk index (matches Numba chunking in _process_all_orders_ccf_numba()).

line_mask_chunk_restrict_velocity_range_m_s(wl_lo_um, wl_hi_um, *, v_prior_m_s, v_span_lo, v_span_hi)[source]

Velocity bounds for restrict_mask_to_chunk() on one line-window chunk.

Combines the pipeline prior v_prior_m_s (ccf_input_velocity) with the chunk wavelength span \([\lambda_{\rm lo},\lambda_{\rm hi}]\) via \(\Delta v \approx c\,(\lambda_{\rm hi}-\lambda_{\rm lo})/\bar\lambda\), intersected with [v_span_lo, v_span_hi] (already the tightened coarse span when line-window mode is active).

line_mask_line_window_velocity_half_width_m_s(wave, order_tasks, mask_lines, *, v_center_m_s, zb, min_good_pixels, half_width_m_s, v_step_m_s)[source]

Effective half-width (m/s) for a uniform centered CCF grid in line-window mode.

Returns the caller half-width (floored by a few velocity steps) for build_centered_uniform_velocity_grid(), plus the maximum Voronoi chunk Doppler span \(c\,\Delta\lambda/\lambda\) for logging.

The CCF grid is not expanded to the Voronoi chunk span: that produced \(10^5\)–\(10^6\)-point grids for sparse/line-by-line masks. Per-chunk mask membership still uses line_mask_chunk_restrict_velocity_range_m_s() with the chunk Δλ.

line_mask_n_chunks_for_order_line_by_line(wave_um, mask_lines, *, v_center_m_s, zb, min_good_pixels=10)[source]

Return n_chunk for one order under build_line_mask_chunk_wavelength_intervals_line_by_line().

mask_line_window_spectrum_band_um(wl_center_um, window_size_um, w_min_um, w_max_um, *, rel_pad=None)[source]

Observed-frame µm interval for spectrum + mask-CCF pixels in line-window line-mask.

Band is centered on wl_center_um (predicted observed mask-line λ at the chunking velocity) with total width window_size_um * (1 + rel_pad), clipped to the echelle pixel support [w_min_um, w_max_um].

masked_ccf_rv(wave, spec, spec_err, mask, template_ln, template_flux, v_min=-500000.0, v_max=500000.0, v_step=500.0, *, v_grid=None, zb=0.0, min_good_pixels=10, return_ccf=False, diagnostics=False)[source]

Radial velocity from a single masked spectrum via log-λ CCF and Gaussian peak fit.

Builds a weighted covariance CCF on a velocity grid, then calls fit_ccf_rv() (sub-grid RV); on failure uses the grid peak and a HWHM-based error.

Parameters:
  • wave (np.ndarray) – Wavelength per pixel, micron.

  • spec (np.ndarray) – Flux and uncertainty.

  • spec_err (np.ndarray) – Flux and uncertainty.

  • mask (np.ndarray) – Boolean bad-pixel mask; ``True`` excludes the pixel from the weighted CCF.

  • template_ln (np.ndarray) – Stellar template sampled on natural log wavelength (ln µm) and flux, covering the observed wavelength interval.

  • template_flux (np.ndarray) – Stellar template sampled on natural log wavelength (ln µm) and flux, covering the observed wavelength interval.

  • v_min (float, optional) – Uniform CCF velocity range and step (m/s) when v_grid is not passed. Ignored if v_grid is given.

  • v_max (float, optional) – Uniform CCF velocity range and step (m/s) when v_grid is not passed. Ignored if v_grid is given.

  • v_step (float, optional) – Uniform CCF velocity range and step (m/s) when v_grid is not passed. Ignored if v_grid is given.

  • v_grid (np.ndarray or None, optional) – Explicit velocity samples (m/s), e.g. from build_centered_uniform_velocity_grid(). When passed, v_min / v_max / v_step are not used to build the grid.

  • zb (float, optional) – Barycentric factor in the template \(\ln\lambda\) shift (see _ccf_chunk_ccf_numba()).

  • min_good_pixels (int, optional) – Minimum good pixels required before building the CCF and fitting.

Returns:

tuple –

  • Default: (rv, rv_err) with RV and uncertainty (m/s).

  • return_ccf=True: (rv, rv_err, v_grid, ccf).

  • diagnostics=True: (rv, rv_err, diagnostics).

  • Both flags: (rv, rv_err, v_grid, ccf, diagnostics).

Notes

Calls fit_ccf_rv() for sub-grid Gaussian RV when the weighted CCF is valid; otherwise falls back to the discrete peak with a HWHM-style error estimate.

See also

rv_per_chunks

Per-chunk CCFs along an order.

median_pixel_dv_m_s(wave_um)[source]

Median detector-pixel velocity width (m/s) from a 1-D wavelength row.

numba_thread_scope(num_threads=None)[source]

Temporarily set Numba’s thread pool, then restore the previous setting.

On entry, this uses the same logic as resolve_numba_threads(): it determines the maximum number of threads Numba allows on this build (probed once and cached; often matches CPU count but may be as low as 2 on CI), then sets the active count to num_threads clamped to that maximum and to os.cpu_count(). This addresses environments where set_num_threads(6) raises because Numba enforces Nthreads <= 2.

Parameters:

num_threads (int or None, optional) – Explicit thread count, or None / 0 for all logical CPUs (capped). Default is None.

Examples

>>> with numba_thread_scope(4):  # noqa: SIM117
...     ...  # Numba parallel regions here
pixel_edges_from_wavelength(wave_um)[source]

Pixel bin left/right edges (µm) from a sorted wavelength array (midpoints + end padding).

prepare_template_for_doppler_paint(wave_rest_um, flux_rest, wave_obs_um, *, samples_per_pixel=8.0, resolution_floor=300000.0, resolution_ceiling=10000000.0)[source]

Densify a rest-frame spectrum for doppler_paint_lanczos().

Inserts PCHIP knots only where local R falls below the value returned by template_min_resolution_for_doppler_paint() for wave_obs_um. Native samples are preserved (see simulate_rate_map._upsample_spectrum).

Returns:

wave_rest_um, flux_rest – Float64 arrays, strictly ascending wavelength.

process_all_orders_rvs_numba(wave_2d, spec_2d, spec_err_2d, dq_2d, do_not_use, template_ln, template_flux, window_size_um, order_indices, n_chunks_per_order, chunk_start, v_min, v_max, v_step, *, return_ccf=False, numba_threads=None, ccf_center_m_s=None, ccf_half_window_m_s=20000.0, min_good_pixels=10, zb=0.0)[source]

High-throughput per-chunk RVs: Numba CCF grid, then SciPy Gaussian per chunk.

Workhorse behind process_orders_rvs_numba_parallel().

When ccf_center_m_s is None, uses a single grid (v_min, v_max, v_step).

When ccf_center_m_s is set, uses a uniform centered window center ± ccf_half_window_m_s sampled at v_step (see build_centered_uniform_velocity_grid()).

process_one_order_rvs(wave, spec, spec_err, dq, do_not_use, template_ln, template_flux, window_size_um, do_continuum_normalize=False, continuum_lowpass_window=None, continuum_poly_order=None, *, return_ccf=False, ccf_v_min=None, ccf_v_max=None, ccf_v_step=None, ccf_center_m_s=None, ccf_half_window_m_s=20000.0)[source]

One echelle order: clip template, optional continuum norm, chunk RVs.

Serial-friendly (picklable) path used when not using the Numba multi-order driver. Returns empty arrays if the template has fewer than 20 points in the order wavelength range. When ccf_center_m_s is set, delegates to process_orders_rvs_numba_parallel() (centered uniform window).

Parameters:
  • wave (np.ndarray) – 1-D wavelength (micron), flux, uncertainty.

  • spec (np.ndarray) – 1-D wavelength (micron), flux, uncertainty.

  • spec_err (np.ndarray) – 1-D wavelength (micron), flux, uncertainty.

  • dq (np.ndarray, uint32) – Data quality; pixels with (dq & do_not_use) != 0 are masked.

  • do_not_use (int) – DQ bitmask for bad pixels.

  • template_ln (np.ndarray) – Full-template arrays (log micron, flux).

  • template_flux (np.ndarray) – Full-template arrays (log micron, flux).

  • window_size_um (float) – Wavelength chunk width (micron).

  • do_continuum_normalize (bool, optional) – If True and a continuum option is set, normalize flux before CCF.

  • continuum_lowpass_window (int or None, optional) – Passed to continuum_normalize().

  • continuum_poly_order (int or None, optional) – Passed to continuum_normalize().

  • return_ccf (bool, optional) – If True, also return v_grid and per-chunk CCF ccf_2d (uses ccf_v_min / ccf_v_max / ccf_v_step or defaults _V_*).

  • ccf_v_min (float or None, optional) – Uniform velocity grid (m/s). When ccf_center_m_s is set, ccf_v_step samples the centered window; otherwise they define the sole grid for rv_per_chunks(). Defaults use module V_MIN_DEFAULT_M_S, V_MAX_DEFAULT_M_S, V_STEP_DEFAULT_M_S.

  • ccf_v_max (float or None, optional) – Uniform velocity grid (m/s). When ccf_center_m_s is set, ccf_v_step samples the centered window; otherwise they define the sole grid for rv_per_chunks(). Defaults use module V_MIN_DEFAULT_M_S, V_MAX_DEFAULT_M_S, V_STEP_DEFAULT_M_S.

  • ccf_v_step (float or None, optional) – Uniform velocity grid (m/s). When ccf_center_m_s is set, ccf_v_step samples the centered window; otherwise they define the sole grid for rv_per_chunks(). Defaults use module V_MIN_DEFAULT_M_S, V_MAX_DEFAULT_M_S, V_STEP_DEFAULT_M_S.

  • ccf_center_m_s (float or None, optional) – When finite, delegates to process_orders_rvs_numba_parallel() on this single order with a uniform window centered here. When None, uses the uniform broad grid only (via rv_per_chunks).

  • ccf_half_window_m_s (float, optional) – Half-width (m/s) of the centered uniform window when ccf_center_m_s is set.

Returns:
  • rvs (np.ndarray) – Per-chunk RV (m/s).

  • rv_errs (np.ndarray) – Per-chunk uncertainties (m/s).

  • chunk_centers (np.ndarray) – Chunk center wavelengths (micron).

  • v_grid, ccf_2d (np.ndarray, optional) – Returned only when return_ccf is True.

See also

process_orders_rvs_numba_parallel

Faster path for many orders at once.

process_orders_rvs_numba_parallel(wave_2d, spec_2d, spec_err_2d, dq_2d, do_not_use, template_ln, template_flux, window_size_um, order_tasks, max_cores=None, *, return_ccf=False, ccf_v_min=None, ccf_v_max=None, ccf_v_step=None, ccf_center_m_s=None, ccf_half_window_m_s=20000.0, min_good_pixels=10, zb=0.0)[source]

Stellar-RV fast path: many orders × wavelength chunks in one call.

Flattens order_tasks into chunk index arrays, runs process_all_orders_rvs_numba() (Numba CCF + Python Gaussian fit per chunk), and optionally sets Numba thread count via max_cores.

Parameters:
  • wave_2d (np.ndarray, shape (n_orders, n_pix)) – Wavelength in micron.

  • spec_2d (np.ndarray) – Flux and uncertainty per order.

  • spec_err_2d (np.ndarray) – Flux and uncertainty per order.

  • dq_2d (np.ndarray, uint32) – Data quality flags.

  • do_not_use (int) – Bit mask; pixels with (dq & do_not_use) != 0 are excluded.

  • template_ln (np.ndarray) – Full stellar template.

  • template_flux (np.ndarray) – Full stellar template.

  • window_size_um (float) – Wavelength span per chunk (micron).

  • order_tasks (list of tuple) – (order_row_index, order_number) for each order to include.

  • max_cores (int, optional) – Numba parallel thread count for the order-parallel CCF loop. None or 0 uses all logical CPUs (see resolve_numba_threads()). 1 forces single-threaded execution (reproducible, slower).

  • return_ccf (bool, optional) – If True, also return per-chunk CCF stacks, the velocity grid, per-chunk order_indices, and per-chunk good-pixel counts for previews / RVCCF supplements (see implementation return tuple).

  • ccf_v_min (float, optional) – Uniform CCF velocity range (m/s). When ccf_center_m_s is set, ccf_v_step is the sampling of the centered window (ccf_v_min / ccf_v_max are unused). Defaults are V_MIN_DEFAULT_M_S, V_MAX_DEFAULT_M_S, V_STEP_DEFAULT_M_S.

  • ccf_v_max (float, optional) – Uniform CCF velocity range (m/s). When ccf_center_m_s is set, ccf_v_step is the sampling of the centered window (ccf_v_min / ccf_v_max are unused). Defaults are V_MIN_DEFAULT_M_S, V_MAX_DEFAULT_M_S, V_STEP_DEFAULT_M_S.

  • ccf_v_step (float, optional) – Uniform CCF velocity range (m/s). When ccf_center_m_s is set, ccf_v_step is the sampling of the centered window (ccf_v_min / ccf_v_max are unused). Defaults are V_MIN_DEFAULT_M_S, V_MAX_DEFAULT_M_S, V_STEP_DEFAULT_M_S.

  • ccf_center_m_s (float or None, optional) – When set, uses a uniform window center ± ccf_half_window_m_s at ccf_v_step; see build_centered_uniform_velocity_grid().

  • ccf_half_window_m_s (float, optional) – Half-width (m/s) of the centered uniform window; default matches StellarRVPrimitive.

  • min_good_pixels (int, optional) – Minimum good spectral pixels per chunk for CCF evaluation and Gaussian RV fit (same role as ccf_min_good_pixels on StellarRVPrimitive).

  • zb (float, optional) – Barycentric factor \(z_b\) in \(\ln\lambda\) template shifts, \(\Delta\ln\lambda = \ln\frac{1+v/c}{1+z_b}\) (matches mask-line mapping when z_b is small).

Returns:
  • all_rvs (np.ndarray) – Per-chunk RV (m/s), 1-D flattened over all orders.

  • all_rv_errs (np.ndarray) – Per-chunk uncertainty (m/s).

  • all_wl (np.ndarray) – Chunk center wavelength (micron).

  • n_chunks_per_order, chunk_start (np.ndarray) – Chunk layout (always returned). Use with flat_chunk_echelle_orders() to map flat chunk index → echelle order number.

  • all_ccf, v_grid, order_indices, all_n_good (np.ndarray, optional) – Extra arrays when return_ccf is True (for preview / RVCCF supplement columns).

Notes

Performance: Phase A (Numba prange over orders) fills total_chunks × n_vel with n_vel ≈ (v_max - v_min) / v_step. Phase B runs fit_ccf_rv() per chunk in a serial Python loop. Dominant levers: numba_threads (max_cores) for Phase A, and optional coarser ccf_v_step if acceptable for the use case.

resolve_ccf_broad_grid_m_s(v_min=None, v_max=None, v_step=None)[source]

Broad uniform CCF velocity grid (m/s); None uses module defaults.

resolve_numba_threads(max_cores)[source]

Map a requested parallelism level to a thread count safe for this host and Numba build.

Uses the same maximum-thread probe and clamping as numba_thread_scope().

  • None or 0: use all logical CPUs, capped to Numba’s maximum.

  • Positive max_cores: use at most that many threads, capped the same way.

This prevents ValueError from set_num_threads on runners where Numba allows fewer threads than os.cpu_count() (e.g. GitHub Actions).

restrict_mask_to_chunk(mask_lines, w_min_um, w_max_um, *, v_min_m_s, v_max_m_s, zb=0.0)[source]

Keep lines whose rest centers can Doppler-shift into [w_min_um, w_max_um] for some velocity in [v_min_m_s, v_max_m_s] (m/s) with denominator (1+zb).

run_ccf_line_mask_for_fiber(*, input_model, fiber, do_orders, order_vec, window_size_um, mask_path, mask_wavelength=None, mask_weight=None, 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, zb=0.0, max_cores=None, want_preview=False, debug_ccf=False, min_good_pixels=10, mask_ccf_pixel_interp_order=3, window_line_by_line=False)[source]

Run line-mask CCF RV for one fiber (StellarRVPrimitive(algorithm="ccf_line_mask")).

Reads SPEC_FIB*, SPEC_ERR_FIB*, SPEC_DQ_FIB*, WAVE_FIB* from input_model, resolves mask lines via stellar_rv_ccf_mask_lines(), and processes each requested echelle order with rv_per_chunks_line_mask(). Per-chunk CCFs use Numba Lanczos / linear sampling (_calc_mask_ccf_chunks_numba() / _poly_interp_sorted_1d(), controlled by mask_ccf_pixel_interp_order and parallelized under max_cores). Final RVs are Gaussian centroids from fit_ccf_rv() (parabolic-vertex refine removed); preview metadata use finalize_ccf_preview_dict().

Parameters:
  • input_model – L2-like datamodel with fiber spectra and wavelengths.

  • fiber (str) – Fiber label (e.g. "A") used in attribute names.

  • do_orders (list of int) – Echelle orders to include.

  • order_vec (list of int) – Full order indexing aligned with array axis 0.

  • window_size_um (float) – Wavelength chunk width (µm).

  • mask_path (str or None) – Path to mask file when not using in-memory mask_wavelength / mask_weight; None selects the packaged default (see README). Loaded via load().

  • mask_wavelength (array-like or None, optional) – When both are set, build the mask in memory (rest wavelengths in µm, weights same length) and ignore mask_path for loading. See stellar_rv_ccf_mask_lines().

  • mask_weight (array-like or None, optional) – When both are set, build the mask in memory (rest wavelengths in µm, weights same length) and ignore mask_path for loading. See stellar_rv_ccf_mask_lines().

  • v_min_m_s (float, optional) – Broad uniform velocity search (m s⁻¹). When ccf_center_m_s is set, only v_step_m_s is used (as the sampling of the centered window); when unset, they define the sole CCF grid.

  • v_max_m_s (float, optional) – Broad uniform velocity search (m s⁻¹). When ccf_center_m_s is set, only v_step_m_s is used (as the sampling of the centered window); when unset, they define the sole CCF grid.

  • v_step_m_s (float, optional) – Broad uniform velocity search (m s⁻¹). When ccf_center_m_s is set, only v_step_m_s is used (as the sampling of the centered window); when unset, they define the sole CCF grid.

  • ccf_center_m_s (float or None) – When ccf_center_m_s is finite, CCF is evaluated on a uniform window center ± ccf_half_window_m_s at v_step_m_s (build_centered_uniform_velocity_grid()). When None / not finite, an auto-center scout runs on the broad grid, then all chunks are evaluated on a centered uniform window at the scout peak.

  • ccf_half_window_m_s (float or None) – When ccf_center_m_s is finite, CCF is evaluated on a uniform window center ± ccf_half_window_m_s at v_step_m_s (build_centered_uniform_velocity_grid()). When None / not finite, an auto-center scout runs on the broad grid, then all chunks are evaluated on a centered uniform window at the scout peak.

  • zb (float, optional) – Barycentric factor for mask shift.

  • max_cores (int or None, optional) – Numba thread count cap forwarded to rv_per_chunks_line_mask() for chunk-parallel mask CCF evaluation.

  • want_preview (bool, optional) – If True, build order-averaged CCF data for Plotly preview.

  • debug_ccf (bool, optional) – Extra logging per order.

  • min_good_pixels (int, optional) – Minimum unmasked finite spectral pixels required per chunk (see rv_per_chunks_line_mask).

  • mask_ccf_pixel_interp_order (int, optional) – Lanczos parameter a on the echelle wavelength axis when evaluating mask CCFs (1 = linear; default 3 = Lanczos-3). Forwarded to rv_per_chunks_line_mask().

  • window_line_by_line (bool, optional) – When true, spectral chunks follow mask lines in the observed frame at ccf_center_m_s (requires finite ccf_center_m_s). Forwarded to rv_per_chunks_line_mask().

Returns:
  • all_wavelengths (np.ndarray) – Chunk center wavelengths (µm).

  • all_rvs (np.ndarray) – Per-chunk RVs (m s⁻¹); within one echelle order, values are identical when the order-mean CCF Gaussian fit succeeds.

  • all_rv_errs (np.ndarray) – Per-chunk uncertainties (same within each order when the Gaussian fit succeeds).

  • all_orders (np.ndarray) – Echelle order index per chunk (-1 if length mismatch).

  • preview_detail (dict or None) – Payload for stellar RV preview, or None.

  • rvccf_chunk_supplement (astropy.table.Table) – Columns CHUNK_ID, N_GOOD, V_MIN, V_MAX, V_STEP, N_VEL, CCF merged into RVCCF_FIB* via assemble_rvccf_fib_table().

Notes

Mask and algorithm provenance: module docstring References; hispecdrp/data/masks/README.md.

rv_per_chunks(wave, spec, spec_err, mask, template_ln, template_flux, window_size_um, v_min=-500000.0, v_max=500000.0, v_step=500.0, *, return_ccf=False)[source]

Split one echelle spectrum into wavelength chunks; one RV per chunk.

Each chunk with at least 20 finite pixels uses _masked_ccf_rv_core() once (Numba CCF when available). Chunks with fewer valid pixels are left as NaN RVs.

Parameters:
  • wave (np.ndarray) – 1-D wavelength samples (µm), same length as spec.

  • spec (np.ndarray) – Flux and per-pixel uncertainty.

  • spec_err (np.ndarray) – Flux and per-pixel uncertainty.

  • mask (np.ndarray) – Boolean; ``True`` excludes pixels from the CCF (same convention as masked_ccf_rv()).

  • template_ln (np.ndarray) – Template on ln(µm) and flux, covering the order’s wavelength span.

  • template_flux (np.ndarray) – Template on ln(µm) and flux, covering the order’s wavelength span.

  • window_size_um (float) – Target chunk width (µm); chunk count is ccf_order_n_chunks_for_span() applied to the order wavelength span.

  • v_min (float, optional) – Uniform velocity grid (m/s) for the CCF inside each chunk.

  • v_max (float, optional) – Uniform velocity grid (m/s) for the CCF inside each chunk.

  • v_step (float, optional) – Uniform velocity grid (m/s) for the CCF inside each chunk.

  • return_ccf (bool, optional) – If True, also return v_grid and a 2-D array ccf_2d with shape (n_chunk, n_vel) (NaN rows where a chunk did not run).

Returns:
  • rvs, rv_errs, chunk_centers (np.ndarray) – Per-chunk RV (m/s), uncertainty (m/s), and chunk center wavelength (µm).

  • v_grid, ccf_2d (np.ndarray, optional) – Returned only when return_ccf=True: shared velocity axis and stacked CCF rows.

See also

masked_ccf_rv

Single-spectrum masked CCF on one segment.

rv_per_chunks_line_mask(wave_um, spec, spec_err, dq_bad_mask, mask_lines, *, window_size_um, v_min_m_s=-500000.0, v_max_m_s=500000.0, v_step_m_s=50.0, v_grid_m_s=None, zb=0.0, max_cores=None, return_ccf=False, min_good_pixels=10, mask_ccf_pixel_interp_order=3, window_line_by_line=False, line_mask_line_chunk_v_center_m_s=None, gaussian_seed_mean_m_s=None)[source]

Compute per-chunk RVs and optional CCF stacks for one echelle order.

By default splits the order into equal-wavelength bins (count from ccf_order_n_chunks_for_span() given the order span and window_size_um), then computes chunk CCF rows in one Numba batch via _calc_mask_ccf_chunks_numba() (parallel over chunks; delta-line interpolation at each Doppler-shifted rest wavelength), followed by a Numba chunk-parallel discrete-peak seed. Chunks on an echelle row are iterated longest λ first (descending chunk-center wavelength, red → blue along the row), so downstream RVCCF rows and mask-overlay segments follow the same ordering as ascending echelle order in the exposure. RV extraction assumes a fixed absorption-line convention for all chunks and orders (fit on -CCF, not data-driven emission/absorption guessing). Peak selection uses a 5-point smoothed CCF and a combined score (wide-window integrated excess above the global median times √prominence) over strict local maxima—favoring the broad, physically coherent peak at the true RV over narrow spurious maxima. A fast Numba estimate is computed first; then chunk RVs are updated with a Numba-parallel Gaussian+fixed-baseline LM centroid (fit_ccf_rv_rows_numba(), same peak-up / fixed-baseline convention as fit_ccf_rv() for line-mask rows). If the Gaussian path does not return a finite RV, the Numba seed is kept. Returns flattened lists of chunk centers and RVs.

ccf_2d is the weight-normalized mask CCF used for RV extraction and stacking; ccf_preview_2d holds the same rows before the per-chunk sign flip applied for ccf_2d (both match the physical weighted CCF up to that convention).

Parameters:
  • wave_um (np.ndarray) – Wavelength (µm), flux, and error; same length. Detector order may decrease in λ (HDF WAVE); each chunk is sorted to increasing λ before pixel edges and interpolation.

  • spec (np.ndarray) – Wavelength (µm), flux, and error; same length. Detector order may decrease in λ (HDF WAVE); each chunk is sorted to increasing λ before pixel edges and interpolation.

  • spec_err (np.ndarray) – Wavelength (µm), flux, and error; same length. Detector order may decrease in λ (HDF WAVE); each chunk is sorted to increasing λ before pixel edges and interpolation.

  • dq_bad_mask (np.ndarray) – True where pixel should be excluded (e.g. DO_NOT_USE).

  • mask_lines (MaskLines) – Full-order mask; restricted per chunk via restrict_mask_to_chunk().

  • window_size_um (float) – Target maximum segment width in µm; one full-order chunk if span ≤ this value. Ignored for chunk count when window_line_by_line is true (still used for the symmetric spectral band about each line’s predicted λ).

  • v_min_m_s (float, optional) – Velocity search grid (m s⁻¹). Ignored when v_grid_m_s is provided.

  • v_max_m_s (float, optional) – Velocity search grid (m s⁻¹). Ignored when v_grid_m_s is provided.

  • v_step_m_s (float, optional) – Velocity search grid (m s⁻¹). Ignored when v_grid_m_s is provided.

  • v_grid_m_s (np.ndarray or None, optional) – Explicit velocity samples (m s⁻¹), e.g. from build_centered_uniform_velocity_grid(). When set, v_min_m_s / v_max_m_s / v_step_m_s are not used to build the grid, but together with v_grid_m_s they still define the velocity span used to restrict mask lines per chunk via restrict_mask_to_chunk() (same coarse bounds passed in).

  • zb (float, optional) – Barycentric factor passed to the CCF shift.

  • max_cores (int or None, optional) – Numba thread count cap for chunk-parallel CCF evaluation and the Numba-parallel Gaussian centroid batch (numba_thread_scope() around _calc_mask_ccf_chunks_numba() / fit_ccf_rv_rows_numba()).

  • return_ccf (bool, optional) – If True, also return mean CCF rows per chunk (stacked for preview).

  • min_good_pixels (int, optional) – Minimum unmasked finite pixels required per chunk.

  • mask_ccf_pixel_interp_order (int, optional) – Lanczos parameter a for sampling flux onto Doppler-shifted mask wavelengths (1 = linear; default 3 = Lanczos-3). Clamped to [1, MAX_MASK_CCF_PIXEL_INTERP_ORDER].

  • window_line_by_line (bool, optional) – When true, chunk by mask lines (requires finite line_mask_line_chunk_v_center_m_s).

  • line_mask_line_chunk_v_center_m_s (float or None, optional) – Observed-frame line-window center (m s⁻¹) for line-by-line chunking; also preferred Gaussian-fit seed when set.

  • gaussian_seed_mean_m_s (float or None, optional) – Optional Gaussian-fit seed (m s⁻¹) when line_mask_line_chunk_v_center_m_s is unset (e.g. centered-grid / auto-scout center).

Returns:
  • rvs (np.ndarray) – Per-chunk RV (m s⁻¹). After the Numba seed, each chunk is replaced by the Numba-parallel Gaussian centroid when that fit returns a finite value; otherwise the Numba seed is kept.

  • rv_errs (np.ndarray) – Per-chunk RV uncertainty (m s−1): Gaussian fit uncertainty when that path succeeds; otherwise the Numba heuristic from _rv_from_ccf_line_mask_numba_single().

  • centers (np.ndarray) – Chunk center wavelength (µm).

  • v_grid (np.ndarray) – Velocity grid used for the CCF.

  • ccf_2d (np.ndarray or None) – If return_ccf, shape (n_chunks, n_v) of weight-normalized CCF rows, sign-flipped per chunk to match the stored absorption-peak convention; used for RVCCF supplements and chunk-level diagnostics. Else None.

  • wl_lo, wl_hi (np.ndarray) – Per-chunk wavelength bounds (µm), same length as rvs.

  • n_good (np.ndarray) – Per-chunk count of good pixels used in the mask CCF.

  • ccf_line_std_2d (np.ndarray or None) – If return_ccf, shape (n_chunks, n_v): per-velocity flux-error–propagated interpolator uncertainty \(\sigma_{\mathrm{meas}}\) (see _calc_mask_ccf_chunks_numba()). Line-to-line flux scatter is not included. Not flipped with the CCF row; use as a symmetric band around ccf_preview_2d. If return_ccf is False, None.

  • ccf_preview_2d (np.ndarray or None) – If return_ccf, same shape as ccf_2d: weight-normalized mask CCF (matching _calc_mask_ccf_chunks_numba()) before the per-chunk sign flip applied for ccf_2d. Else None.

science_centroid_spec_err(spec, spec_err, spec_uncal=None, spec_uncal_err=None)[source]

Per-pixel σ for centroiding blaze-corrected (or native) flux.

A multiplicative fiberflat / blaze error is almost entirely amplitude, not line centroid. When L1 spec_uncal / spec_uncal_err are present, map the science-extract relative error onto spec:

σ = |spec| · |spec_uncal_err / spec_uncal|

(equivalent to σ_uncal / blaze). Fall back to spec_err where those arrays are missing or invalid.

stellar_rv_ccf_mask_lines(*, mask_path, mask_wavelength=None, mask_weight=None)[source]

Resolve mask lines for line-mask CCF (path, default package mask, or in-memory arrays).

template_min_resolution_for_doppler_paint(wave_obs_um, *, samples_per_pixel=8.0, resolution_floor=300000.0, resolution_ceiling=10000000.0)[source]

Minimum template resolving power R = lambda / dlambda for Doppler paint.

Ensures at least samples_per_pixel rest-frame knots span one median observed-pixel width on wave_obs_um. BT-Settl in the BSPEC band is often already R > 3e5 but can still be undersampled for cm/s Doppler paint when only ~one native knot falls inside a BSPEC pixel (~500 m/s wide).

Parameters:
  • wave_obs_um

  • (um) (Observed wavelength grid)

  • the (typically one echelle order from)

  • index. (instrument WAVE solution. May increase or decrease with pixel)

samples_per_pixel

Target number of template samples per observed pixel (default 8).

resolution_floor, resolution_ceiling

Clamp the returned R to [floor, ceiling].

Returns:

float – Resolving power to pass to prepare_template_for_doppler_paint() / simulate_rate_map._upsample_spectrum.

validate_line_mask_line_window_chunking_config(*, algorithm, window_line_by_line, ccf_input_velocity_m_s)[source]

Validate window_line_by_line against algorithm and ccf_input_velocity.

Raises:

ValueError – If line-by-line chunking is enabled but incompatible with the algorithm, or if ccf_input_velocity is missing when line windowing is requested.