Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/post-filter-shg.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The post-retrieval spectral window no longer removes the whole retrieved field for SHG: the session pipeline and the retrieve stage now window with `TraceData.fundamental_window` (for SHG the spectrum window λs, for PG/SD the trace window λm as before) rather than the trace window, which for SHG lies at the second harmonic (#22).
1 change: 1 addition & 0 deletions changelog.d/spectrum-window.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The independent fundamental spectrum is windowed by its own wavelength range, `lams_lims` in `load_and_clean` (λs in the Prepare stage; `lams_min_nm`/`lams_max_nm` in a session), instead of the trace window λm mapped through the interaction's carrier scaling. It defaults to the spectrum's full extent, so an SHG spectrum is no longer cut by twice the trace window, and the spectrum's outer wings now reach the spectral regularisation target and the initial guess unless λs is narrowed. This applies to PG and SD too: `load_and_clean` without `lams_lims` no longer tapers the spectrum at λm. Session files are now `options_version = 3`; a session saved by an earlier croak reads back with λs set to its λm mapped to the fundamental (×2 for SHG), so it prepares its spectrum exactly as before (#23).
1 change: 1 addition & 0 deletions changelog.d/trust-windows.breaking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`auto_third_order_exponent` takes `trace_window` (the trace marginal's wavelengths) and `spectrum_window` (the independent spectrum's; default its full range, where `window` used to apply 210-1000 nm to both) in place of the single `window`, and the marginal-check stage has a trust region for each. The spectrum's region in the GUI defaults to the spectrum's full range, measured or not, so a spectrum crossing 1 µm is no longer clipped at 1000 nm; the trace's region still defaults to 190-1000 nm for a measured trace. Replace `window=w` with `trace_window=w`, and pass `spectrum_window=w` as well to reproduce the old behaviour exactly (#23).
9 changes: 8 additions & 1 deletion croak/gui/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@
from .retrieval_views import ResultPage
from .stage import PageBase
from .stage_dispersion import StageDispersion
from .stage_load import StageLoad, compute_preproc_defaults, trace_signature
from .stage_load import (
StageLoad,
adopt_spectrum_bounds,
compute_preproc_defaults,
trace_signature,
)
from .stage_marginal_check import StageMarginalCheck
from .stage_preprocess import StagePreprocess
from .stage_retrieve import StageRetrieve
Expand Down Expand Up @@ -147,6 +152,7 @@ def _restore_measured(self) -> bool:
state.set_load_data(data)
state.trace_sig = trace_signature(state.load)
state.preproc_defaults = compute_preproc_defaults(data)
adopt_spectrum_bounds(state.preproc, state.preproc_defaults)
# A measured session's loader is a StageLoad (the entry chose it).
cast(StageLoad, self.entry_page)._draw(data)
return True
Expand All @@ -173,6 +179,7 @@ def _restore_simulated(self) -> bool:
state.set_load_data(data)
state.trace_sig = simulated_signature(state.simulated)
state.preproc_defaults = compute_preproc_defaults(data)
adopt_spectrum_bounds(state.preproc, state.preproc_defaults)
loader._draw(data)
if state.simulated.raw_direct:
try:
Expand Down
47 changes: 47 additions & 0 deletions croak/gui/stage_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
"tau_bound_max_fs",
"lamm_bound_min_nm",
"lamm_bound_max_nm",
"lams_bound_min_nm",
"lams_bound_max_nm",
"lam_bound_min_nm",
"lam_bound_max_nm",
)
Expand Down Expand Up @@ -109,6 +111,16 @@ def compute_preproc_defaults(data) -> PreprocParams:
pp.lamm_min_nm, pp.lamm_max_nm = lmin, lmax
pp.lamm_bound_min_nm, pp.lamm_bound_max_nm = lmin, lmax

