diff --git a/README.md b/README.md index a480afb..189af7b 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,9 @@ instead models the measurement physics directly: through the nonlinear medium, with refractive indices of glasses, crystals and gases from [optmat](https://optmat.readthedocs.io); for SHG, phase matching and group-velocity mismatch in a Type I crystal such as BBO; -- **geometric delay smearing** of the crossed-beam (BOXCARS) geometry, with a - closed-form kernel set by the mask geometry, or fitted from the data; +- **geometric delay smearing** of the crossed-beam geometry (BOXCARS for PG and + SD, two beams for SHG), with a closed-form kernel set by the beam geometry, or + fitted from the data; - **chromatic focusing and the collection aperture**, as a coherent chromatic filter on the signal (the full focal model). diff --git a/changelog.d/shg-smearing.added.md b/changelog.d/shg-smearing.added.md new file mode 100644 index 0000000..e4c79c2 --- /dev/null +++ b/changelog.d/shg-smearing.added.md @@ -0,0 +1 @@ +Two-beam delay smearing for SHG FROG: `croak.smearing.shg_two_beam_kernel` builds the delay blur of two Gaussian beams from a `croak.geometry.TwoBeamGeometry` with a `beam_diameter` (rms width w0 tan(alpha) / (sqrt 2 c) = lambda d / (sqrt 2 pi D c), after Taft et al. 1996), and the forward models, solvers and smearing fit accept it for SHG, with or without a crystal; `croak.smearing.check_kernel` refuses a kernel with a shape parameter for SHG. Sessions take `beam_diameter_mm` and build the kernel from the crystal's own beams at the pulse's wavelength, and the GUI's Beam geometry group has the diameter, the smearing switch and a width read-out. See [Two-beam SHG](docs/howto/geometric_smearing.md#two-beam-shg) (#24). diff --git a/changelog.d/split-fit-shape-channel.changed.md b/changelog.d/split-fit-shape-channel.changed.md new file mode 100644 index 0000000..518bba0 --- /dev/null +++ b/changelog.d/split-fit-shape-channel.changed.md @@ -0,0 +1 @@ +A split smearing fit (`fit_smearing_split`) is now refused, with a clear error, for a kernel with no shape channel (`sigma_p = 0`): the two-beam SD kernel (`collinear_sd_kernel`, a session's `smear_layout="sd2"`) and the two-beam SHG kernel. Its shape-channel multiplier could not move the trace, so it stayed where it started and the covariance reported it as exact. Fit the one width with `fit_smearing` alone (`croak.smearing.check_split_fit`). diff --git a/croak/cmaes.py b/croak/cmaes.py index f9f305d..80f726c 100644 --- a/croak/cmaes.py +++ b/croak/cmaes.py @@ -48,7 +48,7 @@ from .focal import FocalMixture from .forward_jax import make_param_trace_fn from .result import RetrievalResult -from .smearing import SmearingKernel +from .smearing import SmearingKernel, check_split_fit from .solver import ( Retriever, assemble_result, @@ -199,7 +199,8 @@ class CMAES(Retriever): Forward-model options shared with the gradient solvers. smearing : SmearingKernel or None, optional Geometric time-smearing kernel of a non-collinear BOXCARS geometry - (default ``None`` = off). PG (TG) and SD only. See :mod:`croak.smearing` + (default ``None`` = off): a BOXCARS kernel for PG (TG) and SD, or the + two-beam kernel for SHG. See :mod:`croak.smearing` and :doc:`/howto/geometric_smearing`. reg_amp, reg_phase, reg_spectrum, spectrum_target Smoothness / spectral-match regularisation weights, identical to the @@ -361,6 +362,7 @@ def _solve( scale_tau = ( float(np.median(np.abs(np.diff(delays)))) if delays.size > 1 else 1.0 ) + check_split_fit(self.smearing, self.fit_smearing_split) spec = ExtraParamSpec( fit_thickness=self.fit_thickness, thickness0=self.thickness, diff --git a/croak/covariance.py b/croak/covariance.py index 4aa5098..55dad2a 100644 --- a/croak/covariance.py +++ b/croak/covariance.py @@ -62,7 +62,7 @@ from .crystals import CrystalSetup from .forward_jax import make_param_trace_fn # enables jax_enable_x64 at import from .result import RetrievalResult -from .smearing import SmearingKernel +from .smearing import SmearingKernel, check_split_fit from .uncertainty import ( NoiseModel, UncertaintyResult, @@ -269,6 +269,7 @@ def _compute_core( ) delays = np.asarray(result.delays, dtype=float) scale_tau = float(np.median(np.abs(np.diff(delays)))) if delays.size > 1 else 1.0 + check_split_fit(smearing, fit_smearing_split) spec = ExtraParamSpec( fit_thickness=fit_thickness, thickness0=central_thickness, diff --git a/croak/forward.py b/croak/forward.py index 2929404..929c58a 100644 --- a/croak/forward.py +++ b/croak/forward.py @@ -37,7 +37,7 @@ from . import crystals from .crystals import CrystalSetup from .interactions import Interaction, get_interaction -from .smearing import SmearingKernel, delay_frequency_grid +from .smearing import SmearingKernel, check_kernel, delay_frequency_grid __all__ = ["ForwardModel", "quadrature_nodes_weights", "maketrace"] @@ -198,12 +198,7 @@ def __init__( # depth quadrature rather than coupling to it. self.smearing = smearing if smearing is not None: - if self.interaction.name not in ("pg", "sd"): - raise ValueError( - f"geometrical smearing is not supported for the " - f"{self.interaction.name.upper()} interaction; only PG (TG) and SD " - f"have the required three-arm form" - ) + check_kernel(self.interaction, smearing) self.p_nodes, self.p_weights = smearing.nodes_weights() self.p_mu, self.p_sigma = smearing.conditional_delay(self.p_nodes) self.delay_omega = delay_frequency_grid(self.delays, smearing.sigma_delta) @@ -314,7 +309,13 @@ def _trace_smeared( """ per_node = np.empty((self.n, self.m, self.p_nodes.size), dtype=float) for j, tau in enumerate(self.delays): - per_node[:, j, :] = np.abs(self.signal_smeared(ew, tau)) ** 2 + if self.interaction.name == "shg": + # two beams: no shape parameter (check_kernel), one node, and the + # unsmeared signal with each arm's own propagator (a crystal's + # arms differ, CrystalSetup.arm_shift) + per_node[:, j, 0] = np.abs(self.signal_single(ew, tau)) ** 2 + else: + per_node[:, j, :] = np.abs(self.signal_smeared(ew, tau)) ** 2 # Characteristic function of N(mu_k, sigma^2), shape (M, K): # exp(-i Omega mu - sigma^2 Omega^2 / 2) omega_delay = self.delay_omega[:, None] diff --git a/croak/forward_jax.py b/croak/forward_jax.py index f8461cb..827bda0 100644 --- a/croak/forward_jax.py +++ b/croak/forward_jax.py @@ -62,6 +62,7 @@ from .maths import wlfreq # noqa: E402 - see the x64 note above from .smearing import ( # noqa: E402 - see the x64 note above SmearingKernel, + check_kernel, delay_frequency_grid, ) @@ -107,8 +108,8 @@ } #: JAX twin of :meth:`croak.interactions.Interaction.smeared_signal`: combine the -#: ``p``-independent replica with the pair at ``varying_base -/+ p/2``. SHG is absent — -#: geometric smearing is only defined for the three-arm PG/SD forms. +#: ``p``-independent replica with the pair at ``varying_base -/+ p/2``. SHG is absent: +#: with two beams its smearing has no ``p`` and is a pure delay convolution. _JAX_SMEARED_INTERACTIONS: dict[ str, Callable[[jnp.ndarray, jnp.ndarray, jnp.ndarray], jnp.ndarray] ] = { @@ -659,11 +660,8 @@ def make_param_trace_fn( also be a length-2 vector for split channel scaling. """ inter = get_interaction(interaction) - if smearing is not None and inter.name not in _JAX_SMEARED_INTERACTIONS: - raise ValueError( - f"geometrical smearing is not supported for the {inter.name.upper()} " - f"interaction; only PG (TG) and SD have the required three-arm form" - ) + if smearing is not None: + check_kernel(inter, smearing) # Same guard as the forward model: SHG needs a crystal (croak.crystals). crystals.check_medium( inter, @@ -1130,13 +1128,31 @@ def trace(ew, thickness_v, tau0_v, smear_scale=1.0): # (s_p, s_d) at fixed rho maps the node positions to s_p*p_k and the conditional # delay moments to s_d*mu_k and s_d*sigma_cond — so a split scale is exact, not # an approximation. + omega_delay = jnp.asarray(delay_frequency_grid(delays, smearing.sigma_delta)) + if inter.name == "shg": + # Two beams: only the delay offset survives (check_kernel), so the smeared + # trace is the unsmeared one (each arm with its own propagator, which a + # crystal needs) convolved along delay with N(0, sigma_delta^2). + sigma_delta = smearing.sigma_delta + + def shg_trace(ew, thickness_v, tau0_v, smear_scale=1.0): + _, scale_d = _smear_scale_pair(smear_scale) + psis = jax.vmap(lambda tau: signal(ew, tau, thickness_v, tau0_v))(delays_j) + kernel = jnp.exp(-0.5 * (scale_d * sigma_delta) ** 2 * omega_delay**2) + spec = jnp.fft.fft(jnp.abs(psis) ** 2, axis=0) + t = jnp.real(jnp.fft.ifft(spec * kernel[:, None], axis=0)).T + if normalize: + t = t / jnp.max(t) + return t + + return shg_trace + smeared_map = _JAX_SMEARED_INTERACTIONS[inter.name] p_nodes_np, p_weights_np = smearing.nodes_weights() mu_np, sigma_delta_cond = smearing.conditional_delay(p_nodes_np) p_nodes = jnp.asarray(p_nodes_np) p_weights = jnp.asarray(p_weights_np) mu_nodes = jnp.asarray(mu_np) - omega_delay = jnp.asarray(delay_frequency_grid(delays, smearing.sigma_delta)) def signal_smeared(ew, tau, thickness_v, tau0_v, scale_p): ew_bin = jnp.fft.ifftshift(ew) diff --git a/croak/gui/stage_retrieve.py b/croak/gui/stage_retrieve.py index 9894fd2..40f5c24 100644 --- a/croak/gui/stage_retrieve.py +++ b/croak/gui/stage_retrieve.py @@ -32,8 +32,10 @@ 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, ) @@ -270,6 +272,18 @@ class StageRetrieve(RunControls, Stage): "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.", + ), ], ), ( @@ -580,7 +594,6 @@ def __init__(self, state): form.addRow("Npoints", self.npoints_spin) self.controls.addWidget(box) self._build_crystal_groups() - self._update_medium_groups() self.smear_box, form = group("Geometrical smearing") box = self.smear_box @@ -974,6 +987,8 @@ def __init__(self, state): self.set_plot_area(self.pages, strip) self._update_extras_readout(None) + # every group exists now: show the slab or the crystal (none loaded yet) + self._update_medium_groups() self.apply_help() # Remember the Retrieve combo's help tooltip so the B-spline lock can # swap in an explanation and restore it afterwards. @@ -1124,7 +1139,21 @@ def _build_crystal_groups(self) -> None: 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_smearing_check = check( + "Model the delay smearing", p.smearing, self._on_shg_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) @@ -1164,6 +1193,15 @@ def _on_geometry_f_changed(self, value: float) -> None: 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() + + def _gate_shg_smearing(self, params: set[str]) -> None: + """Enable SHG smearing for crossing beams and a solver (``params``) for it.""" + crossing = self.state.retrieve.beam_separation_mm > 0 + self.shg_smearing_check.setEnabled(crossing and "smearing" in params) + def _on_focal_f_changed(self, value: float) -> None: self.state.retrieve.focal_f_mm = float(value) self.geometry_f_spin.blockSignals(True) @@ -1179,6 +1217,16 @@ def _update_medium_groups(self) -> None: """Show the crystal and beam geometry for SHG, the material slab otherwise.""" shg = self._is_shg() self.disp_box.setVisible(not shg) + self.smear_box.setVisible(not shg) # SHG's smearing is in Beam geometry + self.focal_box.setVisible(not shg) # the focal mixture is PG/SD's + if shg and self.state.retrieve.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) + self.set_status( + "The focal mixture is for PG/SD; switched off for this SHG trace.", + "warn", + ) self.crystal_box.setVisible(shg) self.geometry_box.setVisible(shg) if shg: @@ -1188,13 +1236,18 @@ def _update_medium_groups(self) -> None: 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) - self.crystal_check.blockSignals(True) - self.crystal_check.setChecked(p.dispersive) - self.crystal_check.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: @@ -1214,11 +1267,19 @@ def _refresh_crystal(self) -> None: self.delayed_beam_combo.setEnabled( crossing and p.polarization == "perpendicular" ) - if crossing: - alpha = math.degrees(math.atan(p.beam_separation_mm / (2 * p.focal_f_mm))) - self.geometry_readout.setText(f"Crossing half-angle α = {alpha:.3f}°") + 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") + self.geometry_readout.setText("Collinear beams: no delay smearing") self.crystal_readout.setText(self._crystal_summary()) def _crystal_summary(self) -> str: @@ -1302,6 +1363,12 @@ 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 + for box in (self.smearing_check, self.shg_smearing_check): + box.blockSignals(True) + box.setChecked(bool(value)) + box.blockSignals(False) # The reduced kernel and the explicit focal mixture are two models of # the same physics — never both. Enabling one disarms the other. if bool(value) and self.state.retrieve.focal: @@ -1311,7 +1378,7 @@ def _on_smearing_changed(self, value): def _on_focal_changed(self, value): self.state.retrieve.focal = bool(value) if bool(value) and self.state.retrieve.smearing: - self.smearing_check.setChecked(False) + self._on_smearing_changed(False) self._update_solver_caps() def _on_collection_changed(self, value): @@ -1386,19 +1453,19 @@ def _smear_wavelength(self) -> float: def _refresh_smear_sigma(self) -> None: """Recompute and display σ from the current geometry, signal-safe.""" p = self.state.retrieve - try: - sigma_fs = ( - smearing.square_boxcars_delay_width( - self._smear_interaction(), - hole_diameter=p.smear_hole_diameter_mm * 1e-3, - hole_spacing=p.smear_hole_spacing_mm * 1e-3, - wavelength=self._smear_wavelength(), - ) - * 1e15 - ) - except ValueError: - # SHG has no three-arm form; leave the displayed width alone. + 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 return + sigma_fs = ( + smearing.square_boxcars_delay_width( + self._smear_interaction(), + hole_diameter=p.smear_hole_diameter_mm * 1e-3, + hole_spacing=p.smear_hole_spacing_mm * 1e-3, + wavelength=self._smear_wavelength(), + ) + * 1e15 + ) p.smear_sigma_delay_fs = sigma_fs self.smear_sigma_spin.blockSignals(True) self.smear_sigma_spin.setValue(sigma_fs) @@ -1527,6 +1594,7 @@ def _update_solver_caps(self): # Capability comes from the constructor signature, so this follows # automatically. self.smear_box.setEnabled("smearing" in params) + self._gate_shg_smearing(params) # The explicit chromatic focal mixture rides the same capability # mechanism: only solvers whose constructors take `focal` can model it. self.focal_box.setEnabled("focal" in params) @@ -1545,9 +1613,11 @@ def _update_solver_caps(self): has_fit_thickness and self.state.retrieve.dispersive and not self._is_shg() ) self.fit_tau0_check.setEnabled(has_fit_tau0) - self.fit_smearing_check.setEnabled( - has_fit_smearing and self.state.retrieve.smearing + # the width needs a kernel: for SHG, crossing beams + has_kernel = self.state.retrieve.smearing and ( + not self._is_shg() or self.state.retrieve.beam_separation_mm > 0 ) + self.fit_smearing_check.setEnabled(has_fit_smearing and has_kernel) # Two-phase polish is a local-solver option; the global cma-es frees the # extras from the start, so it has no `polish` argument. self.polish_check.setEnabled( @@ -1675,6 +1745,8 @@ def _seed_crystal_widgets(self) -> None: 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) @@ -1968,15 +2040,11 @@ def _update_view(self): def _smear_width_fs(self, smear_scale: float, td) -> float | None: """The modelled smearing delay width (fs) at ``smear_scale``, or ``None``. - ``None`` when there is no kernel to measure — smearing switched off, or an - SHG trace, which has no three-arm form and so no smearing model at all — so - the read-out can fall back to reporting the bare multiplier or nothing. + ``None`` when there is no kernel to measure (smearing switched off, or + collinear SHG beams), so the read-out can fall back to reporting the bare + multiplier or nothing. """ - try: - kernel = smearing_kernel(self.state.retrieve, td) - except ValueError: - # SHG: square_boxcars_kernel refuses, and rightly so. - return None + kernel = smearing_kernel(self.state.retrieve, td) if kernel is None: return None return kernel.sigma_delta * smear_scale / 1e-15 diff --git a/croak/lbfgs_ad.py b/croak/lbfgs_ad.py index 040ac9e..cfc3898 100644 --- a/croak/lbfgs_ad.py +++ b/croak/lbfgs_ad.py @@ -42,7 +42,7 @@ from .focal import FocalMixture from .forward_jax import make_param_trace_fn from .result import RetrievalResult -from .smearing import SmearingKernel +from .smearing import SmearingKernel, check_split_fit from .solver import ( Retriever, assemble_result, @@ -82,7 +82,8 @@ class LBFGSAD(Retriever): :class:`croak.forward.ForwardModel`. smearing : SmearingKernel or None, optional Geometric time-smearing kernel of a non-collinear BOXCARS geometry - (default ``None`` = off). PG (TG) and SD only. See :mod:`croak.smearing` + (default ``None`` = off): a BOXCARS kernel for PG (TG) and SD, or the + two-beam kernel for SHG. See :mod:`croak.smearing` and :doc:`/howto/geometric_smearing`. focal : FocalMixture or None, optional Chromatic focal mixture (:mod:`croak.focal`) in place of ``smearing``: @@ -349,6 +350,7 @@ def _solve( scale_tau = ( float(np.median(np.abs(np.diff(delays)))) if delays.size > 1 else 1.0 ) + check_split_fit(self.smearing, self.fit_smearing_split) spec = ExtraParamSpec( fit_thickness=self.fit_thickness, thickness0=self.thickness, diff --git a/croak/lm.py b/croak/lm.py index deae9d9..b644c04 100644 --- a/croak/lm.py +++ b/croak/lm.py @@ -47,7 +47,7 @@ from .focal import FocalMixture from .forward_jax import make_param_trace_fn from .result import RetrievalResult -from .smearing import SmearingKernel +from .smearing import SmearingKernel, check_split_fit from .solver import ( Retriever, assemble_result, @@ -76,7 +76,8 @@ class LM(Retriever): Dispersive-slab parameters; see :class:`croak.forward.ForwardModel`. smearing : SmearingKernel or None, optional Geometric time-smearing kernel of a non-collinear BOXCARS geometry - (default ``None`` = off). PG (TG) and SD only. See :mod:`croak.smearing` + (default ``None`` = off): a BOXCARS kernel for PG (TG) and SD, or the + two-beam kernel for SHG. See :mod:`croak.smearing` and :doc:`/howto/geometric_smearing`. focal : FocalMixture or None, optional Chromatic focal mixture (:mod:`croak.focal`) in place of ``smearing``: @@ -261,6 +262,7 @@ def _solve( scale_tau = ( float(np.median(np.abs(np.diff(delays)))) if delays.size > 1 else 1.0 ) + check_split_fit(self.smearing, self.fit_smearing_split) spec = ExtraParamSpec( fit_thickness=self.fit_thickness, thickness0=self.thickness, diff --git a/croak/optimistix_lbfgs.py b/croak/optimistix_lbfgs.py index f3955ec..778cb8c 100644 --- a/croak/optimistix_lbfgs.py +++ b/croak/optimistix_lbfgs.py @@ -53,7 +53,8 @@ class OptxLBFGS(Retriever): Dispersive-slab parameters; see :class:`croak.forward.ForwardModel`. smearing : SmearingKernel or None, optional Geometric time-smearing kernel of a non-collinear BOXCARS geometry - (default ``None`` = off). PG (TG) and SD only. See :mod:`croak.smearing` + (default ``None`` = off): a BOXCARS kernel for PG (TG) and SD, or the + two-beam kernel for SHG. See :mod:`croak.smearing` and :doc:`/howto/geometric_smearing`. focal : FocalMixture or None, optional Chromatic focal mixture (:mod:`croak.focal`) in place of ``smearing``: diff --git a/croak/optimistix_lm.py b/croak/optimistix_lm.py index 12cfb36..7456bb3 100644 --- a/croak/optimistix_lm.py +++ b/croak/optimistix_lm.py @@ -32,7 +32,7 @@ from .focal import FocalMixture from .forward_jax import make_param_trace_fn from .result import RetrievalResult -from .smearing import SmearingKernel +from .smearing import SmearingKernel, check_split_fit from .solver import ( Retriever, assemble_result, @@ -82,7 +82,8 @@ class OptxLM(Retriever): Dispersive-slab parameters; see :class:`croak.forward.ForwardModel`. smearing : SmearingKernel or None, optional Geometric time-smearing kernel of a non-collinear BOXCARS geometry - (default ``None`` = off). PG (TG) and SD only. See :mod:`croak.smearing` + (default ``None`` = off): a BOXCARS kernel for PG (TG) and SD, or the + two-beam kernel for SHG. See :mod:`croak.smearing` and :doc:`/howto/geometric_smearing`. focal : FocalMixture or None, optional Chromatic focal mixture (:mod:`croak.focal`) in place of ``smearing``: @@ -275,6 +276,7 @@ def _solve( scale_tau = ( float(np.median(np.abs(np.diff(delays)))) if delays.size > 1 else 1.0 ) + check_split_fit(self.smearing, self.fit_smearing_split) spec = ExtraParamSpec( fit_thickness=self.fit_thickness, thickness0=self.thickness, diff --git a/croak/pipeline.py b/croak/pipeline.py index bc9ab27..a14571b 100644 --- a/croak/pipeline.py +++ b/croak/pipeline.py @@ -218,9 +218,10 @@ def retrieve_from_tracedata( for SHG in a Type I crystal (``npoints`` at least :func:`croak.crystals.depth_points`). smearing : SmearingKernel or None, optional - Geometric time-smearing kernel of a non-collinear BOXCARS geometry - (``None`` = off). Only the autodiff solvers can model it; asking for it - with any other algorithm raises rather than silently dropping it. See + Geometric time-smearing kernel of a non-collinear geometry (``None`` = + off): BOXCARS for PG and SD, two beams for SHG. Only the autodiff solvers + can model it; asking for it with any other algorithm raises rather than + silently dropping it. See :mod:`croak.smearing` and :doc:`/howto/geometric_smearing`. focal : FocalMixture or None, optional Explicit chromatic focal-plane mixture, optionally carrying a diff --git a/croak/session/params.py b/croak/session/params.py index d9c7bda..0be9506 100644 --- a/croak/session/params.py +++ b/croak/session/params.py @@ -360,6 +360,10 @@ class RetrieveParams: #: Beam separation (mm) at the focusing optic of focal length ``focal_f_mm``: #: the crossing half-angle is atan(d / 2f). ``0`` models collinear beams. beam_separation_mm: float = 5.0 + #: 1/e² diameter (mm) of each beam at the focusing optic. With ``smearing`` it + #: sets the focal spot and so the SHG delay smearing + #: (croak.smearing.shg_two_beam_kernel). + beam_diameter_mm: float = 3.0 # Default node count kept consistent with the tied defaults below: # thickness_um / delta_z_um = 10 µm / 1 µm = 10. npoints: int = 10 @@ -369,8 +373,10 @@ class RetrieveParams: # ``npoints`` back-computes the step. Only ``npoints`` reaches the forward # model (:class:`croak.forward.ForwardModel`) — ``delta_z_um`` is the GUI knob. delta_z_um: float = 1.0 - # Geometric time smearing of a non-collinear BOXCARS geometry (PG/SD only, - # autodiff solvers only). The mask hole diameter and edge-to-edge spacing are + # Geometric time smearing (autodiff solvers only). For PG/SD a non-collinear + # BOXCARS mask; for SHG the two beams of beam_separation_mm, focal_f_mm and + # beam_diameter_mm (croak.smearing.shg_two_beam_kernel), and the mask fields + # below do not apply. The mask hole diameter and edge-to-edge spacing are # the physical inputs; the resulting delay-offset width is tied to them via # croak.smearing.square_boxcars_delay_width at the measured carrier, so editing # either geometry field updates the width and editing the width back-computes diff --git a/croak/session/pipeline.py b/croak/session/pipeline.py index f4c85c8..61211d4 100644 --- a/croak/session/pipeline.py +++ b/croak/session/pipeline.py @@ -51,7 +51,12 @@ shiftnorm, ) from ..result import RetrievalResult -from ..smearing import SmearingKernel, collinear_sd_kernel, square_boxcars_kernel +from ..smearing import ( + SmearingKernel, + collinear_sd_kernel, + shg_two_beam_kernel, + square_boxcars_kernel, +) from ..uncertainty import ( NoiseModel, UncertaintyResult, @@ -780,10 +785,22 @@ def smearing_kernel(p: RetrieveParams, td: TraceData) -> SmearingKernel | None: The mask geometry is the stored truth (the displayed delay width is a derived GUI convenience), and the carrier comes from the measurement itself, so the kernel is always evaluated at the wavelength the trace was actually taken at. + For SHG the kernel is the two beams' delay blur + (:func:`~croak.smearing.shg_two_beam_kernel`) from :func:`beam_geometry`, the + same beams the crystal uses, at :func:`pulse_wavelength`, without the fixed + multiplier ``smear_scale`` (which the mask geometry needs); collinear beams + give ``None``. """ if not p.smearing: return None - if p.smear_layout == "sd2": + if td.interaction == "shg": + geometry = beam_geometry(p) + if geometry is None: + return None # collinear beams: no crossing, nothing to smear + # the beams set the width directly; the fixed multiplier below exists for + # the mask geometry's unreachable widths and does not apply + return shg_two_beam_kernel(geometry, pulse_wavelength(td)) + elif p.smear_layout == "sd2": # Two-beam self-diffraction: sigma_p is identically zero, so this is # NOT the "sd" branch of the boxcars closed form (which assumes two # separate unconjugated holes and would add a ~0.4 fs p channel). @@ -806,6 +823,22 @@ def smearing_kernel(p: RetrieveParams, td: TraceData) -> SmearingKernel | None: return kernel if p.smear_scale == 1.0 else kernel.scaled(p.smear_scale) +def pulse_wavelength(td: TraceData) -> float: + """Return the pulse's wavelength (m): the spectrum's centroid, else the carrier. + + The SHG smearing width scales with the wavelength (the focal spot does), and + the centroid of the independent spectrum is where the pulse's energy is, + which the grid's centre need not be. + """ + omega = td.omega0_pulse + if td.Iomega is not None and np.sum(td.Iomega) > 0: + weights = np.asarray(td.Iomega, dtype=float) + omega = float( + np.sum((td.grid.omega + td.omega0_pulse) * weights) / weights.sum() + ) + return 2.0 * np.pi * C / omega + + def generation_envelope(p: RetrieveParams): r"""Build the generation envelope g(z) at the depth-quadrature nodes, or ``None``. @@ -839,6 +872,19 @@ def generation_envelope(p: RetrieveParams): return amp * np.exp(1j * p.envelope_gouy * np.arctan(u)) +def beam_geometry(p: RetrieveParams) -> TwoBeamGeometry | None: + """Return the two beams the settings describe, or ``None`` for collinear beams. + + The one source of the crossing angle for both the crystal's phase matching + and the SHG delay smearing. + """ + if p.beam_separation_mm <= 0: + return None + return TwoBeamGeometry( + p.beam_separation_mm * 1e-3, p.focal_f_mm * 1e-3, p.beam_diameter_mm * 1e-3 + ) + + def crystal_setup(p: RetrieveParams) -> CrystalSetup: """Build the SHG crystal the retrieval settings describe. @@ -868,11 +914,7 @@ def crystal_setup(p: RetrieveParams) -> CrystalSetup: raise ValueError( f"angle_mode must be 'tilt' or 'phase-match', got {p.angle_mode!r}" ) - geometry = ( - TwoBeamGeometry(p.beam_separation_mm * 1e-3, p.focal_f_mm * 1e-3) - if p.beam_separation_mm > 0 - else None - ) + geometry = beam_geometry(p) in_plane = p.polarization == "perpendicular" return CrystalSetup( builtin_crystal(p.crystal), @@ -927,6 +969,14 @@ def fits_thickness(p: RetrieveParams, medium: str | CrystalSetup | None) -> bool return p.fit_thickness and isinstance(medium, str) +def fits_smearing(p: RetrieveParams, kernel: SmearingKernel | None) -> bool: + """Return whether the smearing width is fitted: only when there is a kernel. + + Collinear SHG beams, or smearing switched off, give no kernel to scale. + """ + return p.fit_smearing and kernel is not None + + def crystal_tilt_error( p: RetrieveParams, td: TraceData, result: RetrievalResult ) -> float | None: @@ -1209,6 +1259,7 @@ def run_retrieval( td = apply_spectrum_frame(p, td) thickness, tau0, smear_scale, smear_delta = extra_param_centres(p, extras_seed) medium = retrieval_medium(p, td) + kernel = smearing_kernel(p, td) result = retrieve_from_tracedata( td, algorithm=p.solver, @@ -1220,7 +1271,7 @@ def run_retrieval( material=medium, thickness=thickness, npoints=retrieval_npoints(p, td, medium, thickness), - smearing=smearing_kernel(p, td), + smearing=kernel, focal=focal, depth_weight=generation_envelope(p), reg_amp=p.reg_amp, @@ -1240,8 +1291,8 @@ def run_retrieval( fit_thickness=fits_thickness(p, medium), fit_tau0=p.fit_tau0, # the smearing strength is only fittable when a kernel is being modelled - fit_smearing=p.fit_smearing and p.smearing, - fit_smearing_split=p.fit_smearing_split and p.fit_smearing and p.smearing, + fit_smearing=fits_smearing(p, kernel), + fit_smearing_split=fits_smearing(p, kernel) and p.fit_smearing_split, polish=p.polish_two_phase, delay_origin=p.delay_origin, tau0_bound=p.tau0_bound_fs * 1e-15, @@ -1307,6 +1358,7 @@ def bootstrap_solver_kwargs(p: RetrieveParams, td: TraceData) -> dict: """ medium = retrieval_medium(p, td) thickness = p.thickness_um * 1e-6 if p.dispersive else 0.0 + kernel = smearing_kernel(p, td) return { "algorithm": p.solver, "maxiters": p.maxiters, @@ -1315,7 +1367,7 @@ def bootstrap_solver_kwargs(p: RetrieveParams, td: TraceData) -> dict: "material": medium, "thickness": thickness, "npoints": retrieval_npoints(p, td, medium, thickness), - "smearing": smearing_kernel(p, td), + "smearing": kernel, "depth_weight": generation_envelope(p), "phase_only": not p.full, "phase_basis": p.phase_basis, @@ -1329,8 +1381,8 @@ def bootstrap_solver_kwargs(p: RetrieveParams, td: TraceData) -> dict: "time_window": (p.reg_time_lo_fs * 1e-15, p.reg_time_hi_fs * 1e-15), "fit_thickness": fits_thickness(p, medium), "fit_tau0": p.fit_tau0, - "fit_smearing": p.fit_smearing and p.smearing, - "fit_smearing_split": p.fit_smearing_split and p.fit_smearing and p.smearing, + "fit_smearing": fits_smearing(p, kernel), + "fit_smearing_split": fits_smearing(p, kernel) and p.fit_smearing_split, "polish": p.polish_two_phase, "strategy": p.cma_strategy, "popsize": p.cma_popsize, @@ -1349,6 +1401,7 @@ def covariance_kwargs(p: RetrieveParams, td: TraceData | None = None) -> dict: (:func:`retrieval_medium`); without it the slab is ``p.material``. """ thickness = p.thickness_um * 1e-6 if p.dispersive else 0.0 + kernel = smearing_kernel(p, td) if td is not None else None if td is None: medium: str | CrystalSetup | None = p.material if p.dispersive else None npoints = p.npoints @@ -1359,17 +1412,15 @@ def covariance_kwargs(p: RetrieveParams, td: TraceData | None = None) -> dict: "material": medium, "thickness": thickness, "npoints": npoints, - "smearing": smearing_kernel(p, td) if td is not None else None, + "smearing": kernel, "phase_only": not p.full, "phase_basis": p.phase_basis, "n_nodes": p.n_nodes, "R_omega": p.R_omega, "fit_thickness": fits_thickness(p, medium), "fit_tau0": p.fit_tau0, - "fit_smearing": p.fit_smearing and p.smearing and td is not None, - "fit_smearing_split": ( - p.fit_smearing_split and p.fit_smearing and p.smearing and td is not None - ), + "fit_smearing": fits_smearing(p, kernel), + "fit_smearing_split": fits_smearing(p, kernel) and p.fit_smearing_split, } diff --git a/croak/smearing.py b/croak/smearing.py index b095c15..325c76c 100644 --- a/croak/smearing.py +++ b/croak/smearing.py @@ -1,4 +1,9 @@ -r"""Geometric (pulse-front-tilt) time smearing in a non-collinear BOXCARS geometry. +r"""Geometric (pulse-front-tilt) time smearing in a non-collinear geometry. + +Most of this module concerns the three-arm BOXCARS geometry of PG (TG) and SD. Two-beam +SHG is simpler: only the relative delay of the two arms varies across the focus, so +its kernel (:func:`shg_two_beam_kernel`) has no shape parameter and the trace is the +unsmeared one convolved along delay. In a non-collinear geometry the input beams reach the interaction plane with tilted pulse fronts, so the relative arrival time between arms varies linearly across the @@ -103,10 +108,14 @@ from numpy.polynomial.hermite_e import hermegauss from numpy.typing import ArrayLike, NDArray +from .geometry import TwoBeamGeometry from .interactions import Interaction, get_interaction __all__ = [ + "check_kernel", + "check_split_fit", "collinear_sd_kernel", + "shg_two_beam_kernel", "AIRY6_RMS_COEFF", "deconvolve_delay", "SmearingKernel", @@ -589,6 +598,145 @@ def square_boxcars_kernel( return kernel +def check_kernel(interaction: str | Interaction, kernel: SmearingKernel) -> None: + """Check that a smearing kernel has a meaning for the interaction. + + PG and SD take any kernel. SHG has two beams, so only the delay offset + survives: its kernel must have ``sigma_p = 0`` (:func:`shg_two_beam_kernel`). + + Parameters + ---------- + interaction : str or Interaction + The interaction. + kernel : SmearingKernel + The kernel. + + Raises + ------ + ValueError + If ``interaction`` is SHG and ``kernel.sigma_p`` is not zero. + """ + if get_interaction(interaction).name == "shg" and kernel.sigma_p != 0.0: + raise ValueError( + "an SHG trace has two beams, so its smearing is a pure delay blur with " + f"no shape parameter; got sigma_p={kernel.sigma_p!r}. Build the kernel " + "with croak.smearing.shg_two_beam_kernel" + ) + + +def check_split_fit(kernel: SmearingKernel | None, fit_smearing_split: bool) -> None: + """Refuse a split smearing fit for a kernel with no shape channel. + + A split fit scales the shape (``p``) and delay channels separately. A kernel + with ``sigma_p = 0`` (two-beam SHG, :func:`shg_two_beam_kernel`; two-beam SD, + :func:`collinear_sd_kernel`) has no ``p`` channel, so its multiplier would not + move the trace: fitted, it stays where it started, and a covariance reports a + falsely exact zero uncertainty for it. + + Parameters + ---------- + kernel : SmearingKernel or None + The kernel. + fit_smearing_split : bool + Whether the two channels are fitted separately. + + Raises + ------ + ValueError + If ``fit_smearing_split`` is set and ``kernel.sigma_p`` is zero. + """ + if fit_smearing_split and kernel is not None and kernel.sigma_p == 0.0: + raise ValueError( + "fit_smearing_split needs a kernel with a shape channel (sigma_p > 0); " + "this kernel has none (two beams), so fit the one width with " + "fit_smearing alone" + ) + + +def shg_two_beam_kernel(geometry: TwoBeamGeometry, wavelength: float) -> SmearingKernel: + r"""Delay-smearing kernel of a two-beam (non-collinear) SHG FROG. + + With two beams the signal is :math:`E_1(t)\,E_2(t-\tau+\delta)`: the + two arrival times leave one combination, the relative delay :math:`\delta`, + and no shape parameter :math:`p`. So the measured trace is the unsmeared one + convolved along delay with the distribution of :math:`\delta` across the + focus (Taft et al., IEEE J. Select. Topics Quantum Electron. 2, 575 (1996), + doi:10.1109/2944.571757, Eq. 7). + + Each Gaussian beam of 1/e² diameter :math:`D` at the focusing optic (focal + length :math:`f`) focuses to the waist :math:`w_0 = 2\lambda f/(\pi D)` + (1/e² radius), and the two spots coincide at the crossing point. Across the + crossing plane, at :math:`x` from the bisector, each beam's intensity is + :math:`e^{-2x^2\cos^2\alpha/w_0^2}` (its own transverse coordinate is + :math:`x\cos\alpha`), and the signal is weighted by their product, so + :math:`x` has rms :math:`w_0/(2\sqrt2\cos\alpha)`. There the arms' tilted + wavefronts give the relative delay :math:`\delta = 2x\sin\alpha/c`. Hence + + .. math:: + + \sigma_\delta = \frac{w_0\tan\alpha}{\sqrt2\,c} + = \frac{\lambda d}{\sqrt2\,\pi D c}, + + with :math:`\tan\alpha = d/(2f)` and :math:`d` the beam separation: exactly + independent of the focal length. For beams separated by their diameter + (:math:`d = D`) at 800 nm this is 0.60 fs rms. + + This matches Baltuška et al. (IEEE J. Quantum Electron. 35, 459 (1999), + doi:10.1109/3.753651, Eqs. 28-29), who give :math:`\delta t = \lambda/(2\pi c)`, + 0.42 fs, for that layout, as the term that adds in quadrature to the pulse's + duration inferred from the trace: for Gaussian pulses the trace's delay + marginal is the intensity autocorrelation, whose width grows by + :math:`\sigma_\delta` in quadrature, so the inferred duration grows by + :math:`\sigma_\delta/\sqrt2 = \lambda/(2\pi c)`. The match holds with rms + durations and :math:`d` and :math:`D` read as 1/e² diameters; with FWHM + beam profiles throughout, the figures differ by :math:`2\ln 2`. + + Validity: Gaussian beams, collimated at the optic; a crystal thin against the + Rayleigh range (the spots stay superposed through it); full collection of the + signal beam, which a thick crystal's angular acceptance (it filters the + signal's transverse wavevector) or an aperture violates; and the spot size at + the single ``wavelength`` given (it scales with the wavelength across a broad + spectrum). + + Parameters + ---------- + geometry : TwoBeamGeometry + The beams; ``beam_diameter`` must be set. The same object should describe + the crystal (:class:`croak.crystals.CrystalSetup`), so the phase matching + and the smearing use one crossing angle. + wavelength : float + Wavelength (m) the spot size is taken at, e.g. the pulse's centroid. + + Returns + ------- + SmearingKernel + ``sigma_p = 0``, one node, ``sigma_delta`` as above. + + Raises + ------ + ValueError + If ``geometry.beam_diameter`` is ``None`` or ``wavelength`` is not positive. + + Examples + -------- + >>> g = TwoBeamGeometry(beam_separation=1e-3, focal_length=0.1, beam_diameter=1e-3) + >>> round(shg_two_beam_kernel(g, 800e-9).sigma_delta * 1e15, 2) + 0.6 + """ + if geometry.beam_diameter is None: + raise ValueError( + "the two-beam smearing kernel needs the beams' diameter: set " + "TwoBeamGeometry.beam_diameter (1/e² diameter at the focusing optic)" + ) + if not (math.isfinite(wavelength) and wavelength > 0.0): + raise ValueError(f"wavelength must be finite and positive, got {wavelength!r}") + waist = ( + 2.0 * wavelength * geometry.focal_length / (math.pi * geometry.beam_diameter) + ) + sigma = waist * math.tan(geometry.crossing_half_angle) / (math.sqrt(2.0) * _C_LIGHT) + return SmearingKernel(sigma_p=0.0, sigma_delta=sigma, rho=0.0, npoints=1) + + def deconvolve_delay( trace: ArrayLike, delays: ArrayLike, diff --git a/docs/howto/geometric_smearing.md b/docs/howto/geometric_smearing.md index 9e5770d..9dd260d 100644 --- a/docs/howto/geometric_smearing.md +++ b/docs/howto/geometric_smearing.md @@ -168,7 +168,11 @@ the delay axis) and the gate-shape parameter $p$ (a symmetric split of the gate pair, which for a chirped gate shears the trace along frequency). The joint multiplier scales both together, which is the right physical prior — both derive from the same $d/D$ — but as a *diagnostic* it conflates them. Setting -`fit_smearing_split=True` fits the two widths as independent multipliers: +`fit_smearing_split=True` fits the two widths as independent multipliers. It needs +a kernel with a shape channel: a two-beam kernel (SD's +{func}`~croak.smearing.collinear_sd_kernel`, SHG's +{func}`~croak.smearing.shg_two_beam_kernel`) has none, and the split is refused +({func}`~croak.smearing.check_split_fit`): ```python res = croak.retrieve( @@ -242,19 +246,64 @@ raise. |---|---|---| | `smearing` | `warm-lbfgs`, `lbfgs-ad`, `lm`, `lm-optx`, `lbfgs-optx`, `cma-es` | PG (TG) or SD; uniform delay axis | | `fit_smearing` | `warm-lbfgs`, `lbfgs-ad`, `lm`, `lm-optx`, `cma-es` | a `smearing` kernel | -| `fit_smearing_split` | `warm-lbfgs`, `lbfgs-ad`, `lm`, `lm-optx`, `cma-es` | `fit_smearing` | +| `fit_smearing_split` | `warm-lbfgs`, `lbfgs-ad`, `lm`, `lm-optx`, `cma-es` | `fit_smearing`; a kernel with a shape channel | `copra`, `copra-jax`, `lbfgs` and `lbfgs-hand` cannot model smearing: the incoherent average over the kernel breaks COPRA's magnitude-replacement projection, and the hand-derived adjoint is not extended to it. Asking for smearing with them raises rather than silently dropping the kernel. -SHG raises too: geometric smearing here is defined for the three-arm PG/SD forms. +## Two-beam SHG + +An SHG FROG has two beams, not three, so the arrival times leave only the +relative delay $\delta$ and no shape parameter $p$: the measured trace is the +unsmeared one convolved along delay. For Gaussian beams of 1/e² diameter $D$ at a +focusing optic of focal length $f$, separated by $d$, each focuses to the waist +$w_0 = 2\lambda f/(\pi D)$; across the crossing plane each beam's intensity is +$e^{-2x^2\cos^2\alpha/w_0^2}$, the signal from position $x$ is weighted by their +product, and it sees the relative delay $2x\sin\alpha/c$ with +$\tan\alpha = d/(2f)$ (Taft et al., IEEE J. Select. Topics Quantum Electron. 2, +575 (1996), Eq. 7). So + +$$\sigma_\delta = \frac{w_0\tan\alpha}{\sqrt2\,c} = \frac{\lambda d}{\sqrt2\,\pi D c},$$ + +0.60 fs rms for beams separated by their diameter at 800 nm, whatever the focal +length. {func}`~croak.smearing.shg_two_beam_kernel` builds this kernel from the same +{class}`~croak.geometry.TwoBeamGeometry` that gives a crystal its crossing angle: + +```python +from croak.geometry import TwoBeamGeometry +from croak.smearing import shg_two_beam_kernel + +beams = TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1, beam_diameter=3e-3) +kernel = shg_two_beam_kernel(beams, wavelength=800e-9) # sigma_delta = 1.00 fs + +res = croak.retrieve(trace, g.omega, delays, "shg", algorithm="lbfgs-ad", + smearing=kernel) +``` + +It works with or without a crystal ([SHG with a thick crystal](shg_crystal.md)). +The solver support is as above. The kernel has no shape channel, so a split fit +(`fit_smearing_split`) is refused; `fit_smearing` scales its one width, but how +well an SHG trace determines that width has not been established, so prefer the +width from the measured geometry and treat a fitted one with care. A kernel with a shape parameter is refused for SHG +({func}`~croak.smearing.check_kernel`). The width scales with the wavelength, so +take it at the pulse's centroid; a session does +({func}`~croak.session.pipeline.pulse_wavelength`), and does not apply the mask +geometry's fixed multiplier `smear_scale`. It assumes Gaussian beams collimated +at the optic, a crystal thin against the Rayleigh range and full collection of +the signal beam, which a thick crystal's angular acceptance or an aperture breaks. +Baltuška et al. (IEEE J. Quantum Electron. 35, 459 (1999), Eqs. 28-29) give +$\lambda/(2\pi c) \approx 0.4$ fs for the same layout, as the broadening of the +pulse duration inferred from the trace; that is $\sigma_\delta/\sqrt2$, the same +result when durations are rms widths and diameters 1/e² ones. ## In the GUI -The Retrieve stage has a **Geometrical smearing** group, greyed out unless the -chosen solver supports it: +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 +**Geometrical smearing** group, greyed out unless the chosen solver supports it: - *Enable geometrical smearing* - *Hole diameter (mm)* and *Hole spacing (mm)* (edge to edge) — the physical inputs diff --git a/docs/howto/gui.md b/docs/howto/gui.md index 00d2d7d..aa4d7d9 100644 --- a/docs/howto/gui.md +++ b/docs/howto/gui.md @@ -449,8 +449,9 @@ shows `ε(Iₜ)` alone rather than a number derived from something else. 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), with a read-out of the -internal angle, the tilt, the path and the depth nodes +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 ([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/shg_crystal.md b/docs/howto/shg_crystal.md index 2a8470f..4487aad 100644 --- a/docs/howto/shg_crystal.md +++ b/docs/howto/shg_crystal.md @@ -95,13 +95,33 @@ 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. +## Delay smearing + +The two crossing beams' relative delay varies across the focus, which blurs the +trace along delay. For few-cycle pulses this matters: beams of 20 µm waist crossing +at a half-angle of 2.9° blur the delay by 2.4 fs rms (5.5 fs FWHM), against a 6 fs +pulse. Give the beams their diameter and pass the two-beam kernel built from the +same geometry ([two-beam SHG smearing](geometric_smearing.md#two-beam-shg)): + +```python +from croak.smearing import shg_two_beam_kernel + +beams = TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1, beam_diameter=3e-3) +crystal = CrystalSetup(builtin_crystal("BBO"), math.radians(29.2), + phase_match_wavelength=800e-9, geometry=beams, + polarization="parallel") +res = croak.retrieve( + trace, g.omega, delays, "shg", algorithm="lbfgs-ad", + material=crystal, thickness=thickness, npoints=npoints, omega0=omega0, + smearing=shg_two_beam_kernel(beams, wavelength=800e-9), +) +``` + +In a session, `smearing` switches it on and `beam_diameter_mm` gives the +diameter; the GUI shows both in *Beam geometry*. + ## What is not modelled yet -- **Delay smearing.** The two crossing beams' local delay varies across the - focus, which blurs the trace along delay. croak's smearing kernels do not yet - cover SHG, and for few-cycle pulses this matters: beams of 20 µm waist - crossing at a half-angle of 2.9° blur the delay by 2.4 fs rms (5.5 fs FWHM), - against a 6 fs pulse. - **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. diff --git a/tests/gui/test_stage_retrieve.py b/tests/gui/test_stage_retrieve.py index b620880..52aeafc 100644 --- a/tests/gui/test_stage_retrieve.py +++ b/tests/gui/test_stage_retrieve.py @@ -351,9 +351,19 @@ def test_stage_retrieve_smear_width_is_none_without_a_kernel(stage): assert stage._smear_width_fs(1.1, td) is None -def test_stage_retrieve_smear_width_is_none_for_shg(stage): - stage.state.retrieve.smearing = True - td = SimpleNamespace(interaction="shg", omega0_pulse=2.35e15) +def test_stage_retrieve_smear_width_for_shg_is_the_two_beams_blur(stage): + from croak.session.pipeline import beam_geometry + from croak.smearing import shg_two_beam_kernel + + p = stage.state.retrieve + p.smearing = True + td = SimpleNamespace(interaction="shg", omega0_pulse=2.35e15, Iomega=None) + sigma = shg_two_beam_kernel(beam_geometry(p), 2 * np.pi * 299792458.0 / 2.35e15) + assert stage._smear_width_fs(2.0, td) == pytest.approx( + 2.0 * sigma.sigma_delta / 1e-15 + ) + # collinear beams have no smearing to show + p.beam_separation_mm = 0.0 assert stage._smear_width_fs(1.0, td) is None @@ -397,8 +407,9 @@ def shown(key): assert shown("tau0") == ("2.00 fs", "τ₀ · fit") assert readout.text("smearing").endswith(" fs") assert readout.name("smearing") == "Smearing · ×1.100 fit" - # a kernel the trace cannot carry (SHG) falls back to the bare factor + # without a kernel (SHG with collinear beams) it falls back to the bare factor with_trace.state.tracedata = replace(run[2], interaction="shg") + p.beam_separation_mm = 0.0 with_trace._update_extras_readout(fitted) assert shown("smearing") == ("×1.100", "Smearing · fit") # nothing fitted, no slab: dashes and the nominal fixed values @@ -464,7 +475,7 @@ def _shg_trace(stage): from croak.grid import Grid stage.state.tracedata = SimpleNamespace( - interaction="shg", grid=Grid(64, dt=3e-15), omega0_pulse=2.3546e15 + interaction="shg", grid=Grid(64, dt=3e-15), omega0_pulse=2.3546e15, Iomega=None ) stage.on_enter() return stage @@ -528,14 +539,18 @@ def test_stage_retrieve_delayed_beam_matters_only_in_the_principal_plane(stage): 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" + 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) - assert stage.geometry_readout.text() == "Crossing half-angle α = 1.432°" + # 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)" + ) 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 @@ -605,7 +620,7 @@ def test_stage_retrieve_focal_length_is_one_setting_for_both_groups(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() == "Crossing half-angle α = 0.716°" + assert stage.geometry_readout.text().startswith("Crossing half-angle α = 0.716°") def test_stage_retrieve_unknown_stored_crystal_setting_is_explained(stage): @@ -613,3 +628,65 @@ def test_stage_retrieve_unknown_stored_crystal_setting_is_explained(stage): stage._seed_widgets() _shg_trace(stage) assert stage.crystal_readout.text().startswith("No valid crystal: angle_mode") + + +def test_stage_retrieve_shg_smearing_lives_in_beam_geometry(stage): + _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() + stage.state.tracedata = SimpleNamespace(interaction="pg", omega0_pulse=2.35e15) + stage.on_enter() + assert not stage.smear_box.isHidden() + + +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): + _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 + assert not stage.shg_smearing_check.isEnabled() + assert not stage.fit_smearing_check.isEnabled() + + +def test_stage_retrieve_focal_mixture_is_hidden_for_shg_and_unticks_smearing(stage): + _shg_trace(stage) + assert stage.focal_box.isHidden() + stage.shg_smearing_check.setChecked(True) + stage._on_focal_changed(True) + assert stage.state.retrieve.smearing is False + assert not stage.shg_smearing_check.isChecked() + assert not stage.smearing_check.isChecked() + + +def test_stage_retrieve_switches_off_a_focal_mixture_left_from_pg_data(stage): + stage.state.tracedata = SimpleNamespace(interaction="pg", omega0_pulse=2.35e15) + stage.on_enter() + stage.focal_check.setChecked(True) + assert stage.state.retrieve.focal is True + _shg_trace(stage) + # its box is hidden for SHG, where it cannot be modelled: off, and said so + assert stage.state.retrieve.focal is False + assert not stage.focal_check.isChecked() + assert any("focal mixture is for PG/SD" in text for text in stage.said) diff --git a/tests/gui/test_wizard_flow.py b/tests/gui/test_wizard_flow.py index a667af0..f602edd 100644 --- a/tests/gui/test_wizard_flow.py +++ b/tests/gui/test_wizard_flow.py @@ -1954,14 +1954,13 @@ def test_gas_controls_reach_millibar_and_long_paths(qtbot): assert stage.gas_path.value() == pytest.approx(cm) -def test_retrieval_readout_smearing_survives_an_shg_trace(qtbot): - """Reporting smearing on an SHG trace must not raise. +def test_retrieval_readout_reports_the_smearing_of_an_shg_trace(qtbot): + """The read-out gives an SHG trace's two-beam smearing width. - Regression: the read-out asks for the smearing width whenever the option is - ticked, but ``square_boxcars_kernel`` refuses SHG (no three-arm form), so an - SHG trace with smearing enabled used to raise straight out of the update. + Regression: SHG used to have no smearing kernel, and the read-out raised + when the option was ticked; now it reports the two beams' delay blur. """ - from croak.gui.readout import DASH + from croak.session.pipeline import smearing_kernel w = Driver(qtbot) w.start("synthetic") @@ -1970,10 +1969,12 @@ def test_retrieval_readout_smearing_survives_an_shg_trace(qtbot): rs = w.stages[3] rs.state.retrieve.smearing = True - rs._update_extras_readout(None) # must not raise - assert rs.readout.text("smearing") == DASH - # SHG has no smearing kernel, so there is no width to report - assert rs._smear_width_fs(1.5, w.state.tracedata) is None + rs._update_extras_readout(None) + kernel = smearing_kernel(rs.state.retrieve, w.state.tracedata) + assert rs.readout.text("smearing") == f"{kernel.sigma_delta / 1e-15:.2f} fs" + assert rs._smear_width_fs(1.5, w.state.tracedata) == pytest.approx( + 1.5 * kernel.sigma_delta / 1e-15 + ) def test_preprocess_tau_exclude_auto_button(qtbot, experiment_h5, experiment): diff --git a/tests/test_lbfgs_ad.py b/tests/test_lbfgs_ad.py index a48bab9..f0911bd 100644 --- a/tests/test_lbfgs_ad.py +++ b/tests/test_lbfgs_ad.py @@ -158,7 +158,8 @@ def test_lbfgs_ad_smearing_rejects_shg(): kernel = square_boxcars_kernel( "pg", hole_diameter=1e-3, hole_spacing=0.5e-3, wavelength=800e-9 ) - with pytest.raises(ValueError, match="three-arm"): + # a three-arm (PG) kernel has a shape parameter, which two SHG beams cannot have + with pytest.raises(ValueError, match="two beams"): LBFGSAD(maxiters=10, smearing=kernel).run( trace, g.omega, delays, "shg", guess=ew ) diff --git a/tests/test_session_crystal.py b/tests/test_session_crystal.py index 1b6557d..f023b9d 100644 --- a/tests/test_session_crystal.py +++ b/tests/test_session_crystal.py @@ -279,3 +279,79 @@ def test_run_retrieval_can_leave_the_tilt_check_to_the_caller(monkeypatch): with warnings.catch_warnings(): warnings.simplefilter("error") session_pipeline.run_retrieval(p, td, check_tilt=False) + + +# -- the two beams' delay smearing (croak.smearing.shg_two_beam_kernel) --------- +def test_beam_geometry_is_one_source_for_the_crystal_and_the_smearing(): + from croak.session.pipeline import beam_geometry + + p = RetrieveParams(beam_separation_mm=8.0, focal_f_mm=150.0, beam_diameter_mm=2.5) + geometry = beam_geometry(p) + assert geometry.beam_separation == pytest.approx(8e-3) + assert geometry.focal_length == pytest.approx(0.15) + assert geometry.beam_diameter == pytest.approx(2.5e-3) + assert crystal_setup(p).geometry == geometry + assert beam_geometry(RetrieveParams(beam_separation_mm=0.0)) is None + + +def test_shg_smearing_kernel_is_the_two_beam_blur_at_the_pulse_wavelength(): + from croak.session.pipeline import beam_geometry, pulse_wavelength, smearing_kernel + from croak.smearing import shg_two_beam_kernel + + td = _td() + p = RetrieveParams(smearing=True, beam_separation_mm=10.0, beam_diameter_mm=2.0) + kernel = smearing_kernel(p, td) + assert kernel == shg_two_beam_kernel(beam_geometry(p), pulse_wavelength(td)) + # the mask geometry's fixed multiplier does not apply to the two beams + scaled = smearing_kernel(RetrieveParams(**{**p.__dict__, "smear_scale": 0.5}), td) + assert scaled == kernel + # collinear beams have nothing to smear, and smearing off is off + assert ( + smearing_kernel(RetrieveParams(smearing=True, beam_separation_mm=0.0), td) + is None + ) + assert smearing_kernel(RetrieveParams(smearing=False), td) is None + + +def test_pulse_wavelength_is_the_spectrum_centroid_else_the_carrier(): + from croak.session.pipeline import pulse_wavelength + + td = _td() + assert pulse_wavelength(td) == pytest.approx(800e-9, rel=1e-12, abs=0) + # a spectrum weighted to the blue moves the wavelength the kernel is taken at + omega_abs = td.grid.omega + W0 + td.Iomega = np.exp(-(((omega_abs - 1.05 * W0) / (0.05 * W0)) ** 2)) + centroid = np.sum(omega_abs * td.Iomega) / np.sum(td.Iomega) + assert pulse_wavelength(td) == pytest.approx( + 2 * np.pi * 299792458.0 / centroid, rel=1e-12, abs=0 + ) + assert pulse_wavelength(td) < 780e-9 + td.Iomega = np.zeros_like(td.Iomega) # an empty spectrum: the carrier + assert pulse_wavelength(td) == pytest.approx(800e-9, rel=1e-12, abs=0) + + +def test_collinear_shg_with_a_smearing_fit_does_not_fit_a_missing_kernel(monkeypatch): + from croak.session.pipeline import fits_smearing, smearing_kernel + + captured: dict = {} + + def _fake(td, **kwargs): + captured.update(kwargs) + return SimpleNamespace(spectrum=np.ones(64)) + + monkeypatch.setattr(session_pipeline, "retrieve_from_tracedata", _fake) + p = RetrieveParams( + solver="lbfgs-ad", + smearing=True, + fit_smearing=True, + fit_smearing_split=True, + beam_separation_mm=0.0, + ) + td = _td() + assert smearing_kernel(p, td) is None + assert fits_smearing(p, None) is False + session_pipeline.run_retrieval(p, td) + assert captured["smearing"] is None + 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 diff --git a/tests/test_smearing.py b/tests/test_smearing.py index a4fce9e..a272e5a 100644 --- a/tests/test_smearing.py +++ b/tests/test_smearing.py @@ -525,7 +525,8 @@ def test_smearing_broadens_the_delay_marginal(setup, interaction): def test_smearing_rejects_shg_and_nonuniform_delays(setup): g, ew, delays = setup kernel = SmearingKernel(sigma_p=0.3e-15, sigma_delta=0.3e-15) - with pytest.raises(ValueError, match="three-arm"): + # SHG has two beams: a kernel with a shape parameter has no meaning for it + with pytest.raises(ValueError, match="two beams.*shg_two_beam_kernel"): maketrace(g.omega, delays, ew, "shg", smearing=kernel) with pytest.raises(ValueError, match="uniformly spaced"): maketrace(g.omega, np.sort(np.append(delays, 1e-15)), ew, "pg", smearing=kernel) diff --git a/tests/test_smearing_shg.py b/tests/test_smearing_shg.py new file mode 100644 index 0000000..c9f2ac7 --- /dev/null +++ b/tests/test_smearing_shg.py @@ -0,0 +1,255 @@ +"""Two-beam delay smearing of SHG FROG (croak.smearing.shg_two_beam_kernel). + +The reference is the reduction's own statement, evaluated by brute force: the +signal from transverse position x in the focus, weighted by the product of the +two beams' intensities there, sees the relative delay tau + 2 x sin(alpha) / c; +the detector sums over x. +""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest +from test_crystals import BBO, W0 + +from croak import crystals +from croak.constants import C +from croak.crystals import CrystalSetup +from croak.forward import ForwardModel +from croak.forward_jax import make_param_trace_fn +from croak.geometry import TwoBeamGeometry +from croak.grid import Grid +from croak.pulses import gaussian_pulse +from croak.smearing import SmearingKernel, check_kernel, shg_two_beam_kernel + +# Beams 10 mm apart at f = 100 mm (2.86 degrees), 2.6 mm across: a 12.5 um focal +# waist and about 1.5 fs of rms delay smearing at 800 nm. +GEOMETRY = TwoBeamGeometry( + beam_separation=10e-3, focal_length=0.1, beam_diameter=2.6e-3 +) +GRID = Grid(128, dt=1.0e-15) +DELAYS = GRID.dt * np.arange(-40, 41) +THICKNESS = 30e-6 + + +def _crystal(geometry=GEOMETRY): + return CrystalSetup( + BBO, + math.radians(29.2), + phase_match_wavelength=800e-9, + geometry=geometry, + polarization="perpendicular", + delayed_beam="toward_axis", + ) + + +def test_kernel_width_is_the_spread_of_delay_across_two_tilted_beams(): + # Independent of the closed form: integrate over the crossing plane two + # Gaussian beams at +-alpha, each of 1/e^2 waist radius w0 measured across its + # own axis, weighting each point by the product of their intensities; each + # beam's pulse front reaches x at x sin(alpha)/c, ahead or behind. + alpha = math.atan(10e-3 / 0.2) + w0 = 2 * 800e-9 * 0.1 / (math.pi * 2.6e-3) + x = np.linspace(-8 * w0, 8 * w0, 200001) + weight = np.exp(-2 * (x * math.cos(alpha)) ** 2 / w0**2) ** 2 + delay = 2 * x * math.sin(alpha) / C + rms = math.sqrt(np.sum(weight * delay**2) / np.sum(weight)) + k = shg_two_beam_kernel(GEOMETRY, 800e-9) + # the sum over 200001 points of a smooth Gaussian is exact to rounding; + # abs=0 because the widths (~1e-15 s) are below approx's default abs tolerance + assert k.sigma_delta == pytest.approx(rms, rel=1e-9, abs=0) + assert (k.sigma_p, k.rho, k.npoints) == (0.0, 0.0, 1) + # exactly the small-angle-free form lambda d / (sqrt 2 pi D c) + closed = 800e-9 * 10e-3 / (math.sqrt(2) * math.pi * 2.6e-3 * C) + assert k.sigma_delta == pytest.approx(closed, rel=1e-12, abs=0) + # the spot, and so the width, scales with the wavelength + assert shg_two_beam_kernel(GEOMETRY, 400e-9).sigma_delta == pytest.approx( + k.sigma_delta / 2, rel=1e-12, abs=0 + ) + + +def test_kernel_needs_the_beam_diameter_and_a_wavelength(): + with pytest.raises(ValueError, match="needs the beams' diameter"): + shg_two_beam_kernel(TwoBeamGeometry(10e-3, 0.1), 800e-9) + for bad in (0.0, -1.0, math.nan): + with pytest.raises(ValueError, match="wavelength must be finite and positive"): + shg_two_beam_kernel(GEOMETRY, bad) + + +def test_check_kernel_refuses_a_shape_parameter_for_shg_only(): + shaped = SmearingKernel(sigma_p=0.2e-15, sigma_delta=0.3e-15) + with pytest.raises(ValueError, match="two beams"): + check_kernel("shg", shaped) + check_kernel("pg", shaped) + check_kernel("shg", shg_two_beam_kernel(GEOMETRY, 800e-9)) + + +def _brute_force(model_kw, ew, sigma): + """Sum the unsmeared trace over focal positions, by Gauss-Hermite quadrature.""" + x, w = np.polynomial.hermite_e.hermegauss(40) + w = w / w.sum() + total = 0.0 + for xi, wi in zip(x, w, strict=True): + # the relative delay at this position, sigma * xi with xi ~ N(0, 1) + model = ForwardModel(GRID.omega, DELAYS + sigma * xi, "shg", **model_kw) + total = total + wi * model.trace(ew, normalize=False) + return total + + +@pytest.mark.parametrize("medium", ["thin", "crystal"]) +def test_smeared_trace_is_the_average_over_the_focus(medium): + ew = gaussian_pulse(GRID, 6e-15, phases=(0.0, 20e-45)) + kernel = shg_two_beam_kernel(GEOMETRY, 800e-9) + if medium == "crystal": + setup = _crystal() + kw = dict( + material=setup, + thickness=THICKNESS, + npoints=crystals.depth_points(setup, GRID.omega, W0, THICKNESS), + omega0=W0, + ) + else: + kw = dict(omega0=W0) + smeared = ForwardModel(GRID.omega, DELAYS, "shg", smearing=kernel, **kw).trace( + ew, normalize=False + ) + reference = _brute_force(kw, ew, kernel.sigma_delta) + unsmeared = ForwardModel(GRID.omega, DELAYS, "shg", **kw).trace(ew, normalize=False) + # The model convolves on the sampled delay axis by DFT (periodic) and the + # reference shifts the delays exactly; the trace has decayed to ~1e-12 of its + # peak at the edges of the +-40 fs axis, so the two agree to rounding. + peak = reference.max() + np.testing.assert_allclose(smeared, reference, rtol=0, atol=1e-9 * peak) + # and the smearing is not negligible here + assert np.abs(smeared - unsmeared).max() > 0.05 * peak + + +def test_numpy_and_jax_agree_with_a_crystal_and_smearing(): + ew = gaussian_pulse(GRID, 6e-15, phases=(10e-30,)) + setup = _crystal() + npoints = crystals.depth_points(setup, GRID.omega, W0, THICKNESS) + kernel = shg_two_beam_kernel(GEOMETRY, 800e-9) + kw = dict(material=setup, npoints=npoints, omega0=W0, smearing=kernel) + numpy_trace = ForwardModel( + GRID.omega, DELAYS, "shg", thickness=THICKNESS, **kw + ).trace(ew, normalize=False) + jax_fn = make_param_trace_fn(GRID.omega, DELAYS, "shg", thickness=THICKNESS, **kw) + jax_trace = np.asarray(jax_fn(ew, THICKNESS, 0.0)) + # same sums in the same order up to FFT rounding + np.testing.assert_allclose( + jax_trace, numpy_trace, rtol=0, atol=1e-10 * numpy_trace.max() + ) + # the smearing scale widens the blur, as for PG/SD (fit_smearing) + wider = np.asarray(jax_fn(ew, THICKNESS, 0.0, 1.5)) + expected = ForwardModel( + GRID.omega, + DELAYS, + "shg", + thickness=THICKNESS, + **{**kw, "smearing": kernel.scaled(1.5)}, + ).trace(ew, normalize=False) + np.testing.assert_allclose(wider, expected, rtol=0, atol=1e-10 * expected.max()) + + +def test_jax_normalised_smeared_shg_trace_has_unit_peak(): + ew = gaussian_pulse(GRID, 6e-15) + kernel = shg_two_beam_kernel(GEOMETRY, 800e-9) + fn = make_param_trace_fn(GRID.omega, DELAYS, "shg", smearing=kernel, normalize=True) + t = np.asarray(fn(ew, 0.0, 0.0)) + expected = ForwardModel(GRID.omega, DELAYS, "shg", smearing=kernel).trace(ew) + assert t.max() == pytest.approx(1.0) + np.testing.assert_allclose(t, expected, rtol=0, atol=1e-10) + + +def test_a_split_smearing_fit_needs_a_shape_channel(): + from croak.lbfgs_ad import LBFGSAD + from croak.smearing import check_split_fit + + kernel = shg_two_beam_kernel(GEOMETRY, 800e-9) + with pytest.raises(ValueError, match="needs a kernel with a shape channel"): + check_split_fit(kernel, True) + check_split_fit(kernel, False) + check_split_fit(None, True) + check_split_fit(SmearingKernel(sigma_p=0.2e-15, sigma_delta=0.3e-15), True) + ew = gaussian_pulse(GRID, 6e-15) + trace = ForwardModel(GRID.omega, DELAYS, "shg", smearing=kernel).trace(ew) + solver = LBFGSAD( + maxiters=2, smearing=kernel, fit_smearing=True, fit_smearing_split=True + ) + with pytest.raises(ValueError, match="shape channel"): + solver.run(trace, GRID.omega, DELAYS, "shg", guess=ew) + + +def test_retrieving_a_smeared_shg_trace_needs_the_kernel(): + # A 6 fs pulse smeared by 1.5 fs: retrieved with the kernel the trace is fitted + # far better, and the pulse's duration recovered, than without it. + import croak + from croak.maths import fwhm + + ew = gaussian_pulse(GRID, 6e-15, phases=(0.0, 20e-45)) + kernel = shg_two_beam_kernel(GEOMETRY, 800e-9) + trace = ForwardModel(GRID.omega, DELAYS, "shg", smearing=kernel).trace(ew) + common = dict(algorithm="lbfgs-ad", maxiters=400, rng=np.random.default_rng(0)) + with_kernel = croak.retrieve( + trace, GRID.omega, DELAYS, "shg", smearing=kernel, **common + ) + without = croak.retrieve(trace, GRID.omega, DELAYS, "shg", **common) + assert with_kernel.error < 0.2 * without.error + + def duration(spectrum): + return fwhm(GRID.t, np.abs(GRID.ifft(spectrum)) ** 2) + + true = duration(ew) + assert abs(duration(with_kernel.spectrum) - true) < 0.03 * true + assert abs(duration(without.spectrum) - true) > 0.05 * true + + +@pytest.mark.parametrize( + "algorithm", ["lbfgs-ad", "lm", "lm-optx", "cma-es", "warm-lbfgs"] +) +def test_every_extras_solver_refuses_a_split_fit_of_a_two_beam_sd_kernel(algorithm): + # The two-beam SD kernel has sigma_p = 0 too; each solver that fits extras + # refuses the split before it starts. + from croak.retrieve import ALGORITHMS + from croak.smearing import collinear_sd_kernel + + kernel = collinear_sd_kernel( + hole_diameter=1e-3, hole_spacing=0.5e-3, wavelength=800e-9 + ) + assert kernel.sigma_p == 0.0 + ew = gaussian_pulse(GRID, 6e-15) + trace = ForwardModel(GRID.omega, DELAYS, "sd", smearing=kernel).trace(ew) + solver = ALGORITHMS[algorithm]( + maxiters=2, smearing=kernel, fit_smearing=True, fit_smearing_split=True + ) + with pytest.raises(ValueError, match="shape channel"): + solver.run(trace, GRID.omega, DELAYS, "sd", guess=ew) + + +def test_the_covariance_refuses_a_split_fit_of_a_two_beam_kernel(): + import croak + from croak.covariance import parameter_covariance + + kernel = shg_two_beam_kernel(GEOMETRY, 800e-9) + ew = gaussian_pulse(GRID, 6e-15) + trace = ForwardModel(GRID.omega, DELAYS, "shg", smearing=kernel).trace(ew) + res = croak.retrieve( + trace, + GRID.omega, + DELAYS, + "shg", + algorithm="lbfgs-ad", + maxiters=5, + smearing=kernel, + ) + with pytest.raises(ValueError, match="shape channel"): + parameter_covariance( + res, + trace, + noise=1e-3, + smearing=kernel, + fit_smearing=True, + fit_smearing_split=True, + )