hispecdrp.primitives.stellar_rv.previews.stellar_rv_preview
Interactive previews for stellar radial-velocity products.
There are three preview surfaces:
Default preview (
create_stellar_rv_preview): two Plotly HTML embeds per save — (a) RV vs λ per fiber with its own mode bar; (b) CCF + residual per fiber (linked velocity axes within each fiber), second mode bar, slot dropdown. Forccf_line_maskwith mask-overlay payload, the top row is the same spectrum/mask content as the standalone*_mask_overlay_debug_fib*.html(initial overlay velocity: finiteccf_input_velocityif set, else0m/s; chunk dropdown usesrestyle). CCF slot dropdown aligns with the CCF legend (x). CCF panels overlay the Gaussian fit, bisector midpoints / wing chords whenbisector_fitis present, and the final Gaussian RV.Spectrum + CCF overlay debug HTML (
write_mask_overlay_debug_pages/write_template_overlay_debug_pages): one shared page implementation (ccf_spectrum_overlay_debug_html+ embeddedccf_spectrum_overlay_unified.html.in) with anoverlay_kindswitch. Mask mode (ccf_line_mask): per-chunk spectrum (equal-µm bins fromwindow_size_um/ccf_order_n_chunks_for_span(), or forwindow_line_by_linethe symmetricwindow_size_umband about each predicted observed mask line atccf_input_velocity/mask_line_window_spectrum_band_um()) with shifted mask segments and the pipeline mask CCF per chunk (same Numba grid as RVCCF; the overlay restores the raw weighted mask statistic whenLINE_MASK_CCF_STORED_NEGATED_FROM_RAWis true inccf_utils, matching the absorption-shaped CCF from the data). Template mode (ccf_stellar_template): same chrome, but the spectrum panel overplots the median-normalized rest-frame template Doppler-shifted onto each chunk’s wavelength samples; the CCF panel still uses the pipeline per-order template CCF from_ccf_preview_by_fiber(one curve per echelle order). Template CCF values are weighted covariances in data units and are often much smaller than 10⁻⁷; they are embedded with significant-figure rounding so fixed-decimal JSON does not zero the curve (the main Plotly preview passes float64 arrays and is unaffected). When the pipeline built_ccf_preview_by_fiber, mask mode can includeccf_v_m_sandccf_err(quadrature of flux-error–propagated uncertainty on the mask-weighted mean and weighted line-to-line dispersion ofF*SN; see_calc_mask_ccf_chunks_numba), interpolated onto the interactive CCF curve. Payload arrays are downsampled before embedding; limits come from envHISPEC_DRP_MASK_OVERLAY_SPECTRUM_MAX_POINTS/HISPEC_DRP_MASK_OVERLAY_CCF_MAX_POINTS(template crop length:HISPEC_DRP_TEMPLATE_OVERLAY_MAX_TEMPLATE_POINTS). Lagrange pixel-interpolation curve on the mask spectrum panel (same stencil asrv_per_chunks_line_mask/mask_ccf_pixel_interp_order) is always embedded in mask overlay debug HTML. The dense λ grid size is derived from the displayed spectrum point count:n_dense = 2 * mask_ccf_pixel_interp_order * N_specpoints(clamped to[24, 8192]), whereN_specpointsis the number of points in the plotted blue spectrum trace.
Gaussian reference curves use fit_ccf_rv();
mask geometry uses ccf_utils (mask loaders).
Entry points. create_stellar_rv_preview() builds the standard multi-panel HTML;
maybe_write_ccf_overlay_debug_html() dispatches from the primitive’s algorithm and overlay
flags into the writers below; write_mask_overlay_debug_pages() /
write_template_overlay_debug_pages() write the shared spectrum+CCF overlay pages
(mask vs. template overlay);
collect_mask_overlay_payload_for_primitive() and related helpers assemble mask/spectrum
payloads from ccf_utils and the L2 model. Environment variables
HISPEC_DRP_MASK_OVERLAY_* and HISPEC_DRP_SHOW_BSPEC_BTSETTL_PREVIEWS adjust downsampling and
browser behavior (see in-file constants and call sites).
Notes
Plotly layout code is HISPEC DRP–original. For mask file format and upstream
line lists, see hispecdrp/data/masks/README.md and spirou-ccf/KPF references
in ccf_utils.
References
spirou-ccf masks: https://github.com/edermartioli/spirou-ccf/tree/main/ccf_masks
KPF radial_velocity
src: https://github.com/Keck-DataReductionPipelines/KPF-Pipeline/tree/81609b0ac0ab6d12536fb771bfdd0112001340c3/modules/radial_velocity/src
Functions
Inverse-variance weighted mean RV and combined σ for all chunks on one echelle order. |
|
|
Overlay bisector cut midpoints (and optional wing chords) from |
|
Paper |
|
Per-chunk RV hint for overlay HTML; falls back to IV-mean over chunks on that order. |
|
Collapse RV vs wavelength preview points when |
|
Uniform stride along velocity for long CCF arrays (display only). |
|
|
|
|
|
Return PNG bytes or |
|
Resolve the first L2 output model from |
|
FITS output path stem (with .fits) used for sibling preview HTML/PNG paths. |
|
Format RV-related numbers for Plotly annotations. |
|
Default y-axis limits for RV scatter: iterative sigma clipping on finite values, then padding so the panel spans the "good" points. |
|
JSON-friendly floats using |
|
Shorter JSON than full float repr; sufficient for Plotly + linear interp in the overlay. |
|
Render one Plotly figure to PNG in an isolated process (for timeout/kill). |
Display-only Gaussian (amplitude, v0, sigma, baseline) for line-mask CCF previews. |
|
|
For |
Build five line-mask refine overlay traces from |
|
Max points per order for embedded spectrum (wave, spec) and CCF σ(v) in overlay HTML. |
|
|
Dense λ grid + Lagrange-interpolated median-normalized spectrum (same convention as mask CCF). |
|
Finite (w,y), ascending |
|
Initial RV (m/s) for spectrum+CCF overlay HTML: |
Per-echelle-order inverse-variance mean RV ± σ from |
|
|
|
Single-chunk RV / RV_ERR from |
|
|
Return (xref, yref) for annotation coordinates in subplot |
|
Plotly x-axis anchor for subplot row |
|
Lagrange interpolation on sorted |
Short legend text for how RV uncertainty was estimated (fit_ok only). |
|
|
Velocity extent for CCF preview axes (m/s). |
Y-limits for CCF / residual panels: robust data range plus symmetric padding. |
|
|
Write unified HTML (and optional stacked PNG), optionally open browser. |
Pipeline RV summaries, per-slot Gaussian cache, and CCF-panel HTML legend strings. |
|
|
Velocity range for drawing the Gaussian CCF model in the preview. |
How many CCF slots (mean + orders) to embed in the Plotly HTML preview. |
|
|
Whether to run Kaleido PNG export. |
|
Truncate preview slots so HTML stays small (default: fiber-mean only). |
|
|
|
Paper coordinates for RV sidebar text beside the RV vs λ axes (not the full SVG). |
|
One hover line per RVCCF scatter point: |
Map (echelle |
|
Max rest-frame template samples per order embedded in template-overlay debug HTML. |
|
|
|
|
|
Shared writer for |
|
Build per-chunk spectrum + mask payload for mask-overlay debug HTML ( |
|
Build per-chunk spectrum + cropped rest-frame template for template-overlay debug HTML. |
|
|
Writes |
When overlay debug is enabled for the active algorithm, write HTML and merge paths into |
|
|
Write debug HTML overlays for mask-shift RV and optionally open them. |
Write debug HTML for |
- 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:
objectTunables 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_sfields); RV results fromfit_ccf_rv()are still returned in m s:sup:`−1`.
- _aggregated_mask_chunk_rv_for_order(order_num, chunk_echelle_order, chunk_rv_m_s, chunk_rv_err_m_s)[source]
Inverse-variance weighted mean RV and combined σ for all chunks on one echelle order.
- _bisector_preview_plotly_traces(fig, row, *, sl, vg, ccf, visible, show_legend)[source]
Overlay bisector cut midpoints (and optional wing chords) from
sl["bisector_fit"].Falls back to the Queloz
bisector/bis_levelscurve when NEID percentile cuts are absent. Always appends two traces (real or empty placeholders) so CCF slot dropdown indices stay aligned across slots.
- _ccf_slot_dropdown_paper_xy(fig_ccf, ccf_row_1based, *, legend)[source]
Paper
(x, y)for the CCF slotupdatemenusdropdown (xref/yref:paper).Horizontally matches the CCF legend (
legend["x"],xanchor="left"). Vertically sits near the top of this fiber’s CCF subplot row so the control stays with its panel; the shared legend is placed lower on the figure so the two do not overlap.
- _chunk_rv_for_overlay_slot(order_num, wl_center_um, chunk_echelle_order, chunk_rv_m_s, chunk_rv_err_m_s, chunk_wavelength_centers_um)[source]
Per-chunk RV hint for overlay HTML; falls back to IV-mean over chunks on that order.
- _collapse_line_mask_rv_scatter_rows(wl_um, rv_m_s, rv_err_m_s, inlier, order_col, *, rv_dup_atol_m_s=0.001)[source]
Collapse RV vs wavelength preview points when
ccf_line_maskduplicated the same order-level RV/ERR at every wavelength chunk center.Line-mask mode evaluates the mask statistic on overlapping wavelength segments of width
window_size_umalong each order (multiple chunks per order). When the order-mean Gaussian + refine path succeeds, the pipeline stores one RV per echelle order on every chunk row ofRVCCF. The RV panel should show one marker per order (λ = mean of chunk centers for that order), not one marker per chunk.
- _downsample_ccf_for_plot(v_m_s, y, y_err, max_points)[source]
Uniform stride along velocity for long CCF arrays (display only).
- _env_flag(name)[source]
- _env_positive_int(name, default, *, floor=32)[source]
- _figure_to_png_bytes_with_timeout(fig, *, scale, timeout_s)[source]
Return PNG bytes or
Noneif Kaleido exceedstimeout_s(process is terminated).
- _first_output_model_from_primitive(primitive)[source]
Resolve the first L2 output model from
primitive._output['output'].Returns
Noneif missing or empty.
- _fits_base_path(primitive, output_model)[source]
FITS output path stem (with .fits) used for sibling preview HTML/PNG paths.
- _format_rv_value(v, *, kind)[source]
Format RV-related numbers for Plotly annotations.
mean_ms— signed pipeline mean RV (m/s).sigma_ms— uncertainty in m/s.
- _gaussian_ccf_model(v, amplitude, v0, sigma, baseline)[source]
- _iterative_sigma_clip_ylim(y, *, y_err=None, sigma=3.0, max_iter=5, pad_frac=0.05)[source]
Default y-axis limits for RV scatter: iterative sigma clipping on finite values, then padding so the panel spans the “good” points.
When
y_erris provided (same length asy), limits expand to the full extent ofy ± y_errfor the sigma-clipped inliers so per-chunk error bars are not clipped by the axes. Flagged outliers should be omitted fromy/y_errby the caller.
- _json_float_list_sigfig(seq, n_sig=8)[source]
JSON-friendly floats using
n_sigsignificant figures.Fixed-decimal
round()(as in_json_round_list()) maps typical stellar-template weighted-covariance CCF amplitudes to all zeros when|x| < 0.5·10⁻ⁿfor the chosenndigits. Significant-figure formatting preserves the CCF shape for the overlay HTML.
- _json_opt_float(x)[source]
- _json_round_list(seq, ndigits=8)[source]
Shorter JSON than full float repr; sufficient for Plotly + linear interp in the overlay.
- _kaleido_render_png_worker(fig_json, scale)[source]
Render one Plotly figure to PNG in an isolated process (for timeout/kill).
- _line_mask_preview_gaussian_overlay_params(sl, params, diag, vg, ccf)[source]
Display-only Gaussian (amplitude, v0, sigma, baseline) for line-mask CCF previews.
Uses the LevMar Gaussian centroid
params["v0"]as the final RV, applies the samesigmasanity caps as before, then solves for (amplitude, baseline) by linear least squares on the slot CCF:ccf ≈ amplitude * exp(-0.5 * ((v - v0) / sigma)^2) + baseline.
- _line_mask_refine_ccf_add_plotly_traces(fig, row, *, sl, vg, ccf, params, diag, visible, show_legend, ylim_lo, ylim_hi)[source]
For
ccf_line_mask, overlay a vertical line at the pipeline final RV (Gaussian fit centroid) plus bisector diagnostic traces.Always appends five refine traces (final RV line or empty placeholders), then two bisector traces, so dropdown indices stay aligned.
- _line_mask_refine_plotly_traces_from_cached_rmeta(fig, row, *, rv_r_m_s, rmeta, visible, show_legend, ylim_lo, ylim_hi, bisector_fit=None)[source]
Build five line-mask refine overlay traces from
rmeta(Gaussian final RV).Slots: (0) smoothed ±1σ band, (1) smoothed CCF, (2–3) reserved placeholders (formerly diagnostic overlays; left empty), (4) final Gaussian RV line.
- _mask_overlay_downsample_limits()[source]
Max points per order for embedded spectrum (wave, spec) and CCF σ(v) in overlay HTML.
- _mask_overlay_spec_interp_curve(w_native_um, s_norm, *, pixel_interp_order, n_dense, spec_downsample_lim)[source]
Dense λ grid + Lagrange-interpolated median-normalized spectrum (same convention as mask CCF).
Returns downsampled (wave_um, spec) for JSON embedding, or
Noneif not enough points.
- _mask_unique_sorted_xy(w, y)[source]
Finite (w,y), ascending
w; duplicatew→ meany(stable for Lagrange stencil).
- _overlay_v_init_m_s(primitive)[source]
Initial RV (m/s) for spectrum+CCF overlay HTML:
ccf_input_velocitywhen finite, else 0.
- _per_order_pipeline_rv_iv_mean_m_s(tbl)[source]
Per-echelle-order inverse-variance mean RV ± σ from
RVCCF(m/s).Uses every chunk with finite
RV,RV_ERR> 0, andORDER≥ 0 so the summary matches the scatter point(s) for that order (inlier or outlier).
- _pipeline_rv_avg_from_tables(output_model, fiber)[source]
RVCCFAVGRV / RV_ERR in m/s (same reference as the top RV panel).
- _pipeline_rv_for_line_mask_preview_slot(tbl, sl)[source]
Single-chunk RV / RV_ERR from
RVCCF(m/s) whenrvccf_chunk_idis set on the slot.
- _plotly_domain_axis_refs(row_1based)[source]
Return (xref, yref) for annotation coordinates in subplot
row_1based(1-based).Plotly allows
x domain/y domainfor the first row only;x1 domainis invalid (enumerated xref pattern starts at barexorx2, …).
- _plotly_subplot_x_anchor_name(row_1based)[source]
Plotly x-axis anchor for subplot row
row_1based(1-based):x,x2, …
- _poly_interp_sorted_1d_numpy(xq, x, y, order)[source]
Lagrange interpolation on sorted
x(ascending); matches Numba_poly_interp_sorted_1d().
- _preview_abbrev_ccf_uncertainty(diag)[source]
Short legend text for how RV uncertainty was estimated (fit_ok only).
- _preview_ccf_velocity_range_m_s(primitive)[source]
Velocity extent for CCF preview axes (m/s).
Matches stellar-RV defaults:
±v_half_windowaboutccf_input_velocitywhen set, otherwise±v_half_windowabout 0 — not the ±500 km/s scout grid and not a per-fiber scout-centered refined window (those can sit hundreds of km/s from zero when auto-center fails).
- _preview_ccf_y_limits(ccf)[source]
Y-limits for CCF / residual panels: robust data range plus symmetric padding.
Uses the central ~99.9% of finite values as the data span, then expands by 10% of that span (5% margin on each side) so traces do not sit on the axis edges.
- _preview_export_combined_html(primitive, output_model, fig_rv, fig_ccf, title_unified)[source]
Write unified HTML (and optional stacked PNG), optionally open browser.
- Returns:
output_path_html, output_path_png, wrote_png, combined_html
- _preview_gaussian_cache_and_slot_legends(primitive, output_model, fibers_with_ccf)[source]
Pipeline RV summaries, per-slot Gaussian cache, and CCF-panel HTML legend strings.
- _preview_gaussian_curve_v_range_m_s(v0_m_s, sigma_m_s, v_samples_m_s)[source]
Velocity range for drawing the Gaussian CCF model in the preview.
Do not use the LevMar
fit_v_lo/fit_v_hiwindow (often hundreds of km/s): that stretches the red curve across the panel, hides the peak, and makes residuals look wrong. Use a symmetric span aroundv0scaled bysigmainstead.
- _preview_kaleido_png_max_ccf_traces()[source]
- _preview_kaleido_png_timeout_s()[source]
- _preview_max_plot_slots()[source]
How many CCF slots (mean + orders) to embed in the Plotly HTML preview.
- _preview_should_write_png(primitive)[source]
Whether to run Kaleido PNG export.
PNG via Kaleido is often several seconds for large multi-panel figures; HTML is usually much faster.
When env
HISPEC_DRP_SHOW_BSPEC_BTSETTL_PREVIEWSis set (typical interactive / test preview runs), PNG export is disabled and only HTML is written whensave_previewis True.Otherwise, when
save_previewis True, PNGs are written alongside HTML unless the environment disables them as above.
- _preview_slots_for_plot(slots)[source]
Truncate preview slots so HTML stays small (default: fiber-mean only).
- _primitive_output_dir(primitive)[source]
- _rv_sidebar_paper_xy(fig, row_1based, y_frac)[source]
Paper coordinates for RV sidebar text beside the RV vs λ axes (not the full SVG).
For
xref="paper"/yref="paper", Plotly uses the inner plotting area (inside margins), withx,yin[0, 1]. The right edge of the data panel isx=1; we Returnx=1.0; call sites addxshift=RV_SIDEBAR_XSHIFT_PX(px) so the box clears the axes. Do not convert figure margins intoxhere — that put labels nearx≈0.6and overlapped the scatter.y_fracis 0 = bottom, 1 = top of that subplot row, using that row’syaxisdomain.
- _rvcc_hover_order_segment_line(order_col, wl_um, *, collapsed)[source]
One hover line per RVCCF scatter point:
Order m, Segment k/n.For non-collapsed line-mask rows, segment index follows the same descending chunk-center λ ordering as the pipeline / mask-overlay HTML (red → blue within each echelle order). When
_collapse_line_mask_rv_scatter_rows()merged duplicate order-mean RVs, there is no single segment — label with an order-mean note instead.
- _slot_by_order_chunk_from_line_mask_preview(prev)[source]
Map (echelle
ORDER, chunk index along that order) → CCF preview slot dict.
- _template_overlay_max_template_points_from_env()[source]
Max rest-frame template samples per order embedded in template-overlay debug HTML.
- _to_serializable_order_payload(order_payload)[source]
- _to_serializable_template_overlay_payload(order_payload)[source]
- _truthy_env(name)[source]
- _write_ccf_overlay_debug_html_pages(primitive, output_model, *, kind)[source]
Shared writer for
write_mask_overlay_debug_pages()/write_template_*.
- build_ccf_spectrum_overlay_debug_html(*, title, payload_json, v_init_m_s, v_min_m_s, v_max_m_s, v_step_m_s, zb, c_ms, overlay_kind, spectrum_help_html)[source]
Single interactive page for
ccf_line_mask(mask rectangles) andccf_stellar_template(Doppler-shifted template trace).spectrum_help_htmlis inserted inside the help paragraph (trusted HTML fragment from this package only).
- 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 asdoppler_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]ofwave_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.
- 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 returnsceil(span_um / window_um)so each segment has widthspan_um / n_chunks, which is at mostwindow_um.Used for mask-line CCF chunking (
rv_per_chunks_line_mask()), templaterv_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 forccf_line_maskwhenwindow_line_by_lineis true (seerv_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_*orv_samples_m_s), further clipped to the module absolute limitsV_MIN_DEFAULT_M_S…V_MAX_DEFAULT_M_S(m/s), matching the broad CCF grid used inresolve_ccf_broad_grid_m_s()and related paths.
- collect_mask_overlay_payload_for_primitive(primitive, *, input_model, fiber, order_vec, chunk_rv_m_s=None, chunk_rv_err_m_s=None, chunk_echelle_order=None, chunk_wavelength_um=None)[source]
Build per-chunk spectrum + mask payload for mask-overlay debug HTML (
ccf_line_mask).Chunk wavelength bins match
ccf_order_n_chunks_for_span()andwindow_size_umon the primitive. Pixel gates followrv_per_chunks_line_mask(finite flux/error, notDO_NOT_USE); chunks with fewer thanccf_min_good_pixelsincluded pixels are omitted.Each row still uses key
orderfor the echelle order number pluschunk_index/chunk_nfor the segment on that order. Segments on an echelle row are ordered descending in chunk-center wavelength (red → blue), matchingrv_per_chunks_line_mask(). Payload rows includevoronoi_lo_um/voronoi_hi_um(line-window Voronoi chunk bounds),spectrum_band_lo_um/spectrum_band_hi_um(symmetricwindow_size_umband used for pixels, slightly padded),window_edge_lo_um/window_edge_hi_um(±½``window_size_um`` atccf_input_velocityfor guide lines), andchunk_center_um(mean predicted observed mask-line λ in the chunk). Mask lines and weights matchrestrict_mask_to_chunk()for each chunk span.When per-chunk pipeline RV arrays are supplied,
fit_rv_m_s/fit_rv_err_m_smatch the chunk center wavelength whenchunk_wavelength_umaligns with the run.
- collect_template_overlay_payload_for_primitive(primitive, *, input_model, fiber, order_vec, chunk_rv_m_s=None, chunk_rv_err_m_s=None, chunk_echelle_order=None, chunk_wavelength_um=None)[source]
Build per-chunk spectrum + cropped rest-frame template for template-overlay debug HTML.
Chunking matches
window_size_um/ccf_order_n_chunks_for_span()and the sameDO_NOT_USE+ finite flux/error gate as mask CCF, with a minimum ofccf_min_good_pixelspixels per chunk.ccfon each row is optional; when present withccf_v_m_sit populates the CCF panel from the pipeline preview (still per echelle order in the preview dict, shared by all chunks on that order).tpl_wave_um/tpl_fluxare the template in vacuum rest microns over each chunk span (plus margin). Template crop length is capped by envHISPEC_DRP_TEMPLATE_OVERLAY_MAX_TEMPLATE_POINTS.
- combine_rv_estimates_median_mad_weighted(rvs, rv_errs, outlier_sigma=4.0, *, center_m_s=None, rv_err_inflation=3.5)[source]
Error-aware robust rejection, inverse-variance mean, and IVW uncertainty.
Outlier rejection uses the uninflated per-chunk
rv_errswithcombine_rvs_median_mad()(|Δ| <= outlier_sigma * max(MAD, σ_i)). Per-chunkrv_errsare scaled byrv_err_inflationonly for IVW weights (default 3.5) so the mean is not dominated by underdispersed formal σ. The reportedrv_stdis \(\max(\sigma_{\mathrm{IVW}},\,\mathrm{MAD}/\sqrt{N})\) of the inliers: photon-weighted IVW when it is honest, and the empirical line scatter when formal σ are optimistic or systematics dominate. As per-chunk σ → 0 (infinite S/N), this converges toMAD/√N. If the median formal σ is >10⁶× the inlier MAD (broken Hessian), IVW is discarded andMAD/√Nis reported. Inflated IVW SE and empiricalMAD/√Nare returned asrv_std_internalandscatter_sefor diagnostics.
- combine_rvs_median_mad(rvs, rv_errs, outlier_sigma=4.0, *, center_m_s=None)[source]
Error-aware robust outlier mask on per-chunk RVs.
Chunks with finite
rvsand positiverv_errsset the rejection center (sample median, orcenter_m_swhen finite) and the ensemble MAD. A chunk is kept when|RV − center| <= outlier_sigma * max(MAD, σ_i)so points that agree within the MAD are never rejected, while points that are both outside the MAD envelope and inconsistent with their own formal
σ_iare rejected. Invalid chunks are marked not inlier.
- create_stellar_rv_preview(primitive)[source]
Writes
*_preview.htmlwith two Plotly embeds:RV figure — Pipeline RV vs wavelength (Δ vs ⟨RV⟩). For
ccf_line_maskwith the order-mean+refine path, one marker per echelle order (λ = mean of mask chunk centers) when RVCCF repeats the same RV on every chunk row; otherwise one marker per chunk. Own mode bar.CCF figure — Per fiber, CCF vs velocity (y-axis
CCF) then Residual CCF (raw CCF minus the Gaussian model on the full grid, same units). The Gaussian trace is drawn over a narrow symmetric span aroundv₀(not the full LevMar window). Forccf_line_mask, the black dashed vertical line is the final refined RV; for template CCF, a dashed line marks Gaussianv₀. Dropdown switches slot on both rows; velocity zoom/pan is linked (matches). Own mode bar.
Normalized spectrum + mask lines are not shown here; use
*_mask_overlay_debug_fib*.htmlfor that.Hover is limited to the subplot under the cursor when supported (
hoversubplots='single').
- effective_ccf_v_step_for_fit(v_grid)[source]
Finest positive velocity spacing (m/s) on
v_gridfor CCF RV fits.
- 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,
Gaussian1DplusConst1Don 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). Whenfit_ccf_baseline_free=True, or whenline_mask_line_window_by_lineis true (narrow line-mask line-by-line grids) andccf_line_mask_stored_negatedis not true, the baseline is a freeConst1Dterm 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 whenccf_line_mask_stored_negatedis 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 (seeCCFFitConfig) to stabilize the Gaussian amplitude and width. Within each window the fitter runs unclipped χ² passes on the full sample (repeated LM withlevmar_maxiter), then sigma-clipping refinement with relaxed thresholds on the first clipping rounds. Formal uncertainty may use a KPF-inspiredccf_errorscaling 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_spscaling — typicallyeffective_ccf_v_step_for_fit()onv_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). SetNoneto 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 useweights = 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 (whenreturn_paramsis True) as"ccf_line_mask_stored_negated". UseTruefor mask-line CCF rows produced byrv_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). WhenTrue, the fitter does not use the data-driven emission/absorption heuristic: it assumes a peak-up line (positiveGaussian1Damplitude in scaled units, seed at the discrete maximum) and setsGaussian1D.amplitudelower bound to0so 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 fixConst1D). WhenNone(default), use_line_mask_ccf_fit_free_baseline_requested()withline_mask_line_window_by_lineto decide.line_mask_line_window_by_line (bool or None, optional) – Line-mask line-by-line chunking flag (same meaning as
window_line_by_lineon the primitive). Whenfit_ccf_baseline_freeisNoneand this is true, free-baseline mode is enabled automatically unlessccf_line_mask_stored_negatedis true (see_line_mask_ccf_fit_free_baseline_requested()).gaussian_seed_mean_m_s (float or None, optional) – When
ccf_line_mask_stored_negatedis 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 (typicallyccf_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_paramsis 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,CCFFitConfigfieldrv_err_cov_combinechooses ``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 reportedrv_erris 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_erris used only as diagonal inverse-variance weights1/σ²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_kmbranch uses gradients of the raw CCF (√|CCF|scaling) and does not useccf_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 andrv_errrelies on covariance or fallbacks. Withrv_err_cov_combine="min", ``min(gradient, cov)`` can still yield an optimistically smallrv_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 setdiag["lm_gaussian_width_plausible"]=False, drop the covariance branch, and combinerv_errwith_rv_err_slope_propagation_m_s()(CCF +ccf_err) and a widenedσ/√nfallback usingv_step.When the LevMar covariance is used for
rv_err, slope propagation is still computed fordiag["rv_err_slope_propagation_m_s"]but is not forced as a minimum onrv_err(no 200 km/s-style floor frommax(rv_err, σ_slope)).
- 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 widthwindow_size_um * (1 + rel_pad), clipped to the echelle pixel support[w_min_um, w_max_um].
- maybe_write_ccf_overlay_debug_html(primitive, algo_key, output_model, output_extras)[source]
When overlay debug is enabled for the active algorithm, write HTML and merge paths into
output_extras(mask_overlay_debugortemplate_overlay_debug).Called from
StellarRVPrimitive._perform()after per-fiber processing soprimitive._mask_overlay_by_fiber/primitive._template_overlay_by_fiberare populated.
- resolve_ccf_broad_grid_m_s(v_min=None, v_max=None, v_step=None)[source]
Broad uniform CCF velocity grid (m/s);
Noneuses module defaults.
- 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).
- 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).
- write_mask_overlay_debug_pages(primitive, output_model)[source]
Write debug HTML overlays for mask-shift RV and optionally open them.
- Returns:
dict[str, str] – fiber -> html path
- write_template_overlay_debug_pages(primitive, output_model)[source]
Write debug HTML for
ccf_stellar_template: spectrum + Doppler-shifted template overlay.- Returns:
dict[str, str] – fiber -> html path