# independent-spectrum window (fundamental λ): its own extents, if present
if data["lam_spec"] is not None:
# round off the m→nm conversion error first, so a spectrum ending at
# exactly 1000 nm does not ceil to 1001 nm
spec_nm = np.round(np.asarray(data["lam_spec"]) / 1e-9, 6)
smin = float(np.floor(spec_nm.min()))
smax = float(np.ceil(spec_nm.max()))
pp.lams_min_nm, pp.lams_max_nm = smin, smax
pp.lams_bound_min_nm, pp.lams_bound_max_nm = smin, smax

# retrieval grid λ: default to the trace extents × ω0 scaling (= fundamental
# range). Bounds stay generous so the user can widen the grid if needed.
scale = get_interaction(data["interaction"]).omega0_scale
Expand Down Expand Up @@ -146,11 +158,46 @@ def _clamp_preproc_to_bounds(pp: PreprocParams) -> None:
pp.lamm_max_nm = min(
max(pp.lamm_max_nm, pp.lamm_bound_min_nm), pp.lamm_bound_max_nm
)
_clamp_spectrum_window(pp)
for attr in ("tau_min_fs", "tau_max_fs", "taum_min_fs", "taum_max_fs"):
v = getattr(pp, attr)
setattr(pp, attr, min(max(v, pp.tau_bound_min_fs), pp.tau_bound_max_fs))


def _clamp_spectrum_window(pp: PreprocParams) -> None:
"""Clamp the spectrum window λs into its bounds, the spectrum's extent."""
if pp.lams_bound_min_nm is None or pp.lams_bound_max_nm is None:
# no spectrum (any more): its window goes with it
pp.lams_min_nm = pp.lams_max_nm = None
elif pp.lams_min_nm is not None and pp.lams_max_nm is not None:
lo, hi = pp.lams_bound_min_nm, pp.lams_bound_max_nm
low = min(max(pp.lams_min_nm, lo), hi)
high = min(max(pp.lams_max_nm, lo), hi)
# A window that misses a replaced spectrum would clamp to zero width at
# its edge; fall back to the full extent rather than keep a useless one.
if low < high:
pp.lams_min_nm, pp.lams_max_nm = low, high
else:
pp.lams_min_nm = pp.lams_max_nm = None


def adopt_spectrum_bounds(pp: PreprocParams, defaults: PreprocParams) -> None:
"""Take λs's bounds from the reloaded data when a reopened session lacks them.

A session written before the spectrum window existed has its λs migrated
from λm (:meth:`~croak.session.options.SessionOptions.from_dict`) but no
bounds, which are the spectrum's extent and so come from the data. Without
them the Prepare stage would show λs disabled while the window still applies.
The window is then clamped into them; a migrated window that misses the
spectrum falls back to the full extent. Bounds already saved are kept.
"""
if pp.lams_bound_min_nm is not None and pp.lams_bound_max_nm is not None:
return
pp.lams_bound_min_nm = defaults.lams_bound_min_nm
pp.lams_bound_max_nm = defaults.lams_bound_max_nm
_clamp_spectrum_window(pp)


