diff --git a/changelog.d/shg-crystal-integration.added.md b/changelog.d/shg-crystal-integration.added.md index b1d7b0e..9bd24c7 100644 --- a/changelog.d/shg-crystal-integration.added.md +++ b/changelog.d/shg-crystal-integration.added.md @@ -1 +1 @@ -SHG retrievals through a Type I crystal everywhere a slab material is accepted: every solver, `retrieve_from_tracedata`, the bootstraps, the covariance and the thickness uncertainty take a `croak.crystals.CrystalSetup` as `material` (the thickness bootstrap gives each drawn thickness the depth nodes it needs). BBO is a built-in crystal (`croak.crystals.builtin_crystal`, optmat's Tamošauskas 2018 indices), so croak now needs `optmat[gas]>=0.10.0`, the first optmat release with BBO. Sessions describe the crystal (`crystal`, `cut_angle_deg`, `angle_mode`, `tilt_deg`, `phase_match_nm`, `polarization`, `delayed_beam`, `beam_separation_mm`), the GUI's Retrieve stage shows it as *Nonlinear crystal* and *Beam geometry* for SHG data, and the Synthetic stage can generate SHG traces through it. A crystal model refuses a marginal-corrected trace, which `TraceData.marginal_corrected` now records. A session's thickness uncertainty now raises a clear error when dispersive propagation is off, where it used to pass the unused slab material on. See [SHG FROG with a thick crystal](docs/howto/shg_crystal.md) (#24). +SHG retrievals through a Type I crystal everywhere a slab material is accepted: every solver, `retrieve_from_tracedata`, the bootstraps, the covariance and the thickness uncertainty take a `croak.crystals.CrystalSetup` as `material` (the thickness bootstrap gives each drawn thickness the depth nodes it needs). BBO is a built-in crystal (`croak.crystals.builtin_crystal`, optmat's Tamošauskas 2018 indices), so croak now needs `optmat[gas]>=0.10.0`, the first optmat release with BBO. Sessions describe the crystal (`crystal`, `cut_angle_deg`, `angle_mode`, `tilt_deg`, `phase_match_nm`, `polarization`, `delayed_beam`, `beam_separation_mm`), the GUI shows it as *Nonlinear crystal* and *Beam geometry* for SHG data, and the Synthetic stage can generate SHG traces through it. `TraceData.marginal_corrected` records whether the trace was marginal-corrected. A session's thickness uncertainty now raises a clear error when dispersive propagation is off, where it used to pass the unused slab material on. See [SHG FROG with a thick crystal](docs/howto/shg_crystal.md) (#24). diff --git a/changelog.d/shg-marginal-crystal.added.md b/changelog.d/shg-marginal-crystal.added.md new file mode 100644 index 0000000..d68e88c --- /dev/null +++ b/changelog.d/shg-marginal-crystal.added.md @@ -0,0 +1 @@ +The marginal checks and the SHG marginal correction can predict the marginal through a Type I crystal: `croak.crystals.shg_marginal` gives the crystal model's delay-summed marginal, and `predicted_marginal`, `predicted_centroid` and `apply_marginal_correction` take a `croak.crystals.PhaseMatching` (crystal and thickness) with the pulse carrier. `load_and_clean(marginal_correct=True, marginal_crystal=...)` corrects a measured trace onto the crystal's marginal, removing the instrument's spectral response while keeping the phase matching for the crystal model, and records it as `TraceData.marginal_crystal`. A retrieval now refuses a corrected trace only when its medium differs from the one the correction used, instead of refusing every corrected trace with a crystal. Sessions correct through the retrieval's crystal, and the GUI shows the crystal and beam settings on the Data stage, where the Check step uses them. See [Marginal consistency checks](docs/howto/marginal_checks.md#through-an-shg-crystal) (#25). diff --git a/croak/crystals.py b/croak/crystals.py index d202b22..d7e273c 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -115,6 +115,7 @@ "TILT_ERROR_WARN", "CrystalSetup", "CrystalApproximationWarning", + "PhaseMatching", "Propagation", "UniaxialCrystal", "builtin_crystal", @@ -124,6 +125,7 @@ "extraordinary_index", "phase_matching_angle", "propagation", + "shg_marginal", "tilt_field_error", ] @@ -889,6 +891,133 @@ def _depth_points( return math.ceil(phi) + 3 +@dataclass(frozen=True) +class PhaseMatching: + """A crystal of given thickness, as an SHG trace's frequency marginal sees it. + + Attributes + ---------- + setup : CrystalSetup + The crystal, its angle and the beam geometry. + thickness : float + Plate thickness (m) along the face normal, ``>= 0``. + """ + + setup: CrystalSetup + thickness: float + + def __post_init__(self) -> None: + """Validate the thickness.""" + if not (math.isfinite(self.thickness) and self.thickness >= 0.0): + raise ValueError( + f"the crystal thickness must be finite and >= 0, got {self.thickness!r}" + ) + + +def shg_marginal( + omega: ArrayLike, + spectrum: ArrayLike, + phase_matching: PhaseMatching, + omega0: float, +) -> NDArray[np.float64]: + r"""Frequency marginal of a crystal SHG trace, from the fundamental spectrum. + + Summed over a delay range that holds the whole trace, the crystal model's SHG + trace (:class:`croak.forward.ForwardModel` with a :class:`CrystalSetup`) has the + phase-independent frequency marginal + + .. math:: M(\omega_s) \propto a_s(\omega_s)^2 \sum_{\omega_1+\omega_2=\omega_s} + S(\omega_1)\,S(\omega_2)\,P^2\operatorname{sinc}^2\!\big(\Delta k\,P/2\big), + + Parseval's theorem over delay turning the delay sum of :math:`|\psi|^2` into a + sum over component pairs. :math:`a_s` is the generation prefactor and :math:`P` + the path (:func:`propagation`); :math:`\Delta k = k_s(\omega_1+\omega_2) - + k_z(\omega_1) - k_z(\omega_2) - \kappa(\omega_1-\omega_2)` is the pair's + mismatch, with the arms' delay drift :math:`\kappa` + (:meth:`CrystalSetup.arm_shift`), and :math:`P^2\operatorname{sinc}^2` the + modulus squared of its depth integral, done analytically. The drift's sign does + not matter: the pairs :math:`(\omega_1,\omega_2)` and :math:`(\omega_2,\omega_1)` + enter with the same weight. Smearing along delay leaves the marginal unchanged. + At zero thickness the model has no depth integral, and this is :math:`a_s^2\,(S*S)`, + the thin-medium marginal times the prefactor. + + It is the linear convolution: on a retrieval grid it differs from the model's + trace by the pairs that alias round the grid, which carry nothing when the grid + holds the trace. + + Parameters + ---------- + omega : array_like + Absolute angular frequencies (rad/s) of ``spectrum``, uniform and ascending. + spectrum : array_like + Fundamental spectral intensity :math:`S(\omega)` per unit frequency + (``>= 0``). + phase_matching : PhaseMatching + The crystal and its thickness. + omega0 : float + Pulse carrier (rad/s), as the retrieval uses it: it refracts an explicit + tilt, and the path and the delay drift are taken there. + + Returns + ------- + numpy.ndarray + The marginal, unnormalised, on the ``2N - 1`` frequencies + ``2 * omega[0] + k * (omega[1] - omega[0])``. + + Raises + ------ + ValueError + If ``omega`` is not a uniform ascending axis of at least two points, + ``spectrum`` has another shape, or either holds a non-finite value. + """ + omega = np.asarray(omega, dtype=float) + spectrum = np.asarray(spectrum, dtype=float) + if omega.ndim != 1 or omega.size < 2: + raise ValueError("omega must be a 1-D axis with at least 2 samples") + if spectrum.shape != omega.shape: + raise ValueError("spectrum and omega must have the same shape") + if not (np.all(np.isfinite(omega)) and np.all(np.isfinite(spectrum))): + raise ValueError("omega and spectrum must be finite") + spectrum = np.clip(spectrum, 0.0, None) + step = np.diff(omega) + if not (step[0] > 0.0 and np.allclose(step, step[0], rtol=1e-6, atol=0.0)): + raise ValueError("omega must be uniform and ascending") + domega = float(step[0]) + n = omega.size + signal = 2.0 * omega[0] + domega * np.arange(2 * n - 1) + setup, thickness = phase_matching.setup, phase_matching.thickness + # The same propagation constants as the forward model, in its frame (the + # group-delay term beta_1 * Omega cancels in the mismatch, since the signal + # offset is the sum of the pair's offsets). + fundamental = propagation(setup, omega - omega0, omega0, thickness) + generated = propagation(setup, signal - 2.0 * omega0, omega0, thickness) + path = fundamental.path_length + kappa = fundamental.arm_shift + beta_in = fundamental.beta_in + offset = omega - omega0 + out = np.zeros(signal.size) + for k in range(signal.size): + # pairs (j, k - j) with both members on the fundamental axis + j = np.arange(max(0, k - n + 1), min(k, n - 1) + 1) + m = k - j + weight = spectrum[j] * spectrum[m] + if not weight.any(): + continue + mismatch = ( + beta_in[j] + + beta_in[m] + - generated.beta_sig[k] + - kappa * (offset[j] - offset[m]) + ) + # np.sinc(x) = sin(pi x) / (pi x). At zero thickness the model takes one + # node of unit weight (forward.quadrature_nodes_weights), not a zero path. + response = ( + (path * np.sinc(mismatch * path / (2.0 * np.pi))) ** 2 if path > 0 else 1.0 + ) + out[k] = generated.sig_amp[k] ** 2 * float(np.sum(weight * response)) + return out + + def check_medium( interaction: Interaction, material: str | CrystalSetup | None, diff --git a/croak/gui/crystal_panel.py b/croak/gui/crystal_panel.py new file mode 100644 index 0000000..d7316f7 --- /dev/null +++ b/croak/gui/crystal_panel.py @@ -0,0 +1,406 @@ +"""The SHG crystal and the two beams, as one panel for the Data stage. + +The crystal an SHG trace was measured through and the beams that cross in it +describe the apparatus, so they are set with the data: the marginal check +predicts the marginal through them, the marginal correction corrects onto that +prediction, a synthetic trace is generated through them and the retrieval models +them. :class:`CrystalPanel` is that one set of controls, bound to the session's +:class:`~croak.session.params.RetrieveParams` (where the settings are stored, for +session-file compatibility), and each Data page shows it for an SHG trace. The +Retrieve stage shows :func:`retrieve_summary` of the same settings. +""" + +from __future__ import annotations + +import math + +from PySide6.QtCore import Signal +from PySide6.QtWidgets import QLabel, QVBoxLayout, QWidget + +from .. import crystals, smearing +from ..constants import C +from ..session.params import RetrieveParams +from ..session.pipeline import ( + beam_geometry, + crystal_setup, + pulse_carrier, + pulse_wavelength, + retrieval_npoints, +) +from .controls import check, combo, dspin, group +from .help import HelpSections, apply_tooltips, flatten +from .state import WizardState + +__all__ = [ + "CRYSTAL_HELP", + "CrystalPanel", + "crystal_summary", + "geometry_summary", + "readout_carrier", + "retrieve_summary", +] + +#: The crystal settings' labels in the GUI and their values in RetrieveParams. +_ANGLE_MODES = { + "Phase-matched wavelength": "phase-match", + "External tilt": "tilt", +} +_POLARIZATIONS = { + "In the crossing plane": "parallel", + "Perpendicular to the crossing plane": "perpendicular", +} +_DELAYED_BEAMS = { + "Toward the optic axis": "toward_axis", + "Away from the optic axis": "away_from_axis", +} + +#: The panel's help, for the Data pages' help dialogs and the panel's tooltips. +CRYSTAL_HELP: HelpSections = [ + ( + "Nonlinear crystal", + [ + ( + "Model the crystal", + "Model the SHG crystal: phase matching, group-velocity mismatch " + "and the generation prefactor, for crystals thick enough that the " + "ideal-SHG model fails. The marginal check then predicts the " + "marginal through it (and the marginal correction corrects onto " + "that prediction), a synthetic trace is generated through it, and " + "the retrieval models it; the retrieved field is the field at the " + "crystal's entrance face.", + ), + ("Crystal", "Uniaxial crystal (Type I, oo→e)."), + ( + "Thickness (µm)", + "Crystal thickness along its face normal. The depth nodes are the " + "number the phase mismatch needs (croak.crystals.depth_points; " + "read-out below, once the trace is prepared).", + ), + ( + "Cut angle θc (°)", + "The manufacturer's cut: the angle between the optic axis and the " + "face normal.", + ), + ( + "Angle set by", + "Phase-matched wavelength: the crystal is tilted to phase-match " + "the wavelength below (the tilt is solved and shown). External " + "tilt: the tilt you set, measured outside the crystal.", + ), + ( + "Phase-matched λ (nm)", + "Fundamental wavelength the crystal is tuned to phase-match.", + ), + ("External tilt γ (°)", "Tilt of the crystal from normal incidence."), + ( + "Polarisation", + "The fundamental's polarisation relative to the plane in which the " + "beams cross. In the crossing plane, the beams cross perpendicular " + "to the crystal's principal plane and the trace stays symmetric in " + "delay. Perpendicular to it, they cross in the principal plane: " + "the signal's tilt then makes the trace asymmetric, and the " + "delayed beam's side matters.", + ), + ( + "Delayed beam", + "With the beams crossing in the principal plane: whether the " + "delayed beam is on the optic axis's side of the bisector. A " + "crystal's markings do not show it; the two choices mirror the " + "model trace in delay, so retrieve with both and keep the better " + "fit.", + ), + ], + ), + ( + "Beam geometry", + [ + ( + "Beam separation (mm)", + "Distance between the two beams at the focusing optic. With the " + "focal length it sets the crossing half-angle atan(d / 2f), which " + "enters the phase matching. 0 models collinear beams.", + ), + ( + "Focal length (mm)", + "Focal length of the optic that crosses the beams (the same value " + "as the Retrieve stage's focal mixture).", + ), + ( + "Beam diameter (mm)", + "1/e² diameter of each beam at the focusing optic. It sets the " + "focal spot, across which the two beams' relative delay varies: " + "the delay smearing (read-out below), which the Retrieve stage " + "can model.", + ), + ], + ), +] + + +def _label(labels: dict[str, str], value: str) -> str: + """Return the GUI label of a stored setting ``value``, or ``value`` if unknown. + + An unknown value (from an edited session file) is then shown as it is, and the + crystal read-out reports why the settings give no crystal. + """ + return next((k for k, v in labels.items() if v == value), value) + + +def readout_carrier(state: WizardState) -> tuple[float, str]: + """Return the carrier (rad/s) the read-outs are evaluated at, and its source. + + The prepared trace's carrier once there is one; before that, the carrier the + retrieval grid will have (:func:`~croak.session.pipeline.pulse_carrier`) once + a trace is loaded; and before any data, the phase-matched wavelength. + """ + if state.tracedata is not None: + return state.tracedata.omega0_pulse, "the prepared trace's carrier" + if state.load_data is not None: + return pulse_carrier(state.preproc), "the centre of the Prepare band" + wavelength = state.retrieve.phase_match_nm * 1e-9 + return 2.0 * math.pi * C / wavelength, "the phase-matched wavelength" + + +def crystal_summary(p: RetrieveParams, td, omega0: float) -> str: + """Describe the crystal the settings give at ``omega0``, or why they give none. + + ``td`` is the prepared trace (:class:`~croak.preprocess.TraceData`), whose grid + sets the depth nodes; ``None`` before Prepare. + """ + try: + setup = crystal_setup(p) + thickness = p.thickness_um * 1e-6 + lines = [ + f"θ inside = {math.degrees(setup.internal_angle(omega0)):.3f}°, " + f"external tilt γ = {math.degrees(setup.external_tilt(omega0)):.3f}°", + f"path = {setup.path_length(thickness, omega0) * 1e6:.2f} µm", + ] + if td is None: + lines.append("depth nodes: after Prepare") + elif thickness > 0: + lines.append(f"depth nodes = {retrieval_npoints(p, td, setup, thickness)}") + except ValueError as err: + return f"No valid crystal: {err}" + return "\n".join(lines) + + +def geometry_summary(p: RetrieveParams, wavelength: float) -> str: + """Describe the beams' crossing and their delay smearing at ``wavelength`` (m).""" + geometry = beam_geometry(p) + if geometry is None: + return "Collinear beams: no delay smearing" + alpha = math.degrees(geometry.crossing_half_angle) + sigma = smearing.shg_two_beam_kernel(geometry, wavelength).sigma_delta + return ( + f"Crossing half-angle α = {alpha:.3f}°\n" + f"Delay smearing σ = {sigma * 1e15:.2f} fs rms " + f"({2.3548 * sigma * 1e15:.2f} fs FWHM)" + ) + + +def _wavelength(state: WizardState, omega0: float) -> float: + """The pulse wavelength (m): the prepared spectrum's centroid, else the carrier.""" + if state.tracedata is not None: + return pulse_wavelength(state.tracedata) + return 2.0 * math.pi * C / omega0 + + +def retrieve_summary(state: WizardState) -> str: + """Summarise the crystal and the beams for the Retrieve stage, read-only.""" + p = state.retrieve + omega0, _ = readout_carrier(state) + if p.dispersive: + crystal = ( + f"{p.crystal}, {p.thickness_um:g} µm, cut {p.cut_angle_deg:g}°\n" + + crystal_summary(p, state.tracedata, omega0) + ) + else: + crystal = "Crystal not modelled: thin-medium SHG." + if p.beam_separation_mm > 0: + beams = ( + f"Beams {p.beam_separation_mm:g} mm apart, f = {p.focal_f_mm:g} mm, " + f"⌀ {p.beam_diameter_mm:g} mm\n" + ) + else: + beams = "" + return f"{crystal}\n{beams}{geometry_summary(p, _wavelength(state, omega0))}" + + +class CrystalPanel(QWidget): + """The "Nonlinear crystal" and "Beam geometry" sections, on ``state.retrieve``. + + Every edit is stored on the session's retrieval settings at once, so the + marginal check, the preparation and the retrieval read the same crystal. + A Data page adds the panel to its form and shows it for an SHG trace + (:meth:`set_shg`). + + Parameters + ---------- + state : WizardState + The session; the panel reads and writes ``state.retrieve`` (looked up on + each use, so a replaced settings object is followed). + + Attributes + ---------- + edited : Signal + Emitted after an edit has been stored. + """ + + edited = Signal() + + def __init__(self, state: WizardState) -> None: + super().__init__() + self.state = state + p = state.retrieve + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + layout.setSpacing(2) + + self.crystal_box, form = group("Nonlinear crystal") + self.crystal_check = check( + "Model the crystal", p.dispersive, self._setter("dispersive", bool) + ) + form.addRow(self.crystal_check) + self.crystal_combo = combo( + list(crystals.CRYSTALS), p.crystal, self._setter("crystal", str) + ) + form.addRow("Crystal", self.crystal_combo) + # the same range as the Retrieve stage's slab thickness, which is the + # same setting + self.thickness_spin = dspin( + 0, 1000, p.thickness_um, self._setter("thickness_um", float), decimals=1 + ) + form.addRow("Thickness (µm)", self.thickness_spin) + self.cut_angle_spin = dspin( + 0, 90, p.cut_angle_deg, self._setter("cut_angle_deg", float), decimals=2 + ) + form.addRow("Cut angle θc (°)", self.cut_angle_spin) + self.angle_mode_combo = combo( + list(_ANGLE_MODES), + _label(_ANGLE_MODES, p.angle_mode), + lambda v: self._store("angle_mode", _ANGLE_MODES[v]), + ) + form.addRow("Angle set by", self.angle_mode_combo) + self.phase_match_spin = dspin( + 200, + 5000, + p.phase_match_nm, + self._setter("phase_match_nm", float), + decimals=1, + ) + form.addRow("Phase-matched λ (nm)", self.phase_match_spin) + self.tilt_spin = dspin( + -60, 60, p.tilt_deg, self._setter("tilt_deg", float), decimals=2, step=0.1 + ) + form.addRow("External tilt γ (°)", self.tilt_spin) + self.polarization_combo = combo( + list(_POLARIZATIONS), + _label(_POLARIZATIONS, p.polarization), + lambda v: self._store("polarization", _POLARIZATIONS[v]), + ) + form.addRow("Polarisation", self.polarization_combo) + self.delayed_beam_combo = combo( + list(_DELAYED_BEAMS), + _label(_DELAYED_BEAMS, p.delayed_beam), + lambda v: self._store("delayed_beam", _DELAYED_BEAMS[v]), + ) + form.addRow("Delayed beam", self.delayed_beam_combo) + self.crystal_readout = QLabel() + self.crystal_readout.setWordWrap(True) + form.addRow(self.crystal_readout) + layout.addWidget(self.crystal_box) + + self.geometry_box, form = group("Beam geometry") + self.separation_spin = dspin( + 0, + 1000, + p.beam_separation_mm, + self._setter("beam_separation_mm", float), + decimals=2, + step=0.5, + ) + form.addRow("Beam separation (mm)", self.separation_spin) + # the same range as the focal mixture's focal length, the same setting + self.focal_f_spin = dspin( + 1, 10000, p.focal_f_mm, self._setter("focal_f_mm", float), decimals=1 + ) + form.addRow("Focal length (mm)", self.focal_f_spin) + self.beam_diameter_spin = dspin( + 0.01, + 100, + p.beam_diameter_mm, + self._setter("beam_diameter_mm", float), + decimals=2, + step=0.1, + ) + form.addRow("Beam diameter (mm)", self.beam_diameter_spin) + self.geometry_readout = QLabel() + self.geometry_readout.setWordWrap(True) + form.addRow(self.geometry_readout) + layout.addWidget(self.geometry_box) + + apply_tooltips(self, flatten(CRYSTAL_HELP)) + self._update() + + def _setter(self, name: str, kind): + """Return a handler that stores ``kind(value)`` as ``name``.""" + return lambda value: self._store(name, kind(value)) + + def _store(self, name: str, value) -> None: + setattr(self.state.retrieve, name, value) + self._update() + self.edited.emit() + + def set_shg(self, shg: bool) -> None: + """Show the panel for an SHG trace (refreshed from the settings), else hide.""" + self.setHidden(not shg) + if shg: + self.refresh() + + def refresh(self) -> None: + """Show the stored settings, which another stage may have changed.""" + p = self.state.retrieve + values = { + self.crystal_check: p.dispersive, + self.crystal_combo: p.crystal, + self.thickness_spin: p.thickness_um, + self.cut_angle_spin: p.cut_angle_deg, + self.angle_mode_combo: _label(_ANGLE_MODES, p.angle_mode), + self.phase_match_spin: p.phase_match_nm, + self.tilt_spin: p.tilt_deg, + self.polarization_combo: _label(_POLARIZATIONS, p.polarization), + self.delayed_beam_combo: _label(_DELAYED_BEAMS, p.delayed_beam), + self.separation_spin: p.beam_separation_mm, + self.focal_f_spin: p.focal_f_mm, + self.beam_diameter_spin: p.beam_diameter_mm, + } + for widget, value in values.items(): + widget.blockSignals(True) + if isinstance(value, bool): + widget.setChecked(value) + elif isinstance(value, str): + widget.setCurrentText(value) + else: + widget.setValue(value) + widget.blockSignals(False) + self._update() + + def _update(self) -> None: + """Enable the controls the settings use and describe what they give.""" + p = self.state.retrieve + tilt_mode = p.angle_mode == "tilt" + self.tilt_spin.setEnabled(tilt_mode) + self.phase_match_spin.setEnabled(not tilt_mode) + crossing = p.beam_separation_mm > 0 + self.polarization_combo.setEnabled(crossing) + self.delayed_beam_combo.setEnabled( + crossing and p.polarization == "perpendicular" + ) + omega0, source = readout_carrier(self.state) + at = f"at {2.0 * math.pi * C / omega0 * 1e9:.0f} nm ({source})" + self.crystal_readout.setText( + f"{crystal_summary(p, self.state.tracedata, omega0)}\n{at}" + ) + self.geometry_readout.setText( + geometry_summary(p, _wavelength(self.state, omega0)) + ) diff --git a/croak/gui/stage_load.py b/croak/gui/stage_load.py index e8bb667..ab60f28 100644 --- a/croak/gui/stage_load.py +++ b/croak/gui/stage_load.py @@ -28,6 +28,7 @@ from ..session.pipeline import assemble_load_data from .base import Stage from .controls import check, combo, group +from .crystal_panel import CRYSTAL_HELP, CrystalPanel from .state import PreprocParams from .view_panel import ViewPanel from .widgets import SciSpinBox @@ -309,6 +310,7 @@ class StageLoad(Stage): ), ], ), + *CRYSTAL_HELP, ] def __init__(self, state): @@ -365,16 +367,18 @@ def __init__(self, state): 0.0, 1e6, p.energy_j, lambda v: setattr(p, "energy_j", v), sigfigs=3 ) form.addRow("pulse energy (J)", self.energy_spin) - form.addRow( - "interaction", - combo( - ["shg", "sd", "pg"], - p.interaction, - lambda v: setattr(p, "interaction", v), - ), + self.interaction_combo = combo( + ["shg", "sd", "pg"], p.interaction, self._on_interaction ) + form.addRow("interaction", self.interaction_combo) self.controls.addWidget(box) + # The SHG crystal and its beams are part of the apparatus (shown for SHG). + self.crystal_panel = CrystalPanel(state) + self.crystal_panel.set_shg(p.interaction == "shg") + self.crystal_panel.edited.connect(self._on_crystal_edited) + self.controls.addWidget(self.crystal_panel) + # FROG bg/calib (the (λ/µm)^exp third-order correction is tuned on the # marginal-check stage, where its effect on the marginal is visible). box, form = group("Trace corrections") @@ -472,6 +476,8 @@ def on_enter(self) -> None: the saved dataset names so the selection is visible and editable. """ p = self.state.load + # the crystal settings are shared with Retrieve, which may have changed them + self.crystal_panel.set_shg(p.interaction == "shg") if p.frog_path: self.path_edit.setText(p.frog_path) if self._frog_fd is None: @@ -481,6 +487,16 @@ def on_enter(self) -> None: if self._bg_fd is None: self._seed_bg_combos_from_params() + def _on_crystal_edited(self) -> None: + # With the marginal correction on, the prepared trace was corrected + # through the crystal as it was; Prepare redoes it with the new one. + if self.state.preproc.marginal_correct: + self.state.invalidate_tracedata() + + def _on_interaction(self, value: str) -> None: + self.state.load.interaction = value + self.crystal_panel.set_shg(value == "shg") + # -- small layout helpers ---------------------------------------------- def _row(self, *widgets): row = QWidget() diff --git a/croak/gui/stage_marginal_check.py b/croak/gui/stage_marginal_check.py index 5924d85..7292237 100644 --- a/croak/gui/stage_marginal_check.py +++ b/croak/gui/stage_marginal_check.py @@ -4,8 +4,9 @@ preprocess stage. It compares the measured trace's wavelength marginal with the marginal **predicted** from the independent fundamental spectrum (:func:`croak.marginal_checks.predicted_marginal`): exact for SHG (the spectral -autoconvolution), transform-limited for PG/TG/SD. It overlays the predicted -marginal, marks the predicted vs measured centroid, reports the width +autoconvolution, or, with the crystal modelled on the Data stage, the crystal +model's marginal through it), transform-limited for PG/TG/SD. It overlays the +predicted marginal, marks the predicted vs measured centroid, reports the width (bracket) check, and lets the user tune the ``(λ/µm)^exp`` third-order efficiency correction — with an ``Auto`` that matches the marginal centroid onto the prediction. @@ -31,7 +32,9 @@ from PySide6.QtWidgets import QHBoxLayout, QPushButton, QSplitter, QWidget from .. import io +from ..crystals import PhaseMatching from ..marginal_checks import ( + MarginalPrediction, auto_third_order_exponent, centroid, predicted_marginal, @@ -44,7 +47,12 @@ resample_spectrum, third_order_scale, ) -from ..session.pipeline import assemble_load_data, assemble_simulated_load_data +from ..session.pipeline import ( + assemble_load_data, + assemble_simulated_load_data, + marginal_crystal, + pulse_carrier, +) from .base import Stage from .controls import add_wide_row, check, combo, dspin, group from .display import current as current_display @@ -72,7 +80,9 @@ class StageMarginalCheck(Stage): "Quality-control the trace before retrieval using its frequency " "marginal (the trace integrated over delay). The marginal predicted " "from the independent fundamental spectrum is exact for SHG (the " - "spectral autoconvolution) and transform-limited for PG/TG/SD; comparing " + "spectral autoconvolution, or the marginal through the crystal when the " + "crystal is modelled on the Data stage) and transform-limited for " + "PG/TG/SD; comparing " "shape, centroid and width flags calibration, spectral-response, scatter " "and detector-nonlinearity problems. Tune the (λ/µm)^exp third-order " "efficiency correction here; 'Auto' matches the marginal centroid to the " @@ -134,9 +144,13 @@ class StageMarginalCheck(Stage): ( "Marginal correct (SHG)", "Scale the trace's frequency rows onto the SHG marginal " - "predicted from the independent spectrum (the spectral " - "autoconvolution). The correction is applied during preprocess; " - "here a dashed trace-colour curve previews it snapping onto the " + "predicted from the independent spectrum: the spectral " + "autoconvolution, or, with the crystal modelled on the Data " + "stage, the crystal's marginal. Through the crystal it removes " + "the instrument's spectral response but keeps the phase " + "matching, which the retrieval then models with the same " + "crystal. The correction is applied during preprocess; here a " + "dashed trace-colour curve previews it snapping onto the " "prediction. Available for an SHG trace with an independent " "spectrum (all workflows).", ), @@ -195,12 +209,6 @@ def __init__(self, state): self.state.preproc.marginal_correct, self._on_marginal_correct, ) - self.marginal_correct_check.setToolTip( - "Scale the trace's frequency rows onto the spectrum-predicted SHG " - "marginal (the spectral autoconvolution). Applied during preprocess; " - "the dashed curve here previews the snap onto the prediction. SHG only " - "and needs an independent spectrum." - ) form.addRow(self.marginal_correct_check) self.controls.addWidget(box) @@ -222,6 +230,31 @@ def __init__(self, state): self.apply_help() + # -- the SHG crystal ---------------------------------------------------- + def _prediction_crystal(self, interaction: str) -> tuple[PhaseMatching | None, str]: + """The crystal the marginal is predicted through, and a note on it. + + The crystal set on the Data stage for an SHG trace when it is modelled + (:func:`croak.session.pipeline.marginal_crystal`), so the prediction, the + correction and the retrieval describe one medium. Settings that give no + valid crystal fall back to the thin-medium prediction, and the note says + so; it is ``""`` otherwise. + """ + try: + crystal = marginal_crystal(self.state.retrieve, interaction) + except ValueError as exc: + return None, ( + f"⚠ the crystal set on the Data stage is not valid ({exc}): " + "showing the thin-medium prediction" + ) + return crystal, "" + + def _medium_label(self, crystal: PhaseMatching | None, interaction: str) -> str: + """Name the prediction: through the crystal, thin-medium SHG, or none.""" + if crystal is not None: + return f"through the crystal, {crystal.thickness / 1e-6:g} µm" + return "thin medium" if interaction == "shg" else "" + # -- loader coupling ---------------------------------------------------- def _loader_params(self): """The active entry's loader params, or ``None`` for a synthetic trace. @@ -284,6 +317,7 @@ def on_enter(self) -> None: # Auto needs an independent spectrum. self.auto_btn.setEnabled(enabled and data.get("Ilam_spec") is not None) self._seed_marginal_correct(data) + # the prediction reads the crystal set on the Data stage afresh self._draw() def _marginal_correct_available(self, data) -> bool: @@ -302,6 +336,7 @@ def _seed_marginal_correct(self, data) -> None: """ available = self._marginal_correct_available(data) self.marginal_correct_check.setEnabled(available) + self.marginal_correct_check.setToolTip(self._marginal_correct_tip(data)) if not available and self.state.preproc.marginal_correct: self.state.preproc.marginal_correct = False self.marginal_correct_check.blockSignals(True) @@ -310,6 +345,25 @@ def _seed_marginal_correct(self, data) -> None: ) self.marginal_correct_check.blockSignals(False) + def _marginal_correct_tip(self, data) -> str: + """Say what the correction targets: the crystal's marginal or the thin one.""" + crystal, _ = self._prediction_crystal(data.get("interaction", "")) + if crystal is None: + return ( + "Scale the trace's frequency rows onto the spectrum-predicted SHG " + "marginal (the spectral autoconvolution of a thin medium). Applied " + "during preprocess; the dashed curve here previews the snap onto " + "the prediction. SHG only and needs an independent spectrum." + ) + return ( + "Scale the trace's frequency rows onto the SHG marginal predicted " + f"{self._medium_label(crystal, 'shg')}, as set on the Data stage. This " + "removes the instrument's spectral response but keeps the crystal's " + "phase matching, which the retrieval models with the same crystal. " + "Applied during preprocess; the dashed curve here previews the snap " + "onto the prediction. SHG only and needs an independent spectrum." + ) + # -- control callbacks -------------------------------------------------- def _on_trust(self, lo: float, hi: float) -> None: self._trust_nm = (lo, hi) @@ -322,6 +376,8 @@ def _on_marginal_correct(self, checked: bool) -> None: # The flag drives the preprocess regrid (croak.preprocess.load_and_clean); # here we only redraw to preview the marginal snapping onto the prediction. self.state.preproc.marginal_correct = bool(checked) + # a trace prepared with the other setting is stale: Prepare redoes it + self.state.invalidate_tracedata() self._draw() def _on_third_order_toggled(self, value: bool) -> None: @@ -492,7 +548,9 @@ def _marginal_view(self, lam, lam_nm, trace, in_band, data) -> LineView: x_pr, y_pr = pred["lam_nm"], pred["marg_lam"] pb = (x_pr >= lo) & (x_pr <= hi) predicted = _peak_norm(y_pr, pb) - curves.append(CurveView(x_pr, predicted, "predicted", "predicted")) + medium = pred["medium"] + name = f"predicted ({medium})" if medium else "predicted" + curves.append(CurveView(x_pr, predicted, "predicted", name)) if correcting: curves.append( CurveView( @@ -574,7 +632,7 @@ def _predict(self, lam_spec, Ilam_spec, interaction) -> dict | None: omega = np.linspace(wlfreq(lam_hi), wlfreq(lam_lo), _PRED_GRID) try: s_omega = resample_spectrum(lam_s, Il, omega) - pred = predicted_marginal(omega, s_omega, interaction) + pred, crystal, note = self._predict_through(omega, s_omega, interaction) except ValueError, ZeroDivisionError: return None lam_pred = wlfreq(pred.omega) @@ -599,8 +657,41 @@ def _predict(self, lam_spec, Ilam_spec, interaction) -> dict | None: "centroid_is_hard": pred.centroid_is_hard, "width_is_hard": pred.width_is_hard, "centroid_omega": pred.centroid, + # what the prediction is through, and why not the crystal if not + "medium": self._medium_label(crystal, interaction), + "note": note, } + def _predict_through( + self, omega: np.ndarray, s_omega: np.ndarray, interaction: str + ) -> tuple[MarginalPrediction, PhaseMatching | None, str]: + """Predict the marginal through the Data stage's crystal, else thin. + + Returns the prediction, the crystal it went through (``None`` for the + thin medium) and a note on why the crystal was not used (``""`` if it + was, or none was asked for). Raises what the thin prediction raises. + """ + crystal, note = self._prediction_crystal(interaction) + if crystal is not None: + try: + # The crystal's angle and path are taken at the carrier the + # retrieval grid will have, as the correction at preprocess does. + pred = predicted_marginal( + omega, + s_omega, + interaction, + crystal=crystal, + omega0=pulse_carrier(self.state.preproc), + ) + except ValueError as exc: + note = ( + f"⚠ no marginal through the crystal ({exc}): showing the " + "thin-medium prediction" + ) + else: + return pred, crystal, note + return predicted_marginal(omega, s_omega, interaction), None, note + def _measured_moments(self, lam, marg, in_band): """Measured marginal centroid (nm) and RMS width (rad/s) in the trust band.""" sel = in_band & (marg > 0) @@ -618,8 +709,9 @@ def _annotate_checks(self, c_meas_nm, sigma_meas, pred, interaction) -> None: return d_centroid = c_meas_nm - pred["centroid_nm"] hardness = "hard" if pred["centroid_is_hard"] else "TL/soft" + medium = f" ({pred['medium']})" if pred["medium"] else "" lines = [ - f"{interaction.upper()} marginal check", + f"{interaction.upper()} marginal check{medium}", f"centroid: meas {c_meas_nm:.1f} nm vs pred {pred['centroid_nm']:.1f} nm " f"(Δ {d_centroid:+.1f} nm, {hardness})", ] @@ -655,7 +747,9 @@ def _annotate_checks(self, c_meas_nm, sigma_meas, pred, interaction) -> None: f"width RMS: meas {w_meas:.1f} nm | predicted min {w_min:.1f} nm " f"(σ_S) {'✓' if ok else '⚠ below σ_S'}" ) - self.set_status(" • ".join(lines)) + if pred["note"]: + lines.append(pred["note"]) + self.set_status(" • ".join(lines), "warn" if pred["note"] else "ok") def _peak_norm(y: np.ndarray, mask: np.ndarray) -> np.ndarray: diff --git a/croak/gui/stage_preprocess.py b/croak/gui/stage_preprocess.py index 351306b..e4a8b3d 100644 --- a/croak/gui/stage_preprocess.py +++ b/croak/gui/stage_preprocess.py @@ -224,7 +224,7 @@ def __init__(self, state): # bottleneck, but both used to block the UI thread on every change. self._req_id = 0 # bumped per recompute; stale worker results are ignored self._workers: list[PreprocessWorker] = [] - self._pending: tuple | None = None # (params, data) for the exact refine + self._pending: tuple | None = None # (params, data, crystal) to refine # Debounce: coalesce rapid slider/spin changes into one recompute. self._timer = QTimer(self) self._timer.setSingleShot(True) @@ -666,20 +666,36 @@ def apply(self, *, block: bool = False): # Bump first: this invalidates any async worker still in flight, so its # (now stale) result is ignored whether we run inline or dispatch. self._req_id += 1 + # The crystal the marginal correction targets is resolved now too, from + # the Data stage's crystal settings, so the snapshot is complete. + try: + crystal = pipeline.correction_crystal( + params, self.state.retrieve, data["interaction"] + ) + except ValueError as exc: + self.set_status( + f"Preprocess failed: the crystal set on the Data stage is not valid " + f"for the marginal correction ({exc}).", + "error", + ) + return if block: try: - td = pipeline.build_tracedata(params, data) # exact, full-resolution + # exact, full-resolution + td = pipeline.build_tracedata(params, data, crystal=crystal) except Exception as exc: self.set_status(f"Preprocess failed: {exc}", "error") return self._show_tracedata(td) return - self._dispatch(params, data, self._req_id, fast=True) + self._dispatch(params, data, crystal, self._req_id, fast=True) - def _dispatch(self, params, data, rid, *, fast): + def _dispatch(self, params, data, crystal, rid, *, fast): """Launch an off-thread preprocess (``fast`` ⇒ coarse baseline preview).""" - self._pending = (params, data) - worker = PreprocessWorker(params, data, rid, parent=self, fast=fast) + self._pending = (params, data, crystal) + worker = PreprocessWorker( + params, data, rid, parent=self, crystal=crystal, fast=fast + ) worker.finished_ok.connect(self._on_preprocess_done) worker.failed.connect(self._on_preprocess_failed) worker.finished.connect(lambda w=worker: self._discard_worker(w)) @@ -751,8 +767,8 @@ def _on_preprocess_done(self, td, req_id, was_fast): # Refine to the exact baseline, reusing the same request id so a later # parameter change supersedes it; the committed trace ends up exact. if self._pending is not None: - params, data = self._pending - self._dispatch(params, data, req_id, fast=False) + params, data, crystal = self._pending + self._dispatch(params, data, crystal, req_id, fast=False) else: # Exact refinement: replace the stored trace (used for retrieval/save) # without a redraw — visually identical to the preview already shown. diff --git a/croak/gui/stage_retrieve.py b/croak/gui/stage_retrieve.py index 40f5c24..cff531e 100644 --- a/croak/gui/stage_retrieve.py +++ b/croak/gui/stage_retrieve.py @@ -19,7 +19,7 @@ QWidget, ) -from .. import crystals, materials, plotting, smearing +from .. import materials, plotting, smearing from ..constants import C from ..plotting.screen import convergence_view from ..processing import ( @@ -31,17 +31,11 @@ ) from ..retrieve import ALGORITHMS, algorithm_params from ..session.params import reg_defaults, reg_family -from ..session.pipeline import ( - beam_geometry, - crystal_setup, - extra_param_centres, - pulse_wavelength, - retrieval_npoints, - smearing_kernel, -) +from ..session.pipeline import extra_param_centres, smearing_kernel from ..truth_metrics import truth_errors from .base import RunControls, Stage from .controls import check, combo, dspin, group, spin +from .crystal_panel import retrieve_summary from .display import current as current_display from .readout import DASH, RetrievalReadout from .retrieval_views import RetrievalPanels @@ -58,30 +52,6 @@ #: second is all the eye needs. _CONVERGENCE_REDRAW_MS = 100 -#: The crystal settings' labels in the GUI and their values in RetrieveParams. -_ANGLE_MODES = { - "Phase-matched wavelength": "phase-match", - "External tilt": "tilt", -} -_POLARIZATIONS = { - "In the crossing plane": "parallel", - "Perpendicular to the crossing plane": "perpendicular", -} -_DELAYED_BEAMS = { - "Toward the optic axis": "toward_axis", - "Away from the optic axis": "away_from_axis", -} - - -def _label(labels: dict[str, str], value: str) -> str: - """Return the GUI label of a stored setting ``value``, or ``value`` if unknown. - - An unknown value (from an edited session file) is then shown as it is, and the - crystal read-out reports why the settings give no crystal. - """ - return next((k for k, v in labels.items() if v == value), value) - - _INITIAL_GUESSES = { "Automatic (centroid phase)": None, "Transform-limited measured spectrum": "tl_init", @@ -207,82 +177,15 @@ class StageRetrieve(RunControls, Stage): ], ), ( - "Nonlinear crystal", - [ - ( - "Model the crystal", - "Model the SHG crystal in the forward map: phase matching, " - "group-velocity mismatch and the generation prefactor, for " - "crystals thick enough that the ideal-SHG model fails. The " - "retrieved field is the field at the crystal's entrance face.", - ), - ("Crystal", "Uniaxial crystal (Type I, oo→e)."), - ( - "Thickness (µm)", - "Crystal thickness along its face normal. The depth nodes are " - "the number the phase mismatch needs (croak.crystals." - "depth_points; read-out below).", - ), - ( - "Cut angle θc (°)", - "The manufacturer's cut: the angle between the optic axis and " - "the face normal.", - ), - ( - "Angle set by", - "Phase-matched wavelength: the crystal is tilted to phase-match " - "the wavelength below (the tilt is solved and shown). External " - "tilt: the tilt you set, measured outside the crystal.", - ), - ( - "Phase-matched λ (nm)", - "Fundamental wavelength the crystal is tuned to phase-match.", - ), - ("External tilt γ (°)", "Tilt of the crystal from normal incidence."), - ( - "Polarisation", - "The fundamental's polarisation relative to the plane in which " - "the beams cross. In the crossing plane, the beams cross " - "perpendicular to the crystal's principal plane and the trace " - "stays symmetric in delay. Perpendicular to it, they cross in " - "the principal plane: the signal's tilt then makes the trace " - "asymmetric, and the delayed beam's side matters.", - ), - ( - "Delayed beam", - "With the beams crossing in the principal plane: whether the " - "delayed beam is on the optic axis's side of the bisector. A " - "crystal's markings do not show it; the two choices mirror the " - "model trace in delay, so retrieve with both and keep the " - "better fit.", - ), - ], - ), - ( - "Beam geometry", + "Crystal and beams (SHG)", [ - ( - "Beam separation (mm)", - "Distance between the two beams at the focusing optic. With the " - "focal length it sets the crossing half-angle atan(d / 2f), " - "which enters the phase matching. 0 models collinear beams.", - ), - ( - "Focal length (mm)", - "Focal length of the optic that crosses the beams (the same " - "value as the focal mixture's).", - ), - ( - "Beam diameter (mm)", - "1/e² diameter of each beam at the focusing optic. It sets the " - "focal spot, across which the two beams' relative delay varies: " - "the delay smearing (read-out below).", - ), ( "Model the delay smearing", "Blur the model trace along delay by the spread of the two " "beams' relative delay across the focus (Gaussian beams, the " - "signal collected over the whole beam). Autodiff solvers only.", + "signal collected over the whole beam). Autodiff solvers only. " + "The crystal and the beams themselves describe the apparatus " + "and are set on the Data stage; this group summarises them.", ), ], ), @@ -593,7 +496,7 @@ def __init__(self, state): self.npoints_spin = spin(1, 10000, p.npoints, self._on_npoints_changed) form.addRow("Npoints", self.npoints_spin) self.controls.addWidget(box) - self._build_crystal_groups() + self._build_shg_group() self.smear_box, form = group("Geometrical smearing") box = self.smear_box @@ -1057,145 +960,25 @@ def _on_initial_guess_changed(self, label: str) -> None: self.perfect_fwhm_spin.setEnabled(selected == "perfect_init") # -- the SHG crystal and the beam geometry -------------------------------- - # For an SHG trace these two groups replace "Dispersive propagation": the - # crystal shares its on/off switch and thickness with the slab of PG/SD, and - # "Beam geometry" is the one place the crossing angle is set. - def _build_crystal_groups(self) -> None: + # For an SHG trace this group replaces "Dispersive propagation": the crystal + # and the beams describe the apparatus and are set on the Data stage + # (croak.gui.crystal_panel), so here they are only summarised. Modelling the + # delay smearing is a retrieval choice that depends on the solver, so it + # stays here. + def _build_shg_group(self) -> None: p = self.state.retrieve - self.crystal_box, form = group("Nonlinear crystal") - self.crystal_check = check( - "Model the crystal", p.dispersive, self._on_crystal_enabled - ) - form.addRow(self.crystal_check) - self.crystal_combo = combo( - list(crystals.CRYSTALS), p.crystal, self._crystal_setter("crystal", str) - ) - form.addRow("Crystal", self.crystal_combo) - # the same ranges as the slab's thickness and the focal mixture's focal - # length, which drive the same settings - self.crystal_thickness_spin = dspin( - 0, 1000, p.thickness_um, self._on_crystal_thickness_changed, decimals=1 - ) - form.addRow("Thickness (µm)", self.crystal_thickness_spin) - self.cut_angle_spin = dspin( - 0, - 90, - p.cut_angle_deg, - self._crystal_setter("cut_angle_deg", float), - decimals=2, - ) - form.addRow("Cut angle θc (°)", self.cut_angle_spin) - self.angle_mode_combo = combo( - list(_ANGLE_MODES), - _label(_ANGLE_MODES, p.angle_mode), - self._on_angle_mode_changed, - ) - form.addRow("Angle set by", self.angle_mode_combo) - self.phase_match_spin = dspin( - 200, - 5000, - p.phase_match_nm, - self._crystal_setter("phase_match_nm", float), - decimals=1, - ) - form.addRow("Phase-matched λ (nm)", self.phase_match_spin) - self.tilt_spin = dspin( - -60, - 60, - p.tilt_deg, - self._crystal_setter("tilt_deg", float), - decimals=2, - step=0.1, - ) - form.addRow("External tilt γ (°)", self.tilt_spin) - self.polarization_combo = combo( - list(_POLARIZATIONS), - _label(_POLARIZATIONS, p.polarization), - self._on_polarization_changed, - ) - form.addRow("Polarisation", self.polarization_combo) - self.delayed_beam_combo = combo( - list(_DELAYED_BEAMS), - _label(_DELAYED_BEAMS, p.delayed_beam), - lambda v: self._set_crystal("delayed_beam", _DELAYED_BEAMS[v]), - ) - form.addRow("Delayed beam", self.delayed_beam_combo) - self.crystal_readout = QLabel() - self.crystal_readout.setWordWrap(True) - form.addRow(self.crystal_readout) - self.controls.addWidget(self.crystal_box) - - self.geometry_box, form = group("Beam geometry") - self.separation_spin = dspin( - 0, - 1000, - p.beam_separation_mm, - self._crystal_setter("beam_separation_mm", float), - decimals=2, - step=0.5, - ) - form.addRow("Beam separation (mm)", self.separation_spin) - self.geometry_f_spin = dspin( - 1, 10000, p.focal_f_mm, self._on_geometry_f_changed, decimals=1 - ) - form.addRow("Focal length (mm)", self.geometry_f_spin) - self.beam_diameter_spin = dspin( - 0.01, - 100, - p.beam_diameter_mm, - self._crystal_setter("beam_diameter_mm", float), - decimals=2, - step=0.1, - ) - form.addRow("Beam diameter (mm)", self.beam_diameter_spin) + self.shg_box, form = group("Crystal and beams (SHG)") + self.shg_summary = QLabel() + self.shg_summary.setWordWrap(True) + form.addRow(self.shg_summary) + hint = QLabel("The crystal and the beams are set on the Data stage.") + hint.setWordWrap(True) + form.addRow(hint) self.shg_smearing_check = check( - "Model the delay smearing", p.smearing, self._on_shg_smearing_changed + "Model the delay smearing", p.smearing, self._on_smearing_changed ) form.addRow(self.shg_smearing_check) - self.geometry_readout = QLabel() - self.geometry_readout.setWordWrap(True) - form.addRow(self.geometry_readout) - self.controls.addWidget(self.geometry_box) - - def _crystal_setter(self, name: str, kind): - """Return a handler that stores ``kind(value)`` as ``name`` and refreshes.""" - return lambda v: self._set_crystal(name, kind(v)) - - def _set_crystal(self, name: str, value) -> None: - setattr(self.state.retrieve, name, value) - self._refresh_crystal() - - def _on_crystal_enabled(self, value) -> None: - self.dispersive_check.blockSignals(True) - self.dispersive_check.setChecked(bool(value)) - self.dispersive_check.blockSignals(False) - self._on_dispersive_changed(value) - self._refresh_crystal() - - def _on_crystal_thickness_changed(self, value: float) -> None: - # the slab's thickness control drives the same parameter; keep it in step - self.thickness_spin.blockSignals(True) - self.thickness_spin.setValue(value) - self.thickness_spin.blockSignals(False) - self._on_thickness_changed(value) - self._refresh_crystal() - - def _on_angle_mode_changed(self, label: str) -> None: - self._set_crystal("angle_mode", _ANGLE_MODES[label]) - - def _on_polarization_changed(self, label: str) -> None: - self._set_crystal("polarization", _POLARIZATIONS[label]) - - def _on_geometry_f_changed(self, value: float) -> None: - self.state.retrieve.focal_f_mm = float(value) - self.focal_f_spin.blockSignals(True) - self.focal_f_spin.setValue(value) - self.focal_f_spin.blockSignals(False) - self._refresh_crystal() - - def _on_shg_smearing_changed(self, value) -> None: - self._on_smearing_changed(value) - self._refresh_crystal() + self.controls.addWidget(self.shg_box) def _gate_shg_smearing(self, params: set[str]) -> None: """Enable SHG smearing for crossing beams and a solver (``params``) for it.""" @@ -1204,22 +987,38 @@ def _gate_shg_smearing(self, params: set[str]) -> None: def _on_focal_f_changed(self, value: float) -> None: self.state.retrieve.focal_f_mm = float(value) - self.geometry_f_spin.blockSignals(True) - self.geometry_f_spin.setValue(value) - self.geometry_f_spin.blockSignals(False) - self._refresh_crystal() def _is_shg(self) -> bool: td = self.state.tracedata return td is not None and getattr(td, "interaction", "") == "shg" def _update_medium_groups(self) -> None: - """Show the crystal and beam geometry for SHG, the material slab otherwise.""" + """Show the crystal summary for SHG, the material slab otherwise. + + The switch, thickness and focal length are shared with the Data stage's + crystal panel, which may have changed them, so they are shown afresh. + """ + p = self.state.retrieve + for spinbox, value in ( + (self.thickness_spin, p.thickness_um), + (self.focal_f_spin, p.focal_f_mm), + ): + spinbox.blockSignals(True) + spinbox.setValue(value) + spinbox.blockSignals(False) + for checkbox, flag in ( + (self.dispersive_check, p.dispersive), + (self.smearing_check, p.smearing), + (self.shg_smearing_check, p.smearing), + ): + checkbox.blockSignals(True) + checkbox.setChecked(flag) + checkbox.blockSignals(False) shg = self._is_shg() self.disp_box.setVisible(not shg) - self.smear_box.setVisible(not shg) # SHG's smearing is in Beam geometry + self.smear_box.setVisible(not shg) # SHG's smearing is in the SHG group self.focal_box.setVisible(not shg) # the focal mixture is PG/SD's - if shg and self.state.retrieve.focal: + if shg and p.focal: # left on from PG/SD data, it would fail the run and its box is # hidden: switch it off, and say so self.focal_check.setChecked(False) @@ -1227,92 +1026,15 @@ def _update_medium_groups(self) -> None: "The focal mixture is for PG/SD; switched off for this SHG trace.", "warn", ) - self.crystal_box.setVisible(shg) - self.geometry_box.setVisible(shg) + self.shg_box.setVisible(shg) if shg: - # thickness, focal length and the switch are shared with the slab and - # the focal mixture, which may have changed them - p = self.state.retrieve - for spinbox, value in ( - (self.crystal_thickness_spin, p.thickness_um), - (self.geometry_f_spin, p.focal_f_mm), - (self.beam_diameter_spin, p.beam_diameter_mm), - ): - spinbox.blockSignals(True) - spinbox.setValue(value) - spinbox.blockSignals(False) - for checkbox, flag in ( - (self.crystal_check, p.dispersive), - (self.shg_smearing_check, p.smearing), - ): - checkbox.blockSignals(True) - checkbox.setChecked(flag) - checkbox.blockSignals(False) - self._refresh_crystal() - - def _refresh_crystal(self) -> None: - """Enable the controls the settings use and describe the crystal they give. - - Only while the crystal groups are shown (SHG data); showing them refreshes - them. - """ - if not self._is_shg(): - return - p = self.state.retrieve - tilt_mode = p.angle_mode == "tilt" - self.tilt_spin.setEnabled(tilt_mode) - self.phase_match_spin.setEnabled(not tilt_mode) - crossing = p.beam_separation_mm > 0 - self.polarization_combo.setEnabled(crossing) - self.delayed_beam_combo.setEnabled( - crossing and p.polarization == "perpendicular" - ) - self._update_solver_caps() # the smearing controls depend on the beams - geometry, td = beam_geometry(p), self.state.tracedata - if geometry is not None and td is not None: - alpha = math.degrees(geometry.crossing_half_angle) - kernel = smearing.shg_two_beam_kernel(geometry, pulse_wavelength(td)) - sigma = kernel.sigma_delta - self.geometry_readout.setText( - f"Crossing half-angle α = {alpha:.3f}°\n" - f"Delay smearing σ = {sigma * 1e15:.2f} fs rms " - f"({2.3548 * sigma * 1e15:.2f} fs FWHM)" - ) - else: - self.geometry_readout.setText("Collinear beams: no delay smearing") - self.crystal_readout.setText(self._crystal_summary()) - - def _crystal_summary(self) -> str: - """Describe the crystal the settings give, or why they give none.""" - p = self.state.retrieve - td = self.state.tracedata - try: - setup = crystal_setup(p) - omega0 = ( - td.omega0_pulse - if td is not None - else 2.0 * math.pi * C / (p.phase_match_nm * 1e-9) - ) - thickness = p.thickness_um * 1e-6 - lines = [ - f"θ inside = {math.degrees(setup.internal_angle(omega0)):.3f}°, " - f"external tilt γ = {math.degrees(setup.external_tilt(omega0)):.3f}°", - f"path = {setup.path_length(thickness, omega0) * 1e6:.2f} µm", - ] - if td is not None and thickness > 0: - nodes = retrieval_npoints(p, td, setup, thickness) - lines.append(f"depth nodes = {nodes}") - except ValueError as err: - return f"No valid crystal: {err}" - return "\n".join(lines) + self.shg_summary.setText(retrieve_summary(self.state)) + self._update_solver_caps() def _on_dispersive_changed(self, value): # Thickness fitting is only available with dispersive propagation, so # refresh the capability gating when this toggles. self.state.retrieve.dispersive = bool(value) - self.crystal_check.blockSignals(True) - self.crystal_check.setChecked(bool(value)) - self.crystal_check.blockSignals(False) self._update_solver_caps() # -- coupled thickness / Δz / Npoints ----------------------------------- @@ -1363,8 +1085,8 @@ def _on_npoints_changed(self, value: int) -> None: def _on_smearing_changed(self, value): # Fitting the smearing width is only available once the kernel is modelled. self.state.retrieve.smearing = bool(value) - # one switch shown in two groups (the mask's for PG/SD, Beam geometry's - # for SHG): keep both boxes in step whichever changed it + # one switch shown in two groups (the mask's for PG/SD, the SHG + # group's for SHG): keep both boxes in step whichever changed it for box in (self.smearing_check, self.shg_smearing_check): box.blockSignals(True) box.setChecked(bool(value)) @@ -1455,7 +1177,7 @@ def _refresh_smear_sigma(self) -> None: p = self.state.retrieve if self._smear_interaction() == "shg": # the mask geometry describes PG/SD's three arms; SHG's two beams are - # in Beam geometry, which shows their width + # set on the Data stage, whose Beam geometry shows their width return sigma_fs = ( smearing.square_boxcars_delay_width( @@ -1585,7 +1307,8 @@ def _update_solver_caps(self): self.reg_time_lo_spin.setEnabled(has_time) self.reg_time_hi_spin.setEnabled(has_time) self.disp_box.setEnabled("material" in params) - self.crystal_box.setEnabled("material" in params) + # the crystal is modelled through the same capability as the slab + self.shg_summary.setEnabled("material" in params) # Geometrical smearing needs the incoherent quadrature sum. COPRA's LOCAL # projection cannot represent it — there is no single signal whose # modulus the measurement constrains — but its GLOBAL stage is a descent @@ -1727,36 +1450,6 @@ def _seed_widgets(self): w.blockSignals(True) w.setValue(val) w.blockSignals(False) - self._seed_crystal_widgets() - self._update_solver_caps() - - def _seed_crystal_widgets(self) -> None: - """Push the crystal and beam-geometry settings into their widgets.""" - p = self.state.retrieve - values = { - self.crystal_check: p.dispersive, - self.crystal_combo: p.crystal, - self.crystal_thickness_spin: p.thickness_um, - self.cut_angle_spin: p.cut_angle_deg, - self.angle_mode_combo: _label(_ANGLE_MODES, p.angle_mode), - self.phase_match_spin: p.phase_match_nm, - self.tilt_spin: p.tilt_deg, - self.polarization_combo: _label(_POLARIZATIONS, p.polarization), - self.delayed_beam_combo: _label(_DELAYED_BEAMS, p.delayed_beam), - self.separation_spin: p.beam_separation_mm, - self.geometry_f_spin: p.focal_f_mm, - self.beam_diameter_spin: p.beam_diameter_mm, - self.shg_smearing_check: p.smearing, - } - for w, val in values.items(): - w.blockSignals(True) - if isinstance(val, bool): - w.setChecked(val) - elif isinstance(val, str): - w.setCurrentText(val) - else: - w.setValue(val) - w.blockSignals(False) self._update_medium_groups() def _reset_defaults(self): @@ -1777,8 +1470,9 @@ def on_enter(self): # known once a trace is loaded — refresh the readout so it always shows the # width the forward model will actually use. self._refresh_smear_sigma() + # the crystal, the beams and the shared settings may have changed on the + # Data stage self._update_medium_groups() - self._update_solver_caps() # If a result already exists (navigated back/forward, or a restored # session) but this stage hasn't drawn it, restore the view so it is # clear the retrieval is still valid — no re-run needed to proceed. diff --git a/croak/gui/stage_synthetic.py b/croak/gui/stage_synthetic.py index 46bba8f..1fdefa9 100644 --- a/croak/gui/stage_synthetic.py +++ b/croak/gui/stage_synthetic.py @@ -2,7 +2,7 @@ Builds a known pulse (Gaussian or sech², with GDD/TOD/FOD and optional material dispersion), simulates a FROG measurement of it (for SHG optionally through the -nonlinear crystal the Retrieve stage describes) on a user-chosen wavelength × +nonlinear crystal of the page's crystal panel) on a user-chosen wavelength × delay sampling, previews the pulse and trace live, and then hands the synthetic "measurement" into the normal preprocess → retrieve pipeline (so the retriever rediscovers the pulse). The internal computation grid is chosen automatically to @@ -19,7 +19,7 @@ import numpy as np from PySide6.QtCore import QTimer -from PySide6.QtWidgets import QGridLayout, QLabel, QWidget +from PySide6.QtWidgets import QGridLayout, QWidget from .. import dispersion from ..constants import C @@ -41,6 +41,7 @@ group, spin, ) +from .crystal_panel import CrystalPanel from .stage_load import seed_preproc_defaults from .view_panel import ViewPanel from .widgets import RangeControl, ValueControl @@ -162,25 +163,13 @@ def __init__(self, state): self.controls.addWidget(box) # -- SHG crystal ------------------------------------------------ - # The crystal itself (its cut, angle, polarisation and the beams' crossing) - # is the one the Retrieve stage describes, so a trace made here and its - # retrieval share one description; only the thickness is set here. - self.crystal_box, form = group("SHG crystal") - self.use_crystal = check("Generate through the crystal", False, self._changed) - form.addRow(self.use_crystal) - self.crystal_thickness = ValueControl( - 0.0, 1000.0, 20.0, decimals=1, step=1.0, slider_scale=1.0 - ) - self.crystal_thickness.changed.connect(self._changed) - add_wide_row(form, "thickness (µm)", self.crystal_thickness) - note = QLabel( - "Crystal, angle, polarisation and beam geometry as set in the " - "Retrieve stage." - ) - note.setWordWrap(True) - form.addRow(note) - self.controls.addWidget(self.crystal_box) - self.crystal_box.setEnabled(self.interaction.currentText() == "shg") + # The crystal and the beams are the session's (state.retrieve), set on + # this panel as on every Data page: a trace generated through them is + # then predicted, corrected and retrieved through the same crystal. + self.crystal_panel = CrystalPanel(state) + self.crystal_panel.edited.connect(self._changed) + self.crystal_panel.set_shg(self.interaction.currentText() == "shg") + self.controls.addWidget(self.crystal_panel) # -- Noise ------------------------------------------------------ box, form = group("Noise (optional)") @@ -219,6 +208,8 @@ def __init__(self, state): # -- lifecycle ---------------------------------------------------------- def on_enter(self): + # the crystal settings are shared with Retrieve, which may have changed them + self.crystal_panel.set_shg(self.interaction.currentText() == "shg") self._recompute() def _changed(self, *_): @@ -267,7 +258,7 @@ def _on_interaction(self, _value): # the SHG fundamental sits at 2× the signal wavelength, so a mirrored # spectrum window must follow the interaction's omega0 scaling. self._sync_spec_mirror() - self.crystal_box.setEnabled(self.interaction.currentText() == "shg") + self.crystal_panel.set_shg(self.interaction.currentText() == "shg") self._changed() def _on_delay(self, lo, hi): @@ -447,15 +438,18 @@ def _signal_trace(self, grid, ew, omega0): return lam[order], delays, T[order] def _crystal_kwargs(self, grid, omega0) -> dict: - """The forward model's crystal keywords, or none for a thin medium.""" - thickness = self.crystal_thickness.value() * 1e-6 + """The forward model's crystal keywords, or none for a thin medium. + + Through the crystal panel's crystal when it is modelled, as the marginal + check and the retrieval will see it. + """ + p = self.state.retrieve + thickness = p.thickness_um * 1e-6 if not ( - self.interaction.currentText() == "shg" - and self.use_crystal.isChecked() - and thickness > 0 + self.interaction.currentText() == "shg" and p.dispersive and thickness > 0 ): return {} - setup = crystal_setup(self.state.retrieve) + setup = crystal_setup(p) return { "material": setup, "thickness": thickness, diff --git a/croak/gui/state.py b/croak/gui/state.py index c74c77d..df15135 100644 --- a/croak/gui/state.py +++ b/croak/gui/state.py @@ -138,6 +138,20 @@ def set_load_data(self, data) -> None: self.processed = None self.load_data_changed.emit() + def invalidate_tracedata(self) -> None: + """Drop the prepared trace and what was built on it, keeping the loaded data. + + For a setting that changes how the trace is prepared but is not on the + Prepare stage (the marginal correction, the crystal it corrects through), + so that Prepare recomputes on entry instead of keeping a stale trace. + """ + if self.tracedata is None: + return + self.tracedata = None + self.result = None + self.processed = None + self.tracedata_changed.emit() + def set_tracedata(self, td) -> None: self.tracedata = td self.result = None diff --git a/croak/gui/worker.py b/croak/gui/worker.py index bbeb9e1..f3ec0e8 100644 --- a/croak/gui/worker.py +++ b/croak/gui/worker.py @@ -35,7 +35,9 @@ class PreprocessWorker(QThread): filtering/regridding in a thread and hands the result back via a signal; the (main-thread) caller does the plotting. ``params`` is a snapshot the caller takes (so later slider changes can't mutate an in-flight run) and ``data`` - holds read-only arrays. ``request_id`` lets the caller ignore superseded + holds read-only arrays. ``crystal`` is the SHG crystal the marginal correction + targets (:func:`croak.session.pipeline.correction_crystal`), resolved by the + caller with the snapshot. ``request_id`` lets the caller ignore superseded results. ``fast`` selects the coarse, interactive-preview baseline (the caller then refines to the exact baseline once the user settles). @@ -51,17 +53,23 @@ class PreprocessWorker(QThread): finished_ok = Signal(object, int, bool) failed = Signal(str, int) - def __init__(self, params, data, request_id, parent=None, *, fast=False): + def __init__( + self, params, data, request_id, parent=None, *, crystal=None, fast=False + ): super().__init__(parent) self._params = params self._data = data + self._crystal = crystal self._id = int(request_id) self._fast = bool(fast) def run(self) -> None: # noqa: D401 - QThread entry point try: td = pipeline.build_tracedata( - self._params, self._data, fast_baseline=self._fast + self._params, + self._data, + crystal=self._crystal, + fast_baseline=self._fast, ) except Exception as exc: self.failed.emit(str(exc), self._id) diff --git a/croak/marginal_checks.py b/croak/marginal_checks.py index ae0ea49..2881de6 100644 --- a/croak/marginal_checks.py +++ b/croak/marginal_checks.py @@ -54,6 +54,7 @@ import scipy.optimize from numpy.typing import ArrayLike, NDArray +from .crystals import PhaseMatching, shg_marginal from .grid import Grid from .interactions import get_interaction from .maths import moment, wlfreq @@ -170,7 +171,12 @@ def spectral_autoconvolution( def apply_marginal_correction( - trace: ArrayLike, Iomega: ArrayLike + trace: ArrayLike, + Iomega: ArrayLike, + *, + crystal: PhaseMatching | None = None, + omega: ArrayLike | None = None, + omega0: float | None = None, ) -> NDArray[np.float64]: """Rescale a SHG trace's frequency rows onto the spectrum-predicted marginal. @@ -181,6 +187,14 @@ def apply_marginal_correction( are zeroed), which corrects a measured/efficiency tilt along the spectral axis without touching the delay structure. + With a ``crystal`` the prediction is the crystal model's marginal + (:func:`croak.crystals.shg_marginal`): the autoconvolution filtered by the + crystal's phase matching and weighted by its generation prefactor. The + correction then removes only what the model leaves out (the spectrometer's and + detector's response, the nonlinear coefficient's dispersion, the beams' + overlap), and a retrieval with the same crystal sees a trace whose marginal its + model can reproduce. + Shared by :func:`croak.preprocess.load_and_clean` (the ``marginal_correct`` option) and the marginal-check stage's live preview, so the correction is defined in exactly one place. @@ -191,14 +205,31 @@ def apply_marginal_correction( SHG trace ``(Nomega, Ndelay)`` on the centred frequency grid. Iomega : array_like Independent fundamental spectral intensity on the same grid (centred). + crystal : PhaseMatching, optional + The crystal the trace was measured through; ``None`` (default) for a thin + medium. + omega : array_like, optional + The centred frequency grid (rad/s) of ``trace`` and ``Iomega``; needed with + ``crystal``. + omega0 : float, optional + Pulse carrier (rad/s), as the retrieval uses it; needed with ``crystal``. Returns ------- numpy.ndarray A new corrected trace ``(Nomega, Ndelay)``; the input is not mutated. + + Raises + ------ + ValueError + If ``crystal`` is given without ``omega`` and ``omega0``, or ``omega`` is + not the trace's centred frequency grid. """ trace = np.asarray(trace, dtype=float) - IwSHG = spectral_autoconvolution(Iomega, circular=True) + if crystal is None: + IwSHG = spectral_autoconvolution(Iomega, circular=True) + else: + IwSHG = _crystal_trace_marginal(trace, Iomega, crystal, omega, omega0) peak = np.max(IwSHG) if peak > 0: IwSHG = IwSHG / peak @@ -213,6 +244,37 @@ def apply_marginal_correction( return out +def _crystal_trace_marginal( + trace: NDArray[np.float64], + Iomega: ArrayLike, + crystal: PhaseMatching, + omega: ArrayLike | None, + omega0: float | None, +) -> NDArray[np.float64]: + """Return the crystal model's SHG marginal on the trace's own centred grid.""" + if omega is None or omega0 is None: + raise ValueError( + "a crystal marginal correction needs the grid omega and omega0" + ) + omega = np.asarray(omega, dtype=float) + if omega.shape != (trace.shape[0],): + raise ValueError( + f"omega has shape {omega.shape}, the trace {trace.shape[0]} frequency rows" + ) + # The linear marginal starts at twice the grid's first offset; the trace's row k + # sits at offset omega[k] around the signal carrier 2 * omega0. That holds on a + # centred grid (croak.grid.Grid.omega), which has zero offset on a sample. + domega = float(omega[1] - omega[0]) + start = round(-float(omega[0]) / domega) + if not (0 <= start < omega.size and abs(omega[start]) < 1e-6 * abs(domega)): + raise ValueError( + "omega must be the trace's centred grid (offsets from the carrier, with " + "a sample at zero), not absolute frequencies" + ) + marginal = shg_marginal(omega + omega0, Iomega, crystal, omega0) + return marginal[start : start + omega.size] + + def _transform_limited_intensity_factors( omega: NDArray[np.float64], spectrum: NDArray[np.float64] ) -> tuple[NDArray[np.float64], NDArray[np.float64]]: @@ -246,7 +308,12 @@ def _transform_limited_intensity_factors( # Predictions # --------------------------------------------------------------------------- def predicted_centroid( - omega: ArrayLike, spectrum: ArrayLike, interaction: str + omega: ArrayLike, + spectrum: ArrayLike, + interaction: str, + *, + crystal: PhaseMatching | None = None, + omega0: float | None = None, ) -> float: r"""Predicted marginal centroid (rad/s) from the fundamental spectrum. @@ -254,6 +321,8 @@ def predicted_centroid( axis) and :math:`\bar\omega_S` for PG/TG/SD (the marginal sits at the fundamental). For SHG and PG/TG this is a hard, phase-independent check; for SD it holds only for a transform-limited or temporally symmetric pulse. + Through a ``crystal`` (SHG only) it is the centroid of the crystal model's + marginal (:func:`croak.crystals.shg_marginal`), still phase-independent. Parameters ---------- @@ -263,10 +332,23 @@ def predicted_centroid( Fundamental spectral intensity :math:`S(\omega)` (``>= 0``). interaction : str ``"shg"``, ``"sd"``, ``"pg"`` or ``"tg"`` (case-insensitive). + crystal : PhaseMatching, optional + The SHG crystal; ``None`` (default) for a thin medium. + omega0 : float, optional + Pulse carrier (rad/s) as the retrieval uses it; needed with ``crystal``. + + Raises + ------ + ValueError + If ``crystal`` is given for an interaction other than SHG, or without + ``omega0``. """ name = _normalise_interaction(interaction) omega = np.asarray(omega, dtype=float) spectrum = np.asarray(spectrum, dtype=float) + if crystal is not None: + axis, shape = _crystal_shape(omega, spectrum, name, crystal, omega0) + return moment(axis, shape, 1) c_s = moment(omega, spectrum, 1) return 2.0 * c_s if name == "shg" else c_s @@ -316,7 +398,12 @@ class MarginalPrediction: def predicted_marginal( - omega: ArrayLike, spectrum: ArrayLike, interaction: str + omega: ArrayLike, + spectrum: ArrayLike, + interaction: str, + *, + crystal: PhaseMatching | None = None, + omega0: float | None = None, ) -> MarginalPrediction: r"""Predict the FROG marginal and its checks from the fundamental spectrum. @@ -337,6 +424,13 @@ def predicted_marginal( interaction : str ``"shg"``, ``"sd"``, ``"pg"`` or ``"tg"`` (case-insensitive); ``"tg"`` is identical to ``"pg"`` (the transient-grating gate is :math:`|E|^2`). + crystal : PhaseMatching, optional + The SHG crystal. The prediction is then the crystal model's marginal + (:func:`croak.crystals.shg_marginal`): exact for that model, so its + centroid and width stay hard checks, but no longer :math:`2\bar\omega_S` + and :math:`\sqrt2\sigma_S`. ``None`` (default) for a thin medium. + omega0 : float, optional + Pulse carrier (rad/s) as the retrieval uses it; needed with ``crystal``. Returns ------- @@ -347,7 +441,9 @@ def predicted_marginal( Raises ------ ValueError - If ``interaction`` is unknown or ``omega``/``spectrum`` are degenerate. + If ``interaction`` is unknown or ``omega``/``spectrum`` are degenerate, or + ``crystal`` is given for an interaction other than SHG or without + ``omega0``, or the spectrum generates no SHG through it. """ name = _normalise_interaction(interaction) omega = np.asarray(omega, dtype=float) @@ -358,9 +454,22 @@ def predicted_marginal( raise ValueError("spectrum and omega must have the same shape") domega = float(omega[1] - omega[0]) + if crystal is not None: + axis, shape = _crystal_shape(omega, spectrum, name, crystal, omega0) + return MarginalPrediction( + interaction=name, + omega=axis, + marginal=shape / shape.max(), + centroid=moment(axis, shape, 1), + rms_width=rms_width(axis, shape), + width_bracket=None, + centroid_is_hard=True, + width_is_hard=True, + sigma_spectrum=rms_width(omega, spectrum), + ) + c_s = moment(omega, spectrum, 1) sigma_s = rms_width(omega, spectrum) - if name == "shg": shape = spectral_autoconvolution(spectrum) rms = np.sqrt(2.0) * sigma_s @@ -401,6 +510,25 @@ def predicted_marginal( ) +def _crystal_shape( + omega: NDArray[np.float64], + spectrum: NDArray[np.float64], + name: str, + crystal: PhaseMatching, + omega0: float | None, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """Return the crystal model's SHG marginal and its absolute axis (rad/s).""" + if name != "shg": + raise ValueError(f"a crystal marginal is for SHG, not {name!r}") + if omega0 is None: + raise ValueError("a crystal marginal needs the pulse carrier omega0") + shape = shg_marginal(omega, spectrum, crystal, omega0) + if not shape.any(): + raise ValueError("the spectrum generates no SHG through the crystal") + axis = 2.0 * omega[0] + float(omega[1] - omega[0]) * np.arange(shape.size) + return axis, shape + + def _width_of_shape(shape: NDArray[np.float64], domega: float) -> float: """RMS width of a convolution shape on a uniform grid of spacing ``domega``.""" axis = np.arange(shape.size, dtype=float) * domega diff --git a/croak/pipeline.py b/croak/pipeline.py index a14571b..995eda5 100644 --- a/croak/pipeline.py +++ b/croak/pipeline.py @@ -8,6 +8,7 @@ from __future__ import annotations +import math import warnings import numpy as np @@ -342,13 +343,7 @@ def retrieve_from_tracedata( stacklevel=2, ) reg_spectrum = 0.0 - if isinstance(material, CrystalSetup) and td.marginal_corrected: - raise ValueError( - "the trace was marginal-corrected, which already divides out an " - "estimate of the crystal's phase-matching response; a crystal model " - "would apply it twice. Load the trace without marginal_correct to " - "retrieve with the crystal" - ) + _check_marginal_medium(td, material, thickness, depth_weight) algo = algorithm.lower() if algo not in ALGORITHMS: raise ValueError(f"unknown algorithm {algorithm!r}") @@ -443,3 +438,57 @@ def retrieve_from_tracedata( rng=rng, callback=callback, ) + + +def _check_marginal_medium( + td: TraceData, + material: str | CrystalSetup | None, + thickness: float, + depth_weight=None, +) -> None: + """Refuse a marginal-corrected trace retrieved through another medium. + + The correction puts the trace's marginal onto a prediction: the thin-medium + autoconvolution, or a crystal model's marginal (``td.marginal_crystal``). Only a + retrieval through the same medium can reproduce it: a crystal model applied to + a thin-medium correction filters by phase matching a second time, and a thin + model cannot produce a crystal-filtered marginal. A generation envelope + (``depth_weight``) reweights the depth integral, so the crystal's marginal is no + longer the one the correction targeted (:func:`croak.crystals.shg_marginal` + weights every depth equally). + """ + if not td.marginal_corrected: + return + crystal = material if isinstance(material, CrystalSetup) else None + corrected = td.marginal_crystal + if corrected is None and crystal is not None: + raise ValueError( + "the trace was marginal-corrected onto the thin-medium marginal, which " + "divides out the crystal's phase matching; a crystal model would apply " + "it again. Load the trace with marginal_crystal set to the crystal, or " + "without marginal_correct" + ) + if corrected is None: + return + if depth_weight is not None: + raise ValueError( + "the trace was marginal-corrected through a crystal with every depth " + "weighted equally; a generation envelope (depth_weight) changes the " + "crystal's marginal. Retrieve without the envelope, or load the trace " + "without marginal_correct" + ) + if crystal is None: + got = "no crystal" + elif crystal != corrected.setup: + # CrystalSetup compares its index functions by identity, so pass the same + # crystal object (or a built-in one, which is cached) to both + got = "another crystal set-up: pass the CrystalSetup the correction used" + elif not math.isclose(thickness, corrected.thickness): + got = f"{thickness * 1e6:g} um" + else: + return + raise ValueError( + f"the trace was marginal-corrected through {corrected.thickness * 1e6:g} um " + f"of a crystal, so it must be retrieved through the same crystal set-up and " + f"thickness (got {got})" + ) diff --git a/croak/preprocess.py b/croak/preprocess.py index 2d55e1e..d93c277 100644 --- a/croak/preprocess.py +++ b/croak/preprocess.py @@ -37,6 +37,7 @@ from scipy.linalg import solveh_banded from .constants import C +from .crystals import PhaseMatching from .grid import Grid, gridparams_lambda from .interactions import get_interaction from .marginal_checks import apply_marginal_correction @@ -1255,6 +1256,7 @@ def regrid( trange: float | None = None, resample_t: bool = False, marginal_correct: bool = False, + marginal_crystal: PhaseMatching | None = None, prefilter: bool = True, taper_warn_level: float = 0.01, ): @@ -1280,6 +1282,9 @@ def regrid( Resample the delay axis onto the grid time axis. marginal_correct : bool, optional Apply SHG autoconvolution marginal correction (needs a spectrum). + marginal_crystal : PhaseMatching, optional + With ``marginal_correct``, correct onto the marginal through this crystal + (:func:`croak.marginal_checks.apply_marginal_correction`). prefilter : bool, optional Anti-alias before downsampling in :func:`resample_spectrum`. taper_warn_level : float, optional @@ -1345,8 +1350,13 @@ def regrid( if inter.name != "shg": raise ValueError("marginal correction is only implemented for SHG") # Scale each frequency row onto the spectrum-predicted SHG marginal (the - # spectral autoconvolution); shared with the marginal-check preview. - out = apply_marginal_correction(out, Iomega) + # spectral autoconvolution, through the crystal if one is given); shared + # with the marginal-check preview. + out = apply_marginal_correction( + out, Iomega, crystal=marginal_crystal, omega=grid.omega, omega0=omega0_pulse + ) + elif marginal_crystal is not None: + raise ValueError("marginal_crystal applies only with marginal_correct=True") if resample_t: outt = np.empty((grid.n, grid.n)) @@ -1486,9 +1496,14 @@ class TraceData: through the regrid. marginal_corrected : bool Whether the trace's frequency rows were rescaled onto the - spectrum-predicted SHG marginal (``marginal_correct``). A crystal model - refuses such a trace: the correction already divides out an estimate of - the crystal's phase-matching response, which the model would apply again. + spectrum-predicted SHG marginal (``marginal_correct``). + marginal_crystal : PhaseMatching or None + The crystal the marginal correction predicted through, or ``None`` (a + thin medium, or no correction). A retrieval of a corrected trace must use + the same medium: a thin-medium correction divides out the crystal's + phase-matching response, which a crystal model would apply again, and a + crystal correction puts it in, which a thin model cannot reproduce + (:func:`croak.pipeline.retrieve_from_tracedata`). """ interaction: str @@ -1513,6 +1528,7 @@ class TraceData: scalecurve: NDArray[np.float64] taper_loss: float = 0.0 marginal_corrected: bool = False + marginal_crystal: PhaseMatching | None = None @property def omega(self) -> NDArray[np.float64]: @@ -1552,6 +1568,7 @@ def load_and_clean( threshold: float | None = None, roll_bins: int = 3, marginal_correct: bool = False, + marginal_crystal: PhaseMatching | None = None, prefilter: bool = True, taper_warn_level: float = 0.01, lam_spec: ArrayLike | None = None, @@ -1672,6 +1689,13 @@ def load_and_clean( Rescale the trace so its frequency marginal matches the one predicted from the independent spectrum (SHG only; see :mod:`croak.marginal_checks`). Default ``False``. + marginal_crystal : PhaseMatching, optional + With ``marginal_correct``, the SHG crystal the trace was measured through: + the correction then targets the crystal model's marginal + (:func:`croak.crystals.shg_marginal`), so it removes the instrument's + spectral response but keeps the crystal's phase matching for the + retrieval's crystal model to describe. ``None`` (default) for a thin + medium. Recorded as :attr:`TraceData.marginal_crystal`. prefilter : bool, optional Apply the **anti-alias low-pass** before downsampling in :func:`regrid`. Default ``True``, and it should normally stay on: @@ -1764,6 +1788,7 @@ def load_and_clean( trange=trange, resample_t=resample_t, marginal_correct=marginal_correct, + marginal_crystal=marginal_crystal, prefilter=prefilter, taper_warn_level=taper_warn_level, ) @@ -1806,4 +1831,5 @@ def load_and_clean( scalecurve=sc, taper_loss=taper_loss, marginal_corrected=marginal_correct, + marginal_crystal=marginal_crystal, ) diff --git a/croak/scripting.py b/croak/scripting.py index 22778ed..442a02e 100644 --- a/croak/scripting.py +++ b/croak/scripting.py @@ -43,11 +43,14 @@ #: ``data`` and ``tracedata`` are built. Everything after it is shared. _LOAD_STEPS: dict[str, str] = { "experimental": ( - "data = assemble_load_data(load)\ntracedata = build_tracedata(preproc, data)" + "data = assemble_load_data(load)\n" + "crystal = correction_crystal(preproc, retrieve, data['interaction'])\n" + "tracedata = build_tracedata(preproc, data, crystal=crystal)" ), "simulated": ( "data = assemble_simulated_load_data(simulated)\n" - "tracedata = build_tracedata(preproc, data)" + "crystal = correction_crystal(preproc, retrieve, data['interaction'])\n" + "tracedata = build_tracedata(preproc, data, crystal=crystal)" ), # Keep the lightweight display/truth bundle alongside the native-grid trace: # ``data['truth']`` carries the complex ModelPNPS seed when requested. @@ -59,10 +62,13 @@ #: Extra names each variant needs from ``croak.session.params`` / ``.pipeline``. _LOAD_IMPORTS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = { - "experimental": (("LoadParams",), ("assemble_load_data", "build_tracedata")), + "experimental": ( + ("LoadParams",), + ("assemble_load_data", "build_tracedata", "correction_crystal"), + ), "simulated": ( ("SimulatedLoadParams",), - ("assemble_simulated_load_data", "build_tracedata"), + ("assemble_simulated_load_data", "build_tracedata", "correction_crystal"), ), "simulated-raw": ( ("SimulatedLoadParams",), diff --git a/croak/session/engine.py b/croak/session/engine.py index 9c4005e..d0a5536 100644 --- a/croak/session/engine.py +++ b/croak/session/engine.py @@ -95,7 +95,10 @@ def _preproc_stage(options: SessionOptions, data: dict) -> TraceData: """ if options.entry == "simulated" and options.simulated.raw_direct: return pipeline.assemble_simulated_tracedata(options.simulated) - return pipeline.build_tracedata(options.preproc, data) + crystal = pipeline.correction_crystal( + options.preproc, options.retrieve, data["interaction"] + ) + return pipeline.build_tracedata(options.preproc, data, crystal=crystal) def _check_stages(stages: tuple[str, ...]) -> list[str]: diff --git a/croak/session/pipeline.py b/croak/session/pipeline.py index 61211d4..a594a1e 100644 --- a/croak/session/pipeline.py +++ b/croak/session/pipeline.py @@ -29,6 +29,7 @@ CrystalApproximationWarning, CrystalSetup, DelayedBeam, + PhaseMatching, Polarization, builtin_crystal, depth_points, @@ -39,6 +40,7 @@ from ..geometry import TwoBeamGeometry from ..grid import Grid from ..interactions import get_interaction +from ..maths import wlfreq from ..pipeline import retrieve_from_tracedata from ..preprocess import TraceData from ..processing import ( @@ -696,13 +698,22 @@ def assemble_simulated_tracedata(p: SimulatedLoadParams) -> TraceData: def build_tracedata( - p: PreprocParams, data: dict, *, fast_baseline: bool = False + p: PreprocParams, + data: dict, + *, + crystal: PhaseMatching | None = None, + fast_baseline: bool = False, ) -> TraceData: """Clean and regrid a loaded trace into a :class:`~croak.preprocess.TraceData`. Maps the (nm/fs) preprocess parameters onto :func:`croak.preprocess.load_and_clean` SI arguments. + ``crystal`` is the SHG crystal the trace was measured through + (:func:`marginal_crystal`); the marginal correction, when ``p.marginal_correct`` + asks for it, then targets the crystal model's marginal. It is not used + otherwise. + ``fast_baseline`` (off by default) solves the arPLS baseline on a coarse delay grid and skips near-zero rows — a ~3× speedup at ~1 % baseline difference, for the GUI's interactive preview. Headless replay and direct callers get @@ -741,6 +752,7 @@ def build_tracedata( subsample=p.subsample_tau if p.use_subsample else None, threshold=p.threshold if p.use_threshold else None, marginal_correct=p.marginal_correct, + marginal_crystal=crystal if p.marginal_correct else None, prefilter=p.prefilter, lam_spec=data["lam_spec"], Ilam_spec=data["Ilam_spec"], @@ -930,6 +942,44 @@ def crystal_setup(p: RetrieveParams) -> CrystalSetup: ) +def marginal_crystal(p: RetrieveParams, interaction: str) -> PhaseMatching | None: + """Return the crystal an SHG trace's marginal is predicted through, if any. + + The retrieval's crystal and thickness (:func:`crystal_setup`) for an SHG trace + with ``dispersive`` set, so that the marginal correction and the retrieval + always describe the same medium; ``None`` otherwise. + """ + if not p.dispersive or get_interaction(interaction).name != "shg": + return None + return PhaseMatching(crystal_setup(p), p.thickness_um * 1e-6) + + +def correction_crystal( + preproc: PreprocParams, retrieve: RetrieveParams, interaction: str +) -> PhaseMatching | None: + """Return the crystal :func:`build_tracedata` corrects the marginal through. + + :func:`marginal_crystal` when ``preproc.marginal_correct`` asks for a + correction, ``None`` otherwise (so crystal settings that do not describe a + valid crystal fail only when they are used). + """ + if not preproc.marginal_correct: + return None + return marginal_crystal(retrieve, interaction) + + +def pulse_carrier(p: PreprocParams) -> float: + """Return the pulse carrier (rad/s) the regridded retrieval grid will have. + + The middle of the retrieval band in angular frequency, as + :func:`croak.grid.gridparams_lambda` places it; the crystal's angle and path + are taken there, so a prediction made before preprocessing matches the one + the correction makes. The simulated loader's ``raw_direct`` path keeps the + simulation's own carrier instead (and applies no correction). + """ + return 0.5 * float(wlfreq(p.lam_min_nm * 1e-9) + wlfreq(p.lam_max_nm * 1e-9)) + + def retrieval_medium(p: RetrieveParams, td: TraceData) -> str | CrystalSetup | None: """Return what the forward model propagates through: ``None``, a slab or a crystal. @@ -1493,6 +1543,14 @@ def run_uncertainty( "the thickness uncertainty needs dispersive propagation: switch on " "the slab, or for SHG the crystal, whose thickness is uncertain" ) + if td.marginal_crystal is not None: + # each draw would retrieve at another thickness a trace whose marginal + # was put onto the central thickness's prediction + raise ValueError( + "the thickness uncertainty cannot use a trace marginal-corrected " + "through the crystal: the correction fixes its marginal to the " + "central thickness. Switch off the marginal correction for it" + ) # Central thickness from the retrieval settings; 1σ from the uncertainty # stage. The dispersive pair is injected per draw, so drop it from kw to # avoid colliding with the explicit `material=` keyword below. diff --git a/croak/uncertainty.py b/croak/uncertainty.py index 2951cca..66fc6a4 100644 --- a/croak/uncertainty.py +++ b/croak/uncertainty.py @@ -871,7 +871,10 @@ def thickness_bootstrap( forwarded ``retrieve_kwargs`` must reproduce the original settings. measured : array_like The measured trace ``(Nomega, Ndelay)`` to re-fit at each drawn thickness - (the data are held fixed; only the assumed thickness varies). + (the data are held fixed; only the assumed thickness varies). Not a trace + marginal-corrected through the crystal + (:attr:`croak.preprocess.TraceData.marginal_crystal`): the correction fixes + its marginal to the central thickness's, which the draws would then misfit. central_thickness : float Central (measured) substrate thickness :math:`L_0` in **metres**. thickness_sigma : float diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index a4c3323..5d3f778 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -144,13 +144,17 @@ frequency marginal is therefore the sum over pairs of $a^2\lvert E(\omega_1)E(\omega_2)\rvert^2 P^2\mathrm{sinc}^2(\Delta k P/2)$, with $a$ the generation prefactor below, which `tests/test_forward_crystal.py` checks to the quadrature's accuracy. +{func}`croak.crystals.shg_marginal` computes it from the fundamental spectrum, for +the marginal checks and the marginal correction ({doc}`marginals`). **Generation prefactor.** The generated second-harmonic field grows as $\omega_s/n_s$, so the model multiplies the signal by $a(\Omega) = (\omega_s/n_s)/(2\omega_0/n_s(2\omega_0))$. Other spectral factors (the beams' mode overlap, the dispersion of $\chi^{(2)}$, the detector's response) are not modelled; the solvers' per-frequency response `R_omega` absorbs any that -matter. +matter, or, with an independent spectrum, the marginal correction through the +crystal removes them before the retrieval +([Marginal consistency checks](../howto/marginal_checks.md#through-an-shg-crystal)). **The crystal's angle.** A {class}`~croak.crystals.CrystalSetup` takes the manufacturer's cut angle $\theta_c$ and either the external tilt $\gamma$ or the diff --git a/docs/explanation/marginals.md b/docs/explanation/marginals.md index 410b5dc..a958707 100644 --- a/docs/explanation/marginals.md +++ b/docs/explanation/marginals.md @@ -108,6 +108,98 @@ The three identities are: Place the prediction on the second-harmonic frequency axis and compare to the measured marginal after consistent wavelength calibration. +### Through a nonlinear crystal + +In croak's crystal model ({doc}`forward_model`) the second harmonic is generated +throughout the crystal and each component pair carries its own phase matching. The +marginal is still phase-independent, and it follows from the model's signal in +four steps. Frequencies here are offsets from the carriers, $\Omega$ from +$\omega_0$ for a fundamental and from $2\omega_0$ for the signal, and $\tilde E$ is +the fundamental's spectrum, with $S = \lvert\tilde E\rvert^2$. + +**1. The signal of one pair.** The model propagates both arms to depth $z$ +($e^{i\beta_\mathrm{in}z}$), multiplies them, and carries what is generated there to +the exit face ($a(\Omega)\,e^{i\beta_\mathrm{sig}(P-z)}$), integrating over the path +$P$. The gate arm carries the delay as $e^{i\Omega\tau}$. Crossing in the principal +plane, the arms also drift apart in delay with depth, at the rate $\kappa$ +({meth}`~croak.crystals.CrystalSetup.arm_shift`): the test arm carries +$e^{i\kappa\Omega(P/2-z)}$ and the gate its inverse ($\kappa = 0$ otherwise). +A product in time is a convolution in frequency, so with $\Omega_1$ the test +component and $\Omega_2 = \Omega-\Omega_1$ the gate component, up to the +transforms' constant factors, + +```{math} +\psi(\Omega,\tau) = a(\Omega)\,e^{i\beta_\mathrm{sig}(\Omega)P}\int +\tilde E(\Omega_1)\,\tilde E(\Omega_2)\,e^{i\Omega_2\tau}\, +e^{i\kappa(\Omega_1-\Omega_2)P/2} +\int_0^P e^{i q z}\,\mathrm dz\;\mathrm d\Omega_1 , +``` + +with every depth-dependent phase collected in + +```{math} +q(\Omega_1,\Omega_2) = \beta_\mathrm{in}(\Omega_1) + \beta_\mathrm{in}(\Omega_2) +- \beta_\mathrm{sig}(\Omega_1+\Omega_2) - \kappa(\Omega_1-\Omega_2). +``` + +**2. The frame drops out.** Both propagation constants are written in the frame +moving at the fundamental's group velocity, $\beta_\mathrm{in}(\Omega) = +k_z(\omega_0+\Omega) - \beta_1\Omega$ and $\beta_\mathrm{sig}(\Omega) = +k_s(2\omega_0+\Omega) - \beta_1\Omega$. In $q$ the $\beta_1$ terms are +$-\beta_1(\Omega_1+\Omega_2-\Omega)=0$, so $q = -\Delta k - \kappa(\Omega_1-\Omega_2)$ +with the pair's true wavevector mismatch + +```{math} +\Delta k = k_s(\omega_1+\omega_2) - k_z(\omega_1) - k_z(\omega_2), \qquad +\omega_{1,2} = \omega_0+\Omega_{1,2}. +``` + +**3. The depth integral.** $\int_0^P e^{iqz}\,\mathrm dz = P\,e^{iqP/2}\operatorname{sinc}(qP/2)$, +with $\operatorname{sinc}x = \sin x/x$. Its phase, like $e^{i\beta_\mathrm{sig}P}$ and +the drift's reference phase, does not depend on $\tau$. + +**4. Parseval over delay.** For fixed $\Omega$, step 1 is a Fourier integral over +$\Omega_2$ with conjugate variable $\tau$, so integrating $\lvert\psi\rvert^2$ over +every delay gives $2\pi$ times the integral of the modulus squared of its integrand. +Every phase factor has unit modulus and drops out: + +```{math} +M(\Omega) = \int\lvert\psi(\Omega,\tau)\rvert^2\,\mathrm d\tau += 2\pi\,a(\Omega)^2\int S(\Omega_1)\,S(\Omega-\Omega_1)\, +P^2\operatorname{sinc}^2\!\bigl(q\,P/2\bigr)\,\mathrm d\Omega_1 . +``` + +On croak's grid the same steps hold for a sum over the $N$ delays of one period of +the time axis, which gives $N$ times the sum over pairs; the model does the depth +integral by quadrature, accurate to the tolerance of +{func}`~croak.crystals.depth_points`. {func}`croak.crystals.shg_marginal` evaluates +the pair sum with the analytic depth integral, and it matches the model's +delay-summed trace to about $10^{-6}$ of the peak (`tests/test_marginal_crystal.py`). + +What the result says: + +- It is still **phase-independent** and computable from $S$, so it remains an + exact check, but of the model: the centroid and width are those of this $M$, no + longer $2\bar\omega_S$ and $\sqrt2\,\sigma_S$. +- **The drift enters at second order.** The pair $(\Omega_1,\Omega_2)$ and the + swapped pair $(\Omega_2,\Omega_1)$ have the same weight $S(\Omega_1)S(\Omega_2)$ + and the same $\Delta k$, but opposite drift terms. Their sum, + $\operatorname{sinc}^2[(\Delta k + \kappa\delta)P/2] + + \operatorname{sinc}^2[(\Delta k - \kappa\delta)P/2]$ with $\delta = \Omega_1-\Omega_2$, + is even in $\kappa$, so the sign of $\kappa$ does not matter. +- **Smearing leaves it unchanged:** it convolves the trace along delay with a kernel + of unit area, which does not change the delay integral. +- **Zero thickness:** the model then has no depth integral (one node of unit + weight), and $M = a^2\,(S*S)$, the thin-medium marginal times the prefactor. +- **The assumptions are the thin case's:** the delay scan holds the whole trace, + which in a crystal includes the walk-off's tails, and the whole beam is + collected, as the model assumes. + +The same $M$ is the target of the marginal correction for a crystal trace +({func}`croak.marginal_checks.apply_marginal_correction` with a crystal): the +correction then takes out the spectral response the model does not describe and +keeps the phase matching, which the retrieval's crystal model supplies. + ## PG (and TG) — three checks ```{math} diff --git a/docs/howto/geometric_smearing.md b/docs/howto/geometric_smearing.md index 9dd260d..75b08fd 100644 --- a/docs/howto/geometric_smearing.md +++ b/docs/howto/geometric_smearing.md @@ -300,9 +300,10 @@ result when durations are rms widths and diameters 1/e² ones. ## In the GUI -For SHG data the smearing is in the Retrieve stage's **Beam geometry** group: the -beams' separation, focal length and diameter, *Model the delay smearing*, and a -read-out of the width in rms and FWHM. For PG and SD, the Retrieve stage has a +For SHG data the beams' separation, focal length and diameter are set in the +**Beam geometry** group on the Data stage, which reads out the width in rms and +FWHM; the Retrieve stage has *Model the delay smearing*, enabled when the chosen +solver supports it, and a summary of the beams. For PG and SD, the Retrieve stage has a **Geometrical smearing** group, greyed out unless the chosen solver supports it: - *Enable geometrical smearing* diff --git a/docs/howto/gui.md b/docs/howto/gui.md index aa4d7d9..5aee0d2 100644 --- a/docs/howto/gui.md +++ b/docs/howto/gui.md @@ -284,6 +284,29 @@ The trace preview uses the same colour scheme as Prepare (white→viridis for positive, white→red for negative), with the display scaled to the in-trust-band signal so an aggressive efficiency tilt cannot wash the image out. +(the-shg-crystal-and-the-beams)= +#### The SHG crystal and the beams + +For an SHG trace the measured and synthetic loaders show two more sections, +*Nonlinear crystal* and *Beam geometry*. They describe the apparatus, so they +are set with the data: [Check](#check) predicts the marginal through them, the +marginal correction corrects onto that prediction, a synthetic trace is +generated through them, and [Retrieve](#retrieve) models them. **Model the +crystal** switches the crystal on (with it off, SHG is the thin-medium model); +then come the crystal, its **thickness**, **cut angle**, the **phase-matched +wavelength** or **external tilt** that sets its angle, the fundamental's +**polarisation** relative to the plane in which the beams cross, and the +**delayed beam**'s side of the optic axis. *Beam geometry* holds the **beam +separation** and **focal length** that set the crossing angle and the beams' +**diameter**, which sets their delay smearing. Read-outs give the internal +angle, the tilt, the path and the crossing angle, and the smearing width, +evaluated at the prepared trace's carrier once there is one, before that at the +centre of the Prepare band, and before any data at the phase-matched +wavelength; the depth nodes follow once the trace is prepared +([SHG with a thick crystal](shg_crystal.md)). The settings are the session's +retrieval settings, saved with it, so the thickness and focal length are the +same values as Retrieve's slab thickness and focal mixture. + #### Load the scan (simulated) Load a numerically simulated `scansave` scan and preview it live. A @@ -297,7 +320,9 @@ straight to Retrieve. See #### Generate the trace (synthetic) Build a test trace (pulse shape, interaction, delays, optional dispersive slab, -for SHG optionally the nonlinear crystal the Retrieve stage describes, and noise) using {func}`~croak.forward.maketrace`, previewed live. Useful for +for SHG optionally through the [crystal and beams](#the-shg-crystal-and-the-beams) +set on the same page, and noise) using {func}`~croak.forward.maketrace`, +previewed live. Useful for trying the workflow without data. The **duration** is the intensity (power) FWHM of the temporal envelope — both Gaussian and sech² honour this convention ({func}`~croak.pulses.gaussian_pulse`, {func}`~croak.pulses.sech_pulse`). The @@ -316,7 +341,12 @@ the retrieved pulse, and saved with the result. Compare the trace's frequency marginal with the marginal **predicted** from the independent spectrum ({mod}`croak.marginal_checks`): exact for SHG (the spectral autoconvolution) and transform-limited for PG/TG/SD, within the thin local -model; the [marginal guide](marginal_checks.md) states its assumptions. The page +model; the [marginal guide](marginal_checks.md) states its assumptions. When the +crystal is modelled on the [Data stage](#the-shg-crystal-and-the-beams), the +SHG prediction is the crystal model's marginal through it instead, taken at the +carrier of the Prepare band; the legend and the summary say which one is shown +("thin medium" or "through the crystal, L µm"), and settings that give no valid +crystal fall back to the thin-medium prediction with a warning. The page overlays the predicted marginal, marks the predicted vs measured **centroid**, reports the **width-bracket** check, and exposes the spectral **trust region** (defaults to 190–1000 nm for a measured trace, or the full loaded range for the @@ -326,10 +356,15 @@ and the **3rd-order** `(λ/µm)^exp` efficiency correction. Its **Auto** button picks the exponent whose corrected-marginal centroid matches the prediction ({func}`~croak.marginal_checks.auto_third_order_exponent`). The **SHG marginal correction** is available here: it scales the trace's frequency rows onto the -predicted SHG autoconvolution +predicted SHG marginal ({func}`~croak.marginal_checks.apply_marginal_correction`), is enabled only for an SHG trace with an independent spectrum, and previews the snap onto the -prediction live (the correction itself is applied in Prepare). All three kinds +prediction live (the correction itself is applied in Prepare, through the same +crystal). With the crystal modelled it corrects onto the crystal's marginal: it +removes the instrument's spectral response but keeps the phase matching, which +the retrieval then models with the same crystal. The prediction is redrawn each +time the page is entered, so a crystal changed on the Data stage shows at once. +All three kinds of session pass through this stage, except a raw simulated scan; see [Marginal consistency checks](marginal_checks.md). @@ -446,12 +481,11 @@ shows `ε(Iₜ)` alone rather than a number derived from something else. *Dispersive propagation* models a slab (material, thickness, Δz/Npoints — see [The forward model](../explanation/forward_model.md)). For SHG data it is -replaced by *Nonlinear crystal* (the crystal, its thickness, cut angle, -phase-matched wavelength or external tilt, the polarisation relative to the -crossing plane and the delayed beam's side) and *Beam geometry* (the beam -separation and focal length that set the crossing angle, and the beams' diameter -and the switch for the two beams' delay smearing), with read-outs of the -internal angle, the tilt, the path, the depth nodes and the smearing width +replaced by *Crystal and beams (SHG)*: a read-only summary of the crystal and +the beams set on the [Data stage](#the-shg-crystal-and-the-beams) (the crystal, +its thickness and cut, the internal angle, the tilt, the path and the depth +nodes, the beams and their smearing width), and the switch **Model the delay +smearing**, which is a retrieval choice and stays here ([SHG with a thick crystal](shg_crystal.md)). *Geometrical smearing* models the tilted-pulse-front temporal blur of a non-collinear BOXCARS setup from the mask hole diameter and edge-to-edge spacing, with the resulting delay diff --git a/docs/howto/marginal_checks.md b/docs/howto/marginal_checks.md index 3cf4e95..d15a2b0 100644 --- a/docs/howto/marginal_checks.md +++ b/docs/howto/marginal_checks.md @@ -11,6 +11,8 @@ page is the recipe. The identities assume a thin, local interaction and complete delay support; a dispersive slab, smearing or a finite collection aperture also reshape the marginal. +For SHG through a crystal, the prediction can include the crystal's phase matching +(see [Through an SHG crystal](#through-an-shg-crystal) below). ## Predict a marginal from a spectrum @@ -95,6 +97,64 @@ corrected = trace * croak.preprocess.third_order_scale(lam, n)[:, None] This fits one empirical response exponent; it does not correct delay-dependent collection effects. +## Through an SHG crystal + +In a crystal of tens of µm the phase matching filters the SHG marginal strongly, +so the thin-medium $S*S$ would flag a correct trace. Give the prediction the +crystal ({class}`croak.crystals.PhaseMatching`: a +{class}`~croak.crystals.CrystalSetup` and its thickness) and the carrier the +retrieval uses, and it becomes the crystal model's own marginal +({func}`croak.crystals.shg_marginal`): + +```python +import math +from croak.crystals import CrystalSetup, PhaseMatching, builtin_crystal +from croak.geometry import TwoBeamGeometry + +crystal = CrystalSetup( + builtin_crystal("BBO"), + math.radians(29.2), + phase_match_wavelength=800e-9, + geometry=TwoBeamGeometry(beam_separation=5e-3, focal_length=0.2), + polarization="parallel", +) +pm = PhaseMatching(crystal, thickness=50e-6) +pred = mc.predicted_marginal(omega, S, "shg", crystal=pm, omega0=omega0) +pred.centroid, pred.rms_width # of the crystal's marginal, still hard checks +``` + +The centroid and width are no longer $2\bar\omega_S$ and $\sqrt2\,\sigma_S$ but +those of the computed marginal; for the crystal model they are as exact as the +thin-medium ones. The `omega0` is the retrieval grid's carrier +(`td.omega0_pulse`; the middle of the retrieval band), at which an explicit tilt is +refracted and the path and delay drift are taken. + +The **marginal correction** can target the same prediction. Load the trace with +the crystal it was measured through: + +```python +td = croak.preprocess.load_and_clean( + trace, lam, delays, "shg", lam_min=600e-9, lam_max=1100e-9, + lam_spec=lam_spec, Ilam_spec=Ilam_spec, + marginal_correct=True, marginal_crystal=pm, +) +``` + +Each frequency row is then rescaled onto the crystal's marginal, which removes +what the model leaves out (the spectrometer's and detector's response, the +dispersion of the nonlinear coefficient, the beams' overlap) and keeps the phase +matching for the retrieval's crystal model to describe. `td.marginal_crystal` +records the crystal, and {func}`~croak.pipeline.retrieve_from_tracedata` refuses to +retrieve a corrected trace through any other medium: a thin-medium correction +divides out the phase matching, which a crystal model would apply again, and a +crystal correction leaves in a filter a thin model cannot reproduce. A session +uses the retrieval's crystal for the correction +({func}`croak.session.pipeline.correction_crystal`), so the two cannot disagree. + +The correction relies on the same assumption as the check: the delay scan holds +the whole trace. A crystal's walk-off lengthens the trace in delay, so check that +the scan covers its tails. + ## In the GUI All of the above is interactive on the GUI's **Check the marginal** step, the @@ -104,8 +164,10 @@ one, marks the predicted vs measured centroid, reports the width-bracket check, and exposes the trust region, a log/linear toggle and the `(λ/µm)^exp` correction with an `Auto` (centroid-matching) button. The **SHG marginal correction** also lives here: it rescales the trace's frequency rows onto the predicted SHG -autoconvolution ({func}`~croak.marginal_checks.apply_marginal_correction`), -enabled only for an SHG trace with an independent spectrum, and previews the snap +marginal ({func}`~croak.marginal_checks.apply_marginal_correction`): the +autoconvolution, or the crystal's marginal when the crystal is modelled (its +settings are on the Data stage, before this step). It is enabled only for an SHG +trace with an independent spectrum, and previews the snap onto the prediction live (the correction itself is applied during preprocessing, via {func}`~croak.preprocess.load_and_clean`'s `marginal_correct`). See the [GUI guide](gui.md). diff --git a/docs/howto/preprocessing.md b/docs/howto/preprocessing.md index f000af4..14f0c91 100644 --- a/docs/howto/preprocessing.md +++ b/docs/howto/preprocessing.md @@ -102,7 +102,8 @@ A few `load_and_clean` keywords do most of the work: - **`lam_spec`, `Ilam_spec`** — an independently measured fundamental spectrum; when supplied it is resampled onto the grid as `td.Iomega` and can seed the guess, drive the [spectral-match penalty](regularisation.md), or enable SHG - marginal correction (`marginal_correct=True`). + marginal correction (`marginal_correct=True`; through a crystal, also + `marginal_crystal`, see [Marginal consistency checks](marginal_checks.md#through-an-shg-crystal)). ## De-fringing: notch vs. Takeda low-pass diff --git a/docs/howto/shg_crystal.md b/docs/howto/shg_crystal.md index 4487aad..3105128 100644 --- a/docs/howto/shg_crystal.md +++ b/docs/howto/shg_crystal.md @@ -88,12 +88,13 @@ crystal by `crystal`, `cut_angle_deg`, `angle_mode` (`"phase-match"` with `thickness_um` is its thickness. For an SHG trace the session builds the crystal from them ({func}`~croak.session.pipeline.crystal_setup`) and uses the depth nodes it needs. `phase_match_nm` defaults to 800 nm: set it to the wavelength the -crystal was tuned for. In the GUI the Retrieve stage shows these as the -*Nonlinear crystal* and *Beam geometry* groups for SHG data, with a read-out of -the internal angle, the tilt, the path and the depth nodes. The Synthetic stage -can generate an SHG trace through the same crystal, at a thickness set there; -switching the crystal on for the retrieval, at that thickness, is a separate -step in the Retrieve stage. +crystal was tuned for. In the GUI they are set on the Data stage, in the +*Nonlinear crystal* and *Beam geometry* groups shown for SHG data, with a read-out +of the internal angle, the tilt, the path and the depth nodes: they describe the +measurement, and the Check step's marginal prediction and correction use them +before the retrieval does. The Retrieve stage shows a read-only summary. The +Synthetic stage generates an SHG trace through the same crystal when it is +switched on. ## Delay smearing @@ -118,16 +119,39 @@ res = croak.retrieve( ``` In a session, `smearing` switches it on and `beam_diameter_mm` gives the -diameter; the GUI shows both in *Beam geometry*. +diameter; the GUI sets the diameter in *Beam geometry* on the Data stage and the +switch, *Model the delay smearing*, on the Retrieve stage, since only some solvers +support it. + +## The marginal correction + +A measured trace carries the instrument's spectral response (spectrometer, +detector, the nonlinear coefficient's dispersion), which the model does not. The +marginal correction removes it by rescaling the trace's frequency rows onto the +marginal predicted from the independent spectrum. Through a crystal that +prediction must include the phase matching, or the correction divides it out and +the crystal model applies it a second time; give the correction the crystal: + +```python +from croak.crystals import PhaseMatching + +td = croak.preprocess.load_and_clean( + ..., lam_spec=lam_spec, Ilam_spec=Ilam_spec, + marginal_correct=True, marginal_crystal=PhaseMatching(crystal, thickness), +) +``` + +A retrieval of the corrected trace must use the same crystal and thickness, and +refuses anything else. A session does this by itself: with `marginal_correct` on, +the correction uses the retrieval's crystal. The marginal checks predict through +the crystal in the same way; see +[Marginal consistency checks](marginal_checks.md#through-an-shg-crystal). ## What is not modelled yet - **Fitting the crystal.** Its thickness and angle are inputs, not fitted parameters ([issue #26](https://github.com/LupoLab/croak/issues/26)); a session's `fit_thickness` is not applied to a crystal. -- **The marginal correction.** A trace loaded with `marginal_correct=True` has - already had an estimate of the phase-matching response divided out, so a - crystal model refuses it. ## How well it works diff --git a/tests/gui/test_crystal_panel.py b/tests/gui/test_crystal_panel.py new file mode 100644 index 0000000..b399d90 --- /dev/null +++ b/tests/gui/test_crystal_panel.py @@ -0,0 +1,181 @@ +"""Tests for the Data stage's crystal panel (:mod:`croak.gui.crystal_panel`). + +The panel edits the session's retrieval settings directly, enables only the +controls the settings use, and describes the crystal and the beams at the best +carrier the session has so far. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +pytest.importorskip("PySide6") + +from croak.grid import Grid +from croak.gui.crystal_panel import CRYSTAL_HELP, CrystalPanel +from croak.gui.help import flatten +from croak.gui.state import WizardState +from croak.session.params import RetrieveParams + + +@pytest.fixture +def panel(qtbot): + widget = CrystalPanel(WizardState()) + qtbot.addWidget(widget) + widget.edits = [] + widget.edited.connect(lambda: widget.edits.append(True)) + return widget + + +def _prepared(panel): + """Give the session a stand-in prepared SHG trace at 800 nm.""" + panel.state.tracedata = SimpleNamespace( + interaction="shg", grid=Grid(64, dt=3e-15), omega0_pulse=2.3546e15, Iomega=None + ) + panel.refresh() + + +def test_crystal_panel_controls_store_their_settings(panel): + p = panel.state.retrieve + panel.crystal_check.setChecked(True) + panel.crystal_combo.setCurrentText("BBO") + panel.thickness_spin.setValue(55.0) + panel.cut_angle_spin.setValue(33.4) + panel.angle_mode_combo.setCurrentText("External tilt") + panel.tilt_spin.setValue(-1.5) + panel.polarization_combo.setCurrentText("Perpendicular to the crossing plane") + panel.delayed_beam_combo.setCurrentText("Away from the optic axis") + panel.separation_spin.setValue(8.0) + panel.focal_f_spin.setValue(250.0) + panel.beam_diameter_spin.setValue(1.5) + assert p.dispersive is True + assert (p.crystal, p.thickness_um, p.cut_angle_deg) == ("BBO", 55.0, 33.4) + assert (p.angle_mode, p.tilt_deg) == ("tilt", -1.5) + assert (p.polarization, p.delayed_beam) == ("perpendicular", "away_from_axis") + assert (p.beam_separation_mm, p.focal_f_mm, p.beam_diameter_mm) == ( + 8.0, + 250.0, + 1.5, + ) + assert panel.edits # every edit is announced + assert panel.tilt_spin.isEnabled() and not panel.phase_match_spin.isEnabled() + panel.angle_mode_combo.setCurrentText("Phase-matched wavelength") + panel.phase_match_spin.setValue(780.0) + assert (p.angle_mode, p.phase_match_nm) == ("phase-match", 780.0) + assert not panel.tilt_spin.isEnabled() + + +def test_crystal_panel_follows_replaced_settings(panel): + # the session may swap its settings object (a reset, a reopened session) + panel.state.retrieve = RetrieveParams() + panel.thickness_spin.setValue(33.0) + assert panel.state.retrieve.thickness_um == 33.0 + + +def test_crystal_panel_delayed_beam_matters_only_in_the_principal_plane(panel): + panel.separation_spin.setValue(5.0) + panel.polarization_combo.setCurrentText("In the crossing plane") + assert not panel.delayed_beam_combo.isEnabled() + panel.polarization_combo.setCurrentText("Perpendicular to the crossing plane") + assert panel.delayed_beam_combo.isEnabled() + panel.separation_spin.setValue(0.0) # collinear: no crossing plane at all + assert not panel.polarization_combo.isEnabled() + assert not panel.delayed_beam_combo.isEnabled() + assert panel.geometry_readout.text() == "Collinear beams: no delay smearing" + + +def test_crystal_panel_readouts_before_any_data(panel): + panel.separation_spin.setValue(5.0) + panel.focal_f_spin.setValue(100.0) + # d = 5 mm, D = 3 mm, f = 100 mm at 800 nm: sigma = lambda d / (sqrt2 pi D c) + assert panel.geometry_readout.text() == ( + "Crossing half-angle α = 1.432°\nDelay smearing σ = 1.00 fs rms (2.36 fs FWHM)" + ) + text = panel.crystal_readout.text() + assert "θ inside" in text and "path =" in text + assert "depth nodes: after Prepare" in text + assert text.endswith("at 800 nm (the phase-matched wavelength)") + + +def test_crystal_panel_readouts_at_the_prepare_band_once_loaded(panel): + panel.state.load_data = {"interaction": "shg"} + panel.state.preproc.lam_min_nm, panel.state.preproc.lam_max_nm = 700.0, 933.3 + panel.refresh() + # the band's centre in frequency: 1/λ = (1/700 + 1/933.3) / 2 + assert panel.crystal_readout.text().endswith( + "at 800 nm (the centre of the Prepare band)" + ) + + +def test_crystal_panel_readouts_of_a_prepared_trace(panel): + _prepared(panel) + panel.thickness_spin.setValue(100.0) + text = panel.crystal_readout.text() + assert "depth nodes = " in text + assert text.endswith("(the prepared trace's carrier)") + # a zero thickness needs no depth nodes + panel.thickness_spin.setValue(0.0) + assert "depth nodes" not in panel.crystal_readout.text() + + +def test_crystal_panel_explains_settings_that_give_no_crystal(panel): + # a cut the wavelength cannot phase-match at any tilt is explained, not raised + panel.cut_angle_spin.setValue(80.0) + assert panel.crystal_readout.text().startswith("No valid crystal:") + + +def test_crystal_panel_refresh_shows_the_stored_settings(panel): + panel.state.retrieve = RetrieveParams( + dispersive=True, + thickness_um=42.0, + cut_angle_deg=31.0, + angle_mode="tilt", + tilt_deg=2.0, + polarization="perpendicular", + delayed_beam="away_from_axis", + beam_separation_mm=6.0, + focal_f_mm=300.0, + ) + panel.edits.clear() + panel.refresh() + assert not panel.edits # showing is not editing + assert panel.crystal_check.isChecked() + assert panel.thickness_spin.value() == 42.0 + assert panel.cut_angle_spin.value() == 31.0 + assert panel.angle_mode_combo.currentText() == "External tilt" + assert panel.tilt_spin.value() == 2.0 + assert panel.polarization_combo.currentText() == ( + "Perpendicular to the crossing plane" + ) + assert panel.delayed_beam_combo.currentText() == "Away from the optic axis" + assert panel.separation_spin.value() == 6.0 + assert panel.focal_f_spin.value() == 300.0 + + +def test_crystal_panel_unknown_stored_setting_is_explained(panel): + panel.state.retrieve = RetrieveParams(angle_mode="bogus") + panel.refresh() + assert panel.crystal_readout.text().startswith("No valid crystal: angle_mode") + + +def test_crystal_panel_is_shown_for_shg_only(panel): + panel.set_shg(False) + assert panel.isHidden() + panel.state.retrieve.thickness_um = 21.0 + panel.set_shg(True) + assert not panel.isHidden() + assert panel.thickness_spin.value() == 21.0 # refreshed as it is shown + + +def test_crystal_panel_controls_carry_their_help(panel): + help_map = flatten(CRYSTAL_HELP) + assert ( + panel.cut_angle_spin.toolTip() + == help_map[("Nonlinear crystal", "Cut angle θc (°)")] + ) + assert ( + panel.beam_diameter_spin.toolTip() + == help_map[("Beam geometry", "Beam diameter (mm)")] + ) diff --git a/tests/gui/test_stage_load.py b/tests/gui/test_stage_load.py index 1514ab7..051faca 100644 --- a/tests/gui/test_stage_load.py +++ b/tests/gui/test_stage_load.py @@ -426,3 +426,39 @@ def test_stage_load_signature_ignores_reverse_trace(stage): ) def test_stage_load_spectrum_dataset_indices(names, expected): assert stage_load._spectrum_dataset_indices(names) == expected + + +# -- the SHG crystal ------------------------------------------------------------ +def test_stage_load_shows_the_crystal_panel_for_shg(stage): + combo = stage.interaction_combo + combo.setCurrentText("pg") + assert stage.state.load.interaction == "pg" + assert stage.crystal_panel.isHidden() + combo.setCurrentText("shg") + assert stage.state.load.interaction == "shg" + assert not stage.crystal_panel.isHidden() + # the panel edits the session's crystal, which the check and retrieval read + stage.crystal_panel.thickness_spin.setValue(250.0) + assert stage.state.retrieve.thickness_um == 250.0 + + +def test_stage_load_on_enter_shows_crystal_settings_changed_elsewhere(stage): + stage.state.load.interaction = "shg" + stage.state.retrieve.dispersive = True + stage.on_enter() + assert stage.crystal_panel.crystal_check.isChecked() + + +@pytest.mark.parametrize("correct", [False, True]) +def test_stage_load_a_crystal_edit_drops_a_trace_corrected_through_it( + stage, monkeypatch, correct +): + # only a trace corrected through the crystal depends on it before retrieval + dropped = [] + monkeypatch.setattr( + stage.state, "invalidate_tracedata", lambda: dropped.append(True) + ) + stage.interaction_combo.setCurrentText("shg") + stage.state.preproc.marginal_correct = correct + stage.crystal_panel.thickness_spin.setValue(123.0) + assert dropped == ([True] if correct else []) diff --git a/tests/gui/test_stage_marginal_check.py b/tests/gui/test_stage_marginal_check.py index 06174ef..25fc3b2 100644 --- a/tests/gui/test_stage_marginal_check.py +++ b/tests/gui/test_stage_marginal_check.py @@ -142,6 +142,71 @@ def test_stage_marginal_check_shg_correction_needs_a_spectrum(stage): assert "(exact)" in stage.status_label.text() # SHG predicts the width exactly +# -- the SHG crystal set on the Data stage -------------------------------------- +def test_stage_marginal_check_predicts_through_the_crystal_and_back(stage): + spec = _data("shg")["Ilam_spec"] + _enter(stage, _data("shg")) + assert "predicted (thin medium)" in _legend(stage.marg_view) + assert stage.status_label.text().startswith("SHG marginal check (thin medium)") + assert "thin medium" in stage.marginal_correct_check.toolTip() + thin = stage._predict(LAM, spec, "shg") + # the crystal is modelled on the Data stage: entering the check follows it + p = stage.state.retrieve + p.dispersive, p.thickness_um = True, 500.0 + stage.on_enter() + assert "predicted (through the crystal, 500 µm)" in _legend(stage.marg_view) + assert stage.status_label.text().startswith( + "SHG marginal check (through the crystal, 500 µm)" + ) + tip = stage.marginal_correct_check.toolTip() + assert "through the crystal, 500 µm" in tip + assert "keeps the crystal's phase matching" in tip + thick = stage._predict(LAM, spec, "shg") + # 500 µm of BBO accepts far less bandwidth than the 30 nm spectrum spans + assert thick["rms_width"] < 0.8 * thin["rms_width"] + # the correction previews onto the same, crystal, prediction + stage.marginal_correct_check.setChecked(True) + assert "trace marginal (corrected)" in _legend(stage.marg_view) + p.dispersive = False + stage.on_enter() + assert "predicted (thin medium)" in _legend(stage.marg_view) + + +def test_stage_marginal_check_invalid_crystal_falls_back_to_thin(stage): + p = stage.state.retrieve + p.dispersive, p.angle_mode = True, "bogus" + _enter(stage, _data("shg")) + assert "predicted (thin medium)" in _legend(stage.marg_view) + text = stage.status_label.text() + assert "the crystal set on the Data stage is not valid (angle_mode" in text + assert text.endswith("showing the thin-medium prediction") + assert "thin medium" in stage.marginal_correct_check.toolTip() + + +def test_stage_marginal_check_crystal_without_a_marginal_falls_back(stage, monkeypatch): + real = stage_marginal_check.predicted_marginal + + def thin_only(*args, crystal=None, **kwargs): + if crystal is not None: + raise ValueError("the spectrum generates no SHG through the crystal") + return real(*args, **kwargs) + + monkeypatch.setattr(stage_marginal_check, "predicted_marginal", thin_only) + stage.state.retrieve.dispersive = True + _enter(stage, _data("shg")) + assert "predicted (thin medium)" in _legend(stage.marg_view) + assert "no marginal through the crystal (the spectrum generates no SHG" in ( + stage.status_label.text() + ) + + +def test_stage_marginal_check_crystal_is_for_shg_only(stage): + stage.state.retrieve.dispersive = True + _enter(stage, _data("pg")) + assert "predicted" in _legend(stage.marg_view) + assert stage.status_label.text().startswith("PG marginal check •") + + # -- display ------------------------------------------------------------------ def test_stage_marginal_check_wavelength_axis_and_log_scale(stage): _enter(stage, _data()) @@ -208,6 +273,8 @@ def test_stage_marginal_check_width_bracket_flags(stage, sigma_meas, flag): "width_bracket": (1.0, 3.0), "width_is_hard": False, "rms_width": 2.0, + "medium": "", + "note": "", } stage._annotate_checks(801.0, sigma_meas, pred, "pg") text = stage.status_label.text() @@ -226,6 +293,8 @@ def test_stage_marginal_check_sd_reports_only_the_lower_bound(stage, sigma_meas, "width_bracket": None, "width_is_hard": False, "rms_width": 2.0, + "medium": "", + "note": "", } stage._annotate_checks(800.0, sigma_meas, pred, "sd") text = stage.status_label.text() @@ -320,3 +389,11 @@ def test_peak_norm_falls_back_outside_the_mask(): # all-zero data is returned unchanged np.testing.assert_allclose(_peak_norm(np.zeros(3), np.ones(3, bool)), 0.0) assert _peak_norm(np.zeros(0), np.zeros(0, bool)).size == 0 + + +def test_stage_marginal_check_toggling_the_correction_drops_the_prepared_trace(stage): + # the prepared trace was made with the other setting; Prepare must redo it + _enter(stage, _data("shg")) + stage.state.tracedata = "prepared" + stage.marginal_correct_check.setChecked(True) + assert stage.state.tracedata is None diff --git a/tests/gui/test_stage_preprocess.py b/tests/gui/test_stage_preprocess.py index e72d153..602bd6a 100644 --- a/tests/gui/test_stage_preprocess.py +++ b/tests/gui/test_stage_preprocess.py @@ -249,3 +249,51 @@ def test_stage_preprocess_numbers_describe_the_grid(loaded): assert numbers["Taper loss"].property("warn") is True loaded._show_tracedata(replace(td, taper_loss=0.0)) assert numbers["Taper loss"].text() == "< 0.1%" + + +# -- the marginal correction's crystal ------------------------------------------ +def _correct_through_a_crystal(stage): + """Ask for the marginal correction of an SHG trace through a 50 µm crystal.""" + state = stage.state + state.load_data = {**state.load_data, "interaction": "shg"} + state.preproc.marginal_correct = True + state.retrieve.dispersive = True + state.retrieve.thickness_um = 50.0 + + +def test_stage_preprocess_corrects_through_the_data_stages_crystal( + loaded, monkeypatch, qtbot +): + from croak.crystals import PhaseMatching + + _correct_through_a_crystal(loaded) + seen = [] + + def build(params, data, *, crystal=None, fast_baseline=False): + seen.append(crystal) + raise ValueError("stop after the call") + + monkeypatch.setattr(stage_preprocess.pipeline, "build_tracedata", build) + loaded.apply(block=True) + assert loaded.status_label.text() == "Preprocess failed: stop after the call" + # the threaded path snapshots the same crystal with the parameters + loaded.apply() + qtbot.waitUntil(lambda: not loaded._workers, timeout=20000) + assert len(seen) == 2 + for crystal in seen: + assert isinstance(crystal, PhaseMatching) + assert crystal.thickness == pytest.approx(50e-6) + assert loaded._pending[2] is seen[1] + + +def test_stage_preprocess_reports_an_invalid_crystal(loaded): + _correct_through_a_crystal(loaded) + loaded.state.retrieve.angle_mode = "bogus" + loaded.apply() + text = loaded.status_label.text() + assert text.startswith( + "Preprocess failed: the crystal set on the Data stage is not valid" + ) + assert "angle_mode" in text + assert loaded.state.tracedata is None + assert loaded._workers == [] diff --git a/tests/gui/test_stage_retrieve.py b/tests/gui/test_stage_retrieve.py index 52aeafc..0ab140a 100644 --- a/tests/gui/test_stage_retrieve.py +++ b/tests/gui/test_stage_retrieve.py @@ -470,8 +470,9 @@ def test_retrieve_form_finds_a_setting_by_name_or_help(qtbot): # -- the SHG crystal and the beam geometry ---------------------------------------- +# Set on the Data stage (croak.gui.crystal_panel); Retrieve summarises them. def _shg_trace(stage): - """A stand-in SHG trace: what the crystal controls read from the data.""" + """A stand-in SHG trace: what the crystal summary reads from the data.""" from croak.grid import Grid stage.state.tracedata = SimpleNamespace( @@ -485,162 +486,91 @@ def test_stage_retrieve_shows_the_crystal_for_shg_and_the_slab_otherwise(stage): stage.state.tracedata = SimpleNamespace(interaction="pg", omega0_pulse=2.35e15) stage.on_enter() assert not stage.disp_box.isHidden() - assert stage.crystal_box.isHidden() and stage.geometry_box.isHidden() + assert stage.shg_box.isHidden() _shg_trace(stage) assert stage.disp_box.isHidden() - assert not stage.crystal_box.isHidden() and not stage.geometry_box.isHidden() + assert not stage.shg_box.isHidden() -def test_stage_retrieve_crystal_switch_and_thickness_drive_the_slab_settings(stage): - _shg_trace(stage) - stage.crystal_check.setChecked(True) - assert stage.state.retrieve.dispersive is True - assert stage.dispersive_check.isChecked() - stage.crystal_thickness_spin.setValue(55.0) - assert stage.state.retrieve.thickness_um == 55.0 - assert stage.thickness_spin.value() == 55.0 - stage.dispersive_check.setChecked(False) - assert not stage.crystal_check.isChecked() +def test_stage_retrieve_without_a_trace_shows_the_slab_only(qtbot): + fresh = StageRetrieve(WizardState()) + qtbot.addWidget(fresh) + assert not fresh.disp_box.isHidden() + assert fresh.shg_box.isHidden() -def test_stage_retrieve_crystal_controls_store_their_settings(qtbot, stage): - _shg_trace(stage) +def test_stage_retrieve_summarises_the_crystal_set_on_the_data_stage(stage): p = stage.state.retrieve - stage.crystal_combo.setCurrentText("BBO") - stage.cut_angle_spin.setValue(33.4) - stage.angle_mode_combo.setCurrentText("External tilt") - stage.tilt_spin.setValue(-1.5) - stage.polarization_combo.setCurrentText("Perpendicular to the crossing plane") - stage.delayed_beam_combo.setCurrentText("Away from the optic axis") - stage.separation_spin.setValue(8.0) - stage.geometry_f_spin.setValue(250.0) - assert (p.crystal, p.cut_angle_deg, p.angle_mode, p.tilt_deg) == ( - "BBO", - 33.4, - "tilt", - -1.5, - ) - assert (p.polarization, p.delayed_beam) == ("perpendicular", "away_from_axis") - assert (p.beam_separation_mm, p.focal_f_mm) == (8.0, 250.0) - assert stage.focal_f_spin.value() == 250.0 # one focal length for both groups - assert stage.tilt_spin.isEnabled() and not stage.phase_match_spin.isEnabled() - stage.angle_mode_combo.setCurrentText("Phase-matched wavelength") - stage.phase_match_spin.setValue(780.0) - assert (p.angle_mode, p.phase_match_nm) == ("phase-match", 780.0) - assert not stage.tilt_spin.isEnabled() - - -def test_stage_retrieve_delayed_beam_matters_only_in_the_principal_plane(stage): + p.dispersive, p.thickness_um = True, 100.0 + p.beam_separation_mm, p.focal_f_mm = 5.0, 100.0 _shg_trace(stage) - stage.polarization_combo.setCurrentText("In the crossing plane") - assert not stage.delayed_beam_combo.isEnabled() - stage.polarization_combo.setCurrentText("Perpendicular to the crossing plane") - assert stage.delayed_beam_combo.isEnabled() - stage.separation_spin.setValue(0.0) # collinear: no crossing plane at all - assert not stage.polarization_combo.isEnabled() - assert not stage.delayed_beam_combo.isEnabled() - assert stage.geometry_readout.text() == "Collinear beams: no delay smearing" - assert not stage.shg_smearing_check.isEnabled() - - -def test_stage_retrieve_crystal_readout_describes_the_crystal(stage): - _shg_trace(stage) - stage.separation_spin.setValue(5.0) - stage.geometry_f_spin.setValue(100.0) + text = stage.shg_summary.text() + assert text.startswith("BBO, 100 µm, cut 29.2°\nθ inside") + assert "path =" in text and "depth nodes =" in text # d = 5 mm, D = 3 mm, f = 100 mm at 800 nm: sigma = lambda d / (sqrt2 pi D c) - assert stage.geometry_readout.text() == ( - "Crossing half-angle α = 1.432°\nDelay smearing σ = 1.00 fs rms (2.36 fs FWHM)" + assert text.endswith( + "Beams 5 mm apart, f = 100 mm, ⌀ 3 mm\n" + "Crossing half-angle α = 1.432°\n" + "Delay smearing σ = 1.00 fs rms (2.36 fs FWHM)" ) - stage.crystal_thickness_spin.setValue(100.0) - text = stage.crystal_readout.text() - assert "θ inside" in text and "path =" in text and "depth nodes =" in text - # a cut the wavelength cannot phase-match at any tilt is explained, not raised - stage.cut_angle_spin.setValue(80.0) - assert stage.crystal_readout.text().startswith("No valid crystal:") - -def test_stage_retrieve_crystal_readout_without_a_trace(stage): - stage.state.tracedata = None - assert "depth nodes" not in stage._crystal_summary() - assert "θ inside" in stage._crystal_summary() - -def test_stage_retrieve_thickness_fit_is_off_for_a_crystal(stage): +def test_stage_retrieve_summary_of_a_thin_medium_and_collinear_beams(stage): + p = stage.state.retrieve + p.dispersive, p.beam_separation_mm = False, 0.0 _shg_trace(stage) - stage.solver_combo.setCurrentText("lbfgs-ad") - stage._on_dispersive_changed(True) - assert not stage.fit_thickness_check.isEnabled() - - -def test_stage_retrieve_seeds_the_crystal_widgets_from_the_settings(stage): - stage.state.retrieve = RetrieveParams( - dispersive=True, - cut_angle_deg=31.0, - angle_mode="tilt", - tilt_deg=2.0, - polarization="perpendicular", - delayed_beam="away_from_axis", - beam_separation_mm=6.0, - ) - stage._seed_widgets() - assert stage.crystal_check.isChecked() - assert stage.cut_angle_spin.value() == 31.0 - assert stage.angle_mode_combo.currentText() == "External tilt" - assert stage.tilt_spin.value() == 2.0 - assert stage.polarization_combo.currentText() == ( - "Perpendicular to the crossing plane" + assert stage.shg_summary.text() == ( + "Crystal not modelled: thin-medium SHG.\nCollinear beams: no delay smearing" ) - assert stage.delayed_beam_combo.currentText() == "Away from the optic axis" - assert stage.separation_spin.value() == 6.0 - - -def test_stage_retrieve_without_a_trace_shows_the_slab_only(qtbot): - fresh = StageRetrieve(WizardState()) - qtbot.addWidget(fresh) - assert not fresh.disp_box.isHidden() - assert fresh.crystal_box.isHidden() and fresh.geometry_box.isHidden() -def test_stage_retrieve_crystal_shows_settings_changed_through_the_slab(stage): - # thickness, focal length and the switch are shared; changing them on a PG - # trace must show when SHG data arrives - stage.state.tracedata = SimpleNamespace(interaction="pg", omega0_pulse=2.35e15) - stage.on_enter() - stage.thickness_spin.setValue(77.0) - stage.focal_f_spin.setValue(333.0) - stage.dispersive_check.setChecked(True) +def test_stage_retrieve_unknown_stored_crystal_setting_is_explained(stage): + stage.state.retrieve = RetrieveParams(dispersive=True, angle_mode="bogus") + stage._seed_widgets() _shg_trace(stage) - assert stage.crystal_thickness_spin.value() == 77.0 - assert stage.geometry_f_spin.value() == 333.0 - assert stage.crystal_check.isChecked() + assert "No valid crystal: angle_mode" in stage.shg_summary.text() -def test_stage_retrieve_focal_length_is_one_setting_for_both_groups(stage): +def test_stage_retrieve_shows_shared_settings_changed_on_the_data_stage(stage): + # the switch, thickness and focal length are shared with the Data stage's + # crystal panel: entering Retrieve shows their current values _shg_trace(stage) - stage.separation_spin.setValue(5.0) - stage.focal_f_spin.setValue(200.0) - assert stage.geometry_f_spin.value() == 200.0 - assert stage.geometry_readout.text().startswith("Crossing half-angle α = 0.716°") + p = stage.state.retrieve + p.dispersive, p.thickness_um, p.focal_f_mm, p.smearing = True, 77.0, 333.0, True + stage.on_enter() + assert stage.dispersive_check.isChecked() + assert stage.thickness_spin.value() == 77.0 + assert stage.focal_f_spin.value() == 333.0 + assert stage.shg_smearing_check.isChecked() and stage.smearing_check.isChecked() + # and the focal mixture's focal length is the beams' one + stage.focal_f_spin.setValue(150.0) + assert p.focal_f_mm == 150.0 -def test_stage_retrieve_unknown_stored_crystal_setting_is_explained(stage): - stage.state.retrieve = RetrieveParams(dispersive=True, angle_mode="bogus") +def test_stage_retrieve_seeds_the_shared_settings(stage): + stage.state.retrieve = RetrieveParams(dispersive=True, thickness_um=12.0) stage._seed_widgets() + assert stage.dispersive_check.isChecked() + assert stage.thickness_spin.value() == 12.0 + + +def test_stage_retrieve_thickness_fit_is_off_for_a_crystal(stage): _shg_trace(stage) - assert stage.crystal_readout.text().startswith("No valid crystal: angle_mode") + stage.solver_combo.setCurrentText("lbfgs-ad") + stage._on_dispersive_changed(True) + assert not stage.fit_thickness_check.isEnabled() -def test_stage_retrieve_shg_smearing_lives_in_beam_geometry(stage): +def test_stage_retrieve_shg_smearing_lives_in_the_shg_group(stage): + stage.state.retrieve.beam_separation_mm = 5.0 + stage.state.retrieve.beam_diameter_mm = 1.5 _shg_trace(stage) assert stage.smear_box.isHidden() # the mask geometry is PG/SD's - stage.separation_spin.setValue(5.0) stage.shg_smearing_check.setChecked(True) assert stage.state.retrieve.smearing is True assert stage.smearing_check.isChecked() # one switch for both groups - stage.beam_diameter_spin.setValue(1.5) - assert stage.state.retrieve.beam_diameter_mm == 1.5 # half the diameter, twice the focal spot and the blur - assert "σ = 2.00 fs rms" in stage.geometry_readout.text() + assert "σ = 2.00 fs rms" in stage.shg_summary.text() stage.state.tracedata = SimpleNamespace(interaction="pg", omega0_pulse=2.35e15) stage.on_enter() assert not stage.smear_box.isHidden() @@ -650,22 +580,21 @@ def test_stage_retrieve_smearing_switch_follows_the_mask_group(stage): stage.state.tracedata = SimpleNamespace(interaction="pg", omega0_pulse=2.35e15) stage.on_enter() stage.smearing_check.setChecked(True) - stage.state.retrieve.beam_diameter_mm = 4.0 _shg_trace(stage) assert stage.shg_smearing_check.isChecked() - assert stage.beam_diameter_spin.value() == 4.0 def test_stage_retrieve_shg_smearing_needs_a_capable_solver_and_crossing_beams(stage): + stage.state.retrieve.beam_separation_mm = 5.0 _shg_trace(stage) - stage.separation_spin.setValue(5.0) stage.solver_combo.setCurrentText("copra") assert not stage.shg_smearing_check.isEnabled() stage.solver_combo.setCurrentText("lbfgs-ad") assert stage.shg_smearing_check.isEnabled() stage.shg_smearing_check.setChecked(True) assert stage.fit_smearing_check.isEnabled() - stage.separation_spin.setValue(0.0) # collinear: no kernel to fit + stage.state.retrieve.beam_separation_mm = 0.0 # collinear: no kernel to fit + stage.on_enter() assert not stage.shg_smearing_check.isEnabled() assert not stage.fit_smearing_check.isEnabled() diff --git a/tests/gui/test_stage_synthetic.py b/tests/gui/test_stage_synthetic.py index 9ea7856..93586e2 100644 --- a/tests/gui/test_stage_synthetic.py +++ b/tests/gui/test_stage_synthetic.py @@ -191,19 +191,25 @@ def test_preview_draws_the_four_panels(stage): assert stage._last is not None -def test_shg_traces_can_be_made_through_the_retrieve_stages_crystal(stage): +def test_shg_traces_can_be_made_through_the_crystal_panels_crystal(stage): from croak.crystals import depth_points from croak.forward import maketrace from croak.session.pipeline import crystal_setup stage.interaction.setCurrentText("shg") - assert stage.crystal_box.isEnabled() + panel = stage.crystal_panel + assert not panel.isHidden() grid, ew, omega0 = stage._pulse() _, delays, ideal = stage._signal_trace(grid, ew, omega0) - stage.use_crystal.setChecked(True) - stage.crystal_thickness.set_value(100.0) + stage._timer.stop() + panel.crystal_check.setChecked(True) + panel.thickness_spin.setValue(100.0) + # the panel's edits are the session's crystal, and they redraw the preview + assert stage.state.retrieve.dispersive is True + assert stage.state.retrieve.thickness_um == 100.0 + assert stage._timer.isActive() _, _, made = stage._signal_trace(grid, ew, omega0) - # the crystal is the one the Retrieve stage's settings describe + # the crystal is the one the session's settings describe setup = crystal_setup(stage.state.retrieve) expected = maketrace( grid.omega, @@ -222,14 +228,25 @@ def test_shg_traces_can_be_made_through_the_retrieve_stages_crystal(stage): np.testing.assert_allclose(made, want, rtol=0.0, atol=1e-12 * want.max()) # 100 um of phase matching changes the trace assert not np.allclose(made, ideal) - # a zero thickness is the thin medium again - stage.crystal_thickness.set_value(0.0) + # a zero thickness is the thin medium again, as is the crystal unmodelled + panel.thickness_spin.setValue(0.0) + np.testing.assert_array_equal(stage._signal_trace(grid, ew, omega0)[2], ideal) + panel.thickness_spin.setValue(100.0) + panel.crystal_check.setChecked(False) np.testing.assert_array_equal(stage._signal_trace(grid, ew, omega0)[2], ideal) def test_the_crystal_is_for_shg_only(stage): stage.interaction.setCurrentText("pg") - assert not stage.crystal_box.isEnabled() - stage.use_crystal.setChecked(True) - stage.crystal_thickness.set_value(100.0) + assert stage.crystal_panel.isHidden() + stage.state.retrieve.dispersive = True + stage.state.retrieve.thickness_um = 100.0 assert stage._crystal_kwargs(*stage._pulse()[::2]) == {} + stage.interaction.setCurrentText("shg") + assert not stage.crystal_panel.isHidden() + + +def test_entering_shows_crystal_settings_changed_elsewhere(stage): + stage.state.retrieve.thickness_um = 42.0 + stage.on_enter() + assert stage.crystal_panel.thickness_spin.value() == 42.0 diff --git a/tests/gui/test_state.py b/tests/gui/test_state.py index 9e54d81..5def1d4 100644 --- a/tests/gui/test_state.py +++ b/tests/gui/test_state.py @@ -14,3 +14,17 @@ def test_geometry_and_truth_come_from_the_load(): assert state.geometry is None and state.truth is None state.load_data = {"geometry": "g", "truth": "t"} assert state.geometry == "g" and state.truth == "t" + + +def test_invalidate_tracedata_drops_the_trace_and_what_was_built_on_it(qtbot): + state = WizardState() + emitted = [] + state.tracedata_changed.connect(lambda: emitted.append(True)) + state.invalidate_tracedata() # nothing prepared: nothing to drop or announce + assert emitted == [] + state.load_data = {"trace": 1} + state.tracedata, state.result, state.processed = "td", "result", "processed" + state.invalidate_tracedata() + assert (state.tracedata, state.result, state.processed) == (None, None, None) + assert state.load_data == {"trace": 1} + assert emitted == [True] diff --git a/tests/gui/test_worker.py b/tests/gui/test_worker.py index d1fd52f..9305365 100644 --- a/tests/gui/test_worker.py +++ b/tests/gui/test_worker.py @@ -39,15 +39,18 @@ def named(self, name): def test_preprocess_worker_emits_result_with_request_id_and_mode(monkeypatch): seen = {} - def build(params, data, fast_baseline): + def build(params, data, crystal, fast_baseline): seen["fast"] = fast_baseline + seen["crystal"] = crystal return ("td", params, data) monkeypatch.setattr(worker_mod.pipeline, "build_tracedata", build) - w = PreprocessWorker("p", "d", 7, fast=True) + # the crystal the caller resolved with its snapshot goes to the build + w = PreprocessWorker("p", "d", 7, crystal="crystal", fast=True) rec = _Recorder(w, "finished_ok", "failed") w.run() assert seen["fast"] is True + assert seen["crystal"] == "crystal" assert rec.named("finished_ok") == [(("td", "p", "d"), 7, True)] assert rec.named("failed") == [] diff --git a/tests/test_marginal_crystal.py b/tests/test_marginal_crystal.py new file mode 100644 index 0000000..b931662 --- /dev/null +++ b/tests/test_marginal_crystal.py @@ -0,0 +1,488 @@ +"""The SHG frequency marginal through a Type I crystal, and the correction onto it. + +The reference is the crystal forward model itself: summed over the grid's whole time +axis (a full period of delays), its trace's frequency marginal is the pair sum of +:func:`croak.crystals.shg_marginal` exactly (Parseval), up to the depth quadrature +(:func:`croak.crystals.depth_points`, below 1e-6 of the path per pair) and the pairs +that alias round the grid, which the linear sum leaves out and the FFT model keeps. +""" + +from __future__ import annotations + +import math +from dataclasses import replace + +import numpy as np +import pytest +from test_crystals import BBO, W0 + +from croak import crystals, preprocess +from croak import marginal_checks as mc +from croak.crystals import CrystalSetup, PhaseMatching +from croak.forward import ForwardModel +from croak.geometry import TwoBeamGeometry +from croak.grid import Grid +from croak.maths import moment, wlfreq +from croak.pipeline import retrieve_from_tracedata +from croak.pulses import gaussian_pulse + +GRID = Grid(64, dt=3.0e-15) # about 560-1440 nm around 800 nm +GEOMETRY = TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1) # 1.43 degrees +SETUPS = { + "collinear": {}, + "in-plane": {"geometry": GEOMETRY, "polarization": "parallel"}, + "principal-toward": { + "geometry": GEOMETRY, + "polarization": "perpendicular", + "delayed_beam": "toward_axis", + }, + "principal-away": { + "geometry": GEOMETRY, + "polarization": "perpendicular", + "delayed_beam": "away_from_axis", + }, +} + + +def _setup(**kw) -> CrystalSetup: + return CrystalSetup(BBO, math.radians(29.2), phase_match_wavelength=800e-9, **kw) + + +def _pulse(g=GRID): + """A 12 fs Gaussian with 30 fs^2 of GDD, peak-normalised spectrum.""" + ew = gaussian_pulse(g, 12e-15, phases=(30e-30,)) + return ew / np.max(np.abs(ew)) + + +def _full_period_trace(setup, thickness, ew, g=GRID): + """The crystal model's trace over the grid's whole time axis (all delays).""" + model = ForwardModel( + g.omega, + g.t, + "shg", + material=setup, + thickness=thickness, + npoints=crystals.depth_points(setup, g.omega, W0, thickness), + omega0=W0, + ) + return model.trace(ew, normalize=False) + + +def _on_grid(marginal, g=GRID): + """The linear marginal's samples on the centred grid ``g.omega`` (around 2*w0).""" + start = round(-g.omega[0] / g.domega) + return marginal[start : start + g.n] + + +@pytest.mark.parametrize("name", SETUPS) +@pytest.mark.parametrize("thickness", [0.0, 20e-6, 100e-6]) +def test_shg_marginal_is_the_crystal_models_delay_summed_trace(name, thickness): + setup = _setup(**SETUPS[name]) + ew = _pulse() + model = _full_period_trace(setup, thickness, ew).sum(axis=1) + predicted = crystals.shg_marginal( + GRID.omega + W0, np.abs(ew) ** 2, PhaseMatching(setup, thickness), W0 + ) + # Parseval over the N delays of a full period gives N times the pair sum; the + # tolerance is the quadrature's 1e-6 per pair plus the aliased wings (measured + # 4e-7 of the peak), so 2e-6. + np.testing.assert_allclose( + GRID.n * _on_grid(predicted), model, rtol=0, atol=2e-6 * model.max() + ) + + +def test_the_principal_plane_drift_changes_the_marginal(): + # The same crystal crossed out of and in its principal plane: the arms' delay + # drift adds kappa (w1 - w2) to the mismatch. The pairs (w1, w2) and (w2, w1) + # share a weight, so it enters the marginal at second order only: a 5e-4 + # change here, still 250 times the tolerance of the check above, which + # therefore cannot pass by ignoring it. + spectrum = np.abs(_pulse()) ** 2 + omega = GRID.omega + W0 + in_plane = _setup(**SETUPS["in-plane"]) + principal = _setup(**SETUPS["principal-toward"]) + assert crystals.propagation(principal, GRID.omega, W0, 100e-6).arm_shift != 0.0 + a = crystals.shg_marginal(omega, spectrum, PhaseMatching(in_plane, 100e-6), W0) + b = crystals.shg_marginal(omega, spectrum, PhaseMatching(principal, 100e-6), W0) + assert np.max(np.abs(a - b)) > 1e-4 * a.max() + + +def test_zero_thickness_is_the_autoconvolution_times_the_prefactor(): + setup = _setup() + spectrum = np.abs(_pulse()) ** 2 + omega = GRID.omega + W0 + out = crystals.shg_marginal(omega, spectrum, PhaseMatching(setup, 0.0), W0) + signal = 2.0 * omega[0] + GRID.domega * np.arange(2 * GRID.n - 1) + amp = crystals.propagation(setup, signal - 2 * W0, W0, 0.0).sig_amp + np.testing.assert_allclose(out, amp**2 * np.convolve(spectrum, spectrum)) + + +def test_a_thick_crystal_narrows_the_predicted_marginal(): + spectrum = np.abs(_pulse()) ** 2 + omega = GRID.omega + W0 + thin = mc.predicted_marginal( + omega, spectrum, "shg", crystal=PhaseMatching(_setup(), 1e-6), omega0=W0 + ) + thick = mc.predicted_marginal( + omega, spectrum, "shg", crystal=PhaseMatching(_setup(), 200e-6), omega0=W0 + ) + assert thick.rms_width < 0.8 * thin.rms_width + + +def test_predicted_marginal_through_a_crystal_carries_its_moments(): + spectrum = np.abs(_pulse()) ** 2 + omega = GRID.omega + W0 + pm = PhaseMatching(_setup(**SETUPS["principal-toward"]), 50e-6) + shape = crystals.shg_marginal(omega, spectrum, pm, W0) + axis = 2.0 * omega[0] + GRID.domega * np.arange(shape.size) + pred = mc.predicted_marginal(omega, spectrum, "SHG", crystal=pm, omega0=W0) + np.testing.assert_allclose(pred.omega, axis) + np.testing.assert_allclose(pred.marginal, shape / shape.max()) + assert pred.centroid == pytest.approx(moment(axis, shape, 1), rel=1e-12) + assert pred.rms_width == pytest.approx(mc.rms_width(axis, shape), rel=1e-12) + assert pred.width_bracket is None + assert pred.centroid_is_hard and pred.width_is_hard + assert pred.sigma_spectrum == pytest.approx(mc.rms_width(omega, spectrum)) + centroid = mc.predicted_centroid(omega, spectrum, "shg", crystal=pm, omega0=W0) + assert centroid == pytest.approx(pred.centroid, rel=1e-12) + + +def test_a_spectrum_that_makes_no_shg_is_refused(): + with pytest.raises(ValueError, match="generates no SHG"): + mc.predicted_marginal( + GRID.omega + W0, + np.zeros(GRID.n), + "shg", + crystal=PhaseMatching(_setup(), 10e-6), + omega0=W0, + ) + + +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"interaction": "pg"}, "for SHG, not 'pg'"), + ({"omega0": None}, "needs the pulse carrier"), + ], +) +def test_a_crystal_prediction_needs_shg_and_the_carrier(kwargs, match): + args = {"interaction": "shg", "omega0": W0} | kwargs + spectrum = np.abs(_pulse()) ** 2 + pm = PhaseMatching(_setup(), 10e-6) + for predict in (mc.predicted_marginal, mc.predicted_centroid): + with pytest.raises(ValueError, match=match): + predict( + GRID.omega + W0, + spectrum, + args["interaction"], + crystal=pm, + omega0=args["omega0"], + ) + + +@pytest.mark.parametrize( + ("omega", "spectrum", "match"), + [ + (np.array([1.0]), np.array([1.0]), "at least 2 samples"), + (np.arange(1.0, 5.0), np.ones(3), "same shape"), + (np.array([1.0, 2.0, 4.0]), np.ones(3), "uniform and ascending"), + (np.array([3.0, 2.0, 1.0]), np.ones(3), "uniform and ascending"), + ], +) +def test_shg_marginal_rejects_a_bad_axis(omega, spectrum, match): + with pytest.raises(ValueError, match=match): + crystals.shg_marginal(omega * 1e15, spectrum, PhaseMatching(_setup(), 1e-6), W0) + + +@pytest.mark.parametrize("thickness", [-1e-6, math.nan, math.inf]) +def test_phase_matching_rejects_a_bad_thickness(thickness): + with pytest.raises(ValueError, match="finite and >= 0"): + PhaseMatching(_setup(), thickness) + + +def test_the_correction_takes_out_a_spectral_response_and_keeps_the_crystal(): + # A crystal trace seen through a smooth instrument response R(omega): the + # crystal-aware correction recovers the crystal trace (to the identity's + # tolerance), where the thin-medium correction would also remove the + # phase-matching filter. + setup = _setup(**SETUPS["principal-toward"]) + pm = PhaseMatching(setup, 100e-6) + ew = _pulse() + trace = _full_period_trace(setup, pm.thickness, ew) + response = np.exp(-(((GRID.omega - 0.3e15) / 1.5e15) ** 2)) + measured = trace * response[:, None] + spectrum = np.abs(ew) ** 2 + out = mc.apply_marginal_correction( + measured, spectrum, crystal=pm, omega=GRID.omega, omega0=W0 + ) + np.testing.assert_allclose(out / out.max(), trace / trace.max(), rtol=0, atol=1e-5) + thin = mc.apply_marginal_correction(measured, spectrum) + assert np.max(np.abs(thin / thin.max() - trace / trace.max())) > 1e-2 + + +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"omega": None}, "needs the grid omega and omega0"), + ({"omega0": None}, "needs the grid omega and omega0"), + ({"omega": GRID.omega[:-1]}, "frequency rows"), + ], +) +def test_a_crystal_correction_needs_the_grid(kwargs, match): + args = {"omega": GRID.omega, "omega0": W0} | kwargs + with pytest.raises(ValueError, match=match): + mc.apply_marginal_correction( + np.ones((GRID.n, 3)), + np.ones(GRID.n), + crystal=PhaseMatching(_setup(), 1e-6), + omega=args["omega"], + omega0=args["omega0"], + ) + + +# --- through load_and_clean and the retrieval ----------------------------------- + +PIPE_CRYSTAL = _setup(**SETUPS["principal-toward"]) +PIPE_THICKNESS = 30e-6 + + +def _measurement(): + """A crystal SHG trace through a tilted response, with its exact spectrum.""" + g = Grid(128, dt=1.5e-15) + ew = gaussian_pulse(g, 10e-15, phases=(30e-30,)) + delays = 1.5e-15 * np.arange(-24, 25) + model = ForwardModel( + g.omega, + delays, + "shg", + material=PIPE_CRYSTAL, + thickness=PIPE_THICKNESS, + npoints=crystals.depth_points(PIPE_CRYSTAL, g.omega, W0, PIPE_THICKNESS), + omega0=W0, + ) + trace = model.trace(ew, normalize=False) + trace = trace * np.linspace(0.5, 1.5, g.n)[:, None] # the instrument's tilt + lam = wlfreq(g.omega + 2.0 * W0) + trace = trace / (lam**2)[:, None] # per unit wavelength, as measured + order = np.argsort(lam) + lam_spec = wlfreq(g.omega + W0) + spec_order = np.argsort(lam_spec) + # intensity per unit wavelength, from per unit frequency (|dw/dlam| ~ 1/lam^2) + i_lam = np.abs(ew) ** 2 / lam_spec**2 + return dict( + Ifrog=trace[order] / trace.max(), + lam_frog=lam[order], + scanaxis=delays, + interaction="shg", + lam_min=600e-9, + lam_max=1200e-9, + input_unit="delay", + lam_spec=lam_spec[spec_order], + Ilam_spec=i_lam[spec_order] / i_lam.max(), + ) + + +def test_load_and_clean_corrects_through_the_crystal_and_records_it(): + pm = PhaseMatching(PIPE_CRYSTAL, PIPE_THICKNESS) + plain = preprocess.load_and_clean(**_measurement()) + corrected = preprocess.load_and_clean( + **_measurement(), marginal_correct=True, marginal_crystal=pm + ) + assert corrected.marginal_corrected + assert corrected.marginal_crystal == pm + assert plain.marginal_crystal is None + assert plain.Iomega is not None + expected = mc.apply_marginal_correction( + plain.trace, + plain.Iomega, + crystal=pm, + omega=plain.grid.omega, + omega0=plain.omega0_pulse, + ) + np.testing.assert_allclose( + corrected.trace / corrected.trace.max(), + expected / expected.max(), + rtol=0, + atol=1e-12, + ) + + +def test_load_and_clean_refuses_a_crystal_without_the_correction(): + with pytest.raises(ValueError, match="only with marginal_correct=True"): + preprocess.load_and_clean( + **_measurement(), + marginal_crystal=PhaseMatching(PIPE_CRYSTAL, PIPE_THICKNESS), + ) + + +@pytest.fixture(scope="module") +def corrected_tracedata(): + return preprocess.load_and_clean( + **_measurement(), + marginal_correct=True, + marginal_crystal=PhaseMatching(PIPE_CRYSTAL, PIPE_THICKNESS), + ) + + +def _retrieve(td, material, thickness): + return retrieve_from_tracedata( + td, + algorithm="lbfgs-ad", + material=material, + thickness=thickness, + npoints=crystals.depth_points( + PIPE_CRYSTAL, td.grid.omega, td.omega0_pulse, PIPE_THICKNESS + ), + maxiters=3, + ) + + +def test_a_crystal_corrected_trace_retrieves_through_the_same_crystal( + corrected_tracedata, +): + res = _retrieve(corrected_tracedata, PIPE_CRYSTAL, PIPE_THICKNESS) + assert np.all(np.isfinite(res.spectrum)) + + +@pytest.mark.parametrize( + ("material", "thickness", "got"), + [ + (None, 0.0, "no crystal"), + (_setup(), PIPE_THICKNESS, "another crystal set-up: pass the CrystalSetup"), + (PIPE_CRYSTAL, 20e-6, "20 um"), + ], +) +def test_a_crystal_corrected_trace_refuses_another_medium( + corrected_tracedata, material, thickness, got +): + with pytest.raises(ValueError, match=f"through 30 um of a crystal.*got {got}"): + _retrieve(corrected_tracedata, material, thickness) + + +def test_a_thin_corrected_trace_refuses_a_crystal(corrected_tracedata): + td = replace(corrected_tracedata, marginal_crystal=None) + with pytest.raises(ValueError, match="onto the thin-medium marginal"): + _retrieve(td, PIPE_CRYSTAL, PIPE_THICKNESS) + + +@pytest.mark.parametrize("n", [63, 81]) +def test_the_correction_maps_the_marginal_onto_an_odd_grid(n): + # On an odd grid the zero offset is not at n/2; the correction of an exact + # crystal trace must leave it unchanged (to the identity's tolerance). + g = Grid(n, dt=3.0e-15) + setup = _setup(**SETUPS["principal-toward"]) + pm = PhaseMatching(setup, 50e-6) + ew = _pulse(g) + trace = _full_period_trace(setup, pm.thickness, ew, g) + out = mc.apply_marginal_correction( + trace, np.abs(ew) ** 2, crystal=pm, omega=g.omega, omega0=W0 + ) + np.testing.assert_allclose(out / out.max(), trace / trace.max(), atol=1e-5) + + +@pytest.mark.parametrize( + "omega", + [GRID.omega + W0, GRID.omega + 0.3 * GRID.domega, GRID.omega[: GRID.n // 2]], + ids=["absolute", "off-sample", "half-grid"], +) +def test_a_crystal_correction_needs_the_centred_grid(omega): + trace = np.ones((omega.size, 3)) + with pytest.raises(ValueError, match="centred grid"): + mc.apply_marginal_correction( + trace, + np.ones(omega.size), + crystal=PhaseMatching(_setup(), 1e-6), + omega=omega, + omega0=W0, + ) + + +@pytest.mark.parametrize("bad", ["spectrum", "omega"]) +def test_shg_marginal_refuses_non_finite_input(bad): + omega = GRID.omega + W0 + spectrum = np.abs(_pulse()) ** 2 + if bad == "spectrum": + spectrum[10] = np.nan + else: + omega = omega.copy() + omega[-1] = np.inf + with pytest.raises(ValueError, match="must be finite"): + crystals.shg_marginal(omega, spectrum, PhaseMatching(_setup(), 1e-6), W0) + + +def test_load_and_clean_takes_out_a_response_on_a_grid_with_another_carrier(): + # End to end: a crystal trace over a delay scan that holds it, seen through an + # instrument response, regridded on a band whose carrier is not the + # simulation's. Corrected through the crystal it matches the response-free + # trace regridded the same way; the residual is the resampling's (measured + # about 2e-4 of the peak), and uncorrected it is off by several per cent. + g = Grid(256, dt=1.5e-15) # fundamental axis stays at positive frequencies + ew = gaussian_pulse(g, 10e-15, phases=(30e-30,)) + delays = 2.0e-15 * np.arange(-60, 61) + model = ForwardModel( + g.omega, + delays, + "shg", + material=PIPE_CRYSTAL, + thickness=PIPE_THICKNESS, + npoints=crystals.depth_points(PIPE_CRYSTAL, g.omega, W0, PIPE_THICKNESS), + omega0=W0, + ) + clean = model.trace(ew, normalize=False) + response = np.exp(-(((g.omega - 0.4e15) / 2.0e15) ** 2))[:, None] + lam = wlfreq(g.omega + 2.0 * W0) + clean = clean / (lam**2)[:, None] # per unit wavelength, as measured + order = np.argsort(lam) + lam_spec = wlfreq(g.omega + W0) + spec_order = np.argsort(lam_spec) + i_lam = np.abs(ew) ** 2 / lam_spec**2 + common = dict( + lam_frog=lam[order], + scanaxis=delays, + interaction="shg", + lam_min=620e-9, + lam_max=1150e-9, + input_unit="delay", + lam_spec=lam_spec[spec_order], + Ilam_spec=i_lam[spec_order] / i_lam.max(), + ) + reference = preprocess.load_and_clean(clean[order], **common).trace + pm = PhaseMatching(PIPE_CRYSTAL, PIPE_THICKNESS) + measured = (clean * response)[order] + corrected = preprocess.load_and_clean( + measured, **common, marginal_correct=True, marginal_crystal=pm + ) + assert corrected.omega0_pulse != pytest.approx(W0, rel=1e-3) + plain = preprocess.load_and_clean(measured, **common).trace + + def deviation(trace): + return np.max(np.abs(trace / trace.max() - reference / reference.max())) + + assert deviation(corrected.trace) < 1e-3 + assert deviation(plain) > 2e-2 + + +def test_a_crystal_corrected_trace_refuses_a_generation_envelope(corrected_tracedata): + npoints = crystals.depth_points( + PIPE_CRYSTAL, + corrected_tracedata.grid.omega, + corrected_tracedata.omega0_pulse, + PIPE_THICKNESS, + ) + with pytest.raises(ValueError, match="generation envelope"): + retrieve_from_tracedata( + corrected_tracedata, + algorithm="lbfgs-ad", + material=PIPE_CRYSTAL, + thickness=PIPE_THICKNESS, + npoints=npoints, + depth_weight=np.ones(npoints), + maxiters=3, + ) + + +def test_a_thin_corrected_trace_retrieves_without_a_crystal(corrected_tracedata): + # a thin-medium correction and an ideal-SHG retrieval describe the same medium + td = replace(corrected_tracedata, marginal_crystal=None) + res = retrieve_from_tracedata(td, algorithm="lbfgs-ad", maxiters=3) + assert np.all(np.isfinite(res.spectrum)) diff --git a/tests/test_scripting.py b/tests/test_scripting.py index 66a11e3..58b188a 100644 --- a/tests/test_scripting.py +++ b/tests/test_scripting.py @@ -79,7 +79,10 @@ def test_generate_script_uses_the_simulated_loader(simulated_scan_h5): assert "simulated = SimulatedLoadParams(" in source assert f"frog_path={simulated_scan_h5!r}" in source assert "data = assemble_simulated_load_data(simulated)" in source - assert "tracedata = build_tracedata(preproc, data)" in source + assert ( + "crystal = correction_crystal(preproc, retrieve, data['interaction'])" in source + ) + assert "tracedata = build_tracedata(preproc, data, crystal=crystal)" in source # the experimental loader has no business in this script assert "assemble_load_data(load)" not in source assert "LoadParams(" not in source.replace("SimulatedLoadParams(", "") diff --git a/tests/test_session_crystal.py b/tests/test_session_crystal.py index f023b9d..d2bbe2e 100644 --- a/tests/test_session_crystal.py +++ b/tests/test_session_crystal.py @@ -34,6 +34,7 @@ def _td(interaction="shg"): grid=Grid(64, dt=3e-15), omega0_pulse=W0, Iomega=None, + marginal_crystal=None, ) @@ -355,3 +356,79 @@ def _fake(td, **kwargs): assert captured["fit_smearing"] is False and captured["fit_smearing_split"] is False for kwargs in (bootstrap_solver_kwargs(p, td), covariance_kwargs(p, td)): assert kwargs["fit_smearing"] is False + + +@pytest.mark.parametrize( + ("dispersive", "interaction"), [(False, "shg"), (True, "pg"), (True, "sd")] +) +def test_marginal_crystal_is_none_without_an_shg_crystal(dispersive, interaction): + p = RetrieveParams(dispersive=dispersive) + assert session_pipeline.marginal_crystal(p, interaction) is None + + +def test_marginal_crystal_is_the_retrievals_crystal_and_thickness(): + p = RetrieveParams(dispersive=True, thickness_um=40.0) + pm = session_pipeline.marginal_crystal(p, "SHG") + assert pm is not None + assert pm.setup == crystal_setup(p) + assert pm.thickness == pytest.approx(40e-6, rel=1e-12) + + +@pytest.mark.parametrize("correct", [False, True]) +def test_build_tracedata_hands_the_crystal_to_the_correction_only(monkeypatch, correct): + seen = {} + monkeypatch.setattr( + session_pipeline.preprocess, "load_and_clean", lambda *a, **kw: seen.update(kw) + ) + data = dict.fromkeys( + ("trace", "lam", "scanaxis", "interaction", "input_unit", "lam_spec"), None + ) | {"Ilam_spec": None} + pm = crystals.PhaseMatching(crystal_setup(RetrieveParams()), 10e-6) + preproc = SessionOptions().preproc + preproc.marginal_correct = correct + session_pipeline.build_tracedata(preproc, data, crystal=pm) + assert seen["marginal_correct"] is correct + assert seen["marginal_crystal"] is (pm if correct else None) + + +@pytest.mark.parametrize("correct", [False, True]) +def test_the_session_corrects_through_the_retrievals_crystal(monkeypatch, correct): + from croak.session import engine + + seen = {} + monkeypatch.setattr( + engine.pipeline, + "build_tracedata", + lambda p, data, *, crystal: seen.setdefault("crystal", crystal), + ) + options = SessionOptions() + options.retrieve.dispersive = True + options.retrieve.thickness_um = 25.0 + options.preproc.marginal_correct = correct + engine._preproc_stage(options, {"interaction": "shg"}) + if not correct: + assert seen["crystal"] is None + return + assert seen["crystal"].setup == crystal_setup(options.retrieve) + assert seen["crystal"].thickness == pytest.approx(25e-6, rel=1e-12) + + +def test_pulse_carrier_is_the_retrieval_grids_carrier(): + from croak.grid import gridparams_lambda + + preproc = SessionOptions().preproc + preproc.lam_min_nm, preproc.lam_max_nm = 600.0, 1100.0 + _, _, omega0 = gridparams_lambda(100e-15, lambda_min=600e-9, lambda_max=1100e-9) + assert session_pipeline.pulse_carrier(preproc) == pytest.approx(omega0, rel=1e-12) + + +def test_the_thickness_uncertainty_refuses_a_crystal_corrected_trace(): + # each draw would retrieve at another thickness a trace whose marginal the + # correction fixed to the central thickness's + rp = RetrieveParams(solver="lbfgs-ad", dispersive=True) + up = session_pipeline.UncertaintyParams(method="thickness") + td = _td() + td.trace = np.ones((4, 3)) + td.marginal_crystal = crystals.PhaseMatching(crystal_setup(rp), 10e-6) + with pytest.raises(ValueError, match="marginal-corrected through the crystal"): + session_pipeline.run_uncertainty(up, rp, SimpleNamespace(omega0=W0), td) diff --git a/tests/test_session_engine.py b/tests/test_session_engine.py index 3a752bd..2a4dfc9 100644 --- a/tests/test_session_engine.py +++ b/tests/test_session_engine.py @@ -32,8 +32,8 @@ def fn(*args, **kwargs): monkeypatch.setattr(engine.pipeline, name, fn) - stub("assemble_load_data", {"truth": "truth"}) - stub("assemble_simulated_load_data", {"truth": None}) + stub("assemble_load_data", {"truth": "truth", "interaction": "shg"}) + stub("assemble_simulated_load_data", {"truth": None, "interaction": "shg"}) stub("build_tracedata", "td") stub("assemble_simulated_tracedata", "td-raw") stub("run_retrieval", "raw-result") @@ -94,7 +94,8 @@ def test_run_session_orders_stages_and_chains_results(stub_stages): assert process_args == ("dispersed", "td") and process_kw == {"energy": 2e-6} # the bootstrap works on the pre-dispersion result assert stub_stages[6][1][2] == "result" - assert (out.data, out.tracedata, out.result) == ({"truth": "truth"}, "td", "result") + assert out.data == {"truth": "truth", "interaction": "shg"} + assert (out.tracedata, out.result) == ("td", "result") assert (out.dispersed, out.processed, out.uncertainty) == ( "dispersed", "processed", diff --git a/tests/test_session_pipeline.py b/tests/test_session_pipeline.py index 0b40804..0f90e66 100644 --- a/tests/test_session_pipeline.py +++ b/tests/test_session_pipeline.py @@ -381,7 +381,9 @@ def tiny_retrieval(): omega0=wlfreq(800e-9), progress=False, ) - td = SimpleNamespace(trace=trace, Iomega=None, interaction="pg") + td = SimpleNamespace( + trace=trace, Iomega=None, interaction="pg", marginal_crystal=None + ) return result, td