hispecdrp.primitives.stellar_rv.previews.stellar_rv_preview

Interactive previews for stellar radial-velocity products.

There are three preview surfaces:

  1. 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. For ccf_line_mask with mask-overlay payload, the top row is the same spectrum/mask content as the standalone *_mask_overlay_debug_fib*.html (initial overlay velocity: finite ccf_input_velocity if set, else 0 m/s; chunk dropdown uses restyle). CCF slot dropdown aligns with the CCF legend (x). CCF panels overlay the Gaussian fit, bisector midpoints / wing chords when bisector_fit is present, and the final Gaussian RV.

  2. Spectrum + CCF overlay debug HTML (write_mask_overlay_debug_pages / write_template_overlay_debug_pages): one shared page implementation (ccf_spectrum_overlay_debug_html + embedded ccf_spectrum_overlay_unified.html.in) with an overlay_kind switch. Mask mode (ccf_line_mask): per-chunk spectrum (equal-µm bins from window_size_um / ccf_order_n_chunks_for_span(), or for window_line_by_line the symmetric window_size_um band about each predicted observed mask line at ccf_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 when LINE_MASK_CCF_STORED_NEGATED_FROM_RAW is true in ccf_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 include ccf_v_m_s and ccf_err (quadrature of flux-error–propagated uncertainty on the mask-weighted mean and weighted line-to-line dispersion of F*SN; see _calc_mask_ccf_chunks_numba), interpolated onto the interactive CCF curve. Payload arrays are downsampled before embedding; limits come from env HISPEC_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 as rv_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]), where N_specpoints is 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

Functions

_aggregated_mask_chunk_rv_for_order(...)

Inverse-variance weighted mean RV and combined σ for all chunks on one echelle order.

_bisector_preview_plotly_traces(fig, row, *, ...)

Overlay bisector cut midpoints (and optional wing chords) from sl["bisector_fit"].

_ccf_slot_dropdown_paper_xy(fig_ccf, ...)

Paper (x, y) for the CCF slot updatemenus dropdown (xref / yref: paper).

_chunk_rv_for_overlay_slot(order_num, ...)

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, ...)

Collapse RV vs wavelength preview points when ccf_line_mask duplicated the same order-level RV/ERR at every wavelength chunk center.

_downsample_ccf_for_plot(v_m_s, y, y_err, ...)

Uniform stride along velocity for long CCF arrays (display only).

_env_flag(name)

_env_positive_int(name, default, *[, floor])

_figure_to_png_bytes_with_timeout(fig, *, ...)

Return PNG bytes or None if Kaleido exceeds timeout_s (process is terminated).

_first_output_model_from_primitive(primitive)

Resolve the first L2 output model from primitive._output['output'].

_fits_base_path(primitive, output_model)

FITS output path stem (with .fits) used for sibling preview HTML/PNG paths.

_format_rv_value(v, *, kind)

Format RV-related numbers for Plotly annotations.

_iterative_sigma_clip_ylim(y, *[, y_err, ...])

Default y-axis limits for RV scatter: iterative sigma clipping on finite values, then padding so the panel spans the "good" points.

_json_float_list_sigfig(seq[, n_sig])

JSON-friendly floats using n_sig significant figures.

_json_opt_float(x)

_json_round_list(seq[, ndigits])

Shorter JSON than full float repr; sufficient for Plotly + linear interp in the overlay.

_kaleido_render_png_worker(fig_json, scale)

Render one Plotly figure to PNG in an isolated process (for timeout/kill).

_line_mask_preview_gaussian_overlay_params(sl, ...)

Display-only Gaussian (amplitude, v0, sigma, baseline) for line-mask CCF previews.

_line_mask_refine_ccf_add_plotly_traces(fig, ...)

For ccf_line_mask, overlay a vertical line at the pipeline final RV (Gaussian fit centroid) plus bisector diagnostic traces.

_line_mask_refine_plotly_traces_from_cached_rmeta(...)

Build five line-mask refine overlay traces from rmeta (Gaussian final RV).

_mask_overlay_downsample_limits()

Max points per order for embedded spectrum (wave, spec) and CCF σ(v) in overlay HTML.

_mask_overlay_spec_interp_curve(w_native_um, ...)

Dense λ grid + Lagrange-interpolated median-normalized spectrum (same convention as mask CCF).

_mask_unique_sorted_xy(w, y)

Finite (w,y), ascending w; duplicate w → mean y (stable for Lagrange stencil).

_overlay_v_init_m_s(primitive)

Initial RV (m/s) for spectrum+CCF overlay HTML: ccf_input_velocity when finite, else 0.