def seed_preproc_defaults(state, *, reset_values: bool = True) -> None:
"""Seed the preprocess parameters from the loaded data extents.

Expand Down
147 changes: 116 additions & 31 deletions croak/gui/stage_marginal_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@
efficiency correction — with an ``Auto`` that matches the marginal centroid onto
the prediction.

The trust region (190–1000 nm for a measured trace; the full loaded range for
the noise-free simulated/synthetic traces) bounds the peak finding, the
Two trust regions bound what enters the checks, one per instrument. The
**trace** trust region (190–1000 nm for a measured trace; the full loaded range
for the noise-free simulated/synthetic traces) bounds the peak finding, the
centroid/width moments, the marginal normalisation and the trace display
scaling, so out-of-band detector noise — strongly amplified by the tilt — cannot
distort either the checks or the colour scaling (the cause of the load preview
"saturating" as the exponent was raised).
"saturating" as the exponent was raised). The **spectrum** trust region (the
spectrum's full range, measured or not) windows the independent spectrum before
the marginal is predicted from it. They are separate because the two are
measured by different instruments and, for SHG, lie an octave apart.

The marginals are plotted against frequency by default: a marginal is a
frequency density and the convolution/centroid/width identities live in
Expand Down Expand Up @@ -84,18 +88,28 @@ class StageMarginalCheck(Stage):
)
HELP = [
(
"Spectral trust region",
"Spectral trust regions",
[
(
"λ range (nm)",
"Lower/upper wavelength bounds (nm) of the trust region. It "
"windows the centroid/width checks and the marginal "
"normalisation, scales the trace display, and Planck-tapers the "
"independent spectrum before the marginal is predicted — so "
"noisy measured wings (amplified by the (λ/µm)^exp tilt) cannot "
"contaminate the prediction. Defaults to 190–1000 nm for a "
"measured trace; the noise-free simulated/synthetic traces "
"default to their full loaded wavelength range.",
"trace λ (nm)",
"Lower/upper wavelength bounds (nm) of the trace's trust "
"region, in the trace's own wavelengths (for SHG, around half "
"the fundamental). It windows the centroid/width checks and the "
"marginal normalisation and scales the trace display, so noisy "
"wings (amplified by the (λ/µm)^exp tilt) cannot distort them. "
"Defaults to 190–1000 nm for a measured trace; the noise-free "
"simulated/synthetic traces default to their full loaded "
"wavelength range.",
),
(
"spectrum λ (nm)",
"Lower/upper wavelength bounds (nm) of the independent "
"spectrum's trust region, in fundamental wavelengths. The "
"spectrum is Planck-tapered to it before the marginal is "
"predicted, so its noisy wings cannot contaminate the "
"prediction. Independent of the trace's region. Defaults to "
"the spectrum's full range (measured, simulated or synthetic); "
"off without a spectrum.",
),
],
),
Expand Down Expand Up @@ -150,12 +164,22 @@ def __init__(self, state):
# noise-free simulated/synthetic traces, 190–1000 nm for measured).
self._trust_nm = (190.0, 1000.0)
self._trust_key: tuple | None = None # the trace a default was seeded for
# The independent spectrum's own region (fundamental λ); re-seeded to the
# spectrum's range whenever the spectrum changes.
self._spec_trust_nm = (100.0, 3000.0)
self._spec_trust_key: tuple | None = None

# -- trust region --
box, form = group("Spectral trust region")
# -- trust regions --
box, form = group("Spectral trust regions")
self.trust = RangeControl(100.0, 3000.0, *self._trust_nm, decimals=0, step=10.0)
self.trust.changed.connect(self._on_trust)
add_wide_row(form, "λ range (nm)", self.trust)
add_wide_row(form, "trace λ (nm)", self.trust)
self.spec_trust = RangeControl(
*self._spec_trust_nm, *self._spec_trust_nm, decimals=0, step=10.0
)
self.spec_trust.changed.connect(self._on_spec_trust)
self.spec_trust.setEnabled(False)
add_wide_row(form, "spectrum λ (nm)", self.spec_trust)
self.controls.addWidget(box)

# -- display --
Expand Down Expand Up @@ -264,12 +288,41 @@ def _seed_trust(self, data) -> None:
self._trust_key = key
self.trust.set_values(*trust) # signal-safe

def _seed_spec_trust(self, data) -> None:
"""Default the spectrum's trust region for a freshly loaded spectrum.

