From 6a01587dbfef6858d1fcdd25254e3135b678d083 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 10:12:50 +0000 Subject: [PATCH 01/12] Pass a Type I crystal through every solver and the thickness bootstrap The solvers, the covariance and the pipeline forward material to the forward models, so a CrystalSetup works once their types admit it. The thickness bootstrap raises each draw's depth nodes to what its crystal thickness needs. Tests drive every registered solver with a crystal, check that the crystal model fits its own 100 um trace better than ideal SHG, and that a thick bootstrap draw is resolved rather than refused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxN7Kx14WFWk3qbzDq5 --- croak/cmaes.py | 3 +- croak/copra.py | 10 ++- croak/copra_jax.py | 3 +- croak/covariance.py | 7 +- croak/lbfgs.py | 9 ++- croak/lbfgs_ad.py | 3 +- croak/lbfgs_hand.py | 3 +- croak/lm.py | 3 +- croak/optimistix_lbfgs.py | 3 +- croak/optimistix_lm.py | 3 +- croak/pipeline.py | 8 +- croak/uncertainty.py | 28 ++++--- tests/test_pipeline_crystal.py | 144 +++++++++++++++++++++++++++++++++ 13 files changed, 199 insertions(+), 28 deletions(-) create mode 100644 tests/test_pipeline_crystal.py diff --git a/croak/cmaes.py b/croak/cmaes.py index a47b58c..f9f305d 100644 --- a/croak/cmaes.py +++ b/croak/cmaes.py @@ -44,6 +44,7 @@ build_parameterisation, time_window_mask, ) +from .crystals import CrystalSetup from .focal import FocalMixture from .forward_jax import make_param_trace_fn from .result import RetrievalResult @@ -261,7 +262,7 @@ def __init__( strategy: str = "cma", popsize: int = 0, std_init: float = 0.5, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/copra.py b/croak/copra.py index f199f51..1b2013d 100644 --- a/croak/copra.py +++ b/croak/copra.py @@ -20,6 +20,7 @@ import numpy as np from numpy.typing import NDArray +from .crystals import CrystalSetup from .forward import ForwardModel from .grid import Grid from .interactions import get_interaction @@ -313,9 +314,10 @@ class COPRA(Retriever): ``maxiters``); see :func:`run_copra`. abstol : float, optional Absolute target FROG error (default ``0`` = off); see :func:`run_copra`. - material : str or None, optional - Slab material for dispersive propagation (e.g. ``"SiO2"``); ``None`` for - a thin medium. + material : str, CrystalSetup or None, optional + Slab material for dispersive propagation (e.g. ``"SiO2"``) for PG and SD, + or the nonlinear crystal for SHG (:class:`croak.crystals.CrystalSetup`); + ``None`` for a thin medium. thickness : float, optional Slab thickness (m). npoints : int, optional @@ -342,7 +344,7 @@ def __init__( alpha: float = 0.25, reltol: float = 0.0, abstol: float = 0.0, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/copra_jax.py b/croak/copra_jax.py index 57ab365..f4326bd 100644 --- a/croak/copra_jax.py +++ b/croak/copra_jax.py @@ -31,6 +31,7 @@ from numpy.typing import NDArray from . import metrics_jax as mj +from .crystals import CrystalSetup from .forward_jax import make_forward_adjoint_fns from .grid import Grid from .interactions import get_interaction @@ -359,7 +360,7 @@ def __init__( alpha: float = 0.25, reltol: float = 0.0, abstol: float = 0.0, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/covariance.py b/croak/covariance.py index 99a24a8..4aa5098 100644 --- a/croak/covariance.py +++ b/croak/covariance.py @@ -59,6 +59,7 @@ from . import metrics_jax as mj from ._jax_pulse import ExtraParamSpec, augment, ls_parameterisation +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 @@ -209,7 +210,7 @@ def _compute_core( *, noise: NoiseModel | float | None, weights: NDArray[np.float64] | None, - material: str | None, + material: str | CrystalSetup | None, thickness: float, npoints: int, omega0: float | None, @@ -378,7 +379,7 @@ def parameter_covariance( *, noise: NoiseModel | float | None = None, weights: NDArray[np.float64] | None = None, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float | None = None, @@ -507,7 +508,7 @@ def covariance_uncertainty( interval: str = "bias-corrected", rng: np.random.Generator | None = None, weights: NDArray[np.float64] | None = None, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float | None = None, diff --git a/croak/lbfgs.py b/croak/lbfgs.py index fda7f18..ceb331c 100644 --- a/croak/lbfgs.py +++ b/croak/lbfgs.py @@ -17,6 +17,7 @@ import numpy as np from numpy.typing import NDArray +from .crystals import CrystalSetup from .forward import ForwardModel from .metrics import compute_mu, compute_mu_per_freq from .pulses import ArrayPulse @@ -42,8 +43,10 @@ class LBFGS(Retriever): ---------- maxiters : int, optional Maximum number of objective evaluations (default ``300``). - material : str or None, optional - Dispersive slab material; ``None`` (default) is a thin medium. + material : str, CrystalSetup or None, optional + Dispersive slab material (PG, SD), or the nonlinear crystal for SHG + (:class:`croak.crystals.CrystalSetup`); ``None`` (default) is a thin + medium. thickness : float, optional Slab thickness (m). npoints : int, optional @@ -90,7 +93,7 @@ def __init__( self, *, maxiters: int = 300, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/lbfgs_ad.py b/croak/lbfgs_ad.py index d5212d3..040ac9e 100644 --- a/croak/lbfgs_ad.py +++ b/croak/lbfgs_ad.py @@ -37,6 +37,7 @@ build_parameterisation, time_window_mask, ) +from .crystals import CrystalSetup from .delay_origin import DELAY_ORIGINS, recentring from .focal import FocalMixture from .forward_jax import make_param_trace_fn @@ -225,7 +226,7 @@ def __init__( self, *, maxiters: int = 300, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/lbfgs_hand.py b/croak/lbfgs_hand.py index f4a4f17..db84ea8 100644 --- a/croak/lbfgs_hand.py +++ b/croak/lbfgs_hand.py @@ -27,6 +27,7 @@ from . import metrics_jax as mj from ._jax_pulse import make_param_grad_fns, make_spectrum_fn +from .crystals import CrystalSetup from .forward_jax import make_forward_adjoint_fns from .result import RetrievalResult from .solver import ( @@ -66,7 +67,7 @@ def __init__( self, *, maxiters: int = 300, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/lm.py b/croak/lm.py index e372615..deae9d9 100644 --- a/croak/lm.py +++ b/croak/lm.py @@ -43,6 +43,7 @@ from . import metrics_jax as mj from ._jax_pulse import ExtraParamSpec, augment, ls_parameterisation +from .crystals import CrystalSetup from .focal import FocalMixture from .forward_jax import make_param_trace_fn from .result import RetrievalResult @@ -173,7 +174,7 @@ def __init__( *, maxiters: int = 300, method: str = "trf", - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/optimistix_lbfgs.py b/croak/optimistix_lbfgs.py index 050e7af..f3955ec 100644 --- a/croak/optimistix_lbfgs.py +++ b/croak/optimistix_lbfgs.py @@ -22,6 +22,7 @@ from . import metrics_jax as mj from ._jax_pulse import build_parameterisation from ._optimistix import run_optx +from .crystals import CrystalSetup from .focal import FocalMixture from .forward_jax import make_trace_fn from .result import RetrievalResult @@ -106,7 +107,7 @@ def __init__( self, *, maxiters: int = 300, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/optimistix_lm.py b/croak/optimistix_lm.py index c54f6b5..12cfb36 100644 --- a/croak/optimistix_lm.py +++ b/croak/optimistix_lm.py @@ -28,6 +28,7 @@ from . import metrics_jax as mj from ._jax_pulse import ExtraParamSpec, augment, ls_parameterisation from ._optimistix import run_optx +from .crystals import CrystalSetup from .focal import FocalMixture from .forward_jax import make_param_trace_fn from .result import RetrievalResult @@ -180,7 +181,7 @@ def __init__( self, *, maxiters: int = 300, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, omega0: float = 0.0, diff --git a/croak/pipeline.py b/croak/pipeline.py index eed5482..00c3e1b 100644 --- a/croak/pipeline.py +++ b/croak/pipeline.py @@ -14,6 +14,7 @@ from numpy.typing import NDArray from scipy.integrate import cumulative_trapezoid +from .crystals import CrystalSetup from .focal import FocalMixture from .maths import gauss from .preprocess import TraceData @@ -142,7 +143,7 @@ def retrieve_from_tracedata( guess="auto", perfect_fwhm: float = 10e-15, truth: TruthPulse | None = None, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 20, smearing: SmearingKernel | None = None, @@ -212,7 +213,10 @@ def retrieve_from_tracedata( truth : TruthPulse, optional Known complex pulse used when ``guess="truth"``. material, thickness, npoints - Dispersive-slab parameters (dispersive propagation through a material). + Dispersive-slab parameters (dispersive propagation through a material): + a material name for PG and SD, or a :class:`croak.crystals.CrystalSetup` + 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 diff --git a/croak/uncertainty.py b/croak/uncertainty.py index 34bfd6e..2951cca 100644 --- a/croak/uncertainty.py +++ b/croak/uncertainty.py @@ -32,6 +32,8 @@ import scipy.stats from numpy.typing import ArrayLike, NDArray +from . import crystals +from .crystals import CrystalSetup from .forward import maketrace from .grid import Grid from .maths import fwhm as _fwhm @@ -824,7 +826,7 @@ def thickness_bootstrap( *, central_thickness: float, thickness_sigma: float, - material: str, + material: str | CrystalSetup, n_resamples: int = 300, warm_start: bool = True, rng: np.random.Generator | None = None, @@ -875,9 +877,12 @@ def thickness_bootstrap( thickness_sigma : float Standard deviation :math:`\sigma_L` of the thickness prior in **metres** (``>= 0``; ``0`` gives a degenerate, zero-width distribution). - material : str + material : str or CrystalSetup Substrate material name (e.g. ``"SiO2"``), as accepted by - :func:`croak.materials.refractive_index`. + :func:`croak.materials.refractive_index`, or the nonlinear crystal of an + SHG retrieval (:class:`croak.crystals.CrystalSetup`). For a crystal each + draw uses at least :func:`croak.crystals.depth_points` depth nodes for its + thickness, since the phase mismatch to resolve grows with it. n_resamples : int, optional Number of Monte-Carlo draws ``B`` (≈200–300 for a 1σ interval). warm_start : bool, optional @@ -941,9 +946,16 @@ def thickness_bootstrap( # Establish the centre: retrieve once at L0 to define both the reported point # estimate and the warm-start guess shared by every draw. - runner0 = _build_runner( - result, {**base_kwargs, "material": material, "thickness": central_thickness} - ) + def medium(thickness: float) -> dict: + kwargs = {**base_kwargs, "material": material, "thickness": thickness} + if isinstance(material, CrystalSetup): + needed = crystals.depth_points( + material, result.omega, result.omega0, thickness + ) + kwargs["npoints"] = max(int(base_kwargs.get("npoints", 0)), needed) + return kwargs + + runner0 = _build_runner(result, medium(central_thickness)) central_guess = result.spectrum if warm_start else None base = runner0(measured, delays, guess=central_guess, rng=rng) point_estimate, _, _ = _fwhm_and_profile( @@ -961,9 +973,7 @@ def thickness_bootstrap( thickness_b = float( max(clip_min, rng.normal(central_thickness, thickness_sigma)) ) - runner = _build_runner( - result, {**base_kwargs, "material": material, "thickness": thickness_b} - ) + runner = _build_runner(result, medium(thickness_b)) rb = runner(measured, delays, guess=guess, rng=rng) fw, t_over, prof = _fwhm_and_profile( rb.grid, _apply_propagation(rb.spectrum, propagation), oversampling diff --git a/tests/test_pipeline_crystal.py b/tests/test_pipeline_crystal.py new file mode 100644 index 0000000..fc8860e --- /dev/null +++ b/tests/test_pipeline_crystal.py @@ -0,0 +1,144 @@ +"""Retrieval of an SHG trace made in a Type I crystal, through every solver. + +The trace is simulated with the crystal model of :mod:`croak.crystals` (a synthetic +BBO-like Sellmeier pair, 30 µm, crossing in the principal plane) and retrieved with +the same crystal passed as ``material``, which the solvers forward to the forward +models unchanged. +""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest +from test_crystals import BBO, W0 + +from croak import crystals, preprocess +from croak.crystals import CrystalSetup +from croak.forward import ForwardModel +from croak.geometry import TwoBeamGeometry +from croak.grid import Grid +from croak.maths import wlfreq +from croak.pipeline import retrieve_from_tracedata +from croak.pulses import gaussian_pulse +from croak.retrieve import ALGORITHMS +from croak.uncertainty import thickness_bootstrap + +THICKNESS = 30e-6 +CRYSTAL = CrystalSetup( + BBO, + math.radians(29.2), + phase_match_wavelength=800e-9, + geometry=TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1), + polarization="perpendicular", + delayed_beam="toward_axis", +) + + +def _tracedata(thickness): + """A 10 fs pulse with 30 fs^2 of GDD, its SHG trace made in the crystal.""" + g = Grid(128, dt=1.5e-15) + ew = gaussian_pulse(g, 10e-15, phases=(30e-30,)) + delays = 1.5e-15 * np.arange(-24, 25) + npoints = crystals.depth_points(CRYSTAL, g.omega, W0, thickness) + model = ForwardModel( + g.omega, + delays, + "shg", + material=CRYSTAL, + thickness=thickness, + npoints=npoints, + omega0=W0, + ) + trace = model.trace(ew, normalize=False) + omega_abs = g.omega + 2.0 * W0 # the SHG trace sits at twice the carrier + lam = wlfreq(omega_abs) + order = np.argsort(lam) + return preprocess.load_and_clean( + trace[order] / trace.max(), + lam[order], + delays, + "shg", + # the retrieval grid's range, in fundamental wavelengths + lam_min=600e-9, + lam_max=1200e-9, + input_unit="delay", + threshold=1e-6, + ) + + +@pytest.fixture(scope="module") +def crystal_tracedata(): + return _tracedata(THICKNESS) + + +def _depth_points(td, thickness=THICKNESS): + return crystals.depth_points(CRYSTAL, td.grid.omega, td.omega0_pulse, thickness) + + +@pytest.mark.parametrize("algorithm", sorted(ALGORITHMS)) +def test_every_solver_retrieves_with_a_crystal(crystal_tracedata, algorithm): + td = crystal_tracedata + res = retrieve_from_tracedata( + td, + algorithm=algorithm, + maxiters=30, + material=CRYSTAL, + thickness=THICKNESS, + npoints=_depth_points(td), + rng=np.random.default_rng(0), + ) + assert res.algorithm == algorithm + assert np.all(np.isfinite(res.spectrum)) + assert np.isfinite(res.error) + + +def test_the_crystal_model_fits_its_own_trace_better_than_ideal_shg(): + # In 100 um the crystal's phase matching and group-velocity mismatch shape the + # trace; retrieving with the crystal model must fit it better than ideal SHG. + td = _tracedata(100e-6) + common = dict(algorithm="lbfgs-ad", maxiters=300, rng=np.random.default_rng(0)) + with_crystal = retrieve_from_tracedata( + td, + material=CRYSTAL, + thickness=100e-6, + npoints=_depth_points(td, 100e-6), + **common, + ) + ideal = retrieve_from_tracedata(td, **common) + assert with_crystal.error < 0.5 * ideal.error + + +def test_thickness_bootstrap_resolves_each_drawn_crystal(crystal_tracedata): + # A draw thicker than the central crystal has a larger phase mismatch to + # resolve; the bootstrap must raise the depth nodes for it rather than let the + # forward model refuse the under-resolved draw. + td = crystal_tracedata + npoints = _depth_points(td) + base = retrieve_from_tracedata( + td, + algorithm="lbfgs-ad", + maxiters=20, + material=CRYSTAL, + thickness=THICKNESS, + npoints=npoints, + rng=np.random.default_rng(0), + ) + out = thickness_bootstrap( + base, + td.trace, + central_thickness=THICKNESS, + thickness_sigma=40e-6, + material=CRYSTAL, + n_resamples=3, + rng=np.random.default_rng(3), + algorithm="lbfgs-ad", + maxiters=5, + npoints=npoints, + ) + drawn = np.asarray(out.thicknesses) + assert drawn.max() > THICKNESS + needed = crystals.depth_points(CRYSTAL, td.grid.omega, td.omega0_pulse, drawn.max()) + assert needed > npoints # the thickest draw would be refused at npoints + assert np.all(np.isfinite(out.samples)) From 0e681571a422a6d35243c54aec768985bb9a0932 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 10:13:59 +0000 Subject: [PATCH 02/12] Record marginal correction and refuse it with a crystal model TraceData.marginal_corrected says whether load_and_clean rescaled the trace's rows onto the spectrum-predicted SHG marginal. That correction already divides out an estimate of the phase-matching response, so retrieve_from_tracedata refuses a crystal on such a trace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxN7Kx14WFWk3qbzDq5 --- croak/pipeline.py | 7 +++++++ croak/preprocess.py | 7 +++++++ tests/test_pipeline_crystal.py | 15 +++++++++++++++ tests/test_preprocess.py | 19 +++++++++++++++++++ 4 files changed, 48 insertions(+) diff --git a/croak/pipeline.py b/croak/pipeline.py index 00c3e1b..bc9ab27 100644 --- a/croak/pipeline.py +++ b/croak/pipeline.py @@ -341,6 +341,13 @@ 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" + ) algo = algorithm.lower() if algo not in ALGORITHMS: raise ValueError(f"unknown algorithm {algorithm!r}") diff --git a/croak/preprocess.py b/croak/preprocess.py index 14085a7..2d55e1e 100644 --- a/croak/preprocess.py +++ b/croak/preprocess.py @@ -1484,6 +1484,11 @@ class TraceData: clipping live signal, which both discards data *and* frees the retrieved field at the affected frequencies. ``0.0`` when the trace never went 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. """ interaction: str @@ -1507,6 +1512,7 @@ class TraceData: Ilam_spec_filt: NDArray[np.float64] | None scalecurve: NDArray[np.float64] taper_loss: float = 0.0 + marginal_corrected: bool = False @property def omega(self) -> NDArray[np.float64]: @@ -1799,4 +1805,5 @@ def load_and_clean( Ilam_spec_filt=Ilam_spec_filt, scalecurve=sc, taper_loss=taper_loss, + marginal_corrected=marginal_correct, ) diff --git a/tests/test_pipeline_crystal.py b/tests/test_pipeline_crystal.py index fc8860e..32fbbce 100644 --- a/tests/test_pipeline_crystal.py +++ b/tests/test_pipeline_crystal.py @@ -9,6 +9,7 @@ from __future__ import annotations import math +from dataclasses import replace import numpy as np import pytest @@ -142,3 +143,17 @@ def test_thickness_bootstrap_resolves_each_drawn_crystal(crystal_tracedata): needed = crystals.depth_points(CRYSTAL, td.grid.omega, td.omega0_pulse, drawn.max()) assert needed > npoints # the thickest draw would be refused at npoints assert np.all(np.isfinite(out.samples)) + + +def test_a_crystal_refuses_a_marginal_corrected_trace(crystal_tracedata): + # The correction already divides out an estimate of the phase-matching + # response, which the crystal model would apply again. + td = replace(crystal_tracedata, marginal_corrected=True) + with pytest.raises(ValueError, match="marginal-corrected"): + retrieve_from_tracedata( + td, + algorithm="lbfgs-ad", + material=CRYSTAL, + thickness=THICKNESS, + npoints=_depth_points(td), + ) diff --git a/tests/test_preprocess.py b/tests/test_preprocess.py index 1309a2b..a3e94f8 100644 --- a/tests/test_preprocess.py +++ b/tests/test_preprocess.py @@ -1237,3 +1237,22 @@ def test_load_and_clean_carries_the_independent_spectrum(): # the 1600 nm fundamental peaks at the pulse carrier (grid centre), within # 5 % of the grid's half-span assert abs(td.grid.omega[int(np.argmax(td.Iomega))]) < 0.05 * td.grid.omega.max() + + +@pytest.mark.parametrize("correct", [False, True]) +def test_load_and_clean_records_the_marginal_correction(correct): + exp, lam_spec, Ilam_spec, lam_min, lam_max = _shg_experiment() + td = preprocess.load_and_clean( + exp.trace, + exp.lam_nm * 1e-9, + exp.delay_fs * 1e-15, + "shg", + lam_min=lam_min, + lam_max=lam_max, + input_unit="delay", + lam_spec=lam_spec, + Ilam_spec=Ilam_spec, + marginal_correct=correct, + taper_warn_level=0.0, + ) + assert td.marginal_corrected is correct From 1c641bd088e7200917c06c05dba655d990529cdc Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 13:56:14 +0000 Subject: [PATCH 03/12] Add BBO as a built-in crystal from optmat builtin_crystal(name) builds a UniaxialCrystal from optmat's recommended models of both rays, with the range both hold over as its transparency. BBO (Tamosauskas et al. 2018) phase-matches 800 nm SHG at 29.226 degrees, consistent with the paper's nominal 29.2 degree cut and optmat's pin. materials.optmat_index, the wrapper of an optmat model, is now public so both modules use it. Needs optmat with BBO (LupoLab/optmat#48); the dependency bump follows its release. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- croak/crystals.py | 52 ++++++++++++++++++++++++++++++++++++++++++ croak/materials.py | 20 +++++++++++++--- tests/test_crystals.py | 23 +++++++++++++++++++ 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/croak/crystals.py b/croak/crystals.py index d074cbe..34bfbac 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -91,6 +91,7 @@ from __future__ import annotations +import functools import math import warnings from collections.abc import Callable @@ -100,6 +101,7 @@ import numpy as np import scipy.optimize from numpy.typing import ArrayLike, NDArray +from optmat.solid.models.registry import default_model from . import materials from .constants import C @@ -108,11 +110,13 @@ from .maths import derivative, wlfreq __all__ = [ + "CRYSTALS", "TILT_ERROR_WARN", "CrystalSetup", "CrystalApproximationWarning", "Propagation", "UniaxialCrystal", + "builtin_crystal", "check_medium", "check_tilt", "depth_points", @@ -177,6 +181,54 @@ def transparent(self, omega: ArrayLike) -> NDArray[np.bool_]: return inside +#: Names of the built-in crystals. Each uses optmat's recommended models of its +#: ordinary and extraordinary rays (``optmat.solid.models.registry.default_model``), +#: which state their sources and validity ranges. +CRYSTALS: tuple[str, ...] = ("BBO",) + + +def builtin_crystal(name: str) -> UniaxialCrystal: + """Return a built-in crystal by name. + + Parameters + ---------- + name : str + One of :data:`CRYSTALS`, case-insensitive. + + Returns + ------- + UniaxialCrystal + The crystal, with optmat's recommended ordinary and extraordinary + models and, as its transparency range, the range both models hold over. + + Raises + ------ + ValueError + If ``name`` is not a built-in crystal. + """ + match = next((c for c in CRYSTALS if c.lower() == name.lower()), None) + if match is None: + raise ValueError( + f"unknown crystal {name!r}; the built-in crystals are {', '.join(CRYSTALS)}" + ) + return _load_crystal(match) + + +@functools.cache +def _load_crystal(name: str) -> UniaxialCrystal: + """Build a built-in crystal from optmat's models, once per canonical name.""" + ordinary = default_model(name, axis="o") + extraordinary = default_model(name, axis="e") + lo = max(ordinary.wavelength_range[0], extraordinary.wavelength_range[0]) + hi = min(ordinary.wavelength_range[1], extraordinary.wavelength_range[1]) + return UniaxialCrystal( + name, + materials.optmat_index(ordinary), + materials.optmat_index(extraordinary), + (float(lo), float(hi)), + ) + + def extraordinary_index( n_o: ArrayLike, n_e: ArrayLike, theta: ArrayLike ) -> NDArray[np.float64]: diff --git a/croak/materials.py b/croak/materials.py index 4cbb0fd..de492c6 100644 --- a/croak/materials.py +++ b/croak/materials.py @@ -51,6 +51,7 @@ "unregister_material", "make_tabulated_material", "material_model", + "optmat_index", "canonical_name", "read_nk_csv", "MATERIALS", @@ -295,8 +296,21 @@ def material_model(material: str) -> Model: return default_model(builtin.optmat_id, axis=builtin.axis) -def _optmat_index(model: Model) -> Callable[[ArrayLike], NDArray[np.float64]]: - """Wrap an optmat model as croak's ``n(wavelength_m)`` callable.""" +def optmat_index(model: Model) -> Callable[[ArrayLike], NDArray[np.float64]]: + """Wrap an optmat model as croak's ``n(wavelength_m)`` callable. + + Parameters + ---------- + model : optmat.solid.models.base.Model + An optmat refractive-index model, e.g. from :func:`material_model`. + + Returns + ------- + callable + ``n(wavelength_m)``: the real refractive index at vacuum wavelengths (m), + ``nan`` where a wavelength is not positive and finite. The model is + extrapolated without warning beyond its stated range. + """ def n(wavelength_m: ArrayLike) -> NDArray[np.float64]: lam = np.asarray(wavelength_m, dtype=float) @@ -348,7 +362,7 @@ def refractive_index(material: str) -> Callable[[ArrayLike], NDArray[np.float64] if canonical_name(material) not in _BUILTINS: available = ", ".join((*MATERIALS, *_CUSTOM)) raise ValueError(f"unknown material {material!r}; available: {available}") - return _optmat_index(material_model(material)) + return optmat_index(material_model(material)) def beta1(material: str, omega0: float) -> float: diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 4cabaa5..4ae24f4 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -405,3 +405,26 @@ def test_tilt_field_error_needs_a_delay(): ) with pytest.raises(ValueError, match="at least one delay"): crystals.tilt_field_error(setup, GRID.omega, W0, 50e-6, np.ones(GRID.n), []) + + +def test_builtin_bbo_phase_matches_800_nm_at_the_papers_cut(): + # Tamosauskas et al. 2018 (optmat's recommended BBO, both rays) give the + # collinear Type I SHG angle of 800 nm as 29.23 degrees, consistent with the + # paper's nominal 29.2 degree cut; optmat pins 29.226 (TC-1095). The tilt + # solve converges far below the 1e-3 degree tolerance. + bbo = crystals.builtin_crystal("BBO") + setup = CrystalSetup(bbo, math.radians(29.2), phase_match_wavelength=800e-9) + assert math.degrees(setup.internal_angle(W0)) == pytest.approx(29.226, abs=1e-3) + # the range both of optmat's formulas hold over: 0.188-5.2 um (stated) + lo, hi = bbo.transparency + assert 0.18e-6 < lo < 0.19e-6 and 5.1e-6 < hi < 5.3e-6 + + +def test_builtin_crystal_names_are_case_insensitive_and_cached(): + assert crystals.builtin_crystal("bbo") is crystals.builtin_crystal("BBO") + assert crystals.builtin_crystal("bbo").name == "BBO" + + +def test_unknown_builtin_crystal_raises(): + with pytest.raises(ValueError, match="unknown crystal 'KDP'.*BBO"): + crystals.builtin_crystal("KDP") From 650e3bb194aeb42a1566a63e7c0bc54cb43f02ee Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 14:00:39 +0000 Subject: [PATCH 04/12] Describe the SHG crystal in a session and pass it to the retrieval RetrieveParams gains the crystal (built-in name), its cut angle, the angle mode (phase-matched wavelength or external tilt), the fundamental's polarisation relative to the crossing plane, the delayed beam's side and the beam separation, which with focal_f_mm sets the crossing angle (0 is collinear). For an SHG trace with dispersive set, the session builds the CrystalSetup and passes it, with at least the depth nodes it needs, to the retrieval, the bootstraps, the covariance and the thickness uncertainty; PG and SD keep their material slab. The polarisation defaults to the crossing plane, where the trace stays symmetric. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- croak/session/params.py | 29 ++++++ croak/session/pipeline.py | 121 ++++++++++++++++++++++--- tests/test_session.py | 1 + tests/test_session_crystal.py | 161 ++++++++++++++++++++++++++++++++++ 4 files changed, 302 insertions(+), 10 deletions(-) create mode 100644 tests/test_session_crystal.py diff --git a/croak/session/params.py b/croak/session/params.py index ab6b95f..d9c7bda 100644 --- a/croak/session/params.py +++ b/croak/session/params.py @@ -329,8 +329,37 @@ class RetrieveParams: live_preview: bool = True perfect_init_fs: float = 10.0 dispersive: bool = False # dispersive propagation through a slab + #: The slab of a PG/SD retrieval (a material name, croak.materials). material: str = "SiO2" + #: The slab thickness (µm): the material slab of PG/SD, or the SHG crystal + #: along its face normal. thickness_um: float = 10.0 + # The nonlinear crystal of an SHG retrieval, used instead of ``material`` when + # ``dispersive`` is set and the interaction is SHG (croak.crystals.CrystalSetup). + #: A built-in crystal (croak.crystals.CRYSTALS). + crystal: str = "BBO" + #: The manufacturer's cut angle θ_c (degrees): the optic axis to the face normal. + cut_angle_deg: float = 29.2 + #: How the crystal's angle is set: ``"phase-match"`` solves the external tilt + #: that phase-matches ``phase_match_nm``; ``"tilt"`` takes ``tilt_deg``. + angle_mode: str = "phase-match" + #: External tilt γ (degrees) of the crystal, with ``angle_mode="tilt"``. + tilt_deg: float = 0.0 + #: Fundamental wavelength (nm) the crystal is tuned to phase-match, with + #: ``angle_mode="phase-match"``. + phase_match_nm: float = 800.0 + #: Fundamental polarisation relative to the crossing plane: ``"parallel"`` (in + #: it, so the beams cross perpendicular to the principal plane) or + #: ``"perpendicular"`` (the beams cross in the principal plane, which makes the + #: trace asymmetric in delay; see ``delayed_beam``). + polarization: str = "parallel" + #: With ``polarization="perpendicular"``: whether the delayed beam is on the + #: optic axis's side of the bisector (``"toward_axis"``) or not + #: (``"away_from_axis"``). Flipping it mirrors the model trace in delay. + delayed_beam: str = "toward_axis" + #: 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 # Default node count kept consistent with the tied defaults below: # thickness_um / delta_z_um = 10 µm / 1 µm = 10. npoints: int = 10 diff --git a/croak/session/pipeline.py b/croak/session/pipeline.py index d7b2ddd..3ee60dc 100644 --- a/croak/session/pipeline.py +++ b/croak/session/pipeline.py @@ -15,6 +15,7 @@ import os from dataclasses import dataclass from dataclasses import replace as dataclass_replace +from typing import cast import numpy as np @@ -22,8 +23,16 @@ from ..collection import aperture_from_scan, mask_hole_aperture from ..constants import C from ..covariance import covariance_uncertainty +from ..crystals import ( + CrystalSetup, + DelayedBeam, + Polarization, + builtin_crystal, + depth_points, +) from ..focal import FocalMixture, focal_mixture from ..forward import quadrature_nodes_weights +from ..geometry import TwoBeamGeometry from ..grid import Grid from ..interactions import get_interaction from ..pipeline import retrieve_from_tracedata @@ -826,6 +835,86 @@ def generation_envelope(p: RetrieveParams): return amp * np.exp(1j * p.envelope_gouy * np.arctan(u)) +def crystal_setup(p: RetrieveParams) -> CrystalSetup: + """Build the SHG crystal the retrieval settings describe. + + Parameters + ---------- + p : RetrieveParams + Retrieval settings: ``crystal``, ``cut_angle_deg``, ``angle_mode`` with + ``tilt_deg`` or ``phase_match_nm``, ``polarization``, ``delayed_beam``, + ``beam_separation_mm`` and ``focal_f_mm``. + + Returns + ------- + CrystalSetup + The crystal; collinear when ``beam_separation_mm`` is ``0``. + + Raises + ------ + ValueError + If ``angle_mode`` is neither ``"tilt"`` nor ``"phase-match"``, or a + setting is one :class:`~croak.crystals.CrystalSetup` refuses. + """ + if p.angle_mode == "tilt": + angle: dict = {"tilt": np.radians(p.tilt_deg)} + elif p.angle_mode == "phase-match": + angle = {"phase_match_wavelength": p.phase_match_nm * 1e-9} + else: + 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 + ) + in_plane = p.polarization == "perpendicular" + return CrystalSetup( + builtin_crystal(p.crystal), + float(np.radians(p.cut_angle_deg)), + geometry=geometry, + # a polarisation means something only with crossing beams + # CrystalSetup validates both strings + polarization=cast(Polarization, p.polarization) if geometry else None, + delayed_beam=( + cast(DelayedBeam, p.delayed_beam) if geometry and in_plane else None + ), + **angle, + ) + + +def retrieval_medium(p: RetrieveParams, td: TraceData) -> str | CrystalSetup | None: + """Return what the forward model propagates through: ``None``, a slab or a crystal. + + ``None`` without ``dispersive``; for an SHG trace ``td`` the crystal of + :func:`crystal_setup`; for PG and SD the material slab named by ``p.material``. + """ + if not p.dispersive: + return None + if get_interaction(td.interaction).name == "shg": + return crystal_setup(p) + return p.material + + +def retrieval_npoints( + p: RetrieveParams, + td: TraceData, + medium: str | CrystalSetup | None, + thickness: float, +) -> int: + """Return the depth nodes: ``p.npoints``, raised for a crystal to what it needs. + + A crystal's phase mismatch sets how finely its depth must be sampled + (:func:`~croak.crystals.depth_points`), so the settings' node count is raised + to that, never lowered. + """ + if isinstance(medium, CrystalSetup) and thickness > 0: + needed = depth_points(medium, td.grid.omega, td.omega0_pulse, thickness) + return max(p.npoints, needed) + return p.npoints + + def extra_param_centres( p: RetrieveParams, seed: RetrievalResult | None ) -> tuple[float, float, float, float]: @@ -1047,6 +1136,7 @@ def run_retrieval( focal = focal_mixture_from_params(p, td, scan_path, scan_window) td = apply_spectrum_frame(p, td) thickness, tau0, smear_scale, smear_delta = extra_param_centres(p, extras_seed) + medium = retrieval_medium(p, td) return retrieve_from_tracedata( td, algorithm=p.solver, @@ -1055,9 +1145,9 @@ def run_retrieval( guess=resolve_guess(p, guess_override), perfect_fwhm=p.perfect_init_fs * 1e-15, truth=truth, - material=p.material if p.dispersive else None, + material=medium, thickness=thickness, - npoints=p.npoints, + npoints=retrieval_npoints(p, td, medium, thickness), smearing=smearing_kernel(p, td), focal=focal, depth_weight=generation_envelope(p), @@ -1140,14 +1230,16 @@ def bootstrap_solver_kwargs(p: RetrieveParams, td: TraceData) -> dict: internally and filters these by what the chosen algorithm accepts, so it is safe to pass the full candidate set. """ + medium = retrieval_medium(p, td) + thickness = p.thickness_um * 1e-6 if p.dispersive else 0.0 return { "algorithm": p.solver, "maxiters": p.maxiters, "reltol": p.reltol, "abstol": p.abstol, - "material": p.material if p.dispersive else None, - "thickness": p.thickness_um * 1e-6 if p.dispersive else 0.0, - "npoints": p.npoints, + "material": medium, + "thickness": thickness, + "npoints": retrieval_npoints(p, td, medium, thickness), "smearing": smearing_kernel(p, td), "depth_weight": generation_envelope(p), "phase_only": not p.full, @@ -1177,12 +1269,21 @@ def covariance_kwargs(p: RetrieveParams, td: TraceData | None = None) -> dict: This includes the core slab, reduced smearing and phase parameterisation. It does not reconstruct focal/collection, depth-weight or marginal-peak centred models; do not interpret its output as matching those retrievals. - ``td`` supplies the carrier needed to rebuild a reduced smearing kernel. + ``td`` supplies the carrier needed to rebuild a reduced smearing kernel, and + the interaction that decides between a material slab and an SHG crystal + (:func:`retrieval_medium`); without it the slab is ``p.material``. """ + thickness = p.thickness_um * 1e-6 if p.dispersive else 0.0 + if td is None: + medium: str | CrystalSetup | None = p.material if p.dispersive else None + npoints = p.npoints + else: + medium = retrieval_medium(p, td) + npoints = retrieval_npoints(p, td, medium, thickness) return { - "material": p.material if p.dispersive else None, - "thickness": p.thickness_um * 1e-6 if p.dispersive else 0.0, - "npoints": p.npoints, + "material": medium, + "thickness": thickness, + "npoints": npoints, "smearing": smearing_kernel(p, td) if td is not None else None, "phase_only": not p.full, "phase_basis": p.phase_basis, @@ -1266,7 +1367,7 @@ def run_uncertainty( extra = { "central_thickness": rp.thickness_um * 1e-6, "thickness_sigma": up.thickness_sigma_um * 1e-6, - "material": rp.material, + "material": retrieval_medium(rp, td), } # Bootstrapping the thickness systematic and *fitting* the thickness are # alternative ways to account for it — never both, so drop the fit here. diff --git a/tests/test_session.py b/tests/test_session.py index 535fd1e..138f7fc 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -465,6 +465,7 @@ def test_solver_kwargs_forward_extra_fit_flags(): class _TD: Iomega = None + interaction = "pg" # a dispersive PG slab boot = bootstrap_solver_kwargs(p, _TD()) assert boot["fit_thickness"] is True diff --git a/tests/test_session_crystal.py b/tests/test_session_crystal.py new file mode 100644 index 0000000..f31ce23 --- /dev/null +++ b/tests/test_session_crystal.py @@ -0,0 +1,161 @@ +"""The SHG crystal in a session: settings to CrystalSetup, and into the retrieval.""" + +from __future__ import annotations + +import math +from types import SimpleNamespace + +import numpy as np +import pytest + +from croak import crystals +from croak.crystals import CrystalSetup +from croak.grid import Grid +from croak.maths import wlfreq +from croak.session import pipeline as session_pipeline +from croak.session.options import SessionOptions +from croak.session.params import RetrieveParams +from croak.session.pipeline import ( + bootstrap_solver_kwargs, + covariance_kwargs, + crystal_setup, + retrieval_medium, + retrieval_npoints, +) + +W0 = float(wlfreq(800e-9)) + + +def _td(interaction="shg"): + """A stand-in for TraceData: the fields the session reads here.""" + return SimpleNamespace( + interaction=interaction, + grid=Grid(64, dt=3e-15), + omega0_pulse=W0, + Iomega=None, + ) + + +def test_crystal_setup_phase_matched_and_crossing_in_the_principal_plane(): + p = RetrieveParams( + polarization="perpendicular", + delayed_beam="away_from_axis", + beam_separation_mm=10.0, + focal_f_mm=100.0, + ) + setup = crystal_setup(p) + assert setup.crystal is crystals.builtin_crystal("BBO") + assert setup.cut_angle == pytest.approx(math.radians(29.2)) + assert setup.phase_match_wavelength == pytest.approx(800e-9) + assert setup.tilt is None + assert setup.crossing_half_angle == pytest.approx(math.atan(10.0 / 200.0)) + assert setup.in_principal_plane + assert setup.delayed_beam == "away_from_axis" + + +def test_crystal_setup_with_a_tilt_and_the_polarisation_in_the_crossing_plane(): + p = RetrieveParams(angle_mode="tilt", tilt_deg=2.5, polarization="parallel") + setup = crystal_setup(p) + assert setup.tilt == pytest.approx(math.radians(2.5)) + assert setup.phase_match_wavelength is None + assert not setup.in_principal_plane + assert setup.delayed_beam is None # the side matters only in the principal plane + + +def test_crystal_setup_without_beam_separation_is_collinear(): + setup = crystal_setup(RetrieveParams(beam_separation_mm=0.0)) + assert setup.geometry is None + assert setup.polarization is None and setup.delayed_beam is None + + +def test_crystal_setup_refuses_an_unknown_angle_mode(): + with pytest.raises(ValueError, match="angle_mode must be"): + crystal_setup(RetrieveParams(angle_mode="auto")) + + +@pytest.mark.parametrize( + ("dispersive", "interaction", "expected"), + [(False, "shg", type(None)), (True, "pg", str), (True, "shg", CrystalSetup)], +) +def test_retrieval_medium_is_a_slab_or_a_crystal(dispersive, interaction, expected): + p = RetrieveParams(dispersive=dispersive, material="BK7") + medium = retrieval_medium(p, _td(interaction)) + assert isinstance(medium, expected) + if expected is str: + assert medium == "BK7" + + +def test_retrieval_npoints_raises_a_crystals_nodes_to_what_it_needs(): + td = _td() + p = RetrieveParams(dispersive=True, thickness_um=100.0, npoints=2) + medium = retrieval_medium(p, td) + needed = crystals.depth_points(medium, td.grid.omega, W0, 100e-6) + assert needed > 2 + assert retrieval_npoints(p, td, medium, 100e-6) == needed + # never lowered, and a slab keeps the settings' count + many = RetrieveParams(dispersive=True, thickness_um=100.0, npoints=needed + 5) + assert retrieval_npoints(many, td, medium, 100e-6) == needed + 5 + assert retrieval_npoints(p, _td("pg"), "BK7", 100e-6) == 2 + + +def test_run_retrieval_passes_the_crystal_and_its_nodes(monkeypatch): + captured: dict = {} + + def _fake(td, **kwargs): + captured.update(kwargs) + return "result" + + monkeypatch.setattr(session_pipeline, "retrieve_from_tracedata", _fake) + p = RetrieveParams(solver="lbfgs-ad", dispersive=True, thickness_um=50.0) + td = _td() + session_pipeline.run_retrieval(p, td) + assert isinstance(captured["material"], CrystalSetup) + assert captured["thickness"] == pytest.approx(50e-6) + assert captured["npoints"] == crystals.depth_points( + captured["material"], td.grid.omega, W0, 50e-6 + ) + + +def test_uncertainty_kwargs_carry_the_crystal(): + p = RetrieveParams(solver="lbfgs-ad", dispersive=True, thickness_um=50.0) + td = _td() + for kwargs in (bootstrap_solver_kwargs(p, td), covariance_kwargs(p, td)): + assert isinstance(kwargs["material"], CrystalSetup) + assert kwargs["npoints"] >= crystals.depth_points( + kwargs["material"], td.grid.omega, W0, 50e-6 + ) + + +def test_thickness_uncertainty_draws_through_the_crystal(monkeypatch): + captured: dict = {} + + def _fake(result, measured, **kwargs): + captured.update(kwargs) + return "uncertainty" + + monkeypatch.setattr(session_pipeline, "estimate_fwhm_uncertainty", _fake) + rp = RetrieveParams(solver="lbfgs-ad", dispersive=True, thickness_um=50.0) + up = session_pipeline.UncertaintyParams(method="thickness") + td = _td() + td.trace = np.ones((4, 3)) + result = SimpleNamespace(omega0=W0) + session_pipeline.run_uncertainty(up, rp, result, td) + assert isinstance(captured["material"], CrystalSetup) + + +def test_crystal_settings_round_trip_through_options_toml(tmp_path): + retrieve = RetrieveParams( + dispersive=True, + crystal="BBO", + cut_angle_deg=33.4, + angle_mode="tilt", + tilt_deg=-1.5, + phase_match_nm=780.0, + polarization="perpendicular", + delayed_beam="away_from_axis", + beam_separation_mm=7.5, + ) + options = SessionOptions().with_(retrieve=retrieve) + path = str(tmp_path / "options.toml") + options.to_toml(path) + assert SessionOptions.from_toml(path).retrieve == retrieve From 251b0a0c6f022ce30b889a99b00020a2fa51eac6 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 14:04:22 +0000 Subject: [PATCH 05/12] Set up the SHG crystal and the beam geometry in the Retrieve stage For an SHG trace the Retrieve stage shows a Nonlinear crystal group (on/off and thickness shared with the slab, crystal, cut angle, phase-matched wavelength or external tilt, polarisation relative to the crossing plane, delayed beam's side) and a Beam geometry group (beam separation and the focal length the focal mixture also uses), in place of the material slab. A read-out gives the internal angle, the tilt, the path and the depth nodes, or why the settings give no crystal. Thickness fitting stays off for a crystal (#26). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- croak/gui/stage_retrieve.py | 323 ++++++++++++++++++++++++++++++- tests/gui/test_stage_retrieve.py | 118 +++++++++++ 2 files changed, 432 insertions(+), 9 deletions(-) diff --git a/croak/gui/stage_retrieve.py b/croak/gui/stage_retrieve.py index 90bbe20..203f044 100644 --- a/croak/gui/stage_retrieve.py +++ b/croak/gui/stage_retrieve.py @@ -14,11 +14,12 @@ from PySide6.QtWidgets import ( QFileDialog, QHBoxLayout, + QLabel, QPushButton, QWidget, ) -from .. import materials, plotting, smearing +from .. import crystals, materials, plotting, smearing from ..constants import C from ..plotting.screen import convergence_view from ..processing import ( @@ -30,7 +31,12 @@ ) from ..retrieve import ALGORITHMS, algorithm_params from ..session.params import reg_defaults, reg_family -from ..session.pipeline import extra_param_centres, smearing_kernel +from ..session.pipeline import ( + crystal_setup, + extra_param_centres, + retrieval_npoints, + smearing_kernel, +) from ..truth_metrics import truth_errors from .base import RunControls, Stage from .controls import check, combo, dspin, group, spin @@ -50,6 +56,26 @@ #: 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``.""" + return next((k for k, v in labels.items() if v == value), next(iter(labels))) + + _INITIAL_GUESSES = { "Automatic (centroid phase)": None, "Transform-limited measured spectrum": "tl_init", @@ -174,6 +200,74 @@ 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 " + "chosen from the phase mismatch they must resolve (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", + [ + ( + "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).", + ), + ], + ), ( "Geometrical smearing", [ @@ -230,9 +324,9 @@ class StageRetrieve(RunControls, Stage): "Fit medium thickness", "Also fit the dispersive-slab thickness as a retrieval " "parameter (lbfgs-ad / lm / lm-optx / cma-es). Needs " - "dispersive propagation enabled, and is only identifiable for " - "PG/SD (for SHG a slab is a pure spectral phase the retrieved " - "phase absorbs). Starts from the Thickness value above.", + "dispersive propagation enabled, and is PG/SD only: an SHG " + "crystal's thickness is not fitted yet. Starts from the " + "Thickness value above.", ), ( "Fit τ₀ delay offset", @@ -481,6 +575,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.smear_box, form = group("Geometrical smearing") box = self.smear_box @@ -941,10 +1036,189 @@ def _on_initial_guess_changed(self, label: str) -> None: setattr(p, attr, attr == selected) 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: + 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) + self.crystal_thickness_spin = dspin( + 0, 10000, 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, 100000, p.focal_f_mm, self._on_geometry_f_changed, decimals=1 + ) + form.addRow("Focal length (mm)", self.geometry_f_spin) + self.geometry_readout = QLabel() + 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 _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.""" + shg = self._is_shg() + self.disp_box.setVisible(not shg) + self.crystal_box.setVisible(shg) + self.geometry_box.setVisible(shg) + if shg: + self._refresh_crystal() + + def _refresh_crystal(self) -> None: + """Enable the controls the settings use and describe the crystal 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" + ) + 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}°") + else: + self.geometry_readout.setText("Collinear beams") + 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) + 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 ----------------------------------- @@ -1211,6 +1485,7 @@ 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) # 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 @@ -1226,15 +1501,15 @@ def _update_solver_caps(self): self.copra_local_check.setEnabled("stall_patience" in params) # Extra fitted parameters: the AD/LM solvers (lbfgs-ad, lm, lm-optx) and # the global cma-es accept them. Thickness - # fitting additionally needs dispersive propagation enabled (and is PG/SD - # only — the solver guards SHG at run time). The smearing width likewise - # needs a kernel to scale. + # fitting additionally needs dispersive propagation enabled, through a + # PG/SD slab. The smearing width likewise needs a kernel to scale. has_fit_thickness = "fit_thickness" in params has_fit_tau0 = "fit_tau0" in params has_fit_smearing = "fit_smearing" in params self.extra_box.setEnabled(has_fit_thickness or has_fit_tau0 or has_fit_smearing) + # A crystal's thickness is not fitted yet (issue #26). self.fit_thickness_check.setEnabled( - has_fit_thickness and self.state.retrieve.dispersive + 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( @@ -1349,8 +1624,36 @@ 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, + } + 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): """Restore the default retrieval settings (as if re-initialised).""" from .state import RetrieveParams @@ -1369,6 +1672,8 @@ 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() + 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/tests/gui/test_stage_retrieve.py b/tests/gui/test_stage_retrieve.py index 819ff7c..d12d883 100644 --- a/tests/gui/test_stage_retrieve.py +++ b/tests/gui/test_stage_retrieve.py @@ -456,3 +456,121 @@ def test_retrieve_form_finds_a_setting_by_name_or_help(qtbot): assert not regularisation.body.isHidden() # unfolded to show the matches stage.form.find.setText("") assert regularisation.folded and regularisation.body.isHidden() + + +# -- the SHG crystal and the beam geometry ---------------------------------------- +def _shg_trace(stage): + """A stand-in SHG trace: what the crystal controls read from the data.""" + from croak.grid import Grid + + stage.state.tracedata = SimpleNamespace( + interaction="shg", grid=Grid(64, dt=3e-15), omega0_pulse=2.3546e15 + ) + stage.on_enter() + return stage + + +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() + _shg_trace(stage) + assert stage.disp_box.isHidden() + assert not stage.crystal_box.isHidden() and not stage.geometry_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_crystal_controls_store_their_settings(qtbot, stage): + _shg_trace(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): + _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" + + +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°" + 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): + _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.delayed_beam_combo.currentText() == "Away from the optic axis" + assert stage.separation_spin.value() == 6.0 From 6eb13e4cb5ba7e65c57cc4c70a4633012da522f4 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 14:22:02 +0000 Subject: [PATCH 06/12] Generate synthetic SHG traces through the crystal The Synthetic stage can make an SHG trace through the nonlinear crystal the Retrieve stage describes, at a thickness set there, so a trace made in a crystal and its retrieval share one description of the crystal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- croak/gui/stage_synthetic.py | 50 +++++++++++++++++++++++++++++-- tests/gui/test_stage_synthetic.py | 44 +++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 3 deletions(-) diff --git a/croak/gui/stage_synthetic.py b/croak/gui/stage_synthetic.py index 90419a0..374139f 100644 --- a/croak/gui/stage_synthetic.py +++ b/croak/gui/stage_synthetic.py @@ -1,7 +1,8 @@ """Generate-synthetic-trace panel. Builds a known pulse (Gaussian or sech², with GDD/TOD/FOD and optional material -dispersion), simulates a FROG measurement of it on a user-chosen wavelength × +dispersion), simulates a FROG measurement of it (for SHG optionally through the +nonlinear crystal the Retrieve stage describes) 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 @@ -18,10 +19,11 @@ import numpy as np from PySide6.QtCore import QTimer -from PySide6.QtWidgets import QGridLayout, QWidget +from PySide6.QtWidgets import QGridLayout, QLabel, QWidget from .. import dispersion from ..constants import C +from ..crystals import depth_points from ..forward import maketrace from ..grid import Grid from ..interactions import INTERACTIONS, get_interaction @@ -29,6 +31,7 @@ from ..plotting.screen import pulse_field_views, raw_trace_map from ..processing import TruthPulse from ..pulses import gaussian_pulse, sech_pulse +from ..session.pipeline import crystal_setup from .base import Stage from .controls import ( add_wide_row, @@ -158,6 +161,27 @@ def __init__(self, state): add_wide_row(form, "thickness (mm)", self.thickness) 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) + form.addRow( + QLabel( + "Crystal, angle, polarisation and beam geometry as set in the " + "Retrieve stage." + ) + ) + self.controls.addWidget(self.crystal_box) + self.crystal_box.setEnabled(self.interaction.currentText() == "shg") + # -- Noise ------------------------------------------------------ box, form = group("Noise (optional)") self.noise_add = ValueControl( @@ -243,6 +267,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._changed() def _on_delay(self, lo, hi): @@ -410,7 +435,9 @@ def _signal_trace(self, grid, ew, omega0): """ delays = self._delays() interaction = self.interaction.currentText() - trace = maketrace(grid.omega, delays, ew, interaction) # (Nomega, Ndelay) + trace = maketrace( # (Nomega, Ndelay) + grid.omega, delays, ew, interaction, **self._crystal_kwargs(grid, omega0) + ) scale = get_interaction(interaction).omega0_scale omega_abs = grid.omega + omega0 * scale pos = omega_abs > 0 @@ -419,6 +446,23 @@ def _signal_trace(self, grid, ew, omega0): order = np.argsort(lam) 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 + if not ( + self.interaction.currentText() == "shg" + and self.use_crystal.isChecked() + and thickness > 0 + ): + return {} + setup = crystal_setup(self.state.retrieve) + return { + "material": setup, + "thickness": thickness, + "npoints": depth_points(setup, grid.omega, omega0, thickness), + "omega0": omega0, + } + def _add_noise(self, trace): add = self.noise_add.value() pois = self.noise_pois.value() diff --git a/tests/gui/test_stage_synthetic.py b/tests/gui/test_stage_synthetic.py index 9c5283f..9ea7856 100644 --- a/tests/gui/test_stage_synthetic.py +++ b/tests/gui/test_stage_synthetic.py @@ -189,3 +189,47 @@ def test_preview_draws_the_four_panels(stage): assert stage.views["trace"].plot.data is not None assert stage.status_label.text().startswith("Adjust the pulse") assert stage._last is not None + + +def test_shg_traces_can_be_made_through_the_retrieve_stages_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() + 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) + _, _, made = stage._signal_trace(grid, ew, omega0) + # the crystal is the one the Retrieve stage's settings describe + setup = crystal_setup(stage.state.retrieve) + expected = maketrace( + grid.omega, + delays, + ew, + "shg", + material=setup, + thickness=100e-6, + npoints=depth_points(setup, grid.omega, omega0, 100e-6), + omega0=omega0, + ) + pos = grid.omega + 2 * omega0 > 0 + order = np.argsort(1.0 / (grid.omega + 2 * omega0)[pos]) + # the same computation in the same order: equal to rounding, relative to the peak + want = expected[pos][order] + 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) + 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_kwargs(*stage._pulse()[::2]) == {} From 091558ff8363ef3181a5b591043f667b184e8de9 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 14:33:45 +0000 Subject: [PATCH 07/12] Document SHG retrieval with a thick crystal A how-to page covers describing the crystal (built-in or custom indices, cut angle with a tilt or a phase-matched wavelength, the beam geometry and depth nodes), the polarisation and the delayed beam's side, the session and GUI settings, what is not modelled yet (SHG smearing, fitting the crystal, marginal-corrected traces) and how the model compares with full-field simulations. The models guide, the feature list, the GUI and thickness-fitting pages point to it; a release-note fragment records the change. The formatter also rewrapped one test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- changelog.d/shg-crystal-integration.added.md | 1 + docs/howto/fitting_thickness_tau0.md | 6 +- docs/howto/gui.md | 12 +- docs/howto/shg_crystal.md | 113 +++++++++++++++++++ docs/reference/features.md | 5 +- docs/user_guide/models.md | 11 +- tests/gui/test_stage_retrieve.py | 5 +- 7 files changed, 142 insertions(+), 11 deletions(-) create mode 100644 changelog.d/shg-crystal-integration.added.md create mode 100644 docs/howto/shg_crystal.md diff --git a/changelog.d/shg-crystal-integration.added.md b/changelog.d/shg-crystal-integration.added.md new file mode 100644 index 0000000..5287aff --- /dev/null +++ b/changelog.d/shg-crystal-integration.added.md @@ -0,0 +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). 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. See [SHG FROG with a thick crystal](docs/howto/shg_crystal.md) (#24). diff --git a/docs/howto/fitting_thickness_tau0.md b/docs/howto/fitting_thickness_tau0.md index e0846cb..210cf26 100644 --- a/docs/howto/fitting_thickness_tau0.md +++ b/docs/howto/fitting_thickness_tau0.md @@ -63,8 +63,10 @@ trace lies at $+\tau_0$ (the simulated gate uses $e^{i\omega(\tau-\tau_0)}$). integral makes thickness affect the trace beyond a single input spectral phase. Whether a particular trace identifies it is a separate question (see below). -For **SHG**, croak has no dispersive slab model (the signal propagates at -$2\omega_0$), so `fit_thickness` with SHG is rejected with an error. +For **SHG**, the slab is a nonlinear crystal +([SHG with a thick crystal](shg_crystal.md)), whose thickness is not fitted yet +([issue #26](https://github.com/LupoLab/croak/issues/26)): `fit_thickness` with +SHG is rejected with an error. Even within PG/SD, the *bulk-chirp* part of $L$ is partly degenerate with the retrieved phase; only the depth-distributed part constrains it. Thickness is diff --git a/docs/howto/gui.md b/docs/howto/gui.md index 88aa6a6..00d2d7d 100644 --- a/docs/howto/gui.md +++ b/docs/howto/gui.md @@ -296,8 +296,8 @@ straight to Retrieve. See #### Generate the trace (synthetic) -Build a test trace (pulse shape, interaction, delays, optional dispersive slab -and noise) using {func}`~croak.forward.maketrace`, previewed live. Useful for +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 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 @@ -445,7 +445,13 @@ The two spectral ones need the truth's complex field, so an intensity-only file 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)). *Geometrical smearing* +[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), with a read-out of the +internal angle, the tilt, the path and the depth nodes +([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 width shown — and editable, which back-computes the spacing. Both sections grey diff --git a/docs/howto/shg_crystal.md b/docs/howto/shg_crystal.md new file mode 100644 index 0000000..a30978c --- /dev/null +++ b/docs/howto/shg_crystal.md @@ -0,0 +1,113 @@ +# SHG FROG with a thick crystal + +In a thin crystal, an SHG FROG trace is the ideal one: every pair of fundamental +frequencies converts equally well. In a crystal of tens of micrometres, with a +few-cycle pulse, it is not: phase matching filters the signal's spectrum, the +fundamental and the second harmonic walk off in time, and the generated field +grows as $\omega_s/n_s$. A retrieval with the ideal model then attributes all of +that to the pulse. This page shows how to retrieve with croak's model of a Type I +crystal instead. The physics is in +[the forward model](../explanation/forward_model.md#shg-in-a-type-i-crystal). + +## The quick version + +```python +import math + +import croak +from croak.crystals import CrystalSetup, builtin_crystal, depth_points +from croak.geometry import TwoBeamGeometry + +crystal = CrystalSetup( + builtin_crystal("BBO"), + cut_angle=math.radians(29.2), # the manufacturer's cut + phase_match_wavelength=800e-9, # tilted to phase-match 800 nm + geometry=TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1), + polarization="parallel", # fundamental in the crossing plane +) +thickness = 100e-6 +npoints = depth_points(crystal, g.omega, omega0, thickness) + +res = croak.retrieve( + trace, g.omega, delays, "shg", + algorithm="lbfgs-ad", + material=crystal, thickness=thickness, npoints=npoints, omega0=omega0, +) +``` + +`material=` takes the crystal wherever it takes a material name for PG and SD: in +{func}`~croak.forward.maketrace`, {class}`~croak.forward.ForwardModel`, every +solver, {func}`~croak.pipeline.retrieve_from_tracedata` and the uncertainty +estimates. The retrieved field is the field at the crystal's entrance face. + +## Describing the crystal + +- **The crystal.** {func}`~croak.crystals.builtin_crystal` gives a built-in crystal + ({data}`~croak.crystals.CRYSTALS`) with optmat's recommended indices of both + rays; BBO uses Tamošauskas et al. (2018), valid from 188 nm to 5.2 µm. Any + other uniaxial crystal can be described with + {class}`~croak.crystals.UniaxialCrystal` and two index functions. +- **Its angle.** Give the cut angle $\theta_c$ (optic axis to face normal) and + either the external tilt you set (`tilt=`) or the fundamental wavelength the + crystal was tuned to phase-match (`phase_match_wavelength=`), from which the + tilt is solved. {meth}`~croak.crystals.CrystalSetup.internal_angle` and + {meth}`~croak.crystals.CrystalSetup.external_tilt` report the result. +- **The beams.** {class}`~croak.geometry.TwoBeamGeometry` takes the beam + separation at the focusing optic and its focal length, and is the one place + the crossing angle comes from. `geometry=None` models collinear beams. +- **The depth nodes.** {func}`~croak.crystals.depth_points` gives the number of + depth nodes the crystal's phase mismatch needs on your grid; the models refuse + fewer. + +## Polarisation, and which side the delayed beam is on + +In Type I SHG the fundamental is ordinary, polarised perpendicular to the +crystal's principal plane. So the polarisation decides how the beams cross: + +- **`polarization="parallel"`** (the fundamental in the crossing plane): the beams + cross perpendicular to the principal plane. The trace stays symmetric in delay. +- **`polarization="perpendicular"`**: the beams cross in the principal plane. The + signal's tilt then changes its index to first order, which makes the trace + asymmetric in delay. The model includes this, and needs to know whether the + delayed beam is on the optic axis's side of the bisector + (`delayed_beam="toward_axis"` or `"away_from_axis"`). A crystal's markings do + not show it, and the two choices give traces mirrored in delay, so retrieve + with both and keep the better fit. + +{func}`~croak.crystals.check_tilt` estimates what the first-order treatment of +the tilt leaves out for your spectrum, and warns above 1 %. + +## In a session and in the GUI + +The session settings ({class}`~croak.session.params.RetrieveParams`) describe the +crystal by `crystal`, `cut_angle_deg`, `angle_mode` (`"phase-match"` with +`phase_match_nm`, or `"tilt"` with `tilt_deg`), `polarization`, `delayed_beam`, +`beam_separation_mm` and `focal_f_mm`; `dispersive` switches it on and +`thickness_um` is its thickness. For an SHG trace the session builds the crystal +from them ({func}`~croak.session.pipeline.crystal_setup`) and raises the depth +nodes to what it needs. 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. + +## 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: a 6 fs pulse crossing at + 2.9° with a 20 µm waist is blurred by 2.4 fs. +- **Fitting the crystal.** Its thickness and angle are inputs, not fitted + parameters ([issue #26](https://github.com/LupoLab/croak/issues/26)). +- **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 + +On full-field simulations of SHG FROG in BBO (Luna.jl, two Gaussian beams +crossing in two dimensions, the signal collected over the whole beam), the +crystal model reproduces the simulated traces to about 1 % of their peak. A +10 fs pulse with 30 fs² of GDD in 100 µm, crossing at 1.4°, was retrieved with a +duration of 13.80 fs against 13.81 fs and a complex-field error of 0.10, against +0.52 with the ideal model, which narrows the spectrum to mimic the phase-matching +filter. diff --git a/docs/reference/features.md b/docs/reference/features.md index b7d7d42..d85a5c1 100644 --- a/docs/reference/features.md +++ b/docs/reference/features.md @@ -94,8 +94,9 @@ Further reading: [Gradients](../explanation/gradients.md). with analytic adjoints; see [interaction physics](../explanation/interactions.md). - **Dispersive propagation** — a Gauss–Legendre depth integral through a material slab, propagating both the input replicas and the generated signal. Available - on every solver, for PG and SD (the SHG signal is not at the fundamental - frequency). The thin medium is the same code path with zero thickness and one + on every solver, for PG and SD; for SHG the slab is a Type I crystal + ({class}`~croak.crystals.CrystalSetup`), whose signal near $2\omega_0$ is the + extraordinary wave ([SHG with a thick crystal](../howto/shg_crystal.md)). The thin medium is the same code path with zero thickness and one quadrature node. - **Geometric time smearing** — {mod}`croak.smearing` represents an achromatic, fully collected focal average using two timing coordinates: a diff --git a/docs/user_guide/models.md b/docs/user_guide/models.md index 888116c..6f251fc 100644 --- a/docs/user_guide/models.md +++ b/docs/user_guide/models.md @@ -14,6 +14,7 @@ hierarchy of models croak provides and when each is needed. | My instrument has… | Read | |---|---| | a nonlinear medium thick enough to disperse the pulse (PG, SD) | [The forward model](../explanation/forward_model.md) | +| an SHG crystal thick enough to filter or stretch the signal | [SHG FROG with a thick crystal](../howto/shg_crystal.md) | | crossed beams (BOXCARS) whose arrival times vary across the focus | [Modelling geometric time smearing](../howto/geometric_smearing.md) | | a collection aperture that clips the signal beam chromatically | [Modelling the collection aperture](../howto/collection_aperture.md) | | an uncertain thickness or delay zero to fit | [Fitting the medium thickness and delay-zero](../howto/fitting_thickness_tau0.md) | @@ -22,6 +23,7 @@ hierarchy of models croak provides and when each is needed. :maxdepth: 1 ../explanation/forward_model +../howto/shg_crystal ../howto/geometric_smearing ../howto/collection_aperture ``` @@ -30,7 +32,9 @@ hierarchy of models croak provides and when each is needed. The models form a ladder. The **standard** model is the thin, local interaction. The **dispersive slab** propagates the input and signal fields -through a medium of given material and thickness (PG and SD only). The +through a medium of given material and thickness (PG and SD); for SHG the +**crystal** model propagates the ordinary fundamentals and the extraordinary +signal through a Type I crystal. The **extended** model adds geometric delay smearing as a kernel set by the mask geometry. The **full** model replaces the kernel with an explicit chromatic focal quadrature and a modelled collection aperture. Each step costs more, and @@ -39,8 +43,9 @@ model defines; compare fields only at the same plane. ## Main entry points -- {class}`~croak.forward.ForwardModel`: the forward model, with material, - thickness and depth quadrature. +- {class}`~croak.forward.ForwardModel`: the forward model, with material (or an + SHG crystal, {class}`~croak.crystals.CrystalSetup`), thickness and depth + quadrature. - {func}`~croak.smearing.square_boxcars_kernel`, {class}`~croak.smearing.SmearingKernel`: geometric smearing from the mask geometry. - {func}`~croak.focal.focal_mixture`: the chromatic focal quadrature. diff --git a/tests/gui/test_stage_retrieve.py b/tests/gui/test_stage_retrieve.py index d12d883..b8a7640 100644 --- a/tests/gui/test_stage_retrieve.py +++ b/tests/gui/test_stage_retrieve.py @@ -504,7 +504,10 @@ def test_stage_retrieve_crystal_controls_store_their_settings(qtbot, stage): 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, + "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) From 7f9312ddc5860bc951b16f761bd7f960a404816f Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 14:45:56 +0000 Subject: [PATCH 08/12] Address review of the crystal integration - A crystal gets the depth nodes its phase mismatch needs, not the slab's tied count, and its thickness is not fitted (as without dispersive). - A session retrieval crossing in the principal plane runs check_tilt on the retrieved spectrum. - The thickness uncertainty raises a clear error when dispersive propagation is off. - An optmat without a built-in crystal's models raises a ValueError, which the GUI read-out shows. - The GUI keeps the crystal's thickness, focal length and switch in step with the slab and the focal mixture, shows the slab alone before a trace is loaded, uses the same ranges for the shared settings, and shows an unknown stored setting as it is, with the read-out saying why. - The Synthetic stage's note wraps to its column. - Tests check that every solver receives the crystal and run a covariance through it; the docs give the smearing width as rms and FWHM, the tilt check, the defaults and the sources of the full-field figures. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- README.md | 3 +- changelog.d/shg-crystal-integration.added.md | 2 +- croak/crystals.py | 11 ++- croak/gui/stage_retrieve.py | 49 +++++++++++--- croak/gui/stage_synthetic.py | 10 +-- croak/session/pipeline.py | 68 +++++++++++++++---- docs/howto/shg_crystal.md | 25 ++++--- tests/gui/test_stage_retrieve.py | 36 ++++++++++ tests/test_crystals.py | 13 ++++ tests/test_pipeline_crystal.py | 29 +++++++- tests/test_session_crystal.py | 70 ++++++++++++++++++-- 11 files changed, 272 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 2c7234a..a480afb 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,8 @@ instead models the measurement physics directly: - **dispersive propagation** of the input fields and the generated signal through the nonlinear medium, with refractive indices of glasses, crystals and - gases from [optmat](https://optmat.readthedocs.io); + 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; - **chromatic focusing and the collection aperture**, as a coherent chromatic diff --git a/changelog.d/shg-crystal-integration.added.md b/changelog.d/shg-crystal-integration.added.md index 5287aff..97c056a 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). 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. 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). 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). diff --git a/croak/crystals.py b/croak/crystals.py index 34bfbac..2417d74 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -101,6 +101,7 @@ import numpy as np import scipy.optimize from numpy.typing import ArrayLike, NDArray +from optmat.exceptions import OptmatError from optmat.solid.models.registry import default_model from . import materials @@ -217,8 +218,14 @@ def builtin_crystal(name: str) -> UniaxialCrystal: @functools.cache def _load_crystal(name: str) -> UniaxialCrystal: """Build a built-in crystal from optmat's models, once per canonical name.""" - ordinary = default_model(name, axis="o") - extraordinary = default_model(name, axis="e") + try: + ordinary = default_model(name, axis="o") + extraordinary = default_model(name, axis="e") + except OptmatError as err: + raise ValueError( + f"the installed optmat has no indices for {name}: {err} (croak needs an " + f"optmat with {name}'s models)" + ) from err lo = max(ordinary.wavelength_range[0], extraordinary.wavelength_range[0]) hi = min(ordinary.wavelength_range[1], extraordinary.wavelength_range[1]) return UniaxialCrystal( diff --git a/croak/gui/stage_retrieve.py b/croak/gui/stage_retrieve.py index 203f044..252a187 100644 --- a/croak/gui/stage_retrieve.py +++ b/croak/gui/stage_retrieve.py @@ -72,8 +72,12 @@ def _label(labels: dict[str, str], value: str) -> str: - """Return the GUI label of a stored setting ``value``.""" - return next((k for k, v in labels.items() if v == value), next(iter(labels))) + """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 = { @@ -214,8 +218,8 @@ class StageRetrieve(RunControls, Stage): ( "Thickness (µm)", "Crystal thickness along its face normal. The depth nodes are " - "chosen from the phase mismatch they must resolve (read-out " - "below).", + "the number the phase mismatch needs (croak.crystals." + "depth_points; read-out below).", ), ( "Cut angle θc (°)", @@ -576,6 +580,7 @@ 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 @@ -703,7 +708,7 @@ def __init__(self, state): 1.0, 10000, p.focal_f_mm, - lambda v: setattr(p, "focal_f_mm", float(v)), + self._on_focal_f_changed, decimals=1, step=10.0, ) @@ -1051,8 +1056,10 @@ def _build_crystal_groups(self) -> None: 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, 10000, p.thickness_um, self._on_crystal_thickness_changed, decimals=1 + 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( @@ -1114,7 +1121,7 @@ def _build_crystal_groups(self) -> None: ) form.addRow("Beam separation (mm)", self.separation_spin) self.geometry_f_spin = dspin( - 1, 100000, p.focal_f_mm, self._on_geometry_f_changed, decimals=1 + 1, 10000, p.focal_f_mm, self._on_geometry_f_changed, decimals=1 ) form.addRow("Focal length (mm)", self.geometry_f_spin) self.geometry_readout = QLabel() @@ -1157,6 +1164,13 @@ def _on_geometry_f_changed(self, value: float) -> None: self.focal_f_spin.blockSignals(False) self._refresh_crystal() + 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" @@ -1168,10 +1182,29 @@ def _update_medium_groups(self) -> None: self.crystal_box.setVisible(shg) self.geometry_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), + ): + 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) self._refresh_crystal() def _refresh_crystal(self) -> None: - """Enable the controls the settings use and describe the crystal they give.""" + """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) diff --git a/croak/gui/stage_synthetic.py b/croak/gui/stage_synthetic.py index 374139f..46bba8f 100644 --- a/croak/gui/stage_synthetic.py +++ b/croak/gui/stage_synthetic.py @@ -173,12 +173,12 @@ def __init__(self, state): ) self.crystal_thickness.changed.connect(self._changed) add_wide_row(form, "thickness (µm)", self.crystal_thickness) - form.addRow( - QLabel( - "Crystal, angle, polarisation and beam geometry as set in the " - "Retrieve stage." - ) + 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") diff --git a/croak/session/pipeline.py b/croak/session/pipeline.py index 3ee60dc..31a6089 100644 --- a/croak/session/pipeline.py +++ b/croak/session/pipeline.py @@ -28,6 +28,7 @@ DelayedBeam, Polarization, builtin_crystal, + check_tilt, depth_points, ) from ..focal import FocalMixture, focal_mixture @@ -903,18 +904,53 @@ def retrieval_npoints( medium: str | CrystalSetup | None, thickness: float, ) -> int: - """Return the depth nodes: ``p.npoints``, raised for a crystal to what it needs. + """Return the depth nodes: ``p.npoints`` for a slab, what a crystal needs. - A crystal's phase mismatch sets how finely its depth must be sampled - (:func:`~croak.crystals.depth_points`), so the settings' node count is raised - to that, never lowered. + A crystal's phase mismatch sets how finely its depth must be sampled, and + :func:`~croak.crystals.depth_points` gives the count that resolves it; the + slab's ``npoints`` (tied to its depth step in the GUI) does not apply. """ if isinstance(medium, CrystalSetup) and thickness > 0: - needed = depth_points(medium, td.grid.omega, td.omega0_pulse, thickness) - return max(p.npoints, needed) + return depth_points(medium, td.grid.omega, td.omega0_pulse, thickness) return p.npoints +def fits_thickness(p: RetrieveParams, medium: str | CrystalSetup | None) -> bool: + """Return whether the thickness is fitted: a slab's, not yet a crystal's (#26). + + Like ``fit_thickness`` without ``dispersive``, a ticked fit with a crystal is + not applied; the GUI greys the control out for SHG data. + """ + return p.fit_thickness and isinstance(medium, str) + + +def check_crystal_tilt( + medium: str | CrystalSetup | None, + td: TraceData, + thickness: float, + result: RetrievalResult, +) -> None: + """Warn if the crystal's first-order tilt model is not enough for this pulse. + + Only for beams crossing in the principal plane + (:func:`~croak.crystals.check_tilt`), with the retrieved spectrum and nine + delays across the trace's live delay range. + """ + if not (isinstance(medium, CrystalSetup) and medium.in_principal_plane): + return + marginal = np.asarray(td.trace).sum(axis=0) + live = np.asarray(td.delays)[marginal > 1e-2 * marginal.max()] + delays = np.linspace(live.min(), live.max(), 9) + check_tilt( + medium, + td.grid.omega, + td.omega0_pulse, + thickness, + np.abs(result.spectrum), + delays, + ) + + def extra_param_centres( p: RetrieveParams, seed: RetrievalResult | None ) -> tuple[float, float, float, float]: @@ -1137,7 +1173,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) - return retrieve_from_tracedata( + result = retrieve_from_tracedata( td, algorithm=p.solver, full=p.full, @@ -1164,8 +1200,8 @@ def run_retrieval( tau0=tau0, smear_scale=smear_scale, smear_scale_delta=smear_delta, - # thickness fitting needs a dispersive slab (the solver guards SHG) - fit_thickness=p.fit_thickness and p.dispersive, + # thickness fitting needs a dispersive slab, not yet a crystal (#26) + 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, @@ -1186,6 +1222,8 @@ def run_retrieval( rng=rng, callback=callback, ) + check_crystal_tilt(medium, td, thickness, result) + return result # --------------------------------------------------------------------------- @@ -1252,7 +1290,7 @@ def bootstrap_solver_kwargs(p: RetrieveParams, td: TraceData) -> dict: "spectrum_target": td.Iomega if p.reg_spectrum > 0 and p.full else None, "reg_time": p.reg_time, "time_window": (p.reg_time_lo_fs * 1e-15, p.reg_time_hi_fs * 1e-15), - "fit_thickness": p.fit_thickness and p.dispersive, + "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, @@ -1289,7 +1327,7 @@ def covariance_kwargs(p: RetrieveParams, td: TraceData | None = None) -> dict: "phase_basis": p.phase_basis, "n_nodes": p.n_nodes, "R_omega": p.R_omega, - "fit_thickness": p.fit_thickness and p.dispersive, + "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": ( @@ -1361,13 +1399,19 @@ def run_uncertainty( else NoiseModel(sigma=up.noise_sigma) ) elif up.method == "thickness": + medium = retrieval_medium(rp, td) + if medium is None: + raise ValueError( + "the thickness uncertainty needs dispersive propagation: switch on " + "the slab, or for SHG the crystal, whose thickness is uncertain" + ) # 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. extra = { "central_thickness": rp.thickness_um * 1e-6, "thickness_sigma": up.thickness_sigma_um * 1e-6, - "material": retrieval_medium(rp, td), + "material": medium, } # Bootstrapping the thickness systematic and *fitting* the thickness are # alternative ways to account for it — never both, so drop the fit here. diff --git a/docs/howto/shg_crystal.md b/docs/howto/shg_crystal.md index a30978c..2a8470f 100644 --- a/docs/howto/shg_crystal.md +++ b/docs/howto/shg_crystal.md @@ -75,7 +75,9 @@ crystal's principal plane. So the polarisation decides how the beams cross: with both and keep the better fit. {func}`~croak.crystals.check_tilt` estimates what the first-order treatment of -the tilt leaves out for your spectrum, and warns above 1 %. +the tilt leaves out for your spectrum, and warns above 1 %. A session or GUI +retrieval with the beams in the principal plane runs it on the retrieved +spectrum; with the API, call it yourself. ## In a session and in the GUI @@ -84,20 +86,25 @@ crystal by `crystal`, `cut_angle_deg`, `angle_mode` (`"phase-match"` with `phase_match_nm`, or `"tilt"` with `tilt_deg`), `polarization`, `delayed_beam`, `beam_separation_mm` and `focal_f_mm`; `dispersive` switches it on and `thickness_um` is its thickness. For an SHG trace the session builds the crystal -from them ({func}`~croak.session.pipeline.crystal_setup`) and raises the depth -nodes to what it needs. In the GUI the Retrieve stage shows these as the +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. +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. ## 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: a 6 fs pulse crossing at - 2.9° with a 20 µm waist is blurred by 2.4 fs. + 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)). + 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. @@ -106,7 +113,9 @@ can generate an SHG trace through the same crystal. On full-field simulations of SHG FROG in BBO (Luna.jl, two Gaussian beams crossing in two dimensions, the signal collected over the whole beam), the -crystal model reproduces the simulated traces to about 1 % of their peak. A +crystal model reproduces the simulated traces to about 1 % of their peak +([issue #27](https://github.com/LupoLab/croak/issues/27), +[#28](https://github.com/LupoLab/croak/issues/28)). A 10 fs pulse with 30 fs² of GDD in 100 µm, crossing at 1.4°, was retrieved with a duration of 13.80 fs against 13.81 fs and a complex-field error of 0.10, against 0.52 with the ideal model, which narrows the spectrum to mimic the phase-matching diff --git a/tests/gui/test_stage_retrieve.py b/tests/gui/test_stage_retrieve.py index b8a7640..b620880 100644 --- a/tests/gui/test_stage_retrieve.py +++ b/tests/gui/test_stage_retrieve.py @@ -577,3 +577,39 @@ def test_stage_retrieve_seeds_the_crystal_widgets_from_the_settings(stage): ) 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) + _shg_trace(stage) + assert stage.crystal_thickness_spin.value() == 77.0 + assert stage.geometry_f_spin.value() == 333.0 + assert stage.crystal_check.isChecked() + + +def test_stage_retrieve_focal_length_is_one_setting_for_both_groups(stage): + _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() == "Crossing half-angle α = 0.716°" + + +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_readout.text().startswith("No valid crystal: angle_mode") diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 4ae24f4..fcb6441 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -428,3 +428,16 @@ def test_builtin_crystal_names_are_case_insensitive_and_cached(): def test_unknown_builtin_crystal_raises(): with pytest.raises(ValueError, match="unknown crystal 'KDP'.*BBO"): crystals.builtin_crystal("KDP") + + +def test_a_builtin_crystal_missing_from_optmat_is_a_value_error(monkeypatch): + # An optmat without the crystal's models raises its own error; croak reports + # it as a ValueError naming what is missing, which the GUI read-out catches. + from optmat.exceptions import DataError + + def missing(name, axis): + raise DataError(f"no dispersion model is recommended for {name} yet") + + monkeypatch.setattr(crystals, "default_model", missing) + with pytest.raises(ValueError, match="the installed optmat has no indices for BBO"): + crystals._load_crystal.__wrapped__("BBO") diff --git a/tests/test_pipeline_crystal.py b/tests/test_pipeline_crystal.py index 32fbbce..5be217b 100644 --- a/tests/test_pipeline_crystal.py +++ b/tests/test_pipeline_crystal.py @@ -8,6 +8,7 @@ from __future__ import annotations +import functools import math from dataclasses import replace @@ -21,6 +22,7 @@ from croak.geometry import TwoBeamGeometry from croak.grid import Grid from croak.maths import wlfreq +from croak.covariance import parameter_covariance from croak.pipeline import retrieve_from_tracedata from croak.pulses import gaussian_pulse from croak.retrieve import ALGORITHMS @@ -79,7 +81,19 @@ def _depth_points(td, thickness=THICKNESS): @pytest.mark.parametrize("algorithm", sorted(ALGORITHMS)) -def test_every_solver_retrieves_with_a_crystal(crystal_tracedata, algorithm): +def test_every_solver_retrieves_with_a_crystal(crystal_tracedata, algorithm, monkeypatch): + # Spy on the solver's constructor: the crystal must reach it unchanged (a + # solver that dropped `material` would otherwise still return finite numbers). + original = ALGORITHMS[algorithm] + received: dict = {} + + class Spy(original): # type: ignore[valid-type, misc] + @functools.wraps(original.__init__) + def __init__(self, **kwargs): + received.update(kwargs) + super().__init__(**kwargs) + + monkeypatch.setitem(ALGORITHMS, algorithm, Spy) td = crystal_tracedata res = retrieve_from_tracedata( td, @@ -90,11 +104,22 @@ def test_every_solver_retrieves_with_a_crystal(crystal_tracedata, algorithm): npoints=_depth_points(td), rng=np.random.default_rng(0), ) - assert res.algorithm == algorithm + assert received["material"] is CRYSTAL + assert received["thickness"] == THICKNESS assert np.all(np.isfinite(res.spectrum)) assert np.isfinite(res.error) +def test_parameter_covariance_runs_through_the_crystal(crystal_tracedata): + td = crystal_tracedata + kw = dict(material=CRYSTAL, thickness=THICKNESS, npoints=_depth_points(td)) + res = retrieve_from_tracedata( + td, algorithm="lbfgs-ad", maxiters=200, rng=np.random.default_rng(0), **kw + ) + cov = parameter_covariance(res, td.trace, noise=1e-3, omega0=td.omega0_pulse, **kw) + assert np.all(np.isfinite(cov.cov)) and cov.rank > 0 + + def test_the_crystal_model_fits_its_own_trace_better_than_ideal_shg(): # In 100 um the crystal's phase matching and group-velocity mismatch shape the # trace; retrieving with the crystal model must fit it better than ideal SHG. diff --git a/tests/test_session_crystal.py b/tests/test_session_crystal.py index f31ce23..c998287 100644 --- a/tests/test_session_crystal.py +++ b/tests/test_session_crystal.py @@ -19,6 +19,7 @@ bootstrap_solver_kwargs, covariance_kwargs, crystal_setup, + fits_thickness, retrieval_medium, retrieval_npoints, ) @@ -85,25 +86,84 @@ def test_retrieval_medium_is_a_slab_or_a_crystal(dispersive, interaction, expect assert medium == "BK7" -def test_retrieval_npoints_raises_a_crystals_nodes_to_what_it_needs(): +def test_retrieval_npoints_gives_a_crystal_the_nodes_it_needs(): td = _td() p = RetrieveParams(dispersive=True, thickness_um=100.0, npoints=2) medium = retrieval_medium(p, td) needed = crystals.depth_points(medium, td.grid.omega, W0, 100e-6) assert needed > 2 + # the crystal's own count, whatever the slab's (GUI-tied) npoints says assert retrieval_npoints(p, td, medium, 100e-6) == needed - # never lowered, and a slab keeps the settings' count - many = RetrieveParams(dispersive=True, thickness_um=100.0, npoints=needed + 5) - assert retrieval_npoints(many, td, medium, 100e-6) == needed + 5 + many = RetrieveParams(dispersive=True, thickness_um=100.0, npoints=needed + 50) + assert retrieval_npoints(many, td, medium, 100e-6) == needed + # a slab keeps the settings' count assert retrieval_npoints(p, _td("pg"), "BK7", 100e-6) == 2 +def test_a_crystals_thickness_is_not_fitted_yet(): + p = RetrieveParams(solver="lbfgs-ad", dispersive=True, fit_thickness=True) + assert fits_thickness(p, "BK7") is True + assert fits_thickness(p, crystal_setup(p)) is False + assert fits_thickness(p, None) is False + td = _td() + assert bootstrap_solver_kwargs(p, td)["fit_thickness"] is False + assert covariance_kwargs(p, td)["fit_thickness"] is False + + +def test_run_retrieval_does_not_fit_a_crystals_thickness(monkeypatch): + 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", dispersive=True, fit_thickness=True) + session_pipeline.run_retrieval(p, _td()) + assert captured["fit_thickness"] is False + + +def test_a_retrieval_crossing_in_the_principal_plane_checks_the_tilt(monkeypatch): + # A 5 fs-wide spectrum in 300 um crossing at 2.86 degrees: the first-order + # tilt model leaves about 2 % (tests/test_forward_crystal.py), so it warns. + from croak.crystals import CrystalApproximationWarning + from croak.pulses import gaussian_pulse + + td = _td() + td.delays = np.linspace(-30e-15, 30e-15, 21) + td.trace = np.ones((td.grid.n, td.delays.size)) + spectrum = gaussian_pulse(td.grid, 5e-15) + monkeypatch.setattr( + session_pipeline, + "retrieve_from_tracedata", + lambda td, **kw: SimpleNamespace(spectrum=spectrum), + ) + p = RetrieveParams( + solver="lbfgs-ad", + dispersive=True, + thickness_um=300.0, + polarization="perpendicular", + beam_separation_mm=10.0, + ) + with pytest.warns(CrystalApproximationWarning, match="first order only"): + session_pipeline.run_retrieval(p, td) + + +def test_the_thickness_uncertainty_needs_dispersive_propagation(): + rp = RetrieveParams(solver="lbfgs-ad", dispersive=False) + up = session_pipeline.UncertaintyParams(method="thickness") + td = _td() + td.trace = np.ones((4, 3)) + with pytest.raises(ValueError, match="needs dispersive propagation"): + session_pipeline.run_uncertainty(up, rp, SimpleNamespace(omega0=W0), td) + + def test_run_retrieval_passes_the_crystal_and_its_nodes(monkeypatch): captured: dict = {} def _fake(td, **kwargs): captured.update(kwargs) - return "result" + return SimpleNamespace(spectrum=np.ones(64)) monkeypatch.setattr(session_pipeline, "retrieve_from_tracedata", _fake) p = RetrieveParams(solver="lbfgs-ad", dispersive=True, thickness_um=50.0) From 4a160d9f74601183ae9c8ffdbaf46b6393f534fa Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 14:46:27 +0000 Subject: [PATCH 09/12] Wrap the solver test's signature to the line limit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- tests/test_pipeline_crystal.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_pipeline_crystal.py b/tests/test_pipeline_crystal.py index 5be217b..a6ceabb 100644 --- a/tests/test_pipeline_crystal.py +++ b/tests/test_pipeline_crystal.py @@ -17,12 +17,12 @@ from test_crystals import BBO, W0 from croak import crystals, preprocess +from croak.covariance import parameter_covariance from croak.crystals import CrystalSetup from croak.forward import ForwardModel from croak.geometry import TwoBeamGeometry from croak.grid import Grid from croak.maths import wlfreq -from croak.covariance import parameter_covariance from croak.pipeline import retrieve_from_tracedata from croak.pulses import gaussian_pulse from croak.retrieve import ALGORITHMS @@ -81,7 +81,9 @@ def _depth_points(td, thickness=THICKNESS): @pytest.mark.parametrize("algorithm", sorted(ALGORITHMS)) -def test_every_solver_retrieves_with_a_crystal(crystal_tracedata, algorithm, monkeypatch): +def test_every_solver_retrieves_with_a_crystal( + crystal_tracedata, algorithm, monkeypatch +): # Spy on the solver's constructor: the crystal must reach it unchanged (a # solver that dropped `material` would otherwise still return finite numbers). original = ALGORITHMS[algorithm] From 53ebe9d09e71cfae4f2b04e95ab84d5c78c48ab7 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 14:55:47 +0000 Subject: [PATCH 10/12] Make the crystal tilt check cheap, robust and visible in the GUI crystal_tilt_error estimates what the first-order tilt model leaves out on the part of the grid the pulse occupies (its live band, doubled), so it no longer costs seconds on wide grids, and returns None where there is nothing to check instead of raising after the retrieval. run_retrieval warns from it unless check_tilt=False; the GUI worker turns that off, since capturing warnings in a thread is unsafe, and sends the estimate to the Retrieve stage as a notice. The per-solver test now checks that each solver's own model trace is the crystal model's, which a solver ignoring the crystal fails. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- croak/gui/stage_retrieve.py | 1 + croak/gui/worker.py | 16 +++++++ croak/session/pipeline.py | 77 +++++++++++++++++++++++++--------- tests/gui/test_worker.py | 29 ++++++++++++- tests/test_pipeline_crystal.py | 17 +++++++- tests/test_session_crystal.py | 60 ++++++++++++++++++++++++++ 6 files changed, 177 insertions(+), 23 deletions(-) diff --git a/croak/gui/stage_retrieve.py b/croak/gui/stage_retrieve.py index 252a187..9894fd2 100644 --- a/croak/gui/stage_retrieve.py +++ b/croak/gui/stage_retrieve.py @@ -1787,6 +1787,7 @@ def _run(self): self._worker.finished_ok.connect(self._on_finished) self._worker.stopped.connect(self._on_stopped) self._worker.failed.connect(self._on_failed) + self._worker.notice.connect(lambda text: self.set_status(text, "warn")) self._errors: list[float] = [] # Blank the read-out rather than leaving the previous run's numbers on # screen; the extras block shows what this run starts from. diff --git a/croak/gui/worker.py b/croak/gui/worker.py index 12cf50f..bbeb9e1 100644 --- a/croak/gui/worker.py +++ b/croak/gui/worker.py @@ -12,6 +12,7 @@ import numpy as np from PySide6.QtCore import QThread, Signal +from ..crystals import TILT_ERROR_WARN from ..session import pipeline __all__ = [ @@ -96,6 +97,10 @@ class RetrievalWorker(QThread): when the user pressed Stop and a snapshot was available. failed : str An error message on failure (or a bare Stop with no snapshot available). + notice : str + A caution about a finished result, after ``finished_ok``: what an SHG + crystal's first-order tilt model leaves out, when it is more than + :data:`croak.crystals.TILT_ERROR_WARN`. """ #: Shortest wall-clock interval (s) between live previews. Presenting one costs @@ -115,6 +120,7 @@ class RetrievalWorker(QThread): finished_ok = Signal(object, float) stopped = Signal(object, float) failed = Signal(str) + notice = Signal(str) def __init__( self, @@ -211,8 +217,18 @@ def run(self) -> None: # noqa: D401 - QThread entry point callback=self._callback, scan_path=self._scan_path, scan_window=self._scan_window, + # warnings are process-wide state, not safe to capture in a + # thread: the tilt estimate is reported as a notice instead + check_tilt=False, ) self.finished_ok.emit(result, time.perf_counter() - self._t0) + error = pipeline.crystal_tilt_error(self._p, self._td, result) + if error is not None and error > TILT_ERROR_WARN: + self.notice.emit( + f"The crystal model keeps the signal's tilt to first order " + f"only; what it leaves out changes the signal by {error:.1%} " + f"for this pulse." + ) except StopRetrieval: elapsed = time.perf_counter() - self._t0 if self._stop_result is not None: diff --git a/croak/session/pipeline.py b/croak/session/pipeline.py index 31a6089..f4c85c8 100644 --- a/croak/session/pipeline.py +++ b/croak/session/pipeline.py @@ -13,6 +13,7 @@ from __future__ import annotations import os +import warnings from dataclasses import dataclass from dataclasses import replace as dataclass_replace from typing import cast @@ -24,12 +25,14 @@ from ..constants import C from ..covariance import covariance_uncertainty from ..crystals import ( + TILT_ERROR_WARN, + CrystalApproximationWarning, CrystalSetup, DelayedBeam, Polarization, builtin_crystal, - check_tilt, depth_points, + tilt_field_error, ) from ..focal import FocalMixture, focal_mixture from ..forward import quadrature_nodes_weights @@ -924,33 +927,60 @@ def fits_thickness(p: RetrieveParams, medium: str | CrystalSetup | None) -> bool return p.fit_thickness and isinstance(medium, str) -def check_crystal_tilt( - medium: str | CrystalSetup | None, - td: TraceData, - thickness: float, - result: RetrievalResult, -) -> None: - """Warn if the crystal's first-order tilt model is not enough for this pulse. +def crystal_tilt_error( + p: RetrieveParams, td: TraceData, result: RetrievalResult +) -> float | None: + """Return what the crystal's first-order tilt model leaves out, or ``None``. + + The relative field error of :func:`~croak.crystals.tilt_field_error` for the + retrieved spectrum, at nine delays across the trace's live delay range. Only + for an SHG crystal with the beams crossing in its principal plane; ``None`` + otherwise, and when the trace or the retrieved spectrum has nothing to check + (no live delays, or no finite, positive spectrum). - Only for beams crossing in the principal plane - (:func:`~croak.crystals.check_tilt`), with the retrieved spectrum and nine - delays across the trace's live delay range. + The pair sum costs :math:`N^2` per delay, so it runs on the part of the grid + the pulse occupies: the spectrum's live band, doubled (every pair's sum + frequency then lies on the cropped grid without wrapping round), with margin. """ + medium = retrieval_medium(p, td) if not (isinstance(medium, CrystalSetup) and medium.in_principal_plane): - return - marginal = np.asarray(td.trace).sum(axis=0) + return None + amplitude = np.abs(np.asarray(result.spectrum)) + marginal = np.asarray(td.trace, dtype=float).sum(axis=0) + if not (np.all(np.isfinite(amplitude)) and amplitude.max() > 0): + return None + if not (np.all(np.isfinite(marginal)) and marginal.max() > 0): + return None live = np.asarray(td.delays)[marginal > 1e-2 * marginal.max()] - delays = np.linspace(live.min(), live.max(), 9) - check_tilt( + omega = td.grid.omega + band = np.abs(omega[amplitude > 1e-3 * amplitude.max()]).max() + keep = np.abs(omega) <= 2.2 * band + # a centred grid stays centred when cropped symmetrically about its zero bin + centre = int(np.argmin(np.abs(omega))) + half = int(keep.sum() // 2) + 1 + window = slice(max(centre - half, 0), min(centre + half, omega.size)) + return tilt_field_error( medium, - td.grid.omega, + omega[window], td.omega0_pulse, - thickness, - np.abs(result.spectrum), - delays, + p.thickness_um * 1e-6, + amplitude[window], + np.linspace(live.min(), live.max(), 9), ) +def warn_crystal_tilt(error: float | None) -> None: + """Warn when :func:`crystal_tilt_error` exceeds the crystals module's threshold.""" + if error is not None and error > TILT_ERROR_WARN: + warnings.warn( + f"the crystal model keeps the signal's tilt to first order only; what " + f"it leaves out changes the signal field by {error:.1%} for this pulse " + f"(croak.crystals.check_tilt)", + CrystalApproximationWarning, + stacklevel=3, + ) + + def extra_param_centres( p: RetrieveParams, seed: RetrievalResult | None ) -> tuple[float, float, float, float]: @@ -1126,6 +1156,7 @@ def run_retrieval( focal=None, scan_path: str | None = None, scan_window: str | int | None = None, + check_tilt: bool = True, ) -> RetrievalResult: """Run :func:`~croak.pipeline.retrieve_from_tracedata` from a ``RetrieveParams``. @@ -1166,6 +1197,11 @@ def run_retrieval( Which collection hole of a multi-aperture scan the trace came from (the loader's ``window_key``); with ``p.collection == "file"`` the aperture is rebuilt from that hole's record. ``None`` = the first window. + check_tilt : bool, optional + Warn (:class:`~croak.crystals.CrystalApproximationWarning`) when an SHG + crystal crossed in its principal plane needs more than the first-order + tilt model for the retrieved pulse (:func:`crystal_tilt_error`). The GUI + turns it off and reports the estimate itself. """ rng = np.random.default_rng() if rng is None else rng if focal is None: @@ -1222,7 +1258,8 @@ def run_retrieval( rng=rng, callback=callback, ) - check_crystal_tilt(medium, td, thickness, result) + if check_tilt: + warn_crystal_tilt(crystal_tilt_error(p, td, result)) return result diff --git a/tests/gui/test_worker.py b/tests/gui/test_worker.py index 6d91f09..d1fd52f 100644 --- a/tests/gui/test_worker.py +++ b/tests/gui/test_worker.py @@ -67,8 +67,11 @@ def build(*_args, **_kwargs): # -- RetrievalWorker --------------------------------------------------------- -def _stub_retrieval(monkeypatch, body): - """Replace run_retrieval by ``body(callback)`` and return the kwargs it saw.""" +def _stub_retrieval(monkeypatch, body, tilt_error=None): + """Replace run_retrieval by ``body(callback)`` and return the kwargs it saw. + + The crystal tilt estimate the worker asks for afterwards is ``tilt_error``. + """ seen = {} def run_retrieval(p, td, **kwargs): @@ -76,6 +79,9 @@ def run_retrieval(p, td, **kwargs): return body(kwargs["callback"]) monkeypatch.setattr(worker_mod.pipeline, "run_retrieval", run_retrieval) + monkeypatch.setattr( + worker_mod.pipeline, "crystal_tilt_error", lambda p, td, result: tilt_error + ) return seen @@ -98,9 +104,28 @@ def test_retrieval_worker_success_forwards_arguments(monkeypatch): assert seen["guess_override"] == "g" and seen["extras_seed"] == "x" assert seen["truth"] == "t" assert seen["scan_path"] == "scan.h5" and seen["scan_window"] == 2 + # the tilt estimate is reported by the worker, not warned in the thread + assert seen["check_tilt"] is False assert rec.named("failed") == rec.named("stopped") == [] +@pytest.mark.parametrize( + ("error", "noticed"), [(None, False), (0.005, False), (0.02, True)] +) +def test_retrieval_worker_reports_a_large_crystal_tilt_error( + monkeypatch, error, noticed +): + _stub_retrieval(monkeypatch, lambda cb: "result", tilt_error=error) + w = RetrievalWorker("td", "params") + rec = _Recorder(w, "finished_ok", "notice") + w.run() + assert len(rec.named("finished_ok")) == 1 + notices = rec.named("notice") + assert len(notices) == int(noticed) + if noticed: + assert "2.0%" in notices[0][0] + + def test_retrieval_worker_failure_emits_message(monkeypatch): def body(_cb): raise RuntimeError("solver diverged") diff --git a/tests/test_pipeline_crystal.py b/tests/test_pipeline_crystal.py index a6ceabb..12e759c 100644 --- a/tests/test_pipeline_crystal.py +++ b/tests/test_pipeline_crystal.py @@ -109,7 +109,22 @@ def __init__(self, **kwargs): assert received["material"] is CRYSTAL assert received["thickness"] == THICKNESS assert np.all(np.isfinite(res.spectrum)) - assert np.isfinite(res.error) + + # The solver's own model trace of its result is the crystal model's, not ideal + # SHG's: a solver that accepted the crystal and then ignored it fails here. + def model_trace(**kw): + t = ForwardModel( + td.grid.omega, td.delays, "shg", omega0=td.omega0_pulse, **kw + ).trace(res.spectrum) + return t / t.max() + + own = res.trace / res.trace.max() + crystal = model_trace( + material=CRYSTAL, thickness=THICKNESS, npoints=_depth_points(td) + ) + ideal = model_trace() + assert np.abs(own - crystal).max() < 1e-6 + assert np.abs(own - ideal).max() > 1e-3 def test_parameter_covariance_runs_through_the_crystal(crystal_tracedata): diff --git a/tests/test_session_crystal.py b/tests/test_session_crystal.py index c998287..1b6557d 100644 --- a/tests/test_session_crystal.py +++ b/tests/test_session_crystal.py @@ -219,3 +219,63 @@ def test_crystal_settings_round_trip_through_options_toml(tmp_path): path = str(tmp_path / "options.toml") options.to_toml(path) assert SessionOptions.from_toml(path).retrieve == retrieve + + +def _tilt_case(n=256, dt=1.5e-15): + """A 6 fs pulse on a wide grid, crossing at 2.86 degrees in the principal plane.""" + from croak.pulses import gaussian_pulse + + grid = Grid(n, dt=dt) + td = SimpleNamespace( + interaction="shg", + grid=grid, + omega0_pulse=W0, + delays=np.linspace(-30e-15, 30e-15, 21), + trace=np.ones((n, 21)), + Iomega=None, + ) + p = RetrieveParams( + dispersive=True, + thickness_um=300.0, + polarization="perpendicular", + beam_separation_mm=10.0, + ) + return p, td, SimpleNamespace(spectrum=gaussian_pulse(grid, 6e-15)) + + +def test_crystal_tilt_error_on_the_cropped_band_matches_the_full_grid(): + # the crop keeps every pair whose amplitude exceeds 1e-3 of the peak and all + # their sum frequencies, so it changes the estimate only at that level + p, td, result = _tilt_case() + setup = crystal_setup(p) + delays = np.linspace(td.delays.min(), td.delays.max(), 9) + full = crystals.tilt_field_error( + setup, td.grid.omega, W0, 300e-6, np.abs(result.spectrum), delays + ) + cropped = session_pipeline.crystal_tilt_error(p, td, result) + assert full > 0.01 + assert cropped == pytest.approx(full, rel=1e-3) + + +@pytest.mark.parametrize("broken", ["parallel", "zero trace", "nan spectrum"]) +def test_crystal_tilt_error_is_none_when_there_is_nothing_to_check(broken): + p, td, result = _tilt_case(n=64, dt=3e-15) + if broken == "parallel": + p = RetrieveParams(dispersive=True, polarization="parallel") + elif broken == "zero trace": + td.trace = np.zeros_like(td.trace) + else: + result = SimpleNamespace(spectrum=np.full(td.grid.n, np.nan)) + assert session_pipeline.crystal_tilt_error(p, td, result) is None + + +def test_run_retrieval_can_leave_the_tilt_check_to_the_caller(monkeypatch): + import warnings + + p, td, result = _tilt_case(n=64, dt=3e-15) + monkeypatch.setattr( + session_pipeline, "retrieve_from_tracedata", lambda td, **kw: result + ) + with warnings.catch_warnings(): + warnings.simplefilter("error") + session_pipeline.run_retrieval(p, td, check_tilt=False) From 9f327024350431cf5e8721aa6b6af76d48f31e24 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 15:05:16 +0000 Subject: [PATCH 11/12] Give the test stand-in workers the notice signal Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- tests/gui/test_wizard_flow.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/gui/test_wizard_flow.py b/tests/gui/test_wizard_flow.py index e4fb6fc..a667af0 100644 --- a/tests/gui/test_wizard_flow.py +++ b/tests/gui/test_wizard_flow.py @@ -1880,7 +1880,7 @@ def test_retrieval_readout_cleared_when_a_run_starts(qtbot, monkeypatch): class _Idle: def __init__(self, *a, **k): self.progress = self.preview = self.finished_ok = _Sig() - self.stopped = self.failed = _Sig() + self.stopped = self.failed = self.notice = _Sig() def start(self): pass @@ -2336,7 +2336,7 @@ def connect(self, _slot): def __init__(self, *a, **k): self.progress = self.preview = self.finished_ok = self._Sig() - self.stopped = self.failed = self._Sig() + self.stopped = self.failed = self.notice = self._Sig() def start(self): pass From 838e35476a1e7122ab417f266593bc055a86f12e Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Tue, 17 Nov 2026 13:45:30 +0000 Subject: [PATCH 12/12] Require optmat 0.10.0, the first release with BBO Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- changelog.d/shg-crystal-integration.added.md | 2 +- pyproject.toml | 2 +- uv.lock | 10 +++++----- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/changelog.d/shg-crystal-integration.added.md b/changelog.d/shg-crystal-integration.added.md index 97c056a..b1d7b0e 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). 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'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). diff --git a/pyproject.toml b/pyproject.toml index 14cb067..2deefbb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ dependencies = [ "nlopt>=2.10.0", "numpy>=2.4.6", "optimistix>=0.1.0", - "optmat[gas]>=0.8.1", + "optmat[gas]>=0.10.0", "scipy>=1.17.1", "tomli-w>=1.2.0", "tqdm>=4.66.0", diff --git a/uv.lock b/uv.lock index cb22c61..a34f367 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.14" [[package]] @@ -368,7 +368,7 @@ requires-dist = [ { name = "nlopt", specifier = ">=2.10.0" }, { name = "numpy", specifier = ">=2.4.6" }, { name = "optimistix", specifier = ">=0.1.0" }, - { name = "optmat", extras = ["gas"], specifier = ">=0.8.1" }, + { name = "optmat", extras = ["gas"], specifier = ">=0.10.0" }, { name = "pyqtgraph", marker = "extra == 'gui'", specifier = ">=0.14" }, { name = "pyside6-essentials", marker = "extra == 'gui'", specifier = ">=6.10.1" }, { name = "scipy", specifier = ">=1.17.1" }, @@ -1324,16 +1324,16 @@ wheels = [ [[package]] name = "optmat" -version = "0.8.1" +version = "0.10.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jaxtyping" }, { name = "numpy" }, { name = "scipy" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/72/1d/70957d38e53bfca14cf362559d6b3c21255d01ad7f6ee8b32139cf655b0a/optmat-0.8.1.tar.gz", hash = "sha256:3eb902731b39716a35df369b7bdd5bae2889b4dfba130eee4f44c7c6d814bc2a", size = 17527157, upload-time = "2026-10-16T21:46:14.09Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/76/a9a66b2af5d5bbd90bd6f7f14529f728275c336bb7d664b9d317131d8ef9/optmat-0.10.0.tar.gz", hash = "sha256:02bb82795eee9768623338fec84c32be4229ae1f9e69abc5b62ddfba6894694b", size = 17643182, upload-time = "2026-11-17T12:37:38.984Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/2e/fbd99043f6b2a0068654003713c468c683fb5ba59d5ef100783a4c598748/optmat-0.8.1-py3-none-any.whl", hash = "sha256:266dfe57c8a3deb8eaf3e540da49de74b08685dc27f72404cef9c1901eee331f", size = 17648193, upload-time = "2026-10-16T21:46:10.82Z" }, + { url = "https://files.pythonhosted.org/packages/a0/0e/aa8de92e8d798a1af3addd8944984116910bc09e9dc4ee3c5b83feea25ba/optmat-0.10.0-py3-none-any.whl", hash = "sha256:215b28360f3904a09160a175d29df7aa1c25a216cc6daca70c7c2c6957de1e40", size = 17809459, upload-time = "2026-11-17T12:37:34.911Z" }, ] [package.optional-dependencies]