_per_order_pipeline_rv_iv_mean_m_s(tbl)

Per-echelle-order inverse-variance mean RV ± σ from RVCCF (m/s).

_pipeline_rv_avg_from_tables(output_model, fiber)

RVCCFAVG RV / RV_ERR in m/s (same reference as the top RV panel).

_pipeline_rv_for_line_mask_preview_slot(tbl, sl)

Single-chunk RV / RV_ERR from RVCCF (m/s) when rvccf_chunk_id is set on the slot.

_plotly_domain_axis_refs(row_1based)

Return (xref, yref) for annotation coordinates in subplot row_1based (1-based).

_plotly_subplot_x_anchor_name(row_1based)

Plotly x-axis anchor for subplot row row_1based (1-based): x, x2, …

_poly_interp_sorted_1d_numpy(xq, x, y, order)

Lagrange interpolation on sorted x (ascending); matches Numba _poly_interp_sorted_1d().

_preview_abbrev_ccf_uncertainty(diag)

Short legend text for how RV uncertainty was estimated (fit_ok only).

_preview_ccf_velocity_range_m_s(primitive)

Velocity extent for CCF preview axes (m/s).

_preview_ccf_y_limits(ccf)

Y-limits for CCF / residual panels: robust data range plus symmetric padding.

_preview_export_combined_html(primitive, ...)

Write unified HTML (and optional stacked PNG), optionally open browser.

_preview_gaussian_cache_and_slot_legends(...)

Pipeline RV summaries, per-slot Gaussian cache, and CCF-panel HTML legend strings.

_preview_gaussian_curve_v_range_m_s(v0_m_s, ...)

Velocity range for drawing the Gaussian CCF model in the preview.

_preview_kaleido_png_max_ccf_traces()

_preview_kaleido_png_timeout_s()

_preview_max_plot_slots()

How many CCF slots (mean + orders) to embed in the Plotly HTML preview.

_preview_should_write_png(primitive)

Whether to run Kaleido PNG export.

_preview_slots_for_plot(slots)

Truncate preview slots so HTML stays small (default: fiber-mean only).

_primitive_output_dir(primitive)

_rv_sidebar_paper_xy(fig, row_1based, y_frac)

Paper coordinates for RV sidebar text beside the RV vs λ axes (not the full SVG).

_rvcc_hover_order_segment_line(order_col, ...)

One hover line per RVCCF scatter point: Order m, Segment k/n.

_slot_by_order_chunk_from_line_mask_preview(prev)

Map (echelle ORDER, chunk index along that order) → CCF preview slot dict.

_template_overlay_max_template_points_from_env()

Max rest-frame template samples per order embedded in template-overlay debug HTML.

_to_serializable_order_payload(order_payload)

_to_serializable_template_overlay_payload(...)

_truthy_env(name)

_write_ccf_overlay_debug_html_pages(...)

Shared writer for write_mask_overlay_debug_pages() / write_template_*.

collect_mask_overlay_payload_for_primitive(...)

Build per-chunk spectrum + mask payload for mask-overlay debug HTML (ccf_line_mask).

collect_template_overlay_payload_for_primitive(...)

Build per-chunk spectrum + cropped rest-frame template for template-overlay debug HTML.

create_stellar_rv_preview(primitive)

Writes *_preview.html with two Plotly embeds:

maybe_write_ccf_overlay_debug_html(...)

When overlay debug is enabled for the active algorithm, write HTML and merge paths into output_extras (mask_overlay_debug or template_overlay_debug).

write_mask_overlay_debug_pages(primitive, ...)

Write debug HTML overlays for mask-shift RV and optionally open them.

write_template_overlay_debug_pages(...)

Write debug HTML for ccf_stellar_template: spectrum + Doppler-shifted template overlay.

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
_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_levels curve 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 slot updatemenus dropdown (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_mask duplicated 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_um along 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 of RVCCF. 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 None if Kaleido exceeds timeout_s (process is terminated).

_first_output_model_from_primitive(primitive)[source]

Resolve the first L2 output model from primitive._output['output'].

Returns None if 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_err is provided (same length as y), limits expand to the full extent of y ± y_err for the sigma-clipped inliers so per-chunk error bars are not clipped by the axes. Flagged outliers should be omitted from y / y_err by the caller.

_json_float_list_sigfig(seq, n_sig=8)[source]

JSON-friendly floats using n_sig significant 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 chosen ndigits. 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 same sigma sanity 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 None if not enough points.

_mask_unique_sorted_xy(w, y)[source]

Finite (w,y), ascending w; duplicate w → mean y (stable for Lagrange stencil).

_overlay_v_init_m_s(primitive)[source]

Initial RV (m/s) for spectrum+CCF overlay HTML: ccf_input_velocity when 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, and ORDER ≥ 0 so the summary matches the scatter point(s) for that order (inlier or outlier).

_pipeline_rv_avg_from_tables(output_model, fiber)[source]

RVCCFAVG RV / 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) when rvccf_chunk_id is 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 domain for the first row only; x1 domain is invalid (enumerated xref pattern starts at bare x or x2, …).