Every spectrum, measured, simulated or synthetic, defaults to its full
range, as Prepare's spectrum window λs does. The trace's 190–1000 nm
default is a heuristic for the trace detector; applied to a spectrum it
would clip one that crosses 1 µm (a 1030 nm Yb spectrum on a 900–1100 nm
spectrometer would keep only its blue wing). Keyed on the entry and the
spectrum, so a manual adjustment survives navigation while a different
spectrum re-defaults. Disabled without a spectrum.
"""
lam_spec = data.get("lam_spec")
has_spectrum = lam_spec is not None and data.get("Ilam_spec") is not None
self.spec_trust.setEnabled(has_spectrum)
if not has_spectrum:
self._spec_trust_key = None
return
# round off the m→nm conversion error before flooring/ceiling
spec_nm = np.round(np.asarray(lam_spec) / 1e-9, 6)
extent = (float(np.floor(spec_nm.min())), float(np.ceil(spec_nm.max())))
key = (self.state.entry, *extent)
if key == self._spec_trust_key:
return
self._spec_trust_nm = extent
self._spec_trust_key = key
self.spec_trust.set_bounds(*extent)
self.spec_trust.set_values(*extent) # signal-safe

def on_enter(self) -> None:
data = self.state.load_data
if data is None:
self.set_status("Load a trace first.")
return
self._seed_trust(data)
self._seed_spec_trust(data)
params = self._loader_params()
enabled = params is not None
self.third_order_check.setEnabled(enabled)
Expand Down Expand Up @@ -315,6 +368,10 @@ def _on_trust(self, lo: float, hi: float) -> None:
self._trust_nm = (lo, hi)
self._draw() # trust only affects display/QC, no re-assembly

def _on_spec_trust(self, lo: float, hi: float) -> None:
self._spec_trust_nm = (lo, hi)
self._draw()

def _on_scale(self, _value: str) -> None:
self._draw()

Expand Down Expand Up @@ -354,7 +411,11 @@ def _auto_exponent(self) -> None:
# along delay), so the fit returns the absolute exponent to apply.
if params.third_order:
marg = marg / third_order_scale(lam, params.third_order_exp)
window = (self._trust_nm[0] * 1e-9, self._trust_nm[1] * 1e-9)
trace_window = (self._trust_nm[0] * 1e-9, self._trust_nm[1] * 1e-9)
spectrum_window = (
self._spec_trust_nm[0] * 1e-9,
self._spec_trust_nm[1] * 1e-9,
)
# Match the *displayed* predicted centroid (same spectrum windowing as the
# overlay) so the two dashed centroid lines coincide after the fit.
pred = self._predict(data["lam_spec"], data["Ilam_spec"], data["interaction"])
Expand All @@ -367,7 +428,8 @@ def _auto_exponent(self) -> None:
data["lam_spec"],
data["Ilam_spec"],
data["interaction"],
window=window,
trace_window=trace_window,
spectrum_window=spectrum_window,
target_centroid=target,
),
2,
Expand Down Expand Up @@ -470,7 +532,9 @@ def _marginal_view(self, lam, lam_nm, trace, in_band, data) -> LineView:
if data.get("Ilam_spec") is not None:
lam_spec = np.asarray(data["lam_spec"])
Ilam_spec = np.asarray(data["Ilam_spec"])
sl_band = (lam_spec / 1e-9 >= lo) & (lam_spec / 1e-9 <= hi)
# the spectrum is normalised within its own trust region
s_lo, s_hi = self._spec_trust_nm
sl_band = (lam_spec / 1e-9 >= s_lo) & (lam_spec / 1e-9 <= s_hi)
if freq:
x_sp, y_sp = wlfreq(lam_spec) / _TWO_PI_PHZ, Ilam_spec * lam_spec**2
else:
Expand Down Expand Up @@ -512,7 +576,8 @@ def _marginal_view(self, lam, lam_nm, trace, in_band, data) -> LineView:
marks.append((to_x(pred["spectrum_centroid_nm"]), "measured"))
marks.append((to_x(pred["centroid_nm"]), "predicted"))

self._annotate_checks(c_meas_nm, sigma_meas, pred, interaction)
has_spectrum = data.get("Ilam_spec") is not None
self._annotate_checks(c_meas_nm, sigma_meas, pred, interaction, has_spectrum)
return LineView(
curves=tuple(curves),
title="Marginal against the spectrum",
Expand All @@ -534,22 +599,22 @@ def _f_hi(self) -> float:

# -- physics plumbing ---------------------------------------------------
def _trust_window(self, lam: np.ndarray) -> np.ndarray:
"""Near-hard window over the trust region (1 inside, 0 outside).
"""Near-hard window over the spectrum's trust region (1 inside, 0 outside).

Zero outside ``[lo, hi]`` with only a few-nm Planck roll-off just inside
the bounds — enough to stop the sharp cut ringing through the FFTs, but
narrow enough that it does not reshape the in-band spectrum (a wide taper
would clip a broadband spectrum's wing and bias the predicted centroid).
"""
lo_nm, hi_nm = self._trust_nm
lo_nm, hi_nm = self._spec_trust_nm
lo, hi = lo_nm * 1e-9, hi_nm * 1e-9
edge = min(0.02 * max(hi - lo, 1e-12), 5e-9)
return planck_taper(lam, lo, lo + edge, hi - edge, hi)

def _predict(self, lam_spec, Ilam_spec, interaction) -> dict | None:
"""Predicted marginal on the trace's wavelength axis, plus its centroid (nm).

Planck-tapers the spectrum to the **trust region** first — the noisy
Planck-tapers the spectrum to **its own trust region** first — the noisy
measured wings outside it would otherwise contaminate the transform-limited
field and the autoconvolution — then resamples onto a uniform
angular-frequency grid (applying the λ→ω Jacobian), predicts the marginal,
Expand All @@ -563,10 +628,9 @@ def _predict(self, lam_spec, Ilam_spec, interaction) -> dict | None:
Il = np.clip(Ilam_spec[order], 0.0, None) * self._trust_window(lam_s)
if not np.any(Il > 0):
return None
# Predict on a grid spanning the trust ∩ spectrum band, so the spectrum
# width σ_S is measured over the same window as the trace marginal — the
# width bracket and the measured width are then directly comparable.
lo_nm, hi_nm = self._trust_nm
# Predict on a grid spanning the trusted part of the spectrum, so the
# spectrum width σ_S is measured over the band that feeds the prediction.
lo_nm, hi_nm = self._spec_trust_nm
lam_lo = max(lo_nm * 1e-9, float(lam_s[0]))
lam_hi = min(hi_nm * 1e-9, float(lam_s[-1]))
if lam_hi <= lam_lo:
Expand Down Expand Up @@ -611,10 +675,31 @@ def _measured_moments(self, lam, marg, in_band):
c = centroid(omega, weights)
return float(wlfreq(c) / 1e-9), rms_width(omega, weights)

def _annotate_checks(self, c_meas_nm, sigma_meas, pred, interaction) -> None:
"""Write the numeric centroid/width QC summary to the ready line."""
if pred is None or c_meas_nm is None:
self.set_status("No independent spectrum: showing the trace marginal only.")
def _annotate_checks(
self, c_meas_nm, sigma_meas, pred, interaction, has_spectrum
) -> None:
"""Write the numeric centroid/width QC summary to the ready line.

Without a summary, the status says which input is missing: no spectrum
at all, a spectrum with none of it usable in its trust region, or a trace
marginal with too little signal in the trace's trust region.
"""
if pred is None:
if not has_spectrum:
self.set_status(
"No independent spectrum: showing the trace marginal only."
)
else:
self.set_status(
"No usable spectrum within the spectrum trust region: "
"showing the trace marginal only."
)
return
if c_meas_nm is None:
self.set_status(
"Too little trace marginal in the trace trust region: no "
"centroid/width check."
)
return
d_centroid = c_meas_nm - pred["centroid_nm"]
hardness = "hard" if pred["centroid_is_hard"] else "TL/soft"
Expand Down
Loading
Loading