_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_window about ccf_input_velocity when set, otherwise ±v_half_window about 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_hi window (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 around v0 scaled by sigma instead.

_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_PREVIEWS is set (typical interactive / test preview runs), PNG export is disabled and only HTML is written when save_preview is True.

Otherwise, when save_preview is 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), with x, y in [0, 1]. The right edge of the data panel is x=1; we Return x=1.0; call sites add xshift=RV_SIDEBAR_XSHIFT_PX (px) so the box clears the axes. Do not convert figure margins into x here — that put labels near x≈0.6 and overlapped the scatter.

y_frac is 0 = bottom, 1 = top of that subplot row, using that row’s yaxis domain.

_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) and ccf_stellar_template (Doppler-shifted template trace). spectrum_help_html is 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 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.

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.

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() and window_size_um on the primitive. Pixel gates follow rv_per_chunks_line_mask (finite flux/error, not DO_NOT_USE); chunks with fewer than ccf_min_good_pixels included pixels are omitted.

Each row still uses key order for the echelle order number plus chunk_index / chunk_n for the segment on that order. Segments on an echelle row are ordered descending in chunk-center wavelength (red → blue), matching rv_per_chunks_line_mask(). Payload rows include voronoi_lo_um / voronoi_hi_um (line-window Voronoi chunk bounds), spectrum_band_lo_um / spectrum_band_hi_um (symmetric window_size_um band used for pixels, slightly padded), window_edge_lo_um / window_edge_hi_um (±½``window_size_um`` at ccf_input_velocity for guide lines), and chunk_center_um (mean predicted observed mask-line λ in the chunk). Mask lines and weights match restrict_mask_to_chunk() for each chunk span.

When per-chunk pipeline RV arrays are supplied, fit_rv_m_s / fit_rv_err_m_s match the chunk center wavelength when chunk_wavelength_um aligns 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 same DO_NOT_USE + finite flux/error gate as mask CCF, with a minimum of ccf_min_good_pixels pixels per chunk.

ccf on each row is optional; when present with ccf_v_m_s it 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_flux are the template in vacuum rest microns over each chunk span (plus margin). Template crop length is capped by env HISPEC_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_errs with combine_rvs_median_mad() (|Δ| <= outlier_sigma * max(MAD, σ_i)). Per-chunk rv_errs are scaled by rv_err_inflation only for IVW weights (default 3.5) so the mean is not dominated by underdispersed formal σ. The reported rv_std is \(\max(\sigma_{\mathrm{IVW}},\,\mathrm{MAD}/\sqrt{N})\) of the inliers: photon-weighted IVW when it is honest, and the empirical line scatter when formal σ are optimistic or systematics dominate. As per-chunk σ → 0 (infinite S/N), this converges to MAD/√N. If the median formal σ is >10⁶× the inlier MAD (broken Hessian), IVW is discarded and MAD/√N is reported. Inflated IVW SE and empirical MAD/√N are returned as rv_std_internal and scatter_se for diagnostics.

combine_rvs_median_mad(rvs, rv_errs, outlier_sigma=4.0, *, center_m_s=None)[source]

Error-aware robust outlier mask on per-chunk RVs.

Chunks with finite rvs and positive rv_errs set the rejection center (sample median, or center_m_s when finite) and the ensemble MAD. A chunk is kept when

|RV − center| <= outlier_sigma * max(MAD, σ_i)

so points that agree within the MAD are never rejected, while points that are both outside the MAD envelope and inconsistent with their own formal σ_i are rejected. Invalid chunks are marked not inlier.

create_stellar_rv_preview(primitive)[source]

Writes *_preview.html with two Plotly embeds:

  1. RV figure — Pipeline RV vs wavelength (Δ vs ⟨RV⟩). For ccf_line_mask with 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.

  2. 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 around v₀ (not the full LevMar window). For ccf_line_mask, the black dashed vertical line is the final refined RV; for template CCF, a dashed line marks Gaussian v₀. 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*.html for 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_grid for 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, 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)).

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].

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_debug or template_overlay_debug).

Called from StellarRVPrimitive._perform() after per-fiber processing so primitive._mask_overlay_by_fiber / primitive._template_overlay_by_fiber are populated.

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.

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