From 87814e091bf0a2c912882cf12ed753535a55cc07 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 17:05:35 +0000 Subject: [PATCH 01/16] Model Type I SHG in a uniaxial crystal croak.crystals supplies separate propagation constants for the ordinary fundamentals (with the crossing angle) and the extraordinary signal near 2*omega0, and the omega_s/n_s generation prefactor; keeping the carrier wavevectors, the depth sum carries the exact phase mismatch. The crystal is given by its cut angle and an external tilt, or the wavelength it is tuned to. croak.geometry holds the two-beam geometry, the one source of the crossing angle. Both forward models take a CrystalSetup for SHG and check the depth resolution and the neglected signal tilt. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- croak/crystals.py | 647 +++++++++++++++++++++++++++++++++++++++++ croak/forward.py | 59 ++-- croak/forward_jax.py | 106 ++++--- croak/geometry.py | 71 +++++ tests/test_crystals.py | 275 ++++++++++++++++++ 5 files changed, 1094 insertions(+), 64 deletions(-) create mode 100644 croak/crystals.py create mode 100644 croak/geometry.py create mode 100644 tests/test_crystals.py diff --git a/croak/crystals.py b/croak/crystals.py new file mode 100644 index 0000000..510a887 --- /dev/null +++ b/croak/crystals.py @@ -0,0 +1,647 @@ +r"""Type I (oo→e) second-harmonic generation in a uniaxial crystal. + +The forward model (:mod:`croak.forward`, :mod:`croak.forward_jax`) integrates the +signal generated at every depth :math:`z` of the medium and propagates it to the +exit face. For PG and SD the fundamental and the signal share one propagation +constant. For SHG they do not: the signal lives near :math:`2\omega_0`, and in a +Type I crystal it is the extraordinary wave while the fundamentals are ordinary. +This module supplies the two propagation constants and the generation prefactor. + +Propagation constants +--------------------- +Both are written on the model's centred grid :math:`\Omega` (relative to the pulse +carrier :math:`\omega_0` for the fundamental, and to :math:`2\omega_0` for the +signal) and in **one** frame moving with the fundamental's group velocity +:math:`\beta_1 = \mathrm d k_z/\mathrm d\omega|_{\omega_0}`: + +.. math:: + + \beta_\mathrm{in}(\Omega) &= k_z(\omega_0+\Omega) - \beta_1\Omega, \qquad + k_z(\omega) = \sqrt{k_o(\omega)^2 - (\omega\sin\alpha/c)^2}, \\ + \beta_\mathrm{sig}(\Omega) &= k_s(2\omega_0+\Omega) - \beta_1\Omega, \qquad + k_s(\omega) = \frac{\omega}{c}\, n_e(\theta, \omega). + +:math:`k_o = \omega n_o/c` is the ordinary wavevector. :math:`k_z` is its +component along the bisector of two beams crossing at the external half-angle +:math:`\alpha` (:class:`~croak.geometry.TwoBeamGeometry`): the transverse +wavevector :math:`\omega\sin\alpha/c` is conserved across the entrance face, and +the ordinary index does not depend on direction, so no refraction step is needed. +:math:`n_e(\theta,\omega)` is the extraordinary index of a wave at the internal +angle :math:`\theta` to the optic axis, +:math:`1/n_e(\theta)^2 = \cos^2\theta/n_o^2 + \sin^2\theta/n_e^2`. + +The carrier wavevectors are kept. A component pair :math:`(\omega_1, \omega_2)` +generated at depth :math:`z` and propagated to the exit then carries +:math:`\exp(-i\Delta k\, z)` with the exact mismatch + +.. math:: \Delta k = k_s(\omega_1+\omega_2) - k_z(\omega_1) - k_z(\omega_2), + +because the frame terms cancel: :math:`-\beta_1(\Omega_1+\Omega_2)z +-\beta_1\Omega_s(L-z) = -\beta_1\Omega_s L` does not depend on :math:`z`, and only +adds a linear spectral phase, which the trace :math:`|\psi|^2` cannot see. The depth +sum therefore produces the phase-matching response, +:math:`\mathrm{sinc}(\Delta k L/2)` per pair, by itself. + +Generation prefactor +-------------------- +The second-harmonic field generated by a polarisation :math:`P` grows as +:math:`i\omega_s P/(2 n_s c)` (slowly varying envelope). The model multiplies the +signal by :math:`(\omega_s/n_s)/(2\omega_0/n_s(2\omega_0))`, normalised at the +carrier. Other spectral factors (the beams' mode overlap, the dispersion of +:math:`\chi^{(2)}`, the detector) are left to the solvers' ``R_omega``. + +Crystal angle +------------- +The manufacturer specifies the cut angle :math:`\theta_c` between the optic axis +and the face normal. A crystal tilted by the external angle :math:`\gamma` (in the +principal plane; positive increases the angle to the optic axis) refracts the beams +to :math:`\gamma_\mathrm{int} = \arcsin(\sin\gamma / n_o)`, so that +:math:`\theta = \theta_c + \gamma_\mathrm{int}`, and the path through a plate of +thickness :math:`L` is :math:`L/\cos\gamma_\mathrm{int}`. :class:`CrystalSetup` +takes either :math:`\gamma` or the wavelength the crystal was tuned to +phase-match, from which :math:`\theta` is solved. Approximations: the refraction +uses :math:`n_o` at one wavelength (the phase-matched one, else the carrier), and the +crossing geometry is taken at normal incidence. + +Validity +-------- +* Type I only, fundamentals ordinary; no walk-off (thin crystal, full collection). +* The signal of a pair :math:`(\omega_1,\omega_2)` leaves at a small angle + :math:`\delta\theta \approx (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to the + bisector, which the model neglects. When the beams cross in the crystal's + principal plane (fundamental polarisation perpendicular to the crossing plane), + that tilt changes :math:`n_e(\theta)` to first order; + :func:`tilt_phase_error` estimates the phase it adds and the forward models warn + above :data:`TILT_PHASE_WARN`. When the polarisation lies in the crossing plane, + the principal plane is perpendicular to it and the first-order term vanishes. + +See :doc:`/explanation/forward_model` for the full model. +""" + +from __future__ import annotations + +import math +import warnings +from collections.abc import Callable +from dataclasses import dataclass +from typing import Literal, cast + +import numpy as np +import scipy.optimize +from numpy.typing import ArrayLike, NDArray + +from . import materials +from .constants import C +from .geometry import TwoBeamGeometry +from .interactions import Interaction +from .maths import derivative, wlfreq + +__all__ = [ + "TILT_PHASE_WARN", + "CrystalSetup", + "CrystalApproximationWarning", + "Propagation", + "UniaxialCrystal", + "check_medium", + "depth_points", + "extraordinary_index", + "phase_matching_angle", + "propagation", + "tilt_phase_error", +] + +#: Phase (rad) of the neglected signal-tilt term above which the forward models warn. +#: At 0.1 rad the per-pair sinc² response changes by under 1 % of its peak. +TILT_PHASE_WARN = 0.1 + +#: Largest grid used to estimate the mismatch over all component pairs; finer grids +#: are subsampled. The mismatch varies smoothly, so 256 points resolve its extremes. +_PAIR_GRID = 256 + +Index = Callable[[NDArray[np.float64]], NDArray[np.float64]] +Polarization = Literal["parallel", "perpendicular"] + + +class CrystalApproximationWarning(UserWarning): + """The crystal model's neglected signal-tilt phase is not small.""" + + +@dataclass(frozen=True) +class UniaxialCrystal: + """A uniaxial crystal's principal refractive indices. + + Parameters + ---------- + name : str + Label, e.g. ``"BBO"``. + n_o, n_e : callable + Ordinary and principal extraordinary index as functions of the vacuum + wavelength (m), vectorised over NumPy arrays. + """ + + name: str + n_o: Index + n_e: Index + + +def extraordinary_index( + n_o: ArrayLike, n_e: ArrayLike, theta: float +) -> NDArray[np.float64]: + r"""Extraordinary index of a wave at angle ``theta`` to the optic axis. + + :math:`1/n(\theta)^2 = \cos^2\theta/n_o^2 + \sin^2\theta/n_e^2`. + + Parameters + ---------- + n_o, n_e : array_like + Ordinary and principal extraordinary indices. + theta : float + Angle between the wavevector and the optic axis (rad). + + Returns + ------- + numpy.ndarray + The index; ``n_o`` at ``theta = 0`` and ``n_e`` at ``pi/2``. + + Examples + -------- + >>> float(extraordinary_index(1.6, 1.5, 0.0)) + 1.6 + >>> float(extraordinary_index(1.6, 1.5, np.pi / 2)) + 1.5 + """ + n_o = np.asarray(n_o, dtype=float) + n_e = np.asarray(n_e, dtype=float) + inv2 = np.cos(theta) ** 2 / n_o**2 + np.sin(theta) ** 2 / n_e**2 + return 1.0 / np.sqrt(inv2) + + +def _dn_dtheta(n_o, n_e, theta: float) -> NDArray[np.float64]: + """Return the derivative of :func:`extraordinary_index` in ``theta``.""" + n = extraordinary_index(n_o, n_e, theta) + return -0.5 * n**3 * np.sin(2.0 * theta) * (1.0 / n_e**2 - 1.0 / n_o**2) + + +def _k_fundamental( + crystal: UniaxialCrystal, omega: NDArray[np.float64], sin_alpha: float +) -> NDArray[np.float64]: + """Ordinary wavevector along the bisector, ``sqrt(k_o^2 - (w sin a / c)^2)``.""" + k_o = omega / C * crystal.n_o(wlfreq(omega)) + return np.sqrt(k_o**2 - (omega * sin_alpha / C) ** 2) + + +def _k_signal( + crystal: UniaxialCrystal, omega: NDArray[np.float64], theta: float +) -> NDArray[np.float64]: + """Extraordinary wavevector of the signal at internal angle ``theta``.""" + lam = wlfreq(omega) + return omega / C * extraordinary_index(crystal.n_o(lam), crystal.n_e(lam), theta) + + +def phase_matching_angle( + crystal: UniaxialCrystal, wavelength: float, crossing_half_angle: float = 0.0 +) -> float: + r"""Solve for the internal angle that phase-matches Type I SHG of ``wavelength``. + + Solves :math:`k_s(2\omega) = 2k_z(\omega)` for :math:`\theta`, with the + fundamentals crossing at the external half-angle ``crossing_half_angle``. + + Parameters + ---------- + crystal : UniaxialCrystal + The crystal. + wavelength : float + Fundamental vacuum wavelength (m). + crossing_half_angle : float, optional + External half-angle between each beam and the bisector (rad); ``0`` + (default) is collinear. + + Returns + ------- + float + :math:`\theta` (rad), in ``[0, pi/2]``. + + Raises + ------ + ValueError + If no angle phase-matches it (the crystal is not negative uniaxial there, + or its birefringence is too small to cancel the dispersion). + """ + omega = np.array([wlfreq(wavelength)], dtype=float) + target = 2.0 * float( + _k_fundamental(crystal, omega, math.sin(crossing_half_angle))[0] + ) + + def mismatch(theta: float) -> float: + return float(_k_signal(crystal, 2.0 * omega, theta)[0]) - target + + lo, hi = mismatch(0.0), mismatch(0.5 * math.pi) + if not (np.isfinite(lo) and np.isfinite(hi)) or lo * hi > 0.0: + raise ValueError( + f"{crystal.name} cannot phase-match Type I SHG of " + f"{wavelength * 1e9:.1f} nm: k_s(2w) - 2k_z(w) runs from {lo:.3g} to " + f"{hi:.3g} 1/m over 0-90 degrees and never crosses zero" + ) + # cast: brentq returns a float here (full_output is False), but its stub + # widens the return to include the full-output tuple. + return cast(float, scipy.optimize.brentq(mismatch, 0.0, 0.5 * math.pi, xtol=1e-14)) + + +@dataclass(frozen=True) +class CrystalSetup: + r"""A Type I SHG crystal as mounted in the FROG. + + Give the cut angle and **either** the external tilt **or** the wavelength the + crystal was tuned to phase-match (the usual case: rotated for the strongest + signal, angle not recorded). See the module docstring for the conventions. + + Parameters + ---------- + crystal : UniaxialCrystal + The crystal's indices. + cut_angle : float + Angle between the optic axis and the face normal, :math:`\theta_c` (rad), + in ``[0, pi/2]``. + tilt : float or None, optional + External tilt :math:`\gamma` of the crystal in its principal plane (rad); + positive increases the internal angle to the optic axis. + phase_match_wavelength : float or None, optional + Fundamental vacuum wavelength (m) the crystal is tuned to phase-match; + the tilt follows. + geometry : TwoBeamGeometry or None, optional + The two crossing beams; ``None`` (default) is collinear. + polarization : {"parallel", "perpendicular"} or None, optional + The fundamental polarisation relative to the beams' crossing plane. + Required with a ``geometry``. ``"perpendicular"`` puts the principal plane + (which is perpendicular to the ordinary polarisation) in the crossing + plane, where the neglected signal tilt matters to first order; + ``"parallel"`` makes them perpendicular, where it does not. + + Raises + ------ + ValueError + If not exactly one of ``tilt`` and ``phase_match_wavelength`` is given, + the cut angle is out of range, or ``polarization`` is missing or invalid. + """ + + crystal: UniaxialCrystal + cut_angle: float + tilt: float | None = None + phase_match_wavelength: float | None = None + geometry: TwoBeamGeometry | None = None + polarization: Polarization | None = None + + def __post_init__(self) -> None: + """Validate the angle specification and the geometry.""" + if (self.tilt is None) == (self.phase_match_wavelength is None): + raise ValueError( + "give exactly one of tilt (the external tilt) and " + "phase_match_wavelength (the wavelength the crystal is tuned to)" + ) + if not 0.0 <= self.cut_angle <= 0.5 * math.pi: + raise ValueError( + f"cut_angle must lie in [0, pi/2] rad, got {self.cut_angle!r}" + ) + if self.geometry is not None and self.polarization not in ( + "parallel", + "perpendicular", + ): + raise ValueError( + "with a two-beam geometry give polarization='parallel' or " + "'perpendicular' (the fundamental polarisation relative to the " + f"crossing plane), got {self.polarization!r}" + ) + + @property + def crossing_half_angle(self) -> float: + """External half-angle of the crossing beams (rad); ``0`` if collinear.""" + return 0.0 if self.geometry is None else self.geometry.crossing_half_angle + + def internal_angle(self, omega0: float) -> float: + r"""Return the internal angle :math:`\theta` to the optic axis (rad). + + Parameters + ---------- + omega0 : float + Pulse carrier (rad/s); refracts an explicit ``tilt``, unused when the + crystal is tuned to ``phase_match_wavelength``. + """ + if self.phase_match_wavelength is not None: + return phase_matching_angle( + self.crystal, self.phase_match_wavelength, self.crossing_half_angle + ) + return self.cut_angle + self._refract(float(self.tilt or 0.0), omega0) + + def internal_tilt(self, omega0: float) -> float: + r"""Return the internal tilt :math:`\theta - \theta_c` (rad).""" + return self.internal_angle(omega0) - self.cut_angle + + def external_tilt(self, omega0: float) -> float: + r"""External tilt :math:`\gamma` (rad): the given one, or the one solved.""" + if self.tilt is not None: + return self.tilt + gamma_int = self.internal_tilt(omega0) + n = float(self.crystal.n_o(np.array([self._refraction_wavelength(omega0)]))[0]) + sin_gamma = n * math.sin(gamma_int) + if abs(sin_gamma) > 1.0: + raise ValueError( + f"phase matching at {float(self.phase_match_wavelength or 0) * 1e9:.1f}" + f" nm needs an internal tilt of {math.degrees(gamma_int):.1f} degrees," + f" beyond total internal reflection for this " + f"{math.degrees(self.cut_angle):.1f}-degree cut" + ) + return math.asin(sin_gamma) + + def path_length(self, thickness: float, omega0: float) -> float: + """Path through a plate of ``thickness`` (m): ``thickness / cos(gamma_int)``.""" + return thickness / math.cos(self.internal_tilt(omega0)) + + def _refraction_wavelength(self, omega0: float) -> float: + """Return the wavelength whose ordinary index refracts the tilt (m).""" + if self.phase_match_wavelength is not None: + return self.phase_match_wavelength + return float(wlfreq(omega0)) + + def _refract(self, gamma: float, omega0: float) -> float: + """Refract an external tilt ``gamma`` inside (Snell, ordinary index).""" + n = float(self.crystal.n_o(np.array([self._refraction_wavelength(omega0)]))[0]) + return math.asin(math.sin(gamma) / n) + + +@dataclass(frozen=True) +class Propagation: + """Propagation constants and generation prefactor on a model's grid. + + Attributes + ---------- + beta_in : numpy.ndarray + Fundamental propagation constant (rad/m), centred order. + beta_sig : numpy.ndarray + Signal propagation constant (rad/m), centred order. + sig_amp : numpy.ndarray + Real generation prefactor of the signal, centred order (ones for PG, SD + and a dispersionless medium). + path_length : float + Distance the beams travel through the medium (m). + """ + + beta_in: NDArray[np.float64] + beta_sig: NDArray[np.float64] + sig_amp: NDArray[np.float64] + path_length: float + + +def propagation( + material: str | CrystalSetup | None, + omega: ArrayLike, + omega0: float, + thickness: float, +) -> Propagation: + """Propagation constants of a medium on the centred grid ``omega``. + + Parameters + ---------- + material : str, CrystalSetup or None + A named isotropic material (:func:`croak.materials.beta`, shared by the + fundamental and the signal: PG, SD), a :class:`CrystalSetup` (SHG), or + ``None`` for a dispersionless medium. + omega : array_like + Centred angular-frequency grid (rad/s). + omega0 : float + Pulse carrier (rad/s). + thickness : float + Plate thickness (m). + + Returns + ------- + Propagation + The two propagation constants, the prefactor and the path length. + """ + omega = np.asarray(omega, dtype=float) + if not isinstance(material, CrystalSetup): + beta = materials.beta(material, omega, omega0) + return Propagation(beta, beta, np.ones_like(omega), float(thickness)) + setup = material + theta = setup.internal_angle(omega0) + sin_alpha = math.sin(setup.crossing_half_angle) + crystal = setup.crystal + with np.errstate(divide="ignore", invalid="ignore"): + k_in = _k_fundamental(crystal, omega + omega0, sin_alpha) + k_sig = _k_signal(crystal, omega + 2.0 * omega0, theta) + beta1 = _group_delay(crystal, omega0, sin_alpha) + beta_in = k_in - beta1 * omega + beta_sig = k_sig - beta1 * omega + # Prefactor omega_s / n_s, normalised at the carrier 2*omega0 (k_s = omega n / c, + # so omega/n = omega^2 / (c k_s)). + omega_s = omega + 2.0 * omega0 + k_s0 = float(_k_signal(crystal, np.array([2.0 * omega0]), theta)[0]) + with np.errstate(divide="ignore", invalid="ignore"): + sig_amp = (omega_s**2 / k_sig) / ((2.0 * omega0) ** 2 / k_s0) + # As materials.beta: a non-positive frequency or one outside the indices' range + # carries no light; zero it rather than let NaN reach the FFTs. The positivity + # masks are explicit because a Sellmeier formula, even in lambda^2, returns a + # finite (meaningless) index at a negative "wavelength". + beta_in[~(np.isfinite(beta_in) & (omega + omega0 > 0))] = 0.0 + bad_sig = ~(np.isfinite(beta_sig) & np.isfinite(sig_amp) & (omega_s > 0)) + beta_sig[bad_sig] = 0.0 + sig_amp[bad_sig] = 0.0 + return Propagation( + beta_in, beta_sig, sig_amp, setup.path_length(float(thickness), omega0) + ) + + +def _group_delay(crystal: UniaxialCrystal, omega0: float, sin_alpha: float) -> float: + r""":math:`\beta_1 = \mathrm d k_z/\mathrm d\omega` at ``omega0`` (s/m).""" + + def k(w: float) -> float: + return float(_k_fundamental(crystal, np.array([w]), sin_alpha)[0]) + + return derivative(k, float(omega0), order=1) + + +def _pair_mismatch( + setup: CrystalSetup, omega: NDArray[np.float64], omega0: float +) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64], float]: + """Mismatch over the grid's component pairs that land on the signal grid. + + Returns ``(dk, w1, w2, theta)`` for every pair ``(w1, w2)`` of grid + frequencies (subsampled to :data:`_PAIR_GRID`) whose sum lies on the signal + grid; aliased pairs and frequencies without a finite index are dropped. + """ + grid = ( + omega + if omega.size <= _PAIR_GRID + else np.linspace(omega.min(), omega.max(), _PAIR_GRID) + ) + half = float(np.max(np.abs(omega))) + o1, o2 = np.meshgrid(grid, grid) + keep = np.abs(o1 + o2) <= half + w1 = o1[keep] + omega0 + w2 = o2[keep] + omega0 + theta = setup.internal_angle(omega0) + sin_alpha = math.sin(setup.crossing_half_angle) + crystal = setup.crystal + with np.errstate(divide="ignore", invalid="ignore"): + dk = ( + _k_signal(crystal, w1 + w2, theta) + - _k_fundamental(crystal, w1, sin_alpha) + - _k_fundamental(crystal, w2, sin_alpha) + ) + ok = np.isfinite(dk) & (w1 > 0) & (w2 > 0) + return dk[ok], w1[ok], w2[ok], theta + + +def depth_points( + setup: CrystalSetup, omega: ArrayLike, omega0: float, thickness: float +) -> int: + r"""Gauss–Legendre depth nodes needed to resolve the crystal's phase mismatch. + + The depth integral of one component pair is :math:`\int_0^L e^{-i\Delta k z} + \mathrm dz`, an oscillation of :math:`2\varphi` rad with + :math:`\varphi = |\Delta k| L/2`. Gauss–Legendre with :math:`n` nodes + integrates it to an absolute error below :math:`10^{-6}` of :math:`L` once + :math:`n \ge \lceil\varphi\rceil + 3` (checked for :math:`0.5 \le \varphi \le + 60` in ``tests/test_crystals.py``). :math:`\varphi` is the maximum over every + pair of grid frequencies that lands on the signal grid, so the rule holds + wherever the retrieved field puts energy. + + Parameters + ---------- + setup : CrystalSetup + The crystal. + omega : array_like + Centred angular-frequency grid (rad/s). + omega0 : float + Pulse carrier (rad/s). + thickness : float + Plate thickness (m). + + Returns + ------- + int + The number of nodes; ``1`` for a zero thickness. + """ + if thickness == 0.0: + return 1 + dk, *_ = _pair_mismatch(setup, np.asarray(omega, dtype=float), omega0) + phi = float(np.max(np.abs(dk))) * setup.path_length(thickness, omega0) / 2.0 + return math.ceil(phi) + 3 + + +def tilt_phase_error( + setup: CrystalSetup, omega: ArrayLike, omega0: float, thickness: float +) -> float: + r"""Largest phase of the neglected signal tilt over the grid (rad). + + The signal of the pair :math:`(\omega_1,\omega_2)` leaves at + :math:`\delta\theta = (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to the + bisector. In the principal plane (``polarization="perpendicular"``) that + changes its index by :math:`(\mathrm dn_e/\mathrm d\theta)\,\delta\theta`, and its + phase over the half-path by :math:`(\omega_s/c)(\mathrm dn_e/\mathrm + d\theta)\,\delta\theta\, L/2`. Out of the principal plane + (``"parallel"``), or collinear, the first-order term vanishes and this returns + ``0``. + + Parameters + ---------- + setup : CrystalSetup + The crystal. + omega : array_like + Centred angular-frequency grid (rad/s). + omega0 : float + Pulse carrier (rad/s). + thickness : float + Plate thickness (m). + + Returns + ------- + float + The estimate, maximised over the grid's component pairs (an upper bound on + what a field confined to part of the grid sees). + """ + if setup.geometry is None or setup.polarization != "perpendicular" or not thickness: + return 0.0 + _, w1, w2, theta = _pair_mismatch(setup, np.asarray(omega, dtype=float), omega0) + ws = w1 + w2 + lam = wlfreq(ws) + n_o, n_e = setup.crystal.n_o(lam), setup.crystal.n_e(lam) + n_s = extraordinary_index(n_o, n_e, theta) + dtheta = (w1 - w2) * math.sin(setup.crossing_half_angle) / (ws * n_s) + phase = ws / C * np.abs(_dn_dtheta(n_o, n_e, theta) * dtheta) + return float(np.max(phase)) * setup.path_length(thickness, omega0) / 2.0 + + +def check_medium( + interaction: Interaction, + material: str | CrystalSetup | None, + thickness: float, + npoints: int, + omega: ArrayLike, + omega0: float, +) -> None: + r"""Check that a medium suits the interaction; the forward models' shared guard. + + Parameters + ---------- + interaction : Interaction + The nonlinear interaction. + material : str, CrystalSetup or None + The medium (see :func:`propagation`). + thickness : float + Plate thickness (m). + npoints : int + Depth quadrature nodes the model will use. + omega : array_like + Centred angular-frequency grid (rad/s). + omega0 : float + Pulse carrier (rad/s). + + Raises + ------ + ValueError + If an isotropic slab is given for SHG (its signal lies near + :math:`2\omega_0`, outside a material's single propagation constant), a + crystal for an interaction other than SHG, or too few depth nodes for the + crystal's phase mismatch (see :func:`depth_points`). + + Warns + ----- + CrystalApproximationWarning + If the neglected signal-tilt phase (:func:`tilt_phase_error`) exceeds + :data:`TILT_PHASE_WARN`. + """ + is_crystal = isinstance(material, CrystalSetup) + if interaction.omega0_scale != 1.0 and material is not None and thickness: + if not is_crystal: + raise ValueError( + f"dispersive propagation in an isotropic slab ({material!r}) " + f"cannot model {interaction.name.upper()}: its signal lies near " + f"{interaction.omega0_scale:g}x the carrier, so it needs its own " + f"propagation constant; give a croak.crystals.CrystalSetup" + ) + if is_crystal and interaction.name != "shg": + raise ValueError( + f"a CrystalSetup models Type I SHG only, not " + f"{interaction.name.upper()}; give a material name for a " + f"{interaction.name.upper()} slab" + ) + if not is_crystal or not thickness: + return + needed = depth_points(material, omega, omega0, thickness) + if npoints < needed: + raise ValueError( + f"{npoints} depth nodes under-resolve the crystal's phase mismatch over " + f"this grid: use npoints >= {needed} (croak.crystals.depth_points)" + ) + error = tilt_phase_error(material, omega, omega0, thickness) + if error > TILT_PHASE_WARN: + warnings.warn( + f"the crystal model neglects the signal's tilt in the principal plane, " + f"which here shifts the phase of the widest component pairs by up to " + f"{error:.2f} rad (above {TILT_PHASE_WARN} rad): the model is " + f"approximate in the spectral wings. A thinner crystal, a smaller " + f"crossing angle, or the fundamental polarised in the crossing plane " + f"avoids it", + CrystalApproximationWarning, + stacklevel=3, + ) diff --git a/croak/forward.py b/croak/forward.py index 5b8e5cb..6f39851 100644 --- a/croak/forward.py +++ b/croak/forward.py @@ -34,7 +34,8 @@ from numpy.polynomial.legendre import leggauss from numpy.typing import ArrayLike, NDArray -from . import materials +from . import crystals +from .crystals import CrystalSetup from .interactions import Interaction, get_interaction from .smearing import SmearingKernel, delay_frequency_grid @@ -88,7 +89,7 @@ def quadrature_nodes_weights( class ForwardModel: - """Nonlinear-process forward map and adjoint for fixed grid/delays/interaction. + r"""Nonlinear-process forward map and adjoint for fixed grid/delays/interaction. Parameters ---------- @@ -98,13 +99,19 @@ class ForwardModel: Delay axis (s). interaction : str or Interaction Nonlinear interaction (``"shg"``, ``"sd"``, ``"pg"``). - material : str or None, optional - Dispersive material for the slab (e.g. ``"SiO2"``); ``None`` (default) - is a thin, dispersionless medium. + material : str, CrystalSetup or None, optional + The medium: a material name for a PG/SD slab (e.g. ``"SiO2"``), whose + fundamental and signal share one propagation constant; a + :class:`~croak.crystals.CrystalSetup` for SHG in a Type I crystal, whose + signal propagates as the extraordinary wave near :math:`2\omega_0` + (see :mod:`croak.crystals`); or ``None`` (default), a thin, + dispersionless medium. thickness : float, optional - Slab thickness (m). Default ``0``. + Slab thickness (m), along the face normal for a tilted crystal. Default + ``0``. npoints : int, optional - Number of depth quadrature points (default ``1``). + Number of depth quadrature points (default ``1``). A crystal needs at + least :func:`croak.crystals.depth_points`. omega0 : float, optional Carrier angular frequency (rad/s), used to build ``beta``. quadrature : str, optional @@ -130,7 +137,7 @@ def __init__( delays: ArrayLike, interaction: str | Interaction, *, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 1, omega0: float = 0.0, @@ -147,30 +154,32 @@ def __init__( self.thickness = float(thickness) self.omega0 = float(omega0) - # The slab propagation phase β(ω) is built at the *fundamental* carrier, - # but the SHG signal lives near 2ω0 — propagating it with β(ω) is - # physically inconsistent. Dispersive propagation is only meaningful for - # interactions whose signal stays at the fundamental (PG, SD). - if material is not None and thickness and self.interaction.omega0_scale != 1.0: - raise ValueError( - f"dispersive propagation is not supported for the " - f"{self.interaction.name.upper()} interaction (its signal is not at " - f"the fundamental frequency); use a thin medium (material=None)" - ) + # An SHG signal lives near 2ω0, so it needs its own propagation constant: + # only a crystal supplies one (croak.crystals). PG/SD share the material's. + crystals.check_medium( + self.interaction, material, self.thickness, npoints, self.omega, omega0 + ) + prop = crystals.propagation(material, self.omega, omega0, self.thickness) + self.path_length = prop.path_length # Work internally in DFT-bin order. self.omega_bin = scipy.fft.ifftshift(self.omega) - beta = materials.beta(material, self.omega, omega0) - beta_bin = scipy.fft.ifftshift(beta) + beta_in_bin = scipy.fft.ifftshift(prop.beta_in) + beta_sig_bin = scipy.fft.ifftshift(prop.beta_sig) + sig_amp_bin = scipy.fft.ifftshift(prop.sig_amp) - nodes, weights = quadrature_nodes_weights(self.thickness, npoints, quadrature) + # Depth runs along the beams' path, longer than the plate in a tilted crystal. + nodes, weights = quadrature_nodes_weights(self.path_length, npoints, quadrature) self.nodes = nodes self.weights = weights self.q = nodes.size - # Propagation phase matrices, shape (N, Q), in DFT-bin order. - self.input_prop = np.exp(1j * np.outer(beta_bin, nodes)) - self.signal_prop = np.exp(1j * np.outer(beta_bin, self.thickness - nodes)) + # Propagation phase matrices, shape (N, Q), in DFT-bin order: the field + # travels to depth z_q, the signal born there travels the rest of the path. + self.input_prop = np.exp(1j * np.outer(beta_in_bin, nodes)) + self.signal_prop = sig_amp_bin[:, None] * np.exp( + 1j * np.outer(beta_sig_bin, self.path_length - nodes) + ) # Geometric smearing. The (p, delta) statistics are independent of depth — the # pulse-front tilts are set before the medium and the longitudinal walk-off @@ -362,7 +371,7 @@ def maketrace( ew: Complex, interaction: str | Interaction, *, - material: str | None = None, + material: str | CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 1, omega0: float = 0.0, diff --git a/croak/forward_jax.py b/croak/forward_jax.py index 6a76d8e..e26d883 100644 --- a/croak/forward_jax.py +++ b/croak/forward_jax.py @@ -45,7 +45,10 @@ import numpy as np # noqa: E402 - must follow the x64 update above from numpy.typing import ArrayLike, NDArray # noqa: E402 - see the x64 note above -from . import materials # noqa: E402 - binds jax.numpy; see the x64 note above +from . import ( # noqa: E402 - binds jax.numpy; see the x64 note above + crystals, + materials, +) from .collection import ( # noqa: E402 - see the x64 note above CollectionAperture, transform_phases, @@ -129,6 +132,25 @@ def _smear_scale_pair(smear_scale) -> tuple[jnp.ndarray, jnp.ndarray]: return s[0], s[1] +def _static_props(material, omega, omega0, thickness, npoints, quadrature): + """``(input_prop, signal_prop, weights)`` for a fixed medium, as ForwardModel. + + Propagation phase matrices ``(N, Q)`` in DFT-bin order: the field travels to + depth ``z_q``, the signal born there the rest of the path, which in a tilted + crystal is longer than the plate (:mod:`croak.crystals`). + """ + prop = crystals.propagation(material, omega, omega0, thickness) + nodes, weights = quadrature_nodes_weights(prop.path_length, npoints, quadrature) + beta_in = np.fft.ifftshift(prop.beta_in) + beta_sig = np.fft.ifftshift(prop.beta_sig) + sig_amp = np.fft.ifftshift(prop.sig_amp) + input_prop = np.exp(1j * np.outer(beta_in, nodes)) + signal_prop = sig_amp[:, None] * np.exp( + 1j * np.outer(beta_sig, prop.path_length - nodes) + ) + return input_prop, signal_prop, weights + + class _SignalConstants: """Static problem geometry shared by the JAX forward signal and its adjoint. @@ -152,22 +174,13 @@ def __init__( self, omega, interaction, *, material, thickness, npoints, omega0, quadrature ): inter = get_interaction(interaction) - # Same physical guard as ForwardModel: a slab built at the fundamental - # cannot consistently propagate an SHG signal that lives near 2*omega0. - if material is not None and thickness and inter.omega0_scale != 1.0: - raise ValueError( - f"dispersive propagation is not supported for the " - f"{inter.name.upper()} interaction (its signal is not at the " - f"fundamental frequency); use a thin medium (material=None)" - ) omega = np.asarray(omega, dtype=float) + # Same guard and propagation as ForwardModel (croak.crystals). + crystals.check_medium(inter, material, float(thickness), npoints, omega, omega0) omega_bin = np.fft.ifftshift(omega) - beta = materials.beta(material, omega, omega0) - beta_bin = np.fft.ifftshift(beta) - nodes, weights = quadrature_nodes_weights(float(thickness), npoints, quadrature) - # Propagation phase matrices (N, Q), DFT-bin order — identical to ForwardModel. - input_prop = np.exp(1j * np.outer(beta_bin, nodes)) - signal_prop = np.exp(1j * np.outer(beta_bin, float(thickness) - nodes)) + input_prop, signal_prop, weights = _static_props( + material, omega, omega0, float(thickness), npoints, quadrature + ) self.inter = inter self.n = int(omega.size) @@ -236,7 +249,7 @@ def make_signal_fn( delays: ArrayLike, interaction: str, *, - material: str | None = None, + material: str | crystals.CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 1, omega0: float = 0.0, @@ -289,7 +302,7 @@ def make_forward_adjoint_fns( delays: ArrayLike, interaction: str, *, - material: str | None = None, + material: str | crystals.CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 1, omega0: float = 0.0, @@ -350,7 +363,7 @@ def make_trace_fn( delays: ArrayLike, interaction: str, *, - material: str | None = None, + material: str | crystals.CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 1, omega0: float = 0.0, @@ -511,7 +524,7 @@ def make_param_trace_fn( *, depth_weight: ArrayLike | None = None, depth_node_phase: ArrayLike | None = None, - material: str | None = None, + material: str | crystals.CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 1, omega0: float = 0.0, @@ -647,14 +660,29 @@ def make_param_trace_fn( f"geometrical smearing is not supported for the {inter.name.upper()} " f"interaction; only PG (TG) and SD have the required three-arm form" ) - # Same physical guard as the forward model: a slab built at the fundamental - # cannot consistently propagate a signal that lives away from omega0 (SHG). - if material is not None and thickness and inter.omega0_scale != 1.0: - raise ValueError( - f"dispersive propagation is not supported for the " - f"{inter.name.upper()} interaction (its signal is not at the " - f"fundamental frequency); use a thin medium (material=None)" - ) + # Same guard as the forward model: SHG needs a crystal (croak.crystals). + crystals.check_medium( + inter, material, float(thickness), npoints, np.asarray(omega, float), omega0 + ) + # The paths below that build on a single propagation constant (thickness + # fitting, the focal mixture, depth_transverse) take the isotropic slab only. + slab = None if isinstance(material, crystals.CrystalSetup) else material + if isinstance(material, crystals.CrystalSetup): + refused = [ + name + for name, on in ( + ("fit_thickness", fit_thickness), + ("focal", focal is not None), + ("depth_transverse", depth_transverse), + ) + if on + ] + if refused: + raise ValueError( + f"the SHG crystal model does not support {', '.join(refused)}: " + f"these are built for an isotropic slab's single propagation " + f"constant (PG/SD)" + ) if fit_thickness and (material is None or thickness <= 0.0): raise ValueError( "fitting thickness requires a dispersive slab " @@ -718,7 +746,7 @@ def make_param_trace_fn( "footprint (a large chromatic hole, or a wide chromatic=False " "k window) instead of collection=None" ) - if material is None or thickness <= 0.0: + if slab is None or thickness <= 0.0: raise ValueError( "depth_transverse requires a dispersive slab (material set and " "thickness > 0): the phase accumulates over the remaining " @@ -726,7 +754,7 @@ def make_param_trace_fn( ) g_dt = _depth_phase_rate( focal.collection, - material, + slab, np.asarray(omega, dtype=float) + float(omega0), ) # Depth-resolved mixture (fc-z): the mixture's EvolveSpec must agree with @@ -760,15 +788,15 @@ def make_param_trace_fn( f"must sit on the same depth nodes as the propagation phases" ) omega = np.asarray(omega, dtype=float) - beta_bin_np = np.fft.ifftshift(materials.beta(material, omega, omega0)) omega_bin = jnp.asarray(np.fft.ifftshift(omega)) - beta_bin = jnp.asarray(beta_bin_np) signal_map = _JAX_INTERACTIONS[inter.name] delays_j = jnp.asarray(np.asarray(delays, dtype=float)) if fit_thickness: # Normalised quadrature on [0, 1]; thickness scales the nodes/weights at - # call time, keeping the depth integral differentiable in L. + # call time, keeping the depth integral differentiable in L. An isotropic + # slab only (a crystal is refused above), so one beta serves both fields. + beta_bin = jnp.asarray(np.fft.ifftshift(materials.beta(slab, omega, omega0))) nodes0, weights0 = quadrature_nodes_weights(1.0, npoints, quadrature) xi = jnp.asarray(nodes0) w_hat = jnp.asarray(weights0) @@ -786,14 +814,14 @@ def depth_remaining(thk: jnp.ndarray | float) -> jnp.ndarray: else: # Thickness held fixed: bake the propagation matrices once, exactly as the # standard forward model (handles the thin single-node case). - nodes0, weights0 = quadrature_nodes_weights( - float(thickness), npoints, quadrature - ) - input_prop_c = jnp.asarray(np.exp(1j * np.outer(beta_bin_np, nodes0))) - signal_prop_c = jnp.asarray( - np.exp(1j * np.outer(beta_bin_np, float(thickness) - nodes0)) + input_np, signal_np, weights0 = _static_props( + material, omega, omega0, float(thickness), npoints, quadrature ) + input_prop_c = jnp.asarray(input_np) + signal_prop_c = jnp.asarray(signal_np) weights_c = jnp.asarray(weights0) if dw is None else jnp.asarray(weights0) * dw + # depth_transverse only (refused for a crystal), so the path is the plate + nodes0, _ = quadrature_nodes_weights(float(thickness), npoints, quadrature) remaining_c = jnp.asarray(float(thickness) - np.asarray(nodes0)) def props(thk: jnp.ndarray | float): @@ -1142,7 +1170,7 @@ def maketrace_jax( ew: Complex, interaction: str, *, - material: str | None = None, + material: str | crystals.CrystalSetup | None = None, thickness: float = 0.0, npoints: int = 1, omega0: float = 0.0, diff --git a/croak/geometry.py b/croak/geometry.py new file mode 100644 index 0000000..4620b8f --- /dev/null +++ b/croak/geometry.py @@ -0,0 +1,71 @@ +r"""The two-beam (non-collinear SHG) geometry, the one source of the crossing angle. + +A non-collinear SHG FROG splits the pulse into two parallel, collimated beams a +distance ``beam_separation`` apart and focuses both with one optic of focal length +``focal_length``. They cross at the focus with the external half-angle + +.. math:: \alpha = \arctan\!\left(\frac{d}{2f}\right), + +each beam at :math:`\pm\alpha` to their bisector, along which the signal leaves. +The same :math:`\alpha` sets two effects: the phase mismatch of the crystal (the +fundamentals' longitudinal wavevector shrinks as :math:`\cos\alpha`; see +:mod:`croak.crystals`) and the delay smearing across the focal spot. Both read it +from one :class:`TwoBeamGeometry`, so they can never use different angles. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +__all__ = ["TwoBeamGeometry"] + + +@dataclass(frozen=True) +class TwoBeamGeometry: + """Two parallel beams focused to cross by one optic. + + Parameters + ---------- + beam_separation : float + Centre-to-centre distance of the two beams at the focusing optic (m), + ``> 0``. + focal_length : float + Focal length of the focusing optic (m), ``> 0``. + beam_diameter : float or None, optional + 1/e² intensity diameter of each (Gaussian) beam at the focusing optic (m), + ``> 0``. Only the delay-smearing kernel needs it; ``None`` (default) when + smearing is not modelled. + + Raises + ------ + ValueError + If a length is not finite and positive. + + Examples + -------- + >>> g = TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1) + >>> round(math.degrees(g.crossing_half_angle), 3) + 1.432 + """ + + beam_separation: float + focal_length: float + beam_diameter: float | None = None + + def __post_init__(self) -> None: + """Validate the lengths.""" + lengths = { + "beam_separation": self.beam_separation, + "focal_length": self.focal_length, + } + if self.beam_diameter is not None: + lengths["beam_diameter"] = self.beam_diameter + for name, value in lengths.items(): + if not (math.isfinite(value) and value > 0.0): + raise ValueError(f"{name} must be finite and positive, got {value!r}") + + @property + def crossing_half_angle(self) -> float: + """External half-angle between each beam and their bisector (rad).""" + return math.atan(0.5 * self.beam_separation / self.focal_length) diff --git a/tests/test_crystals.py b/tests/test_crystals.py new file mode 100644 index 0000000..bea09b1 --- /dev/null +++ b/tests/test_crystals.py @@ -0,0 +1,275 @@ +"""Type I SHG crystal: indices, angles, propagation constants, depth resolution. + +The crystal used throughout is a three-term Sellmeier pair with BBO-like +coefficients (Tamošauskas et al., Opt. Mater. Express 8, 1410 (2018), Eq. (1)), +written out here so the tests do not depend on a material registry. They are a +realistic negative uniaxial crystal; the physics tested does not depend on their +exact values. +""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest +from numpy.polynomial.legendre import leggauss + +from croak import crystals +from croak.constants import C +from croak.crystals import CrystalSetup, UniaxialCrystal +from croak.geometry import TwoBeamGeometry +from croak.grid import Grid +from croak.maths import wlfreq + + +def _sellmeier(b, c): + def n(lam): + l2 = (np.asarray(lam, dtype=float) * 1e6) ** 2 + return np.sqrt(1.0 + sum(bi * l2 / (l2 - ci) for bi, ci in zip(b, c))) + + return n + + +BBO = UniaxialCrystal( + "BBO-like", + _sellmeier((0.90291, 0.83155, 0.76536), (0.003926, 0.018786, 60.01)), + _sellmeier((1.151075, 0.21803, 0.656), (0.007142, 0.02259, 263.0)), +) +W0 = float(wlfreq(800e-9)) +GRID = Grid(256, dt=3.0e-15) # spans roughly 560-1400 nm around 800 nm + + +def _tuned(**kw) -> CrystalSetup: + return CrystalSetup(BBO, math.radians(29.2), phase_match_wavelength=800e-9, **kw) + + +def _sinc_integral(phi): + """(1/L) * integral_0^L exp(2 i phi z / L) dz, exactly.""" + return np.where(phi == 0, 1.0, (np.exp(2j * phi) - 1.0) / (2j * phi)) + + +# -- indices and angles --------------------------------------------------------- +def test_extraordinary_index_limits(): + assert crystals.extraordinary_index(1.6, 1.5, 0.0) == pytest.approx(1.6) + assert crystals.extraordinary_index(1.6, 1.5, np.pi / 2) == pytest.approx(1.5) + # 1/n^2 is linear in sin^2(theta): halfway at 45 degrees + n45 = crystals.extraordinary_index(1.6, 1.5, np.pi / 4) + assert 1 / n45**2 == pytest.approx(0.5 / 1.6**2 + 0.5 / 1.5**2) + + +def test_dn_dtheta_matches_a_finite_difference(): + theta, h = 0.5, 1e-6 + fd = ( + crystals.extraordinary_index(1.66, 1.55, theta + h) + - crystals.extraordinary_index(1.66, 1.55, theta - h) + ) / (2 * h) + # central difference error ~h^2 * n''' ~ 1e-12; float rounding ~1e-10 + assert crystals._dn_dtheta(1.66, 1.55, theta) == pytest.approx(fd, rel=1e-8) + + +def test_phase_matching_angle_of_800_nm(): + # Tamosauskas et al. cut their type I crystal at 29.2 degrees for SHG of 800 nm + # and state their angles within 0.2 degrees of the measured ones (pp. 1413, 1416). + theta = crystals.phase_matching_angle(BBO, 800e-9) + assert math.degrees(theta) == pytest.approx(29.2, abs=0.2) + omega = np.array([W0]) + dk = crystals._k_signal(BBO, 2 * omega, theta) - 2 * crystals._k_fundamental( + BBO, omega, 0.0 + ) + assert abs(dk[0]) < 1e-6 # rad/m, against k ~ 2.6e7: brentq's xtol + + +def test_crossing_raises_the_phase_matching_angle(): + # k_z = k_o cos(alpha_int) < k_o, so the signal needs a smaller index: theta grows. + collinear = crystals.phase_matching_angle(BBO, 800e-9) + crossed = crystals.phase_matching_angle(BBO, 800e-9, math.radians(2.0)) + assert crossed > collinear + + +def test_phase_matching_angle_raises_without_a_solution(): + # Below ~410 nm BBO cannot phase-match type I SHG (its UV absorption edge). + with pytest.raises(ValueError, match="cannot phase-match"): + crystals.phase_matching_angle(BBO, 380e-9) + + +# -- the setup ------------------------------------------------------------------ +def test_setup_needs_exactly_one_angle_specification(): + with pytest.raises(ValueError, match="exactly one of tilt"): + CrystalSetup(BBO, 0.5) + with pytest.raises(ValueError, match="exactly one of tilt"): + CrystalSetup(BBO, 0.5, tilt=0.0, phase_match_wavelength=800e-9) + + +def test_setup_rejects_a_cut_angle_out_of_range(): + with pytest.raises(ValueError, match="cut_angle"): + CrystalSetup(BBO, -0.1, tilt=0.0) + + +@pytest.mark.parametrize("polarization", [None, "vertical"]) +def test_setup_with_a_geometry_needs_a_polarization(polarization): + geometry = TwoBeamGeometry(5e-3, 0.1) + with pytest.raises(ValueError, match="polarization"): + CrystalSetup(BBO, 0.5, tilt=0.0, geometry=geometry, polarization=polarization) + + +def test_explicit_tilt_refracts_with_snell(): + setup = CrystalSetup(BBO, math.radians(29.0), tilt=math.radians(10.0)) + n = float(BBO.n_o(np.array([800e-9]))[0]) + gamma_int = math.asin(math.sin(math.radians(10.0)) / n) + assert setup.internal_angle(W0) == pytest.approx(math.radians(29.0) + gamma_int) + assert setup.external_tilt(W0) == math.radians(10.0) + assert setup.path_length(10e-6, W0) == pytest.approx(10e-6 / math.cos(gamma_int)) + + +def test_tuned_setup_solves_the_tilt_consistently(): + setup = _tuned() + theta = setup.internal_angle(W0) + gamma = setup.external_tilt(W0) + # re-tilting by the solved external angle lands on the same internal angle + again = CrystalSetup(BBO, math.radians(29.2), tilt=gamma) + n_pm = float(BBO.n_o(np.array([800e-9]))[0]) + assert again.cut_angle + math.asin(math.sin(gamma) / n_pm) == pytest.approx(theta) + assert setup.internal_tilt(W0) == pytest.approx(theta - math.radians(29.2)) + + +def test_tuning_beyond_total_internal_reflection_raises(): + # a 0-degree cut tuned to 800 nm needs ~29 degrees inside: n sin(29) > 1? no, + # but a 80-degree cut needs ~-51 degrees inside, which no external angle gives. + setup = CrystalSetup(BBO, math.radians(80.0), phase_match_wavelength=800e-9) + with pytest.raises(ValueError, match="total internal reflection"): + setup.external_tilt(W0) + + +# -- propagation constants ------------------------------------------------------- +def test_isotropic_material_shares_one_beta(): + prop = crystals.propagation("SiO2", GRID.omega, W0, 10e-6) + np.testing.assert_array_equal(prop.beta_in, prop.beta_sig) + np.testing.assert_array_equal(prop.sig_amp, 1.0) + assert prop.path_length == 10e-6 + + +def test_no_material_is_dispersionless(): + prop = crystals.propagation(None, GRID.omega, W0, 0.0) + np.testing.assert_array_equal(prop.beta_in, 0.0) + + +def test_crystal_propagation_carries_the_exact_mismatch(): + # beta_sig(O1+O2) - beta_in(O1) - beta_in(O2) must equal the physical mismatch + # k_s(w1+w2) - k_z(w1) - k_z(w2): the frame terms cancel exactly. + setup = _tuned( + geometry=TwoBeamGeometry(5e-3, 0.1), polarization="parallel" + ) + prop = crystals.propagation(setup, GRID.omega, W0, 10e-6) + i1, i2 = 128 + 10, 128 - 25 # centred indices of two grid frequencies + i_s = i1 + i2 - 128 # their sum on the centred grid + model = prop.beta_sig[i_s] - prop.beta_in[i1] - prop.beta_in[i2] + w1, w2 = GRID.omega[i1] + W0, GRID.omega[i2] + W0 + theta = setup.internal_angle(W0) + sin_a = math.sin(setup.crossing_half_angle) + physical = ( + crystals._k_signal(BBO, np.array([w1 + w2]), theta) + - crystals._k_fundamental(BBO, np.array([w1]), sin_a) + - crystals._k_fundamental(BBO, np.array([w2]), sin_a) + )[0] + # absolute rounding: three wavevectors ~2.6e7 rad/m at 1e-16 relative + assert model == pytest.approx(physical, abs=1e-6 * 2.6e7 * 1e-6) + # and at the carrier pair the tuned crystal is phase-matched + assert prop.beta_sig[128] - 2 * prop.beta_in[128] == pytest.approx(0.0, abs=1e-6) + + +def test_crystal_prefactor_is_omega_over_n_normalised_at_the_carrier(): + setup = _tuned() + prop = crystals.propagation(setup, GRID.omega, W0, 10e-6) + assert prop.sig_amp[128] == pytest.approx(1.0) + theta = setup.internal_angle(W0) + ws = GRID.omega[140] + 2 * W0 + lam = wlfreq(ws) + n_s = crystals.extraordinary_index(BBO.n_o(lam), BBO.n_e(lam), theta) + lam0 = wlfreq(2 * W0) + n_0 = crystals.extraordinary_index(BBO.n_o(lam0), BBO.n_e(lam0), theta) + assert prop.sig_amp[140] == pytest.approx((ws / n_s) / (2 * W0 / n_0), rel=1e-12) + + +def test_crystal_propagation_zeroes_frequencies_without_light(): + # a grid wide enough to reach negative absolute frequency at its low edge + grid = Grid(64, dt=0.05e-15) + prop = crystals.propagation(_tuned(), grid.omega, W0, 10e-6) + dark = grid.omega + W0 <= 0 + assert dark.any() + assert np.all(prop.beta_in[dark] == 0.0) + assert np.all(np.isfinite(prop.beta_in) & np.isfinite(prop.beta_sig)) + + +# -- depth resolution ------------------------------------------------------------ +@pytest.mark.parametrize("phi", [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 40.0, 60.0]) +def test_depth_rule_resolves_the_oscillation(phi): + # The rule depth_points uses, n = ceil(phi) + 3, integrates exp(2 i phi x) over + # [0, 1] to below 1e-6 (the accuracy the docstring promises). + n = math.ceil(phi) + 3 + x, w = leggauss(n) + x, w = 0.5 * (x + 1.0), 0.5 * w + numeric = np.sum(w * np.exp(2j * phi * x)) + assert abs(numeric - _sinc_integral(np.array(phi))) < 1e-6 + + +def test_depth_points_grow_with_thickness(): + setup = _tuned() + assert crystals.depth_points(setup, GRID.omega, W0, 0.0) == 1 + thin = crystals.depth_points(setup, GRID.omega, W0, 10e-6) + thick = crystals.depth_points(setup, GRID.omega, W0, 100e-6) + assert 3 < thin < thick + # the mismatch scales with L, so phi does too (up to the +3 and the ceiling) + assert thick - 3 == pytest.approx(10 * (thin - 3), abs=10) + + +def test_depth_points_subsample_a_fine_grid(): + setup = _tuned() + fine = Grid(1024, dt=3.0e-15) # the same band as GRID, four times the points + assert crystals.depth_points(setup, fine.omega, W0, 50e-6) == pytest.approx( + crystals.depth_points(setup, GRID.omega, W0, 50e-6), abs=1 + ) + + +# -- the neglected signal tilt ---------------------------------------------------- +def test_tilt_phase_error_vanishes_out_of_the_principal_plane(): + geometry = TwoBeamGeometry(5e-3, 0.1) + parallel = _tuned(geometry=geometry, polarization="parallel") + assert crystals.tilt_phase_error(parallel, GRID.omega, W0, 100e-6) == 0.0 + assert crystals.tilt_phase_error(_tuned(), GRID.omega, W0, 100e-6) == 0.0 + perpendicular = _tuned(geometry=geometry, polarization="perpendicular") + assert crystals.tilt_phase_error(perpendicular, GRID.omega, W0, 0.0) == 0.0 + + +def test_tilt_phase_error_scales_with_thickness_and_angle(): + def error(separation, thickness): + setup = _tuned( + geometry=TwoBeamGeometry(separation, 0.1), polarization="perpendicular" + ) + return crystals.tilt_phase_error(setup, GRID.omega, W0, thickness) + + base = error(3.5e-3, 10e-6) # ~1 degree half-angle + assert base > 0.0 + assert error(3.5e-3, 100e-6) == pytest.approx(10 * base, rel=1e-3) + # linear in sin(alpha) (to the ~1e-3 the solved angle and path move with alpha) + assert error(7.0e-3, 10e-6) == pytest.approx(2 * base, rel=2e-2) + + +def test_tilt_phase_error_matches_a_direct_estimate(): + # One pair, by hand: the grid's extreme pair dominates. + geometry = TwoBeamGeometry(3.5e-3, 0.1) + setup = _tuned(geometry=geometry, polarization="perpendicular") + estimate = crystals.tilt_phase_error(setup, GRID.omega, W0, 100e-6) + theta = setup.internal_angle(W0) + alpha = geometry.crossing_half_angle + half = float(np.max(np.abs(GRID.omega))) + w1, w2 = W0 + half, W0 - half # the widest pair still on the signal grid + ws = w1 + w2 + lam = wlfreq(ws) + n_o, n_e = BBO.n_o(np.array([lam])), BBO.n_e(np.array([lam])) + n_s = crystals.extraordinary_index(n_o, n_e, theta)[0] + dn = crystals._dn_dtheta(n_o, n_e, theta)[0] + by_hand = ws / C * abs(dn) * (w1 - w2) * math.sin(alpha) / (ws * n_s) * 50e-6 + by_hand /= math.cos(setup.internal_tilt(W0)) + # the subsampled pair grid reaches the extreme pair to within a grid step + assert estimate == pytest.approx(by_hand, rel=2e-2) From 40899d42453eefd6226492990c02a75e6df3d535 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 17:08:21 +0000 Subject: [PATCH 02/16] Test the crystal forward models against the exact pair sum The exact double sum over component pairs with the depth integral done analytically, the Parseval form of the frequency marginal (pair sinc^2), the zero-thickness limit, NumPy against JAX, the hand adjoint, the guards, and the neglected signal tilt against a per-pair reference. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- tests/test_forward_crystal.py | 288 ++++++++++++++++++++++++++++++++++ 1 file changed, 288 insertions(+) create mode 100644 tests/test_forward_crystal.py diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py new file mode 100644 index 0000000..ed240f5 --- /dev/null +++ b/tests/test_forward_crystal.py @@ -0,0 +1,288 @@ +"""SHG in a Type I crystal through the forward models. + +The reference throughout is the exact double sum over component pairs: the signal at +grid bin ``k`` is ``sum_j E(j) E_tau(k - j) * amp(k) * H_jk`` with the depth integral +``H_jk = exp(i beta_sig(k) P) * int_0^P exp(i a_jk z) dz`` done analytically +(``a_jk = beta_in(j) + beta_in(k - j) - beta_sig(k)``, ``P`` the path). The models +evaluate the same sum by FFTs and Gauss-Legendre quadrature, so they must agree to the +quadrature's accuracy (:func:`croak.crystals.depth_points`). +""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest +import scipy.fft +from test_crystals import BBO, W0 + +from croak import crystals +from croak.constants import C +from croak.crystals import CrystalApproximationWarning, CrystalSetup +from croak.forward import ForwardModel +from croak.forward_jax import make_param_trace_fn, make_trace_fn +from croak.geometry import TwoBeamGeometry +from croak.grid import Grid + +GRID = Grid(64, dt=3.0e-15) # about 560-1440 nm around 800 nm +GEOMETRY = TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1) # 1.43 degrees + + +def _pulse(g, fwhm=12e-15, gdd=30e-30): + """A chirped Gaussian at the carrier, peak-normalised spectrum.""" + et = np.exp(-0.5 * (g.t / (fwhm / 2.3548)) ** 2).astype(complex) + ew = g.fft(et) * np.exp(0.5j * gdd * g.omega**2) + return ew / np.max(np.abs(ew)) + + +def _setup(**kw) -> CrystalSetup: + return CrystalSetup(BBO, math.radians(29.2), phase_match_wavelength=800e-9, **kw) + + +def _model(setup, thickness, delays, **kw): + npoints = kw.pop("npoints", crystals.depth_points(setup, GRID.omega, W0, thickness)) + return ForwardModel( + GRID.omega, + delays, + "shg", + material=setup, + thickness=thickness, + npoints=npoints, + omega0=W0, + **kw, + ) + + +def _depth_integral(a, path): + """int_0^path exp(i a z) dz, exactly.""" + with np.errstate(divide="ignore", invalid="ignore"): + out = (np.exp(1j * a * path) - 1.0) / (1j * a) + return np.where(np.abs(a * path) < 1e-12, path, out) + + +def _pair_sum(setup, thickness, ew, tau, beta_sig_pair=None): + """Exact double sum over pairs, centred order; ``beta_sig_pair(j, m, k)`` may + replace the signal's propagation constant per pair.""" + prop = crystals.propagation(setup, GRID.omega, W0, thickness) + path = prop.path_length + n = GRID.n + w = scipy.fft.ifftshift(GRID.omega) + b_in = scipy.fft.ifftshift(prop.beta_in) + b_sig = scipy.fft.ifftshift(prop.beta_sig) + amp = scipy.fft.ifftshift(prop.sig_amp) + e = scipy.fft.ifftshift(ew) + e_tau = e * np.exp(1j * w * tau) + j = np.arange(n) + psi = np.zeros(n, dtype=complex) + for k in range(n): + m = (k - j) % n + bs = b_sig[k] if beta_sig_pair is None else beta_sig_pair(j, m, k) + a = b_in[j] + b_in[m] - bs + h = np.exp(1j * bs * path) * _depth_integral(a, path) + psi[k] = amp[k] * np.sum(e[j] * e_tau[m] * h) + return scipy.fft.fftshift(psi) + + +# -- agreement with the exact pair sum ------------------------------------------ +@pytest.mark.parametrize("thickness", [10e-6, 100e-6]) +@pytest.mark.parametrize("tau", [-15e-15, 0.0, 8e-15]) +def test_signal_matches_the_exact_pair_sum(thickness, tau): + setup = _setup(geometry=GEOMETRY, polarization="parallel") + ew = _pulse(GRID) + model = _model(setup, thickness, np.array([tau])) + psi = model.signal_single(ew, tau) + exact = _pair_sum(setup, thickness, ew, tau) + # depth_points promises 1e-6 of the path per pair; summed over at most 64 pairs + # of unit-normalised amplitudes, against a peak of order 10 path lengths. + np.testing.assert_allclose(psi, exact, atol=1e-5 * np.max(np.abs(exact))) + + +def test_too_few_depth_points_are_refused(): + setup = _setup() + needed = crystals.depth_points(setup, GRID.omega, W0, 100e-6) + with pytest.raises(ValueError, match=f"npoints >= {needed}"): + _model(setup, 100e-6, np.array([0.0]), npoints=needed - 1) + + +def test_frequency_marginal_is_the_sum_of_pair_sinc_squares(): + # Over a full period of delays (the grid's own time axis), Parseval turns the + # delay sum of |psi|^2 into N * sum_j |E_j E_m amp H_jk|^2 exactly: the + # pair-resolved phase-matching response sinc^2(a P / 2) (P^2 sinc^2 = |H|^2). + setup = _setup() + thickness = 50e-6 + ew = _pulse(GRID) + model = _model(setup, thickness, GRID.t) + marginal = model.trace(ew, normalize=False).sum(axis=1) + prop = crystals.propagation(setup, GRID.omega, W0, thickness) + path = prop.path_length + e = scipy.fft.ifftshift(ew) + b_in = scipy.fft.ifftshift(prop.beta_in) + b_sig = scipy.fft.ifftshift(prop.beta_sig) + amp = scipy.fft.ifftshift(prop.sig_amp) + j = np.arange(GRID.n) + expected = np.zeros(GRID.n) + for k in range(GRID.n): + m = (k - j) % GRID.n + a = b_in[j] + b_in[m] - b_sig[k] + sinc = np.sinc(a * path / (2 * np.pi)) # np.sinc(x) = sin(pi x) / (pi x) + expected[k] = ( + GRID.n * amp[k] ** 2 * np.sum(np.abs(e[j] * e[m]) ** 2 * (path * sinc) ** 2) + ) + expected = scipy.fft.fftshift(expected) + # quadrature accuracy as above, squared into intensity + np.testing.assert_allclose(marginal, expected, rtol=0, atol=1e-5 * expected.max()) + + +def test_zero_thickness_is_the_ideal_trace_times_the_prefactor(): + setup = _setup() + ew = _pulse(GRID) + delays = np.linspace(-30e-15, 30e-15, 11) + crystal = _model(setup, 0.0, delays).trace(ew, normalize=False) + ideal = ForwardModel(GRID.omega, delays, "shg").trace(ew, normalize=False) + amp = crystals.propagation(setup, GRID.omega, W0, 0.0).sig_amp + np.testing.assert_allclose(crystal, ideal * amp[:, None] ** 2, rtol=1e-12) + + +def test_phase_mismatch_narrows_the_trace_band(): + # A thick crystal tuned to 800 nm passes less of the wings than a thin one. + setup = _setup() + ew = _pulse(GRID, fwhm=6e-15, gdd=0.0) + delays = np.linspace(-20e-15, 20e-15, 9) + + def width(thickness): + m = _model(setup, thickness, delays).trace(ew, normalize=False).sum(axis=1) + m = m / m.sum() + mean = np.sum(GRID.omega * m) + return np.sqrt(np.sum((GRID.omega - mean) ** 2 * m)) + + assert width(200e-6) < 0.9 * width(1e-6) + + +# -- the neglected signal tilt --------------------------------------------------- +def _tilted_signal(setup, thickness): + """Per-pair signal constant including its tilt in the principal plane.""" + prop = crystals.propagation(setup, GRID.omega, W0, thickness) + theta = setup.internal_angle(W0) + sin_a = math.sin(setup.crossing_half_angle) + beta1 = crystals._group_delay(BBO, W0, sin_a) + w = scipy.fft.ifftshift(GRID.omega) + del prop + + def beta_sig_pair(j, m, k): + w1, w2 = w[j] + W0, w[m] + W0 + ws = w[k] + 2 * W0 + lam = 2 * np.pi * C / ws + n_o, n_e = BBO.n_o(np.array([lam])), BBO.n_e(np.array([lam])) + n_s = crystals.extraordinary_index(n_o, n_e, theta)[0] + dtheta = (w1 - w2) * sin_a / (ws * n_s) + n_tilted = crystals.extraordinary_index(n_o, n_e, theta + dtheta) + k_x = (w1 - w2) * sin_a / C + k_mag = ws / C * n_tilted + return np.sqrt(k_mag**2 - k_x**2) - beta1 * w[k] + + return beta_sig_pair + + +def test_the_tilt_estimate_bounds_the_neglected_term(): + thickness = 100e-6 + setup = _setup(geometry=GEOMETRY, polarization="perpendicular") + ew = _pulse(GRID) + estimate = crystals.tilt_phase_error(setup, GRID.omega, W0, thickness) + cheap = _pair_sum(setup, thickness, ew, 0.0) + exact = _pair_sum(setup, thickness, ew, 0.0, _tilted_signal(setup, thickness)) + error = np.max(np.abs(cheap - exact)) / np.max(np.abs(exact)) + # A phase error phi changes a pair's term by at most |exp(i phi) - 1| ~ phi; + # the estimate is the grid's worst pair, so it bounds the field's error. + assert 0.0 < error < estimate + + +def test_the_warning_fires_above_the_threshold(): + setup = _setup(geometry=GEOMETRY, polarization="perpendicular") + assert crystals.tilt_phase_error(setup, GRID.omega, W0, 200e-6) > 0.1 + with pytest.warns(CrystalApproximationWarning, match="neglects the signal's tilt"): + _model(setup, 200e-6, np.array([0.0])) + + +# -- guards ------------------------------------------------------------------------ +def test_an_isotropic_slab_cannot_model_shg(): + with pytest.raises(ValueError, match="dispersive propagation in an isotropic"): + ForwardModel( + GRID.omega, [0.0], "shg", material="SiO2", thickness=10e-6, omega0=W0 + ) + + +def test_a_crystal_models_shg_only(): + with pytest.raises(ValueError, match="Type I SHG only"): + ForwardModel(GRID.omega, [0.0], "pg", material=_setup(), omega0=W0) + + +# -- the JAX models ----------------------------------------------------------------- +def test_jax_trace_matches_numpy(): + setup = _setup(geometry=GEOMETRY, polarization="parallel") + thickness = 50e-6 + ew = _pulse(GRID) + delays = np.linspace(-20e-15, 20e-15, 7) + npoints = crystals.depth_points(setup, GRID.omega, W0, thickness) + expected = _model(setup, thickness, delays).trace(ew, normalize=False) + kw = dict(material=setup, thickness=thickness, npoints=npoints, omega0=W0) + jax_trace = np.asarray(make_trace_fn(GRID.omega, delays, "shg", **kw)(ew)) + param = make_param_trace_fn(GRID.omega, delays, "shg", **kw) + param_trace = np.asarray(param(ew, thickness, 0.0)) + # both evaluate the same FFTs and quadrature in float64 + np.testing.assert_allclose(jax_trace, expected, rtol=1e-10, atol=1e-12) + np.testing.assert_allclose(param_trace, expected, rtol=1e-10, atol=1e-12) + + +@pytest.mark.parametrize( + "option", [dict(fit_thickness=True), dict(depth_transverse=True)] +) +def test_jax_crystal_refuses_slab_only_options(option): + setup = _setup() + npoints = crystals.depth_points(setup, GRID.omega, W0, 50e-6) + with pytest.raises(ValueError, match="does not support"): + make_param_trace_fn( + GRID.omega, + [0.0], + "shg", + material=setup, + thickness=50e-6, + npoints=npoints, + omega0=W0, + **option, + ) + + +# -- the hand-derived adjoint --------------------------------------------------- +def test_adjoint_matches_finite_differences(): + rng = np.random.default_rng(11) + setup = _setup() + thickness = 50e-6 + ew = _pulse(GRID) + 0.05 * ( + rng.standard_normal(GRID.n) + 1j * rng.standard_normal(GRID.n) + ) + delays = np.array([-8e-15, 0.0, 8e-15]) + model = _model(setup, thickness, delays) + weights = rng.standard_normal((GRID.n, 3)) + 1j * rng.standard_normal((GRID.n, 3)) + + ew_bar = np.zeros(GRID.n, dtype=complex) + for col, tau in enumerate(delays): + model.signal_single(ew, tau, record=True) + ew_bar += model.adjoint_single(0.5 * weights[:, col], tau) + + def loss(z): + return sum( + float(np.real(np.sum(np.conj(weights[:, c]) * model.signal_single(z, t)))) + for c, t in enumerate(delays) + ) + + # central differences on a quadratic form: exact up to rounding (~1e-9 at h=1e-6 + # against losses of order 1e2) + h = 1e-6 + for idx in rng.choice(GRID.n, size=6, replace=False): + step = np.zeros(GRID.n, dtype=complex) + step[idx] = h + d_re = (loss(ew + step) - loss(ew - step)) / (2 * h) + d_im = (loss(ew + 1j * step) - loss(ew - 1j * step)) / (2 * h) + assert 2 * ew_bar[idx].real == pytest.approx(d_re, rel=1e-6, abs=1e-6) + assert 2 * ew_bar[idx].imag == pytest.approx(d_im, rel=1e-6, abs=1e-6) From 1ebf2b263bdf148919fce039aa1e4228d928920c Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 18:29:12 +0000 Subject: [PATCH 03/16] Estimate the signal tilt over the pulse's band, and warn from check_tilt The worst pair over the whole grid sits at its edges, where there is no light, and overstated the error some 200-fold. tilt_phase_error takes the fundamental's band (spectral_band), and check_tilt warns once the band is known; the forward models, which do not know the field, no longer warn. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- croak/crystals.py | 116 ++++++++++++++++++++++++++++++---- tests/test_crystals.py | 8 +-- tests/test_forward_crystal.py | 41 +++++++++--- 3 files changed, 141 insertions(+), 24 deletions(-) diff --git a/croak/crystals.py b/croak/crystals.py index 510a887..f10f635 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -71,9 +71,10 @@ bisector, which the model neglects. When the beams cross in the crystal's principal plane (fundamental polarisation perpendicular to the crossing plane), that tilt changes :math:`n_e(\theta)` to first order; - :func:`tilt_phase_error` estimates the phase it adds and the forward models warn - above :data:`TILT_PHASE_WARN`. When the polarisation lies in the crossing plane, - the principal plane is perpendicular to it and the first-order term vanishes. + :func:`tilt_phase_error` estimates the phase it adds over the pulse's band, and + :func:`check_tilt` warns above :data:`TILT_PHASE_WARN`. When the polarisation + lies in the crossing plane, the principal plane is perpendicular to it and the + first-order term vanishes. See :doc:`/explanation/forward_model` for the full model. """ @@ -103,10 +104,12 @@ "Propagation", "UniaxialCrystal", "check_medium", + "check_tilt", "depth_points", "extraordinary_index", "phase_matching_angle", "propagation", + "spectral_band", "tilt_phase_error", ] @@ -529,7 +532,11 @@ def depth_points( def tilt_phase_error( - setup: CrystalSetup, omega: ArrayLike, omega0: float, thickness: float + setup: CrystalSetup, + omega: ArrayLike, + omega0: float, + thickness: float, + band: tuple[float, float] | None = None, ) -> float: r"""Largest phase of the neglected signal tilt over the grid (rad). @@ -552,16 +559,27 @@ def tilt_phase_error( Pulse carrier (rad/s). thickness : float Plate thickness (m). + band : tuple of float or None, optional + Absolute angular frequencies ``(lo, hi)`` (rad/s) of the fundamental's + band (see :func:`spectral_band`); only pairs of components inside it + count. ``None`` (default) takes the whole grid, which overstates the error + badly when the pulse fills only part of it: the worst pair then sits at + the grid's edges, where there is no light. Returns ------- float - The estimate, maximised over the grid's component pairs (an upper bound on - what a field confined to part of the grid sees). + The estimate, maximised over the component pairs in the band. """ if setup.geometry is None or setup.polarization != "perpendicular" or not thickness: return 0.0 _, w1, w2, theta = _pair_mismatch(setup, np.asarray(omega, dtype=float), omega0) + if band is not None: + lo, hi = band + inside = (w1 >= lo) & (w1 <= hi) & (w2 >= lo) & (w2 <= hi) + w1, w2 = w1[inside], w2[inside] + if w1.size == 0: + return 0.0 ws = w1 + w2 lam = wlfreq(ws) n_o, n_e = setup.crystal.n_o(lam), setup.crystal.n_e(lam) @@ -604,11 +622,11 @@ def check_medium( crystal for an interaction other than SHG, or too few depth nodes for the crystal's phase mismatch (see :func:`depth_points`). - Warns + Notes ----- - CrystalApproximationWarning - If the neglected signal-tilt phase (:func:`tilt_phase_error`) exceeds - :data:`TILT_PHASE_WARN`. + The neglected signal tilt depends on where the pulse has light, which the + forward model does not know; :func:`check_tilt` tests it once the band is + known. """ is_crystal = isinstance(material, CrystalSetup) if interaction.omega0_scale != 1.0 and material is not None and thickness: @@ -633,7 +651,80 @@ def check_medium( f"{npoints} depth nodes under-resolve the crystal's phase mismatch over " f"this grid: use npoints >= {needed} (croak.crystals.depth_points)" ) - error = tilt_phase_error(material, omega, omega0, thickness) + + +def spectral_band( + omega: ArrayLike, intensity: ArrayLike, level: float = 1e-3 +) -> tuple[float, float]: + """Frequency band where a spectrum exceeds ``level`` of its peak. + + Parameters + ---------- + omega : array_like + Angular frequencies (rad/s) of the samples. + intensity : array_like + Spectral intensity at those frequencies. + level : float, optional + Threshold relative to the peak (default ``1e-3``), in ``(0, 1)``. + + Returns + ------- + tuple of float + ``(lo, hi)``, the lowest and highest frequency above the threshold. + + Raises + ------ + ValueError + If the spectrum has no positive intensity. + + Examples + -------- + >>> spectral_band([1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 0.5, 0.0]) + (2.0, 3.0) + """ + omega = np.asarray(omega, dtype=float) + intensity = np.asarray(intensity, dtype=float) + peak = float(np.max(intensity)) + if not peak > 0.0: + raise ValueError("the spectrum has no positive intensity") + above = omega[intensity > level * peak] + return float(above.min()), float(above.max()) + + +def check_tilt( + setup: CrystalSetup, + omega: ArrayLike, + omega0: float, + thickness: float, + band: tuple[float, float], +) -> float: + """Warn if the neglected signal tilt matters for light in ``band``. + + Parameters + ---------- + setup : CrystalSetup + The crystal. + omega : array_like + Centred angular-frequency grid (rad/s). + omega0 : float + Pulse carrier (rad/s). + thickness : float + Plate thickness (m). + band : tuple of float + Absolute angular frequencies ``(lo, hi)`` of the fundamental's light, e.g. + from :func:`spectral_band` of the independent spectrum. + + Returns + ------- + float + The estimate of :func:`tilt_phase_error` over the band (rad). + + Warns + ----- + CrystalApproximationWarning + If it exceeds :data:`TILT_PHASE_WARN`. + """ + error = tilt_phase_error(setup, omega, omega0, thickness, band) if error > TILT_PHASE_WARN: warnings.warn( f"the crystal model neglects the signal's tilt in the principal plane, " @@ -643,5 +734,6 @@ def check_medium( f"crossing angle, or the fundamental polarised in the crossing plane " f"avoids it", CrystalApproximationWarning, - stacklevel=3, + stacklevel=2, ) + return error diff --git a/tests/test_crystals.py b/tests/test_crystals.py index bea09b1..484aef7 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -26,7 +26,9 @@ def _sellmeier(b, c): def n(lam): l2 = (np.asarray(lam, dtype=float) * 1e6) ** 2 - return np.sqrt(1.0 + sum(bi * l2 / (l2 - ci) for bi, ci in zip(b, c))) + return np.sqrt( + 1.0 + sum(bi * l2 / (l2 - ci) for bi, ci in zip(b, c, strict=True)) + ) return n @@ -157,9 +159,7 @@ def test_no_material_is_dispersionless(): def test_crystal_propagation_carries_the_exact_mismatch(): # beta_sig(O1+O2) - beta_in(O1) - beta_in(O2) must equal the physical mismatch # k_s(w1+w2) - k_z(w1) - k_z(w2): the frame terms cancel exactly. - setup = _tuned( - geometry=TwoBeamGeometry(5e-3, 0.1), polarization="parallel" - ) + setup = _tuned(geometry=TwoBeamGeometry(5e-3, 0.1), polarization="parallel") prop = crystals.propagation(setup, GRID.omega, W0, 10e-6) i1, i2 = 128 + 10, 128 - 25 # centred indices of two grid frequencies i_s = i1 + i2 - 128 # their sum on the centred grid diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py index ed240f5..1e20cef 100644 --- a/tests/test_forward_crystal.py +++ b/tests/test_forward_crystal.py @@ -184,24 +184,49 @@ def beta_sig_pair(j, m, k): return beta_sig_pair -def test_the_tilt_estimate_bounds_the_neglected_term(): +def _band(ew): + """The pulse's band (absolute rad/s), where its spectrum exceeds 1e-3 of peak.""" + return crystals.spectral_band(GRID.omega + W0, np.abs(ew) ** 2) + + +def test_the_tilt_estimate_over_the_band_bounds_the_neglected_term(): thickness = 100e-6 setup = _setup(geometry=GEOMETRY, polarization="perpendicular") ew = _pulse(GRID) - estimate = crystals.tilt_phase_error(setup, GRID.omega, W0, thickness) + band = _band(ew) + estimate = crystals.tilt_phase_error(setup, GRID.omega, W0, thickness, band) + whole_grid = crystals.tilt_phase_error(setup, GRID.omega, W0, thickness) cheap = _pair_sum(setup, thickness, ew, 0.0) exact = _pair_sum(setup, thickness, ew, 0.0, _tilted_signal(setup, thickness)) error = np.max(np.abs(cheap - exact)) / np.max(np.abs(exact)) - # A phase error phi changes a pair's term by at most |exp(i phi) - 1| ~ phi; - # the estimate is the grid's worst pair, so it bounds the field's error. - assert 0.0 < error < estimate + # A phase error phi changes a pair's term by at most |exp(i phi) - 1| ~ phi, so + # the band's worst pair bounds the field's error; the whole grid's worst pair, + # at edges without light, overstates it far more. + assert 0.0 < error < estimate < whole_grid -def test_the_warning_fires_above_the_threshold(): +def test_check_tilt_warns_above_the_threshold(): setup = _setup(geometry=GEOMETRY, polarization="perpendicular") - assert crystals.tilt_phase_error(setup, GRID.omega, W0, 200e-6) > 0.1 + band = _band(_pulse(GRID, fwhm=5e-15)) # a broad pulse with pytest.warns(CrystalApproximationWarning, match="neglects the signal's tilt"): - _model(setup, 200e-6, np.array([0.0])) + error = crystals.check_tilt(setup, GRID.omega, W0, 300e-6, band) + assert error > crystals.TILT_PHASE_WARN + + +def test_check_tilt_is_silent_below_the_threshold(): + setup = _setup(geometry=GEOMETRY, polarization="perpendicular") + band = _band(_pulse(GRID)) + assert crystals.check_tilt(setup, GRID.omega, W0, 10e-6, band) < 0.1 + + +def test_a_band_without_pairs_has_no_tilt_error(): + setup = _setup(geometry=GEOMETRY, polarization="perpendicular") + assert crystals.tilt_phase_error(setup, GRID.omega, W0, 100e-6, (1.0, 2.0)) == 0.0 + + +def test_spectral_band_needs_light(): + with pytest.raises(ValueError, match="no positive intensity"): + crystals.spectral_band([1.0, 2.0], [0.0, 0.0]) # -- guards ------------------------------------------------------------------------ From 5890ef003406bd1f09602259edf836f1659c6482 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 18:30:35 +0000 Subject: [PATCH 04/16] Document SHG in a Type I crystal Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- changelog.d/shg-crystal.added.md | 1 + docs/explanation/forward_model.md | 91 ++++++++++++++++++++++++++++++- docs/explanation/interactions.md | 12 ++-- docs/reference/api/core.md | 20 +++++++ tests/test_crystals.py | 2 +- 5 files changed, 117 insertions(+), 9 deletions(-) create mode 100644 changelog.d/shg-crystal.added.md diff --git a/changelog.d/shg-crystal.added.md b/changelog.d/shg-crystal.added.md new file mode 100644 index 0000000..d4cc8c6 --- /dev/null +++ b/changelog.d/shg-crystal.added.md @@ -0,0 +1 @@ +SHG in a Type I crystal: `croak.crystals.CrystalSetup` (cut angle with an external tilt or the wavelength the crystal was tuned to, the crossing geometry from `croak.geometry.TwoBeamGeometry`, and the fundamental's polarisation relative to the crossing plane), passed as `material` to the forward models for SHG, propagates the signal near 2ω0 as the extraordinary wave and so models phase matching, group-velocity mismatch and the ω/n generation prefactor. `croak.crystals.depth_points` gives the depth nodes the phase mismatch needs, and `check_tilt` warns where the neglected signal tilt matters (#24). diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index 05dd0a1..a4d7d12 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -108,9 +108,94 @@ trace = croak.maketrace(g.omega, delays, ew, "pg", material="SiO2", thickness=10e-6, npoints=20, omega0=omega0) ``` -Remember that dispersive propagation is supported for **PG** and **SD** only -(their signal stays at the fundamental); SHG raises a `ValueError`. See -[Interactions](interactions.md). +A material slab like this serves **PG** and **SD**, whose signal stays at the +fundamental. SHG needs a crystal, described next; an isotropic slab with SHG +raises a `ValueError`. See [Interactions](interactions.md). + +## SHG in a Type I crystal + +The SHG signal is generated near $2\omega_0$, and in a Type I (oo→e) crystal it is +the extraordinary wave while the two fundamentals are ordinary. It therefore needs +its own propagation constant. {mod}`croak.crystals` supplies two, written on the +model's centred grid and in **one** frame moving with the fundamental's group +velocity $\beta_1$: + +```{math} +\beta_\mathrm{in}(\Omega) = k_z(\omega_0+\Omega) - \beta_1\Omega, \qquad +\beta_\mathrm{sig}(\Omega) = k_s(2\omega_0+\Omega) - \beta_1\Omega, +``` + +with $k_z(\omega) = \sqrt{k_o(\omega)^2 - (\omega\sin\alpha/c)^2}$, the ordinary +wavevector along the bisector of two beams crossing at the external half-angle +$\alpha$, and $k_s(\omega) = \omega\, n_e(\theta,\omega)/c$, the extraordinary +wavevector at the internal angle $\theta$ to the optic axis. In +{eq}`dispersive`, $e^{i\beta z_q}$ becomes $e^{i\beta_\mathrm{in} z_q}$ and +$e^{i\beta(L-z_q)}$ becomes $a(\Omega)\,e^{i\beta_\mathrm{sig}(L-z_q)}$. + +**Why this gives the phase matching.** Both constants keep their carrier +wavevectors. A component pair $(\omega_1,\omega_2)$ generated at depth $z$ then +carries $e^{-i\Delta k\,z}$ with the exact mismatch +$\Delta k = k_s(\omega_1+\omega_2) - k_z(\omega_1) - k_z(\omega_2)$: the frame terms +add up to $-\beta_1\Omega_s L$, independent of $z$, a linear spectral phase the +trace cannot see. The depth sum turns this into the pair's phase-matching +response, $L\,\mathrm{sinc}(\Delta k L/2)$ in amplitude. Over a full period of +delays the frequency marginal is therefore the sum over pairs of +$\lvert E(\omega_1)E(\omega_2)\rvert^2 L^2\mathrm{sinc}^2(\Delta k L/2)$, which +`tests/test_forward_crystal.py` checks to the quadrature's accuracy. + +**Generation prefactor.** The generated second-harmonic field grows as +$\omega_s/n_s$, so the model multiplies the signal by +$a(\Omega) = (\omega_s/n_s)/(2\omega_0/n_s(2\omega_0))$. Other spectral factors (the +beams' mode overlap, the dispersion of $\chi^{(2)}$, the detector's response) are +not modelled; the solvers' per-frequency response `R_omega` absorbs any that +matter. + +**The crystal's angle.** A {class}`~croak.crystals.CrystalSetup` takes the +manufacturer's cut angle $\theta_c$ and either the external tilt $\gamma$ or the +wavelength the crystal was tuned to phase-match, the usual case when it was rotated +for the strongest signal. The beams refract to $\gamma_\mathrm{int} = +\arcsin(\sin\gamma/n_o)$, so $\theta = \theta_c + \gamma_\mathrm{int}$ and the path +is $L/\cos\gamma_\mathrm{int}$. Nothing is derived from the retrieval grid. The +crossing angle comes from a {class}`~croak.geometry.TwoBeamGeometry` (beam +separation and focal length), the one place it is set. + +**Depth resolution.** Each pair's depth integrand oscillates through +$\Delta k L$ rad. Gauss–Legendre integrates it to $10^{-6}$ of $L$ with +$\lceil\lvert\Delta k\rvert L/2\rceil + 3$ nodes; {func}`croak.crystals.depth_points` +takes the maximum over every pair of grid frequencies, and the models refuse fewer +nodes. For a 100 µm BBO crystal and an 800 nm pulse on a 500–1300 nm grid this is +about 33 nodes. + +**What is neglected.** Walk-off (the crystal is thin), Type II, and the signal's +own small tilt: the signal of a pair leaves at +$\delta\theta \approx (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)$ to the bisector. When +the beams cross in the crystal's principal plane (the fundamental polarised +perpendicular to the crossing plane) this changes $n_e(\theta)$ to first order. +{func}`croak.crystals.tilt_phase_error` bounds the phase it adds over the pulse's +band, and {func}`croak.crystals.check_tilt` warns above 0.1 rad. Polarised in the +crossing plane, the principal plane is perpendicular to it and the term vanishes. + +```python +import numpy as np +import croak +from croak.crystals import CrystalSetup, UniaxialCrystal +from croak.geometry import TwoBeamGeometry + +crystal = UniaxialCrystal("BBO", n_o, n_e) # n(λ in m) callables +setup = CrystalSetup( + crystal, + cut_angle=np.radians(29.2), + phase_match_wavelength=800e-9, # tuned for the strongest signal + geometry=TwoBeamGeometry(beam_separation=5e-3, focal_length=0.1), + polarization="parallel", # to the crossing plane +) +omega0 = croak.maths.wlfreq(800e-9) +npoints = croak.crystals.depth_points(setup, g.omega, omega0, 50e-6) +trace = croak.maketrace(g.omega, delays, ew, "shg", material=setup, + thickness=50e-6, npoints=npoints, omega0=omega0) +``` + +The retrieved field is the field at the crystal's entrance face. ## Quadrature convergence diff --git a/docs/explanation/interactions.md b/docs/explanation/interactions.md index a2876c6..08e8a8e 100644 --- a/docs/explanation/interactions.md +++ b/docs/explanation/interactions.md @@ -24,11 +24,13 @@ $\omega_0$. This single number has two consequences: - it sets the wavelength axis of an SHG-FROG trace (handled in [Grids and filtering](../howto/grids_and_filtering.md)); -- it determines which geometries support **dispersive propagation**. The slab - propagation constant $\beta(\omega)$ is built at the fundamental carrier, so it - is only physically consistent for signals that stay there. **Dispersive - propagation is therefore supported for PG and SD, but not SHG** — croak raises a - `ValueError` if you request a dispersive SHG model. +- it determines the **dispersive propagation** each geometry needs. An isotropic + slab's propagation constant $\beta(\omega)$ is built at the fundamental carrier, + which is consistent for PG and SD, whose signal stays there. The SHG signal + propagates near $2\omega_0$ with a constant of its own, which a Type I crystal + supplies ({mod}`croak.crystals`; see + [the forward model](forward_model.md#shg-in-a-type-i-crystal)). An isotropic slab + with SHG raises a `ValueError`. ```{admonition} TG-FROG uses the PG kernel :class: tip diff --git a/docs/reference/api/core.md b/docs/reference/api/core.md index d19b0a8..c0afbb8 100644 --- a/docs/reference/api/core.md +++ b/docs/reference/api/core.md @@ -35,6 +35,26 @@ shows how the grid, pulse and trace functions fit together. :members: ``` +## Nonlinear crystals + +Type I SHG in a uniaxial crystal: the propagation constants of the ordinary +fundamentals and the extraordinary signal, the crystal's angle, and the depth +resolution its phase mismatch needs. + +```{eval-rst} +.. automodule:: croak.crystals + :members: +``` + +## Two-beam geometry + +The crossing beams of a non-collinear SHG FROG, the one source of their angle. + +```{eval-rst} +.. automodule:: croak.geometry + :members: +``` + ## Geometric smearing Mask geometry to smearing-kernel statistics for a non-collinear BOXCARS setup; diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 484aef7..2b8afa5 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -1,7 +1,7 @@ """Type I SHG crystal: indices, angles, propagation constants, depth resolution. The crystal used throughout is a three-term Sellmeier pair with BBO-like -coefficients (Tamošauskas et al., Opt. Mater. Express 8, 1410 (2018), Eq. (1)), +coefficients (Tamošauskas et al., Optical Materials Express 8, 1410 (2018), Eq. (1)), written out here so the tests do not depend on a material registry. They are a realistic negative uniaxial crystal; the physics tested does not depend on their exact values. From f4480de11c83c871438553fc5ade6a63a1ce8b1d Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 18:31:08 +0000 Subject: [PATCH 05/16] Test the two-beam geometry's validation Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- tests/test_geometry.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 tests/test_geometry.py diff --git a/tests/test_geometry.py b/tests/test_geometry.py new file mode 100644 index 0000000..c8c3d4c --- /dev/null +++ b/tests/test_geometry.py @@ -0,0 +1,29 @@ +"""The two-beam geometry: validation and the crossing angle.""" + +import math + +import pytest + +from croak.geometry import TwoBeamGeometry + + +def test_crossing_half_angle_is_half_the_separation_over_the_focal_length(): + g = TwoBeamGeometry(beam_separation=10e-3, focal_length=0.2, beam_diameter=3e-3) + assert g.crossing_half_angle == pytest.approx(math.atan(0.025)) + assert g.beam_diameter == 3e-3 + + +@pytest.mark.parametrize( + ("kwargs", "name"), + [ + (dict(beam_separation=0.0, focal_length=0.1), "beam_separation"), + (dict(beam_separation=5e-3, focal_length=-0.1), "focal_length"), + ( + dict(beam_separation=5e-3, focal_length=0.1, beam_diameter=math.nan), + "beam_diameter", + ), + ], +) +def test_lengths_must_be_finite_and_positive(kwargs, name): + with pytest.raises(ValueError, match=f"{name} must be finite and positive"): + TwoBeamGeometry(**kwargs) From 015e864111842b453f2205441ae058a9df5fe98f Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 19:15:46 +0000 Subject: [PATCH 06/16] Address review of the crystal core - Integrate over the effective path of a tilted plate, L / (cos g + (n_e'/n_e) sin g), the first-order normal mismatch; tested against an exact normal-component solve. - A crystal's transparency range: outside it the signal is absorbed and pairs do not drive the depth-node count. - Guards: omega0 > 0, a reachable tilt, an internal angle in 0-90 degrees, thickness >= 0, Gauss-Legendre quadrature. - check_tilt computes the neglected signal tilt's actual change to the signal over a set of delays (tilt_field_error, by the exact pair sum) and warns above 1 %; at zero delay its first-order effect cancels. - Independent tests of the crossing wavevector, a tilted forward model and the masks; docs and comments corrected. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- croak/crystals.py | 307 ++++++++++++++++++---- croak/forward.py | 8 +- croak/forward_jax.py | 12 +- croak/geometry.py | 3 +- docs/explanation/forward_model.md | 41 ++- docs/tutorials/03_dispersive_retrieval.md | 3 +- tests/test_crystals.py | 98 ++++++- tests/test_forward_crystal.py | 70 ++++- 8 files changed, 464 insertions(+), 78 deletions(-) diff --git a/croak/crystals.py b/croak/crystals.py index f10f635..eb6713a 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -56,8 +56,11 @@ and the face normal. A crystal tilted by the external angle :math:`\gamma` (in the principal plane; positive increases the angle to the optic axis) refracts the beams to :math:`\gamma_\mathrm{int} = \arcsin(\sin\gamma / n_o)`, so that -:math:`\theta = \theta_c + \gamma_\mathrm{int}`, and the path through a plate of -thickness :math:`L` is :math:`L/\cos\gamma_\mathrm{int}`. :class:`CrystalSetup` +:math:`\theta = \theta_c + \gamma_\mathrm{int}`. The mismatch in a tilted plate +of thickness :math:`L` builds up along the face normal, which to first order is the +mismatch along the beams over the effective path +:math:`L/(\cos\gamma_\mathrm{int} + (n_e'/n_e)\sin\gamma_\mathrm{int})` +(:meth:`CrystalSetup.path_length`). :class:`CrystalSetup` takes either :math:`\gamma` or the wavelength the crystal was tuned to phase-match, from which :math:`\theta` is solved. Approximations: the refraction uses :math:`n_o` at one wavelength (the phase-matched one, else the carrier), and the @@ -65,14 +68,16 @@ Validity -------- -* Type I only, fundamentals ordinary; no walk-off (thin crystal, full collection). +* Type I only, fundamentals ordinary; no spatial walk-off of the beams (a thin + crystal, full collection). * The signal of a pair :math:`(\omega_1,\omega_2)` leaves at a small angle :math:`\delta\theta \approx (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to the bisector, which the model neglects. When the beams cross in the crystal's principal plane (fundamental polarisation perpendicular to the crossing plane), that tilt changes :math:`n_e(\theta)` to first order; - :func:`tilt_phase_error` estimates the phase it adds over the pulse's band, and - :func:`check_tilt` warns above :data:`TILT_PHASE_WARN`. When the polarisation + :func:`tilt_phase_error` bounds the phase it adds, :func:`tilt_field_error` + computes the change it makes to a pulse's signal, and :func:`check_tilt` warns + above :data:`TILT_ERROR_WARN`. When the polarisation lies in the crossing plane, the principal plane is perpendicular to it and the first-order term vanishes. @@ -98,7 +103,7 @@ from .maths import derivative, wlfreq __all__ = [ - "TILT_PHASE_WARN", + "TILT_ERROR_WARN", "CrystalSetup", "CrystalApproximationWarning", "Propagation", @@ -110,12 +115,14 @@ "phase_matching_angle", "propagation", "spectral_band", + "tilt_field_error", "tilt_phase_error", ] -#: Phase (rad) of the neglected signal-tilt term above which the forward models warn. -#: At 0.1 rad the per-pair sinc² response changes by under 1 % of its peak. -TILT_PHASE_WARN = 0.1 +#: Relative change of the signal field (at zero delay, transform-limited pulse) from +#: the neglected signal tilt above which :func:`check_tilt` warns: 1 % in field is +#: about 2 % in the trace, the order of a good retrieval's residual. +TILT_ERROR_WARN = 0.01 #: Largest grid used to estimate the mismatch over all component pairs; finer grids #: are subsampled. The mismatch varies smoothly, so 256 points resolve its extremes. @@ -126,7 +133,7 @@ class CrystalApproximationWarning(UserWarning): - """The crystal model's neglected signal-tilt phase is not small.""" + """The crystal model's neglected signal tilt changes the signal noticeably.""" @dataclass(frozen=True) @@ -140,11 +147,29 @@ class UniaxialCrystal: n_o, n_e : callable Ordinary and principal extraordinary index as functions of the vacuum wavelength (m), vectorised over NumPy arrays. + transparency : tuple of float or None, optional + Vacuum wavelengths ``(lo, hi)`` (m) over which the indices hold, e.g. a + Sellmeier formula's stated range. Outside it the signal is absorbed (its + prefactor is zero) and component pairs do not count towards + :func:`depth_points`; there a Sellmeier formula runs into its poles. + ``None`` (default) trusts the indices wherever they are finite. """ name: str n_o: Index n_e: Index + transparency: tuple[float, float] | None = None + + def transparent(self, omega: ArrayLike) -> NDArray[np.bool_]: + """Return where angular frequencies ``omega`` (rad/s) lie in the range.""" + omega = np.asarray(omega, dtype=float) + inside = omega > 0 + if self.transparency is not None: + lo, hi = self.transparency + with np.errstate(divide="ignore"): + lam = wlfreq(np.where(inside, omega, np.inf)) + inside &= (lam >= lo) & (lam <= hi) + return inside def extraordinary_index( @@ -329,11 +354,31 @@ def internal_angle(self, omega0: float) -> float: Pulse carrier (rad/s); refracts an explicit ``tilt``, unused when the crystal is tuned to ``phase_match_wavelength``. """ + if not omega0 > 0.0: + raise ValueError( + f"a crystal needs the pulse carrier omega0 > 0, got {omega0!r}" + ) if self.phase_match_wavelength is not None: - return phase_matching_angle( + theta = phase_matching_angle( self.crystal, self.phase_match_wavelength, self.crossing_half_angle ) - return self.cut_angle + self._refract(float(self.tilt or 0.0), omega0) + n = self._n_refraction(omega0) + if abs(n * math.sin(theta - self.cut_angle)) > 1.0: + raise ValueError( + f"phase matching at {self.phase_match_wavelength * 1e9:.1f} nm " + f"needs an internal tilt of " + f"{math.degrees(theta - self.cut_angle):.1f} degrees, beyond " + f"total internal reflection for this " + f"{math.degrees(self.cut_angle):.1f}-degree cut" + ) + return theta + theta = self.cut_angle + self._refract(float(self.tilt or 0.0), omega0) + if not 0.0 <= theta <= 0.5 * math.pi: + raise ValueError( + f"the tilt puts the beams at {math.degrees(theta):.1f} degrees to the " + f"optic axis, outside 0-90 degrees" + ) + return theta def internal_tilt(self, omega0: float) -> float: r"""Return the internal tilt :math:`\theta - \theta_c` (rad).""" @@ -343,21 +388,38 @@ def external_tilt(self, omega0: float) -> float: r"""External tilt :math:`\gamma` (rad): the given one, or the one solved.""" if self.tilt is not None: return self.tilt - gamma_int = self.internal_tilt(omega0) - n = float(self.crystal.n_o(np.array([self._refraction_wavelength(omega0)]))[0]) - sin_gamma = n * math.sin(gamma_int) - if abs(sin_gamma) > 1.0: - raise ValueError( - f"phase matching at {float(self.phase_match_wavelength or 0) * 1e9:.1f}" - f" nm needs an internal tilt of {math.degrees(gamma_int):.1f} degrees," - f" beyond total internal reflection for this " - f"{math.degrees(self.cut_angle):.1f}-degree cut" - ) - return math.asin(sin_gamma) + # internal_tilt has checked that this is reachable + return math.asin( + self._n_refraction(omega0) * math.sin(self.internal_tilt(omega0)) + ) def path_length(self, thickness: float, omega0: float) -> float: - """Path through a plate of ``thickness`` (m): ``thickness / cos(gamma_int)``.""" - return thickness / math.cos(self.internal_tilt(omega0)) + r"""Effective path (m) through a plate of ``thickness`` (m). + + In a plate tilted by :math:`\gamma_\mathrm{int}` the phase that builds up + is the mismatch of the wavevectors' components along the face normal. The + fundamentals' normal components are :math:`k\cos\gamma_\mathrm{int}`; the + signal, generated with their transverse wavevector, runs at a slightly + different angle, and its normal component shifts with the extraordinary + index's angular dispersion. To first order in the mismatch, + :math:`\Delta k_\perp L = \Delta k\, L_\mathrm{eff}` with + + .. math:: L_\mathrm{eff} = \frac{L}{\cos\gamma_\mathrm{int} + + (n_e'/n_e)\sin\gamma_\mathrm{int}}, + + :math:`n_e' = \mathrm dn_e/\mathrm d\theta` at the signal carrier + :math:`2\omega_0` (derived in ``docs/explanation/forward_model.md``; it + agrees with an exact boundary-value solve to the mismatch's second order, + ``tests/test_crystals.py``). Without a tilt it is ``thickness``. + """ + gamma = self.internal_tilt(omega0) + theta = self.internal_angle(omega0) + lam = np.array([float(wlfreq(2.0 * omega0))]) + n_o, n_e = self.crystal.n_o(lam), self.crystal.n_e(lam) + ratio = float( + _dn_dtheta(n_o, n_e, theta)[0] / extraordinary_index(n_o, n_e, theta)[0] + ) + return thickness / (math.cos(gamma) + ratio * math.sin(gamma)) def _refraction_wavelength(self, omega0: float) -> float: """Return the wavelength whose ordinary index refracts the tilt (m).""" @@ -365,10 +427,14 @@ def _refraction_wavelength(self, omega0: float) -> float: return self.phase_match_wavelength return float(wlfreq(omega0)) + def _n_refraction(self, omega0: float) -> float: + """Return the ordinary index that refracts the tilt.""" + lam = np.array([self._refraction_wavelength(omega0)]) + return float(self.crystal.n_o(lam)[0]) + def _refract(self, gamma: float, omega0: float) -> float: """Refract an external tilt ``gamma`` inside (Snell, ordinary index).""" - n = float(self.crystal.n_o(np.array([self._refraction_wavelength(omega0)]))[0]) - return math.asin(math.sin(gamma) / n) + return math.asin(math.sin(gamma) / self._n_refraction(omega0)) @dataclass(frozen=True) @@ -440,12 +506,16 @@ def propagation( k_s0 = float(_k_signal(crystal, np.array([2.0 * omega0]), theta)[0]) with np.errstate(divide="ignore", invalid="ignore"): sig_amp = (omega_s**2 / k_sig) / ((2.0 * omega0) ** 2 / k_s0) - # As materials.beta: a non-positive frequency or one outside the indices' range - # carries no light; zero it rather than let NaN reach the FFTs. The positivity - # masks are explicit because a Sellmeier formula, even in lambda^2, returns a - # finite (meaningless) index at a negative "wavelength". - beta_in[~(np.isfinite(beta_in) & (omega + omega0 > 0))] = 0.0 - bad_sig = ~(np.isfinite(beta_sig) & np.isfinite(sig_amp) & (omega_s > 0)) + # Outside the transparency range, at a non-positive frequency or without a + # finite index, the indices mean nothing (a Sellmeier formula, even in lambda^2, + # returns a finite index at a negative "wavelength"). As materials.beta does, + # the propagation constant is zeroed there, so a field component passes + # unpropagated; the signal's prefactor is zeroed too, so none is generated. + bad_in = ~(np.isfinite(beta_in) & crystal.transparent(omega + omega0)) + beta_in[bad_in] = 0.0 + bad_sig = ~( + np.isfinite(beta_sig) & np.isfinite(sig_amp) & crystal.transparent(omega_s) + ) beta_sig[bad_sig] = 0.0 sig_amp[bad_sig] = 0.0 return Propagation( @@ -490,7 +560,12 @@ def _pair_mismatch( - _k_fundamental(crystal, w1, sin_alpha) - _k_fundamental(crystal, w2, sin_alpha) ) - ok = np.isfinite(dk) & (w1 > 0) & (w2 > 0) + ok = ( + np.isfinite(dk) + & crystal.transparent(w1) + & crystal.transparent(w2) + & crystal.transparent(w1 + w2) + ) return dk[ok], w1[ok], w2[ok], theta @@ -596,6 +671,7 @@ def check_medium( npoints: int, omega: ArrayLike, omega0: float, + quadrature: str = "gausslegendre", ) -> None: r"""Check that a medium suits the interaction; the forward models' shared guard. @@ -609,6 +685,9 @@ def check_medium( Plate thickness (m). npoints : int Depth quadrature nodes the model will use. + quadrature : str, optional + The depth quadrature; a crystal's node rule is for ``"gausslegendre"`` + (default). omega : array_like Centred angular-frequency grid (rad/s). omega0 : float @@ -643,13 +722,25 @@ def check_medium( f"{interaction.name.upper()}; give a material name for a " f"{interaction.name.upper()} slab" ) - if not is_crystal or not thickness: + if not is_crystal: + return + material.internal_angle(omega0) # the carrier, the angle and the tilt are valid + if thickness < 0.0: + raise ValueError(f"the crystal thickness must be >= 0, got {thickness!r}") + if not thickness: return + if quadrature != "gausslegendre": + raise ValueError( + f"a crystal needs Gauss-Legendre depth quadrature (its node rule, " + f"depth_points, is derived for it), got {quadrature!r}" + ) needed = depth_points(material, omega, omega0, thickness) if npoints < needed: raise ValueError( - f"{npoints} depth nodes under-resolve the crystal's phase mismatch over " - f"this grid: use npoints >= {needed} (croak.crystals.depth_points)" + f"{npoints} depth nodes under-resolve the crystal's phase mismatch: use " + f"npoints >= {needed} (croak.crystals.depth_points; the count is set by " + f"the widest component pairs on the grid within the crystal's " + f"transparency range)" ) @@ -691,14 +782,129 @@ def spectral_band( return float(above.min()), float(above.max()) +def _pair_signal( + setup: CrystalSetup, + omega: NDArray[np.float64], + omega0: float, + thickness: float, + amplitude: NDArray[np.float64], + tau: float, + *, + tilted: bool, +) -> NDArray[np.complex128]: + r"""Signal at delay ``tau`` as the exact sum over component pairs, centred order. + + The depth integral of each pair is done analytically. With ``tilted`` the + signal of each pair propagates in its own direction, at + :math:`\delta\theta` to the bisector (to first order), which the model + neglects. + """ + prop = propagation(setup, omega, omega0, thickness) + path = prop.path_length + n = omega.size + w = np.fft.ifftshift(omega) + b_in = np.fft.ifftshift(prop.beta_in) + b_sig = np.fft.ifftshift(prop.beta_sig) + amp = np.fft.ifftshift(prop.sig_amp) + e = np.fft.ifftshift(amplitude).astype(complex) + e_tau = e * np.exp(1j * w * tau) + theta = setup.internal_angle(omega0) + sin_alpha = math.sin(setup.crossing_half_angle) + beta1 = _group_delay(setup.crystal, omega0, sin_alpha) + j = np.arange(n) + psi = np.zeros(n, dtype=complex) + for k in range(n): + if amp[k] == 0.0: + continue + m = (k - j) % n + bs = np.full(n, b_sig[k]) + if tilted: + w1, w2 = w[j] + omega0, w[m] + omega0 + ws = w[k] + 2.0 * omega0 + lam = np.array([float(wlfreq(ws))]) + n_o, n_e = setup.crystal.n_o(lam), setup.crystal.n_e(lam) + n_s = float(extraordinary_index(n_o, n_e, theta)[0]) + dtheta = (w1 - w2) * sin_alpha / (ws * n_s) + k_mag = ws / C * extraordinary_index(n_o, n_e, theta + dtheta) + k_x = (w1 - w2) * sin_alpha / C + bs = np.sqrt(k_mag**2 - k_x**2) - beta1 * w[k] + a = b_in[j] + b_in[m] - bs + with np.errstate(divide="ignore", invalid="ignore"): + depth = (np.exp(1j * a * path) - 1.0) / (1j * a) + depth = np.where(np.abs(a * path) < 1e-12, path, depth) + psi[k] = amp[k] * np.sum(e[j] * e_tau[m] * np.exp(1j * bs * path) * depth) + return np.fft.fftshift(psi) + + +def tilt_field_error( + setup: CrystalSetup, + omega: ArrayLike, + omega0: float, + thickness: float, + amplitude: ArrayLike, + delays: ArrayLike, +) -> float: + r"""Relative change of the signal field that the neglected signal tilt makes. + + Evaluates the signal of a transform-limited pulse with spectral amplitude + ``amplitude`` at each of ``delays`` twice, by the exact sum over component + pairs: as the model has it, and with each pair's signal propagating in its own + direction (:func:`tilt_phase_error` describes the term). Returns the largest + difference relative to the largest signal over all the delays. ``0`` out of + the principal plane (``polarization="parallel"``) or collinear. + + The delays matter: the extra mismatch is odd in :math:`\omega_1-\omega_2`, so + at zero delay, where the pairs :math:`(\omega_1,\omega_2)` and + :math:`(\omega_2,\omega_1)` enter alike, its first-order effect cancels; away + from zero delay it does not, and is tens of times larger. Delays out to about + the pulse duration capture the worst case. It costs :math:`N^2` operations per + delay for an :math:`N`-point grid. + + Parameters + ---------- + setup : CrystalSetup + The crystal. + omega : array_like + Centred angular-frequency grid (rad/s). + omega0 : float + Pulse carrier (rad/s). + thickness : float + Plate thickness (m). + amplitude : array_like + Spectral amplitude on ``omega`` (centred), e.g. the square root of the + independent spectrum resampled there. + delays : array_like + Delays (s) to evaluate, e.g. a coarse sampling of the measured delay axis + out to about twice the pulse duration. + + Returns + ------- + float + The relative field change. + """ + if setup.geometry is None or setup.polarization != "perpendicular" or not thickness: + return 0.0 + omega = np.asarray(omega, dtype=float) + amplitude = np.abs(np.asarray(amplitude, dtype=float)) + worst, peak = 0.0, 0.0 + for tau in np.asarray(delays, dtype=float).ravel(): + args = (setup, omega, omega0, thickness, amplitude, float(tau)) + model = _pair_signal(*args, tilted=False) + exact = _pair_signal(*args, tilted=True) + worst = max(worst, float(np.max(np.abs(model - exact)))) + peak = max(peak, float(np.max(np.abs(exact)))) + return worst / peak + + def check_tilt( setup: CrystalSetup, omega: ArrayLike, omega0: float, thickness: float, - band: tuple[float, float], + amplitude: ArrayLike, + delays: ArrayLike, ) -> float: - """Warn if the neglected signal tilt matters for light in ``band``. + """Warn if the neglected signal tilt changes this pulse's signal noticeably. Parameters ---------- @@ -710,29 +916,28 @@ def check_tilt( Pulse carrier (rad/s). thickness : float Plate thickness (m). - band : tuple of float - Absolute angular frequencies ``(lo, hi)`` of the fundamental's light, e.g. - from :func:`spectral_band` of the independent spectrum. + amplitude : array_like + Spectral amplitude on ``omega`` (see :func:`tilt_field_error`). + delays : array_like + Delays (s) to evaluate (see :func:`tilt_field_error`). Returns ------- float - The estimate of :func:`tilt_phase_error` over the band (rad). + The relative field change of :func:`tilt_field_error`. Warns ----- CrystalApproximationWarning - If it exceeds :data:`TILT_PHASE_WARN`. + If it exceeds :data:`TILT_ERROR_WARN`. """ - error = tilt_phase_error(setup, omega, omega0, thickness, band) - if error > TILT_PHASE_WARN: + error = tilt_field_error(setup, omega, omega0, thickness, amplitude, delays) + if error > TILT_ERROR_WARN: warnings.warn( f"the crystal model neglects the signal's tilt in the principal plane, " - f"which here shifts the phase of the widest component pairs by up to " - f"{error:.2f} rad (above {TILT_PHASE_WARN} rad): the model is " - f"approximate in the spectral wings. A thinner crystal, a smaller " - f"crossing angle, or the fundamental polarised in the crossing plane " - f"avoids it", + f"which changes this pulse's signal by up to {error:.1%} of its peak " + f"(above {TILT_ERROR_WARN:.0%}). A thinner crystal, a smaller crossing " + f"angle, or the fundamental polarised in the crossing plane avoids it", CrystalApproximationWarning, stacklevel=2, ) diff --git a/croak/forward.py b/croak/forward.py index 6f39851..255fa16 100644 --- a/croak/forward.py +++ b/croak/forward.py @@ -157,7 +157,13 @@ def __init__( # An SHG signal lives near 2ω0, so it needs its own propagation constant: # only a crystal supplies one (croak.crystals). PG/SD share the material's. crystals.check_medium( - self.interaction, material, self.thickness, npoints, self.omega, omega0 + self.interaction, + material, + self.thickness, + npoints, + self.omega, + omega0, + quadrature, ) prop = crystals.propagation(material, self.omega, omega0, self.thickness) self.path_length = prop.path_length diff --git a/croak/forward_jax.py b/croak/forward_jax.py index e26d883..42c3405 100644 --- a/croak/forward_jax.py +++ b/croak/forward_jax.py @@ -176,7 +176,9 @@ def __init__( inter = get_interaction(interaction) omega = np.asarray(omega, dtype=float) # Same guard and propagation as ForwardModel (croak.crystals). - crystals.check_medium(inter, material, float(thickness), npoints, omega, omega0) + crystals.check_medium( + inter, material, float(thickness), npoints, omega, omega0, quadrature + ) omega_bin = np.fft.ifftshift(omega) input_prop, signal_prop, weights = _static_props( material, omega, omega0, float(thickness), npoints, quadrature @@ -662,7 +664,13 @@ def make_param_trace_fn( ) # Same guard as the forward model: SHG needs a crystal (croak.crystals). crystals.check_medium( - inter, material, float(thickness), npoints, np.asarray(omega, float), omega0 + inter, + material, + float(thickness), + npoints, + np.asarray(omega, float), + omega0, + quadrature, ) # The paths below that build on a single propagation constant (thickness # fitting, the focal mixture, depth_transverse) take the isotropic slab only. diff --git a/croak/geometry.py b/croak/geometry.py index 4620b8f..ed4fc88 100644 --- a/croak/geometry.py +++ b/croak/geometry.py @@ -8,7 +8,8 @@ each beam at :math:`\pm\alpha` to their bisector, along which the signal leaves. The same :math:`\alpha` sets two effects: the phase mismatch of the crystal (the -fundamentals' longitudinal wavevector shrinks as :math:`\cos\alpha`; see +fundamentals' longitudinal wavevector shrinks as the cosine of the refracted, +internal half-angle; see :mod:`croak.crystals`) and the delay smearing across the focal spot. Both read it from one :class:`TwoBeamGeometry`, so they can never use different angles. """ diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index a4d7d12..0501d39 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -138,9 +138,11 @@ carries $e^{-i\Delta k\,z}$ with the exact mismatch $\Delta k = k_s(\omega_1+\omega_2) - k_z(\omega_1) - k_z(\omega_2)$: the frame terms add up to $-\beta_1\Omega_s L$, independent of $z$, a linear spectral phase the trace cannot see. The depth sum turns this into the pair's phase-matching -response, $L\,\mathrm{sinc}(\Delta k L/2)$ in amplitude. Over a full period of -delays the frequency marginal is therefore the sum over pairs of -$\lvert E(\omega_1)E(\omega_2)\rvert^2 L^2\mathrm{sinc}^2(\Delta k L/2)$, which +response, $P\,\mathrm{sinc}(\Delta k P/2)$ in amplitude over the path $P$ (the +plate thickness $L$ without a tilt; see below). Over a full period of delays the +frequency marginal is therefore the sum over pairs of +$a^2\lvert E(\omega_1)E(\omega_2)\rvert^2 P^2\mathrm{sinc}^2(\Delta k P/2)$, with +$a$ the generation prefactor below, which `tests/test_forward_crystal.py` checks to the quadrature's accuracy. **Generation prefactor.** The generated second-harmonic field grows as @@ -154,26 +156,43 @@ matter. manufacturer's cut angle $\theta_c$ and either the external tilt $\gamma$ or the wavelength the crystal was tuned to phase-match, the usual case when it was rotated for the strongest signal. The beams refract to $\gamma_\mathrm{int} = -\arcsin(\sin\gamma/n_o)$, so $\theta = \theta_c + \gamma_\mathrm{int}$ and the path -is $L/\cos\gamma_\mathrm{int}$. Nothing is derived from the retrieval grid. The +\arcsin(\sin\gamma/n_o)$, so $\theta = \theta_c + \gamma_\mathrm{int}$. In the tilted +plate the mismatch builds up along the face normal. The fundamentals' normal +wavevectors are $k\cos\gamma_\mathrm{int}$; the signal keeps their transverse +wavevector, so its direction $\psi$ solves $K(\psi)\sin\psi = k_t$ with +$K = k_s(\theta_c+\psi)$. Expanding about $\psi = \gamma_\mathrm{int}$ to first +order in the mismatch $\Delta k$ gives a normal mismatch +$\Delta k/(\cos\gamma_\mathrm{int} + (n_e'/n_e)\sin\gamma_\mathrm{int})$, so the model +integrates over the effective path +$P = L/(\cos\gamma_\mathrm{int} + (n_e'/n_e)\sin\gamma_\mathrm{int})$, with +$n_e' = \mathrm dn_e/\mathrm d\theta$ at the signal carrier. A test checks it against +the exact solve (agreement within 0.3 % of $\Delta k L$ at a 10° tilt, where +$L/\cos\gamma_\mathrm{int}$ is about 1 % off). Nothing is derived from the +retrieval grid. The crossing angle comes from a {class}`~croak.geometry.TwoBeamGeometry` (beam separation and focal length), the one place it is set. **Depth resolution.** Each pair's depth integrand oscillates through $\Delta k L$ rad. Gauss–Legendre integrates it to $10^{-6}$ of $L$ with $\lceil\lvert\Delta k\rvert L/2\rceil + 3$ nodes; {func}`croak.crystals.depth_points` -takes the maximum over every pair of grid frequencies, and the models refuse fewer -nodes. For a 100 µm BBO crystal and an 800 nm pulse on a 500–1300 nm grid this is -about 33 nodes. +takes the maximum over every pair of grid frequencies within the crystal's +transparency range, and the models refuse fewer nodes. It grows with the grid's +width: for 100 µm of BBO tuned to 800 nm, about 18 nodes on a 560–1440 nm grid and +about 50 on a grid twice as wide. **What is neglected.** Walk-off (the crystal is thin), Type II, and the signal's own small tilt: the signal of a pair leaves at $\delta\theta \approx (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)$ to the bisector. When the beams cross in the crystal's principal plane (the fundamental polarised perpendicular to the crossing plane) this changes $n_e(\theta)$ to first order. -{func}`croak.crystals.tilt_phase_error` bounds the phase it adds over the pulse's -band, and {func}`croak.crystals.check_tilt` warns above 0.1 rad. Polarised in the -crossing plane, the principal plane is perpendicular to it and the term vanishes. +The extra mismatch is odd in $\omega_1-\omega_2$, so at zero delay its first-order +effect cancels between the pairs $(\omega_1,\omega_2)$ and $(\omega_2,\omega_1)$; away +from zero delay it does not. For BBO at 800 nm crossing at 1.4°, it changes the +signal by about 0.5 % for a 12 fs pulse in 10 µm, 5 % in 100 µm, and 1 % for a 5 fs +pulse in only 10 µm. {func}`croak.crystals.tilt_field_error` computes this change +for a given spectrum and set of delays by an exact pair sum, and +{func}`croak.crystals.check_tilt` warns above 1 %. Polarised in the crossing plane, +the principal plane is perpendicular to it and the term vanishes. ```python import numpy as np diff --git a/docs/tutorials/03_dispersive_retrieval.md b/docs/tutorials/03_dispersive_retrieval.md index 93d37ba..f32965d 100644 --- a/docs/tutorials/03_dispersive_retrieval.md +++ b/docs/tutorials/03_dispersive_retrieval.md @@ -57,7 +57,8 @@ in the deep ultraviolet. Passing `material`, `thickness`, `npoints` and the carrier `omega0` to {func}`~croak.forward.maketrace` models the propagation of both the input and the signal fields inside the slab. We use the **PG** interaction (the transient-grating -kernel); dispersive propagation is supported for PG and SD, not SHG. +kernel); a material slab serves PG and SD, and SHG takes a crystal instead (see +[the forward model](../explanation/forward_model.md#shg-in-a-type-i-crystal)). We use a 50 µm slab. Its small physical thickness does not imply negligible spectral phase across this pulse's bandwidth: diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 2b8afa5..54eb089 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -13,6 +13,7 @@ import numpy as np import pytest +import scipy.optimize from numpy.polynomial.legendre import leggauss from croak import crystals @@ -90,7 +91,7 @@ def test_crossing_raises_the_phase_matching_angle(): def test_phase_matching_angle_raises_without_a_solution(): - # Below ~410 nm BBO cannot phase-match type I SHG (its UV absorption edge). + # Below ~410 nm BBO's birefringence cannot cancel its dispersion: no type I SHG. with pytest.raises(ValueError, match="cannot phase-match"): crystals.phase_matching_angle(BBO, 380e-9) @@ -121,7 +122,45 @@ def test_explicit_tilt_refracts_with_snell(): gamma_int = math.asin(math.sin(math.radians(10.0)) / n) assert setup.internal_angle(W0) == pytest.approx(math.radians(29.0) + gamma_int) assert setup.external_tilt(W0) == math.radians(10.0) - assert setup.path_length(10e-6, W0) == pytest.approx(10e-6 / math.cos(gamma_int)) + + +@pytest.mark.parametrize( + ("cut_deg", "tilt_deg", "wavelength"), + [(23.2, 10.0, 650e-9), (23.2, 10.0, 600e-9), (29.2, -10.0, 650e-9)], +) +def test_effective_path_matches_the_exact_normal_mismatch( + cut_deg, tilt_deg, wavelength +): + # Independent reference: a degenerate collinear pair in a plate tilted by + # gamma_int. The fundamentals' normal wavevector is 2 k_o cos(gamma_int); the + # signal keeps their transverse wavevector k_t = 2 k_o sin(gamma_int) and its + # direction psi to the normal solves K(psi) sin(psi) = k_t, with K the + # extraordinary wavevector at theta_c + psi; its normal component is + # K cos(psi). The phase over the plate is (normal mismatch) * L. + setup = CrystalSetup(BBO, math.radians(cut_deg), tilt=math.radians(tilt_deg)) + gamma_int = setup.internal_tilt(W0) + omega = float(wlfreq(wavelength)) + lam_s = np.array([wavelength / 2]) + n_o_s, n_e_s = BBO.n_o(lam_s), BBO.n_e(lam_s) + k_o = omega / C * float(BBO.n_o(np.array([wavelength]))[0]) + + def big_k(psi): + n = crystals.extraordinary_index(n_o_s, n_e_s, setup.cut_angle + psi)[0] + return 2 * omega / C * n + + k_t = 2 * k_o * math.sin(gamma_int) + psi = scipy.optimize.brentq( + lambda p: big_k(p) * math.sin(p) - k_t, gamma_int - 0.1, gamma_int + 0.1 + ) + exact = (big_k(psi) * math.cos(psi) - 2 * k_o * math.cos(gamma_int)) * 100e-6 + # the model: the mismatch along the beams over the effective path + theta = setup.internal_angle(W0) + dk = 2 * omega / C * crystals.extraordinary_index(n_o_s, n_e_s, theta)[0] - 2 * k_o + model = dk * setup.path_length(100e-6, W0) + # First order in the mismatch (|dk L| ~ 30-55 rad here): the residual is second + # order, under 0.3 % (the old L / cos(gamma_int) path was off by about 1 %). + assert model == pytest.approx(exact, rel=3e-3) + assert dk * 100e-6 / math.cos(gamma_int) != pytest.approx(exact, rel=3e-3) def test_tuned_setup_solves_the_tilt_consistently(): @@ -136,8 +175,8 @@ def test_tuned_setup_solves_the_tilt_consistently(): def test_tuning_beyond_total_internal_reflection_raises(): - # a 0-degree cut tuned to 800 nm needs ~29 degrees inside: n sin(29) > 1? no, - # but a 80-degree cut needs ~-51 degrees inside, which no external angle gives. + # An 80-degree cut tuned to 800 nm needs about -51 degrees inside, which no + # external angle gives (n_o sin(51 degrees) > 1). setup = CrystalSetup(BBO, math.radians(80.0), phase_match_wavelength=800e-9) with pytest.raises(ValueError, match="total internal reflection"): setup.external_tilt(W0) @@ -273,3 +312,54 @@ def test_tilt_phase_error_matches_a_direct_estimate(): by_hand /= math.cos(setup.internal_tilt(W0)) # the subsampled pair grid reaches the extreme pair to within a grid step assert estimate == pytest.approx(by_hand, rel=2e-2) + + +def test_crossing_wavevector_matches_internal_refraction(): + # Independent form: an ordinary beam entering at external angle alpha refracts to + # asin(sin(alpha)/n_o) and its component along the bisector is k_o cos of that. + alpha = math.radians(2.0) + omega = np.array([W0]) + n_o = float(BBO.n_o(np.array([800e-9]))[0]) + k_o = W0 / C * n_o + expected = k_o * math.cos(math.asin(math.sin(alpha) / n_o)) + got = crystals._k_fundamental(BBO, omega, math.sin(alpha))[0] + assert got == pytest.approx(expected, rel=1e-14) + + +def test_transparency_limits_the_signal_and_the_depth_count(): + narrow = UniaxialCrystal("BBO-like", BBO.n_o, BBO.n_e, (380e-9, 1500e-9)) + setup = CrystalSetup(narrow, math.radians(29.2), phase_match_wavelength=800e-9) + prop = crystals.propagation(setup, GRID.omega, W0, 50e-6) + outside = ~narrow.transparent(GRID.omega + 2 * W0) + assert outside.any() + assert np.all(prop.sig_amp[outside] == 0.0) + assert np.all(prop.beta_sig[outside] == 0.0) + # pairs whose signal is absorbed no longer drive the node count + wide = crystals.depth_points(_tuned(), GRID.omega, W0, 100e-6) + assert crystals.depth_points(setup, GRID.omega, W0, 100e-6) < wide + + +@pytest.mark.parametrize( + ("kwargs", "omega0", "match"), + [ + (dict(tilt=0.0), 0.0, "omega0 > 0"), + (dict(tilt=math.radians(60.0)), W0, "outside 0-90 degrees"), + ], +) +def test_setup_rejects_an_invalid_angle_or_carrier(kwargs, omega0, match): + setup = CrystalSetup(BBO, math.radians(85.0), **kwargs) + with pytest.raises(ValueError, match=match): + setup.internal_angle(omega0) + + +@pytest.mark.parametrize( + ("thickness", "quadrature", "match"), + [(-1e-6, "gausslegendre", "thickness must be >= 0"), (50e-6, "uniform", "Gauss")], +) +def test_check_medium_rejects_bad_crystal_inputs(thickness, quadrature, match): + from croak.interactions import get_interaction + + with pytest.raises(ValueError, match=match): + crystals.check_medium( + get_interaction("shg"), _tuned(), thickness, 99, GRID.omega, W0, quadrature + ) diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py index 1e20cef..badae85 100644 --- a/tests/test_forward_crystal.py +++ b/tests/test_forward_crystal.py @@ -205,18 +205,59 @@ def test_the_tilt_estimate_over_the_band_bounds_the_neglected_term(): assert 0.0 < error < estimate < whole_grid -def test_check_tilt_warns_above_the_threshold(): +DELAYS = np.linspace(-24e-15, 24e-15, 9) + + +def test_tilt_field_error_is_the_pair_sum_difference(): + # The library's estimate against this module's own tilted reference. + thickness = 100e-6 setup = _setup(geometry=GEOMETRY, polarization="perpendicular") - band = _band(_pulse(GRID, fwhm=5e-15)) # a broad pulse + amp = np.abs(_pulse(GRID, gdd=0.0)) + tilted = _tilted_signal(setup, thickness) + pairs = [ + ( + _pair_sum(setup, thickness, amp, t), + _pair_sum(setup, thickness, amp, t, tilted), + ) + for t in DELAYS + ] + worst = max(np.max(np.abs(a - b)) for a, b in pairs) + peak = max(np.max(np.abs(b)) for _, b in pairs) + error = crystals.tilt_field_error(setup, GRID.omega, W0, thickness, amp, DELAYS) + assert error == pytest.approx(worst / peak, rel=1e-9) + + +def test_tilt_field_error_is_far_larger_away_from_zero_delay(): + # At zero delay the first-order term cancels between (w1, w2) and (w2, w1). + setup = _setup(geometry=GEOMETRY, polarization="perpendicular") + amp = np.abs(_pulse(GRID, gdd=0.0)) + at_zero = crystals.tilt_field_error(setup, GRID.omega, W0, 100e-6, amp, [0.0]) + scanned = crystals.tilt_field_error(setup, GRID.omega, W0, 100e-6, amp, DELAYS) + assert scanned > 5 * at_zero + + +def test_tilt_field_error_vanishes_out_of_the_principal_plane(): + amp = np.abs(_pulse(GRID)) + parallel = _setup(geometry=GEOMETRY, polarization="parallel") + args = (GRID.omega, W0, 100e-6, amp, DELAYS) + assert crystals.tilt_field_error(parallel, *args) == 0.0 + assert crystals.tilt_field_error(_setup(), *args) == 0.0 + + +def test_check_tilt_warns_above_one_percent(): + # 12 fs in 100 um at a 1.43 degree crossing: about 5 % (first order, off zero + # delay). + setup = _setup(geometry=GEOMETRY, polarization="perpendicular") + amp = np.abs(_pulse(GRID, gdd=0.0)) with pytest.warns(CrystalApproximationWarning, match="neglects the signal's tilt"): - error = crystals.check_tilt(setup, GRID.omega, W0, 300e-6, band) - assert error > crystals.TILT_PHASE_WARN + error = crystals.check_tilt(setup, GRID.omega, W0, 100e-6, amp, DELAYS) + assert error > crystals.TILT_ERROR_WARN -def test_check_tilt_is_silent_below_the_threshold(): +def test_check_tilt_is_silent_below_one_percent(): setup = _setup(geometry=GEOMETRY, polarization="perpendicular") - band = _band(_pulse(GRID)) - assert crystals.check_tilt(setup, GRID.omega, W0, 10e-6, band) < 0.1 + amp = np.abs(_pulse(GRID, gdd=0.0)) + assert crystals.check_tilt(setup, GRID.omega, W0, 5e-6, amp, DELAYS) < 0.01 def test_a_band_without_pairs_has_no_tilt_error(): @@ -311,3 +352,18 @@ def loss(z): d_im = (loss(ew + 1j * step) - loss(ew - 1j * step)) / (2 * h) assert 2 * ew_bar[idx].real == pytest.approx(d_re, rel=1e-6, abs=1e-6) assert 2 * ew_bar[idx].imag == pytest.approx(d_im, rel=1e-6, abs=1e-6) + + +def test_a_tilted_crystal_integrates_over_its_effective_path(): + # A 23.2 degree cut tilted by 10 degrees: the path differs from the plate by + # 1.3 %, a few tenths of a radian of the mismatch phase, so quadrature over the + # plate instead would miss the pair sum. + setup = CrystalSetup(BBO, math.radians(23.2), tilt=math.radians(10.0)) + thickness = 100e-6 + assert abs(setup.path_length(thickness, W0) / thickness - 1) > 0.01 + ew = _pulse(GRID) + model = _model(setup, thickness, np.array([5e-15])) + exact = _pair_sum(setup, thickness, ew, 5e-15) + np.testing.assert_allclose( + model.signal_single(ew, 5e-15), exact, atol=1e-5 * np.max(np.abs(exact)) + ) From 97bfcf4af6f5c8c4f7c0186375112d131c722a45 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 19:16:54 +0000 Subject: [PATCH 07/16] Cover the tilt check's absorbed signal bins Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- tests/test_forward_crystal.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py index badae85..9f96dca 100644 --- a/tests/test_forward_crystal.py +++ b/tests/test_forward_crystal.py @@ -367,3 +367,27 @@ def test_a_tilted_crystal_integrates_over_its_effective_path(): np.testing.assert_allclose( model.signal_single(ew, 5e-15), exact, atol=1e-5 * np.max(np.abs(exact)) ) + + +def test_tilt_field_error_skips_absorbed_signal_frequencies(): + # Signal bins outside the transparency range carry no signal in either sum. + narrow = crystals.UniaxialCrystal("BBO-like", BBO.n_o, BBO.n_e, (380e-9, 1500e-9)) + setup = CrystalSetup( + narrow, + math.radians(29.2), + phase_match_wavelength=800e-9, + geometry=GEOMETRY, + polarization="perpendicular", + ) + amp = np.abs(_pulse(GRID, gdd=0.0)) + full = crystals.tilt_field_error( + _setup(geometry=GEOMETRY, polarization="perpendicular"), + GRID.omega, + W0, + 100e-6, + amp, + DELAYS, + ) + error = crystals.tilt_field_error(setup, GRID.omega, W0, 100e-6, amp, DELAYS) + # the absorbed bins lie in the far wings, so the error barely moves + assert error == pytest.approx(full, rel=0.2) From f3a4c4424544d2fe24e63bd4e63a9aca045ad0d7 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 20:42:44 +0000 Subject: [PATCH 08/16] Model the signal's tilt in the principal plane as the arms' delay drift Crossing in the crystal's principal plane, the signal of a pair (w1, w2) leaves at an angle psi to the bisector, solving (w_s/c) n_e(theta + psi) sin(psi) = k_x; its index changes to first order, adding the mismatch kappa (w1 - w2), kappa = (n_e'/n_s) sin(alpha) / c. That factorises into opposite delays of the two arms that drift with depth, now carried by separate test and gate propagators in both forward models and the adjoint. The trace is then asymmetric in delay; CrystalSetup.delayed_beam sets the sign, which flipping mirrors the trace in delay. The reference for check_tilt solves the signal's direction self-consistently and measures what is left (second order). The phase bound and band helper are gone. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- changelog.d/shg-crystal.added.md | 2 +- croak/crystals.py | 295 ++++++++++++++++-------------- croak/forward.py | 11 +- croak/forward_jax.py | 27 ++- docs/explanation/forward_model.md | 53 ++++-- tests/test_crystals.py | 84 +++++---- tests/test_forward_crystal.py | 177 +++++++++++------- 7 files changed, 378 insertions(+), 271 deletions(-) diff --git a/changelog.d/shg-crystal.added.md b/changelog.d/shg-crystal.added.md index d4cc8c6..b8227ea 100644 --- a/changelog.d/shg-crystal.added.md +++ b/changelog.d/shg-crystal.added.md @@ -1 +1 @@ -SHG in a Type I crystal: `croak.crystals.CrystalSetup` (cut angle with an external tilt or the wavelength the crystal was tuned to, the crossing geometry from `croak.geometry.TwoBeamGeometry`, and the fundamental's polarisation relative to the crossing plane), passed as `material` to the forward models for SHG, propagates the signal near 2ω0 as the extraordinary wave and so models phase matching, group-velocity mismatch and the ω/n generation prefactor. `croak.crystals.depth_points` gives the depth nodes the phase mismatch needs, and `check_tilt` warns where the neglected signal tilt matters (#24). +SHG in a Type I crystal: `croak.crystals.CrystalSetup` (cut angle with an external tilt or the wavelength the crystal was tuned to, the crossing geometry from `croak.geometry.TwoBeamGeometry`, and the fundamental's polarisation relative to the crossing plane), passed as `material` to the forward models for SHG, propagates the signal near 2ω0 as the extraordinary wave and so models phase matching, group-velocity mismatch and the ω/n generation prefactor. `croak.crystals.depth_points` gives the depth nodes the phase mismatch needs, With the beams crossing in the crystal's principal plane the signal's tilt makes the trace asymmetric in delay; the model includes it, to first order, as opposite delay drifts of the two arms (`delayed_beam` sets its sign, which flipping mirrors the trace in delay), and `check_tilt` warns where the remainder matters (#24). diff --git a/croak/crystals.py b/croak/crystals.py index eb6713a..88167a3 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -72,12 +72,13 @@ crystal, full collection). * The signal of a pair :math:`(\omega_1,\omega_2)` leaves at a small angle :math:`\delta\theta \approx (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to the - bisector, which the model neglects. When the beams cross in the crystal's - principal plane (fundamental polarisation perpendicular to the crossing plane), - that tilt changes :math:`n_e(\theta)` to first order; - :func:`tilt_phase_error` bounds the phase it adds, :func:`tilt_field_error` - computes the change it makes to a pulse's signal, and :func:`check_tilt` warns - above :data:`TILT_ERROR_WARN`. When the polarisation + bisector. When the beams cross in the crystal's principal plane (fundamental + polarisation perpendicular to the crossing plane), that tilt changes + :math:`n_e(\theta)` to first order. The model keeps that first-order term, as + opposite delays of the two arms that drift with depth + (:meth:`CrystalSetup.arm_shift`), and neglects what is left; + :func:`tilt_field_error` computes the remainder's change to a pulse's signal, and + :func:`check_tilt` warns above :data:`TILT_ERROR_WARN`. When the polarisation lies in the crossing plane, the principal plane is perpendicular to it and the first-order term vanishes. @@ -114,14 +115,13 @@ "extraordinary_index", "phase_matching_angle", "propagation", - "spectral_band", "tilt_field_error", - "tilt_phase_error", ] -#: Relative change of the signal field (at zero delay, transform-limited pulse) from -#: the neglected signal tilt above which :func:`check_tilt` warns: 1 % in field is -#: about 2 % in the trace, the order of a good retrieval's residual. +#: Relative change of the signal field (transform-limited pulse, over the delays +#: checked) from what the model leaves out of the signal's tilt, above which +#: :func:`check_tilt` warns: 1 % in field is about 2 % in the trace, the order of a +#: good retrieval's residual. TILT_ERROR_WARN = 0.01 #: Largest grid used to estimate the mismatch over all component pairs; finer grids @@ -130,10 +130,11 @@ Index = Callable[[NDArray[np.float64]], NDArray[np.float64]] Polarization = Literal["parallel", "perpendicular"] +DelayedBeam = Literal["toward_axis", "away_from_axis"] class CrystalApproximationWarning(UserWarning): - """The crystal model's neglected signal tilt changes the signal noticeably.""" + """What the crystal model leaves out of the signal's tilt matters.""" @dataclass(frozen=True) @@ -173,7 +174,7 @@ def transparent(self, omega: ArrayLike) -> NDArray[np.bool_]: def extraordinary_index( - n_o: ArrayLike, n_e: ArrayLike, theta: float + n_o: ArrayLike, n_e: ArrayLike, theta: ArrayLike ) -> NDArray[np.float64]: r"""Extraordinary index of a wave at angle ``theta`` to the optic axis. @@ -183,7 +184,7 @@ def extraordinary_index( ---------- n_o, n_e : array_like Ordinary and principal extraordinary indices. - theta : float + theta : array_like Angle between the wavevector and the optic axis (rad). Returns @@ -200,13 +201,15 @@ def extraordinary_index( """ n_o = np.asarray(n_o, dtype=float) n_e = np.asarray(n_e, dtype=float) + theta = np.asarray(theta, dtype=float) inv2 = np.cos(theta) ** 2 / n_o**2 + np.sin(theta) ** 2 / n_e**2 return 1.0 / np.sqrt(inv2) -def _dn_dtheta(n_o, n_e, theta: float) -> NDArray[np.float64]: +def _dn_dtheta(n_o, n_e, theta: ArrayLike) -> NDArray[np.float64]: """Return the derivative of :func:`extraordinary_index` in ``theta``.""" n = extraordinary_index(n_o, n_e, theta) + theta = np.asarray(theta, dtype=float) return -0.5 * n**3 * np.sin(2.0 * theta) * (1.0 / n_e**2 - 1.0 / n_o**2) @@ -302,14 +305,22 @@ class CrystalSetup: The fundamental polarisation relative to the beams' crossing plane. Required with a ``geometry``. ``"perpendicular"`` puts the principal plane (which is perpendicular to the ordinary polarisation) in the crossing - plane, where the neglected signal tilt matters to first order; - ``"parallel"`` makes them perpendicular, where it does not. + plane, where the signal's tilt changes its index to first order + (modelled, see ``delayed_beam``); ``"parallel"`` makes them + perpendicular, where it does not. + delayed_beam : {"toward_axis", "away_from_axis"} or None, optional + Which side of the bisector the delayed beam crosses on, relative to the + optic axis, in the principal plane: ``"toward_axis"`` if it makes the + smaller angle with the optic axis. Required with + ``polarization="perpendicular"`` and otherwise ignored; it sets the sign + of the arms' opposite delay drift (:meth:`arm_shift`). Raises ------ ValueError If not exactly one of ``tilt`` and ``phase_match_wavelength`` is given, - the cut angle is out of range, or ``polarization`` is missing or invalid. + the cut angle is out of range, or ``polarization`` or ``delayed_beam`` is + missing or invalid. """ crystal: UniaxialCrystal @@ -318,6 +329,7 @@ class CrystalSetup: phase_match_wavelength: float | None = None geometry: TwoBeamGeometry | None = None polarization: Polarization | None = None + delayed_beam: DelayedBeam | None = None def __post_init__(self) -> None: """Validate the angle specification and the geometry.""" @@ -339,6 +351,21 @@ def __post_init__(self) -> None: "'perpendicular' (the fundamental polarisation relative to the " f"crossing plane), got {self.polarization!r}" ) + if self.in_principal_plane and self.delayed_beam not in ( + "toward_axis", + "away_from_axis", + ): + raise ValueError( + "with the beams crossing in the principal plane " + "(polarization='perpendicular') give delayed_beam='toward_axis' or " + "'away_from_axis' (the delayed beam's side of the bisector relative " + f"to the optic axis), got {self.delayed_beam!r}" + ) + + @property + def in_principal_plane(self) -> bool: + """Whether the beams cross in the crystal's principal plane.""" + return self.geometry is not None and self.polarization == "perpendicular" @property def crossing_half_angle(self) -> float: @@ -427,6 +454,32 @@ def _refraction_wavelength(self, omega0: float) -> float: return self.phase_match_wavelength return float(wlfreq(omega0)) + def arm_shift(self, omega0: float) -> float: + r"""Return the rate :math:`\kappa` (s/m) at which the arms' delays drift apart. + + Crossing in the principal plane, the signal of the pair + :math:`(\omega_1,\omega_2)` (test, gate) leaves at + :math:`\delta\theta = \pm(\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to + the bisector, which changes its index by :math:`n_e'\delta\theta`. Its + mismatch grows by :math:`\kappa(\omega_1-\omega_2)` with + :math:`\kappa = \pm(n_e'/n_e)\sin\alpha/c`, taken at the signal carrier. + Over the rest of the path :math:`P-z` that is the phase + :math:`e^{i\kappa\Omega(P-z)}` on the test arm and its inverse on the gate: + opposite delays, :math:`\mp\kappa(P-z)`, that drift with depth. The sign + is ``+`` with the delayed beam toward the optic axis. ``0`` out of the + principal plane, where the term is second order. + """ + if not self.in_principal_plane: + return 0.0 + theta = self.internal_angle(omega0) + lam = np.array([float(wlfreq(2.0 * omega0))]) + n_o, n_e = self.crystal.n_o(lam), self.crystal.n_e(lam) + ratio = float( + _dn_dtheta(n_o, n_e, theta)[0] / extraordinary_index(n_o, n_e, theta)[0] + ) + sign = 1.0 if self.delayed_beam == "toward_axis" else -1.0 + return sign * ratio * math.sin(self.crossing_half_angle) / C + def _n_refraction(self, omega0: float) -> float: """Return the ordinary index that refracts the tilt.""" lam = np.array([self._refraction_wavelength(omega0)]) @@ -452,12 +505,37 @@ class Propagation: and a dispersionless medium). path_length : float Distance the beams travel through the medium (m). + arm_shift : float + Rate (s/m) at which the arms' delays drift apart with depth + (:meth:`CrystalSetup.arm_shift`); ``0`` but for a crystal crossed in its + principal plane. """ beta_in: NDArray[np.float64] beta_sig: NDArray[np.float64] sig_amp: NDArray[np.float64] path_length: float + arm_shift: float = 0.0 + + def arm_props( + self, + beta_in: NDArray[np.float64], + omega: NDArray[np.float64], + nodes: NDArray[np.float64], + ) -> tuple[NDArray[np.complex128], NDArray[np.complex128]]: + r"""Return the test and gate input propagators, shape ``(N, Q)``. + + ``beta_in`` and ``omega`` in the order the caller works in (centred or + DFT-bin). Each arm travels to depth ``z_q`` with ``beta_in``; with an + :attr:`arm_shift` :math:`\kappa`, the test arm also carries + :math:`e^{i\kappa\Omega(P-z_q)}` and the gate its inverse. + """ + base = np.exp(1j * np.outer(beta_in, nodes)) + if self.arm_shift == 0.0: + return base, base + drift = np.exp(1j * self.arm_shift * np.outer(omega, self.path_length - nodes)) + test = np.asarray(base * drift, dtype=np.complex128) + return test, np.asarray(base / drift, dtype=np.complex128) def propagation( @@ -519,7 +597,11 @@ def propagation( beta_sig[bad_sig] = 0.0 sig_amp[bad_sig] = 0.0 return Propagation( - beta_in, beta_sig, sig_amp, setup.path_length(float(thickness), omega0) + beta_in, + beta_sig, + sig_amp, + setup.path_length(float(thickness), omega0), + setup.arm_shift(omega0), ) @@ -606,64 +688,6 @@ def depth_points( return math.ceil(phi) + 3 -def tilt_phase_error( - setup: CrystalSetup, - omega: ArrayLike, - omega0: float, - thickness: float, - band: tuple[float, float] | None = None, -) -> float: - r"""Largest phase of the neglected signal tilt over the grid (rad). - - The signal of the pair :math:`(\omega_1,\omega_2)` leaves at - :math:`\delta\theta = (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to the - bisector. In the principal plane (``polarization="perpendicular"``) that - changes its index by :math:`(\mathrm dn_e/\mathrm d\theta)\,\delta\theta`, and its - phase over the half-path by :math:`(\omega_s/c)(\mathrm dn_e/\mathrm - d\theta)\,\delta\theta\, L/2`. Out of the principal plane - (``"parallel"``), or collinear, the first-order term vanishes and this returns - ``0``. - - Parameters - ---------- - setup : CrystalSetup - The crystal. - omega : array_like - Centred angular-frequency grid (rad/s). - omega0 : float - Pulse carrier (rad/s). - thickness : float - Plate thickness (m). - band : tuple of float or None, optional - Absolute angular frequencies ``(lo, hi)`` (rad/s) of the fundamental's - band (see :func:`spectral_band`); only pairs of components inside it - count. ``None`` (default) takes the whole grid, which overstates the error - badly when the pulse fills only part of it: the worst pair then sits at - the grid's edges, where there is no light. - - Returns - ------- - float - The estimate, maximised over the component pairs in the band. - """ - if setup.geometry is None or setup.polarization != "perpendicular" or not thickness: - return 0.0 - _, w1, w2, theta = _pair_mismatch(setup, np.asarray(omega, dtype=float), omega0) - if band is not None: - lo, hi = band - inside = (w1 >= lo) & (w1 <= hi) & (w2 >= lo) & (w2 <= hi) - w1, w2 = w1[inside], w2[inside] - if w1.size == 0: - return 0.0 - ws = w1 + w2 - lam = wlfreq(ws) - n_o, n_e = setup.crystal.n_o(lam), setup.crystal.n_e(lam) - n_s = extraordinary_index(n_o, n_e, theta) - dtheta = (w1 - w2) * math.sin(setup.crossing_half_angle) / (ws * n_s) - phase = ws / C * np.abs(_dn_dtheta(n_o, n_e, theta) * dtheta) - return float(np.max(phase)) * setup.path_length(thickness, omega0) / 2.0 - - def check_medium( interaction: Interaction, material: str | CrystalSetup | None, @@ -703,9 +727,9 @@ def check_medium( Notes ----- - The neglected signal tilt depends on where the pulse has light, which the - forward model does not know; :func:`check_tilt` tests it once the band is - known. + What the model leaves out of the signal's tilt depends on where the pulse + has light, which the forward model does not know; :func:`check_tilt` tests + it once the spectrum is known. """ is_crystal = isinstance(material, CrystalSetup) if interaction.omega0_scale != 1.0 and material is not None and thickness: @@ -744,42 +768,31 @@ def check_medium( ) -def spectral_band( - omega: ArrayLike, intensity: ArrayLike, level: float = 1e-3 -) -> tuple[float, float]: - """Frequency band where a spectrum exceeds ``level`` of its peak. - - Parameters - ---------- - omega : array_like - Angular frequencies (rad/s) of the samples. - intensity : array_like - Spectral intensity at those frequencies. - level : float, optional - Threshold relative to the peak (default ``1e-3``), in ``(0, 1)``. - - Returns - ------- - tuple of float - ``(lo, hi)``, the lowest and highest frequency above the threshold. - - Raises - ------ - ValueError - If the spectrum has no positive intensity. - - Examples - -------- - >>> spectral_band([1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 0.5, 0.0]) - (2.0, 3.0) +def _signal_direction( + n_o: NDArray[np.float64], + n_e: NDArray[np.float64], + theta: float, + k0: float, + k_x: NDArray[np.float64], + n_s: float, +) -> NDArray[np.float64]: + r"""Solve for the signal's angle :math:`\psi` to the bisector, per pair. + + The signal's wavevector has the transverse component ``k_x`` it inherits from + the beams and the magnitude :math:`k_0 n_e(\theta+\psi)` of an extraordinary + wave in its own direction, so :math:`k_0 n_e(\theta+\psi)\sin\psi = k_x`. + Newton's method from the first-order solution :math:`k_x/(k_0 n_s)`, whose + error is :math:`O(\psi^2)` with :math:`\psi` a few mrad: Newton's quadratic + convergence takes it to rounding in two or three steps, and four leave a + margin (``tests/test_crystals.py`` checks the residual). """ - omega = np.asarray(omega, dtype=float) - intensity = np.asarray(intensity, dtype=float) - peak = float(np.max(intensity)) - if not peak > 0.0: - raise ValueError("the spectrum has no positive intensity") - above = omega[intensity > level * peak] - return float(above.min()), float(above.max()) + psi = k_x / (k0 * n_s) + for _ in range(4): + n = extraordinary_index(n_o, n_e, theta + psi) + f = k0 * n * np.sin(psi) - k_x + df = k0 * (_dn_dtheta(n_o, n_e, theta + psi) * np.sin(psi) + n * np.cos(psi)) + psi = psi - f / df + return psi def _pair_signal( @@ -794,10 +807,11 @@ def _pair_signal( ) -> NDArray[np.complex128]: r"""Signal at delay ``tau`` as the exact sum over component pairs, centred order. - The depth integral of each pair is done analytically. With ``tilted`` the - signal of each pair propagates in its own direction, at - :math:`\delta\theta` to the bisector (to first order), which the model - neglects. + The depth integral of each pair is done analytically. Without ``tilted`` it is the + model: each pair's signal along the bisector, with the arms' first-order delay + drift. With ``tilted`` each pair's signal propagates in its own direction, + found self-consistently with the index in that direction + (:func:`_signal_direction`). """ prop = propagation(setup, omega, omega0, thickness) path = prop.path_length @@ -817,17 +831,19 @@ def _pair_signal( if amp[k] == 0.0: continue m = (k - j) % n - bs = np.full(n, b_sig[k]) + bs = b_sig[k] + prop.arm_shift * (w[j] - w[m]) if tilted: w1, w2 = w[j] + omega0, w[m] + omega0 ws = w[k] + 2.0 * omega0 lam = np.array([float(wlfreq(ws))]) n_o, n_e = setup.crystal.n_o(lam), setup.crystal.n_e(lam) n_s = float(extraordinary_index(n_o, n_e, theta)[0]) - dtheta = (w1 - w2) * sin_alpha / (ws * n_s) - k_mag = ws / C * extraordinary_index(n_o, n_e, theta + dtheta) - k_x = (w1 - w2) * sin_alpha / C - bs = np.sqrt(k_mag**2 - k_x**2) - beta1 * w[k] + sign = 1.0 if setup.delayed_beam == "toward_axis" else -1.0 + # transverse wavevector, positive towards a larger angle to the axis + k_x = sign * (w1 - w2) * sin_alpha / C + direction = _signal_direction(n_o, n_e, theta, ws / C, k_x, n_s) + n_dir = extraordinary_index(n_o, n_e, theta + direction) + bs = ws / C * n_dir * np.cos(direction) - beta1 * w[k] a = b_in[j] + b_in[m] - bs with np.errstate(divide="ignore", invalid="ignore"): depth = (np.exp(1j * a * path) - 1.0) / (1j * a) @@ -844,21 +860,21 @@ def tilt_field_error( amplitude: ArrayLike, delays: ArrayLike, ) -> float: - r"""Relative change of the signal field that the neglected signal tilt makes. + r"""Relative change of the signal field from what the model leaves of the tilt. Evaluates the signal of a transform-limited pulse with spectral amplitude ``amplitude`` at each of ``delays`` twice, by the exact sum over component - pairs: as the model has it, and with each pair's signal propagating in its own - direction (:func:`tilt_phase_error` describes the term). Returns the largest - difference relative to the largest signal over all the delays. ``0`` out of - the principal plane (``polarization="parallel"``) or collinear. + pairs: as the model has it (the arms' first-order delay drift), and with each + pair's signal propagating in its own direction with the exact index there. + Returns the largest difference relative to the largest signal over all the + delays. ``0`` out of the principal plane (``polarization="parallel"``) or + collinear. - The delays matter: the extra mismatch is odd in :math:`\omega_1-\omega_2`, so + Scan the delays: the tilt's mismatch is odd in :math:`\omega_1-\omega_2`, so at zero delay, where the pairs :math:`(\omega_1,\omega_2)` and - :math:`(\omega_2,\omega_1)` enter alike, its first-order effect cancels; away - from zero delay it does not, and is tens of times larger. Delays out to about - the pulse duration capture the worst case. It costs :math:`N^2` operations per - delay for an :math:`N`-point grid. + :math:`(\omega_2,\omega_1)` enter alike, much of its effect cancels. Delays + out to about the pulse duration capture the worst case. It costs :math:`N^2` + operations per delay for an :math:`N`-point grid. Parameters ---------- @@ -904,7 +920,7 @@ def check_tilt( amplitude: ArrayLike, delays: ArrayLike, ) -> float: - """Warn if the neglected signal tilt changes this pulse's signal noticeably. + """Warn if what the model leaves of the signal's tilt matters for this pulse. Parameters ---------- @@ -934,10 +950,11 @@ def check_tilt( error = tilt_field_error(setup, omega, omega0, thickness, amplitude, delays) if error > TILT_ERROR_WARN: warnings.warn( - f"the crystal model neglects the signal's tilt in the principal plane, " - f"which changes this pulse's signal by up to {error:.1%} of its peak " - f"(above {TILT_ERROR_WARN:.0%}). A thinner crystal, a smaller crossing " - f"angle, or the fundamental polarised in the crossing plane avoids it", + f"the crystal model keeps the signal's tilt in the principal plane to " + f"first order only; the rest changes this pulse's signal by up to " + f"{error:.1%} of its peak (above {TILT_ERROR_WARN:.0%}). A thinner " + f"crystal, a smaller crossing angle, or the fundamental polarised in " + f"the crossing plane avoids it", CrystalApproximationWarning, stacklevel=2, ) diff --git a/croak/forward.py b/croak/forward.py index 255fa16..2929404 100644 --- a/croak/forward.py +++ b/croak/forward.py @@ -182,7 +182,12 @@ def __init__( # Propagation phase matrices, shape (N, Q), in DFT-bin order: the field # travels to depth z_q, the signal born there travels the rest of the path. - self.input_prop = np.exp(1j * np.outer(beta_in_bin, nodes)) + # The two arms differ only for a crystal crossed in its principal plane, + # where their delays drift apart with depth (crystals.CrystalSetup.arm_shift); + # otherwise gate_prop is input_prop. + self.input_prop, self.gate_prop = prop.arm_props( + beta_in_bin, self.omega_bin, nodes + ) self.signal_prop = sig_amp_bin[:, None] * np.exp( 1j * np.outer(beta_sig_bin, self.path_length - nodes) ) @@ -229,7 +234,7 @@ def signal_single( phase = np.exp(1j * self.omega_bin * tau) # (N, Q) propagated input spectra for test (undelayed) and gate (delayed) e0 = ew_bin[:, None] * self.input_prop - etau = (ew_bin * phase)[:, None] * self.input_prop + etau = (ew_bin * phase)[:, None] * self.gate_prop test = _fft0(e0) gate = _fft0(etau) sig = self.interaction.signal(test, gate) @@ -366,7 +371,7 @@ def adjoint_single(self, psi_bar: Complex, tau: float) -> Complex: phase = np.exp(1j * self.omega_bin * tau) ew_bar_bin = ( np.conj(self.input_prop) * e0_bar - + np.conj(phase[:, None] * self.input_prop) * etau_bar + + np.conj(phase[:, None] * self.gate_prop) * etau_bar ).sum(axis=1) return scipy.fft.fftshift(ew_bar_bin) diff --git a/croak/forward_jax.py b/croak/forward_jax.py index 42c3405..ec03c39 100644 --- a/croak/forward_jax.py +++ b/croak/forward_jax.py @@ -133,7 +133,7 @@ def _smear_scale_pair(smear_scale) -> tuple[jnp.ndarray, jnp.ndarray]: def _static_props(material, omega, omega0, thickness, npoints, quadrature): - """``(input_prop, signal_prop, weights)`` for a fixed medium, as ForwardModel. + """``(input_prop, gate_prop, signal_prop, weights)`` for a fixed medium. Propagation phase matrices ``(N, Q)`` in DFT-bin order: the field travels to depth ``z_q``, the signal born there the rest of the path, which in a tilted @@ -144,11 +144,11 @@ def _static_props(material, omega, omega0, thickness, npoints, quadrature): beta_in = np.fft.ifftshift(prop.beta_in) beta_sig = np.fft.ifftshift(prop.beta_sig) sig_amp = np.fft.ifftshift(prop.sig_amp) - input_prop = np.exp(1j * np.outer(beta_in, nodes)) + input_prop, gate_prop = prop.arm_props(beta_in, np.fft.ifftshift(omega), nodes) signal_prop = sig_amp[:, None] * np.exp( 1j * np.outer(beta_sig, prop.path_length - nodes) ) - return input_prop, signal_prop, weights + return input_prop, gate_prop, signal_prop, weights class _SignalConstants: @@ -164,6 +164,7 @@ class _SignalConstants: "n", "omega_bin", "input_prop", + "gate_prop", "signal_prop", "weights", "signal_map", @@ -180,7 +181,7 @@ def __init__( inter, material, float(thickness), npoints, omega, omega0, quadrature ) omega_bin = np.fft.ifftshift(omega) - input_prop, signal_prop, weights = _static_props( + input_prop, gate_prop, signal_prop, weights = _static_props( material, omega, omega0, float(thickness), npoints, quadrature ) @@ -188,6 +189,7 @@ def __init__( self.n = int(omega.size) self.omega_bin = jnp.asarray(omega_bin) self.input_prop = jnp.asarray(input_prop) + self.gate_prop = jnp.asarray(gate_prop) self.signal_prop = jnp.asarray(signal_prop) self.weights = jnp.asarray(weights) self.signal_map = _JAX_INTERACTIONS[inter.name] @@ -208,7 +210,7 @@ def _signal_with_tape( phase = jnp.exp(1j * c.omega_bin * tau) # (N, Q) propagated input spectra for the test (undelayed) and gate (delayed) e0 = ew_bin[:, None] * c.input_prop - etau = (ew_bin * phase)[:, None] * c.input_prop + etau = (ew_bin * phase)[:, None] * c.gate_prop test = jnp.fft.fft(e0, axis=0) gate = jnp.fft.fft(etau, axis=0) sig = c.signal_map(test, gate) @@ -241,7 +243,7 @@ def _adjoint( phase = jnp.exp(1j * c.omega_bin * tau) ew_bar_bin = ( jnp.conj(c.input_prop) * e0_bar - + jnp.conj(phase[:, None] * c.input_prop) * etau_bar + + jnp.conj(phase[:, None] * c.gate_prop) * etau_bar ).sum(axis=1) return jnp.fft.fftshift(ew_bar_bin) @@ -816,16 +818,21 @@ def props(thk: jnp.ndarray | float): weights = thk * w_hat return input_prop, signal_prop, weights if dw is None else weights * dw + def gate_props(thk: jnp.ndarray | float, input_prop: jnp.ndarray): + """Gate arm's propagator: the test arm's, for an isotropic slab.""" + return input_prop + def depth_remaining(thk: jnp.ndarray | float) -> jnp.ndarray: """Remaining slab ``L - z_q`` per depth node, differentiable in ``L``.""" return thk * (1.0 - xi) else: # Thickness held fixed: bake the propagation matrices once, exactly as the # standard forward model (handles the thin single-node case). - input_np, signal_np, weights0 = _static_props( + input_np, gate_np, signal_np, weights0 = _static_props( material, omega, omega0, float(thickness), npoints, quadrature ) input_prop_c = jnp.asarray(input_np) + gate_prop_c = jnp.asarray(gate_np) signal_prop_c = jnp.asarray(signal_np) weights_c = jnp.asarray(weights0) if dw is None else jnp.asarray(weights0) * dw # depth_transverse only (refused for a crystal), so the path is the plate @@ -835,6 +842,10 @@ def depth_remaining(thk: jnp.ndarray | float) -> jnp.ndarray: def props(thk: jnp.ndarray | float): return input_prop_c, signal_prop_c, weights_c + def gate_props(thk: jnp.ndarray | float, input_prop: jnp.ndarray): + """Gate arm's propagator (differs for a crystal's arm drift).""" + return gate_prop_c + def depth_remaining(thk: jnp.ndarray | float) -> jnp.ndarray: """Remaining slab ``L - z_q`` per depth node (thickness held fixed).""" return remaining_c @@ -844,7 +855,7 @@ def signal(ew, tau, thickness_v, tau0_v): phase = jnp.exp(1j * omega_bin * (tau - tau0_v)) input_prop, signal_prop, weights = props(thickness_v) e0 = ew_bin[:, None] * input_prop - etau = (ew_bin * phase)[:, None] * input_prop + etau = (ew_bin * phase)[:, None] * gate_props(thickness_v, input_prop) test = jnp.fft.fft(e0, axis=0) gate = jnp.fft.fft(etau, axis=0) sig = signal_map(test, gate) diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index 0501d39..9472541 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -180,19 +180,46 @@ transparency range, and the models refuse fewer nodes. It grows with the grid's width: for 100 µm of BBO tuned to 800 nm, about 18 nodes on a 560–1440 nm grid and about 50 on a grid twice as wide. -**What is neglected.** Walk-off (the crystal is thin), Type II, and the signal's -own small tilt: the signal of a pair leaves at -$\delta\theta \approx (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)$ to the bisector. When -the beams cross in the crystal's principal plane (the fundamental polarised -perpendicular to the crossing plane) this changes $n_e(\theta)$ to first order. -The extra mismatch is odd in $\omega_1-\omega_2$, so at zero delay its first-order -effect cancels between the pairs $(\omega_1,\omega_2)$ and $(\omega_2,\omega_1)$; away -from zero delay it does not. For BBO at 800 nm crossing at 1.4°, it changes the -signal by about 0.5 % for a 12 fs pulse in 10 µm, 5 % in 100 µm, and 1 % for a 5 fs -pulse in only 10 µm. {func}`croak.crystals.tilt_field_error` computes this change -for a given spectrum and set of delays by an exact pair sum, and -{func}`croak.crystals.check_tilt` warns above 1 %. Polarised in the crossing plane, -the principal plane is perpendicular to it and the term vanishes. +**The signal's tilt, and asymmetric SHG traces.** The signal of a pair +$(\omega_1,\omega_2)$ (test, gate) inherits the transverse wavevector +$k_x = (\omega_1-\omega_2)\sin\alpha/c$, so it leaves at an angle $\psi$ to the +bisector. As an extraordinary wave its index depends on that direction, and $\psi$ +solves $(\omega_s/c)\, n_e(\theta+\psi)\sin\psi = k_x$; to first order +$\psi = c k_x/(\omega_s n_s)$, the self-consistency entering only at second order. +When the beams cross in the crystal's principal plane (the fundamental polarised +perpendicular to the crossing plane), the tilt changes the signal's angle to the +optic axis, so its index changes to first order, by $n_e'\psi$. The extra mismatch +is $\kappa(\omega_1-\omega_2)$ with $\kappa = (n_e'/n_s)\sin\alpha/c$, and over the +remaining path it factorises into opposite delays of the two arms, +$\pm\kappa(P-z)$, that drift apart with depth. The model includes this +({meth}`~croak.crystals.CrystalSetup.arm_shift`): about 0.57 fs per 100 µm per arm +for BBO at 800 nm crossing at 1.4°. + +Two consequences follow: + +- **The trace is not symmetric in delay.** The drift distinguishes the two arms, so + $I(\omega,\tau) \ne I(\omega,-\tau)$, unlike the ideal SHG FROG trace. For BBO + at 800 nm crossing at 1.4° the term changes the signal by about 0.5 % for a + 12 fs pulse in 10 µm, 5 % in 100 µm, and 1 % for a 5 fs pulse in 10 µm. At zero + delay its first-order effect cancels between the pairs $(\omega_1,\omega_2)$ and + $(\omega_2,\omega_1)$, so it shows away from zero delay. +- **Its sign depends on which beam is nearer the optic axis** + (`delayed_beam="toward_axis"` or `"away_from_axis"`), which a real crystal's + markings do not reveal: they give the plane of the optic axis and the cut angle, + not which way it leans. Flipping the sign gives exactly the trace mirrored in + delay, so the data decide it: retrieve with both and keep the better fit. A + doubtful delay-axis convention is the same mirror. + +What remains is second order in the tilt. {func}`croak.crystals.tilt_field_error` +computes it for a given spectrum and set of delays, against an exact pair sum with +each pair's signal in its own self-consistent direction, and +{func}`croak.crystals.check_tilt` warns above 1 %. It is under 0.3 % for pulses of +5-12 fs in up to 100 µm at 1.4°. Polarised in the crossing plane, the principal +plane is perpendicular to the crossing plane and the first-order term vanishes. + +**What is neglected.** The beams' spatial walk-off (the crystal is thin), Type II, +the remainder of the signal tilt above, and the dispersion of the refraction at the +entrance face. ```python import numpy as np diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 54eb089..194d9d2 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -270,48 +270,60 @@ def test_depth_points_subsample_a_fine_grid(): ) -# -- the neglected signal tilt ---------------------------------------------------- -def test_tilt_phase_error_vanishes_out_of_the_principal_plane(): +# -- the arms' delay drift -------------------------------------------------------- +def test_arm_shift_is_the_first_order_tilt_rate(): + # kappa = (n_e'/n_s) sin(alpha) / c at the signal carrier, signed by the side of + # the delayed beam; independent of omega_s (it cancels). geometry = TwoBeamGeometry(5e-3, 0.1) - parallel = _tuned(geometry=geometry, polarization="parallel") - assert crystals.tilt_phase_error(parallel, GRID.omega, W0, 100e-6) == 0.0 - assert crystals.tilt_phase_error(_tuned(), GRID.omega, W0, 100e-6) == 0.0 - perpendicular = _tuned(geometry=geometry, polarization="perpendicular") - assert crystals.tilt_phase_error(perpendicular, GRID.omega, W0, 0.0) == 0.0 + toward = _tuned( + geometry=geometry, polarization="perpendicular", delayed_beam="toward_axis" + ) + away = _tuned( + geometry=geometry, polarization="perpendicular", delayed_beam="away_from_axis" + ) + theta = toward.internal_angle(W0) + lam = np.array([400e-9]) + n_o, n_e = BBO.n_o(lam), BBO.n_e(lam) + n_s = crystals.extraordinary_index(n_o, n_e, theta)[0] + expected = ( + crystals._dn_dtheta(n_o, n_e, theta)[0] + / n_s + * math.sin(geometry.crossing_half_angle) + / C + ) + assert toward.arm_shift(W0) == pytest.approx(expected, rel=1e-12) + assert away.arm_shift(W0) == -toward.arm_shift(W0) + # BBO at 800 nm, 1.43 degrees: -0.567 fs per 100 um (the explainer's number) + assert toward.arm_shift(W0) * 100e-6 == pytest.approx(-0.567e-15, abs=0.001e-15) -def test_tilt_phase_error_scales_with_thickness_and_angle(): - def error(separation, thickness): - setup = _tuned( - geometry=TwoBeamGeometry(separation, 0.1), polarization="perpendicular" - ) - return crystals.tilt_phase_error(setup, GRID.omega, W0, thickness) +def test_arm_shift_vanishes_out_of_the_principal_plane(): + geometry = TwoBeamGeometry(5e-3, 0.1) + assert _tuned(geometry=geometry, polarization="parallel").arm_shift(W0) == 0.0 + assert _tuned().arm_shift(W0) == 0.0 - base = error(3.5e-3, 10e-6) # ~1 degree half-angle - assert base > 0.0 - assert error(3.5e-3, 100e-6) == pytest.approx(10 * base, rel=1e-3) - # linear in sin(alpha) (to the ~1e-3 the solved angle and path move with alpha) - assert error(7.0e-3, 10e-6) == pytest.approx(2 * base, rel=2e-2) +@pytest.mark.parametrize("delayed_beam", [None, "upstream"]) +def test_principal_plane_needs_the_delayed_beam_side(delayed_beam): + with pytest.raises(ValueError, match="delayed_beam"): + _tuned( + geometry=TwoBeamGeometry(5e-3, 0.1), + polarization="perpendicular", + delayed_beam=delayed_beam, + ) -def test_tilt_phase_error_matches_a_direct_estimate(): - # One pair, by hand: the grid's extreme pair dominates. - geometry = TwoBeamGeometry(3.5e-3, 0.1) - setup = _tuned(geometry=geometry, polarization="perpendicular") - estimate = crystals.tilt_phase_error(setup, GRID.omega, W0, 100e-6) - theta = setup.internal_angle(W0) - alpha = geometry.crossing_half_angle - half = float(np.max(np.abs(GRID.omega))) - w1, w2 = W0 + half, W0 - half # the widest pair still on the signal grid - ws = w1 + w2 - lam = wlfreq(ws) - n_o, n_e = BBO.n_o(np.array([lam])), BBO.n_e(np.array([lam])) - n_s = crystals.extraordinary_index(n_o, n_e, theta)[0] - dn = crystals._dn_dtheta(n_o, n_e, theta)[0] - by_hand = ws / C * abs(dn) * (w1 - w2) * math.sin(alpha) / (ws * n_s) * 50e-6 - by_hand /= math.cos(setup.internal_tilt(W0)) - # the subsampled pair grid reaches the extreme pair to within a grid step - assert estimate == pytest.approx(by_hand, rel=2e-2) + +def test_signal_direction_solves_the_self_consistent_equation(): + # k0 n_e(theta + psi) sin(psi) = k_x, to rounding, for a spread of k_x. + theta = 0.51 + lam = np.array([400e-9]) + n_o, n_e = BBO.n_o(lam), BBO.n_e(lam) + n_s = float(crystals.extraordinary_index(n_o, n_e, theta)[0]) + k0 = 2 * W0 / C + k_x = np.linspace(-0.01, 0.01, 11) * k0 * n_s + psi = crystals._signal_direction(n_o, n_e, theta, k0, k_x, n_s) + residual = k0 * crystals.extraordinary_index(n_o, n_e, theta + psi) * np.sin(psi) + np.testing.assert_allclose(residual, k_x, rtol=0, atol=1e-9 * k0) def test_crossing_wavevector_matches_internal_refraction(): diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py index 9f96dca..ad629e6 100644 --- a/tests/test_forward_crystal.py +++ b/tests/test_forward_crystal.py @@ -77,7 +77,9 @@ def _pair_sum(setup, thickness, ew, tau, beta_sig_pair=None): psi = np.zeros(n, dtype=complex) for k in range(n): m = (k - j) % n - bs = b_sig[k] if beta_sig_pair is None else beta_sig_pair(j, m, k) + # the model: the signal along the bisector, plus the arms' delay drift + model = b_sig[k] + prop.arm_shift * (w[j] - w[m]) + bs = model if beta_sig_pair is None else beta_sig_pair(j, m, k) a = b_in[j] + b_in[m] - bs h = np.exp(1j * bs * path) * _depth_integral(a, path) psi[k] = amp[k] * np.sum(e[j] * e_tau[m] * h) @@ -85,10 +87,20 @@ def _pair_sum(setup, thickness, ew, tau, beta_sig_pair=None): # -- agreement with the exact pair sum ------------------------------------------ +# The geometries: out of the principal plane, and in it with the arms' delay drift. +GEOMETRIES = { + "parallel": dict(geometry=GEOMETRY, polarization="parallel"), + "principal": dict( + geometry=GEOMETRY, polarization="perpendicular", delayed_beam="toward_axis" + ), +} + + +@pytest.mark.parametrize("plane", GEOMETRIES) @pytest.mark.parametrize("thickness", [10e-6, 100e-6]) @pytest.mark.parametrize("tau", [-15e-15, 0.0, 8e-15]) -def test_signal_matches_the_exact_pair_sum(thickness, tau): - setup = _setup(geometry=GEOMETRY, polarization="parallel") +def test_signal_matches_the_exact_pair_sum(thickness, tau, plane): + setup = _setup(**GEOMETRIES[plane]) ew = _pulse(GRID) model = _model(setup, thickness, np.array([tau])) psi = model.signal_single(ew, tau) @@ -174,66 +186,91 @@ def beta_sig_pair(j, m, k): ws = w[k] + 2 * W0 lam = 2 * np.pi * C / ws n_o, n_e = BBO.n_o(np.array([lam])), BBO.n_e(np.array([lam])) - n_s = crystals.extraordinary_index(n_o, n_e, theta)[0] - dtheta = (w1 - w2) * sin_a / (ws * n_s) - n_tilted = crystals.extraordinary_index(n_o, n_e, theta + dtheta) - k_x = (w1 - w2) * sin_a / C - k_mag = ws / C * n_tilted - return np.sqrt(k_mag**2 - k_x**2) - beta1 * w[k] + k0 = ws / C + sign = 1.0 if setup.delayed_beam == "toward_axis" else -1.0 + k_x = sign * (w1 - w2) * sin_a / C + + # Self-consistent direction psi: k0 n_e(theta + psi) sin(psi) = k_x, solved + # by bisection over +-10 mrad (independently of the library's Newton). + def f(p): + return ( + k0 * crystals.extraordinary_index(n_o, n_e, theta + p) * np.sin(p) - k_x + ) + + lo, hi = np.full_like(k_x, -1e-2), np.full_like(k_x, 1e-2) + for _ in range(60): + mid = 0.5 * (lo + hi) + below = f(mid) < 0 + lo, hi = np.where(below, mid, lo), np.where(below, hi, mid) + psi = 0.5 * (lo + hi) + n_psi = crystals.extraordinary_index(n_o, n_e, theta + psi) + return k0 * n_psi * np.cos(psi) - beta1 * w[k] return beta_sig_pair -def _band(ew): - """The pulse's band (absolute rad/s), where its spectrum exceeds 1e-3 of peak.""" - return crystals.spectral_band(GRID.omega + W0, np.abs(ew) ** 2) - - -def test_the_tilt_estimate_over_the_band_bounds_the_neglected_term(): - thickness = 100e-6 - setup = _setup(geometry=GEOMETRY, polarization="perpendicular") - ew = _pulse(GRID) - band = _band(ew) - estimate = crystals.tilt_phase_error(setup, GRID.omega, W0, thickness, band) - whole_grid = crystals.tilt_phase_error(setup, GRID.omega, W0, thickness) - cheap = _pair_sum(setup, thickness, ew, 0.0) - exact = _pair_sum(setup, thickness, ew, 0.0, _tilted_signal(setup, thickness)) - error = np.max(np.abs(cheap - exact)) / np.max(np.abs(exact)) - # A phase error phi changes a pair's term by at most |exp(i phi) - 1| ~ phi, so - # the band's worst pair bounds the field's error; the whole grid's worst pair, - # at edges without light, overstates it far more. - assert 0.0 < error < estimate < whole_grid - - DELAYS = np.linspace(-24e-15, 24e-15, 9) +PRINCIPAL = dict(geometry=GEOMETRY, polarization="perpendicular") -def test_tilt_field_error_is_the_pair_sum_difference(): - # The library's estimate against this module's own tilted reference. - thickness = 100e-6 - setup = _setup(geometry=GEOMETRY, polarization="perpendicular") - amp = np.abs(_pulse(GRID, gdd=0.0)) - tilted = _tilted_signal(setup, thickness) +def _worst(setup, thickness, amp, beta_sig_pair): + """Largest |model - reference| over DELAYS, relative to the reference's peak.""" + reference = _tilted_signal(setup, thickness) pairs = [ ( - _pair_sum(setup, thickness, amp, t), - _pair_sum(setup, thickness, amp, t, tilted), + _pair_sum(setup, thickness, amp, t, beta_sig_pair), + _pair_sum(setup, thickness, amp, t, reference), ) for t in DELAYS ] worst = max(np.max(np.abs(a - b)) for a, b in pairs) - peak = max(np.max(np.abs(b)) for _, b in pairs) - error = crystals.tilt_field_error(setup, GRID.omega, W0, thickness, amp, DELAYS) - assert error == pytest.approx(worst / peak, rel=1e-9) + return worst / max(np.max(np.abs(b)) for _, b in pairs) -def test_tilt_field_error_is_far_larger_away_from_zero_delay(): - # At zero delay the first-order term cancels between (w1, w2) and (w2, w1). - setup = _setup(geometry=GEOMETRY, polarization="perpendicular") +@pytest.mark.parametrize("side", ["toward_axis", "away_from_axis"]) +def test_arm_drift_captures_the_signal_tilt(side): + # 12 fs in 100 um crossing at 1.43 degrees in the principal plane. Against each + # pair's signal in its own self-consistent direction: with the arms' drift the + # model is within 0.1 % (the residual is second order in the tilt); without it, + # about 5 % off. + setup = _setup(**PRINCIPAL, delayed_beam=side) amp = np.abs(_pulse(GRID, gdd=0.0)) - at_zero = crystals.tilt_field_error(setup, GRID.omega, W0, 100e-6, amp, [0.0]) - scanned = crystals.tilt_field_error(setup, GRID.omega, W0, 100e-6, amp, DELAYS) - assert scanned > 5 * at_zero + with_drift = _worst(setup, 100e-6, amp, None) + prop = crystals.propagation(setup, GRID.omega, W0, 100e-6) + b_sig = scipy.fft.ifftshift(prop.beta_sig) + without = _worst(setup, 100e-6, amp, lambda j, m, k: b_sig[k]) + assert with_drift < 1e-3 + assert without > 0.03 + + +def test_the_wrong_side_is_the_delay_mirror(): + # Flipping the side is the same as mirroring the delay axis (swapping the arms + # of SHG), to quadrature accuracy; the two sides differ, so the data can tell. + delays = np.linspace(-30e-15, 30e-15, 13) + ew = _pulse(GRID, fwhm=8e-15, gdd=40e-30) + toward = _model(_setup(**PRINCIPAL, delayed_beam="toward_axis"), 100e-6, delays) + away = _model(_setup(**PRINCIPAL, delayed_beam="away_from_axis"), 100e-6, delays) + a = toward.trace(ew, normalize=False) + b = away.trace(ew, normalize=False) + # The discrete grid is not exactly symmetric (an even N runs from -N/2 to N/2-1), + # so even a trace without the drift departs from its mirror at the grid edges; + # the side flip must match the mirror to that same level, here about 5e-5. + plain = _model(_setup(geometry=GEOMETRY, polarization="parallel"), 100e-6, delays) + c = plain.trace(ew, normalize=False) + grid_asymmetry = np.max(np.abs(c - c[:, ::-1])) / c.max() + assert np.max(np.abs(a - b[:, ::-1])) / a.max() < 2 * grid_asymmetry + assert np.max(np.abs(a - b)) > 0.03 * a.max() + + +def test_tilt_field_error_is_the_pair_sum_difference(): + # The library's residual estimate against this module's own reference. + setup = _setup(**PRINCIPAL, delayed_beam="toward_axis") + amp = np.abs(_pulse(GRID, gdd=0.0)) + expected = _worst(setup, 100e-6, amp, None) + error = crystals.tilt_field_error(setup, GRID.omega, W0, 100e-6, amp, DELAYS) + # two independent root solves (Newton here, bisection in the test) agree to + # about 1e-15 rad; the differences they leave are far below the residual + assert error == pytest.approx(expected, rel=1e-6) def test_tilt_field_error_vanishes_out_of_the_principal_plane(): @@ -245,32 +282,25 @@ def test_tilt_field_error_vanishes_out_of_the_principal_plane(): def test_check_tilt_warns_above_one_percent(): - # 12 fs in 100 um at a 1.43 degree crossing: about 5 % (first order, off zero - # delay). - setup = _setup(geometry=GEOMETRY, polarization="perpendicular") - amp = np.abs(_pulse(GRID, gdd=0.0)) - with pytest.warns(CrystalApproximationWarning, match="neglects the signal's tilt"): - error = crystals.check_tilt(setup, GRID.omega, W0, 100e-6, amp, DELAYS) + # A 5 fs pulse, 300 um, crossing at 2.86 degrees: the second-order residual + # reaches about 3 %. + setup = _setup( + geometry=TwoBeamGeometry(beam_separation=10e-3, focal_length=0.1), + polarization="perpendicular", + delayed_beam="toward_axis", + ) + amp = np.abs(_pulse(GRID, fwhm=5e-15, gdd=0.0)) + with pytest.warns(CrystalApproximationWarning, match="first order only"): + error = crystals.check_tilt(setup, GRID.omega, W0, 300e-6, amp, DELAYS) assert error > crystals.TILT_ERROR_WARN def test_check_tilt_is_silent_below_one_percent(): - setup = _setup(geometry=GEOMETRY, polarization="perpendicular") + setup = _setup(**PRINCIPAL, delayed_beam="toward_axis") amp = np.abs(_pulse(GRID, gdd=0.0)) - assert crystals.check_tilt(setup, GRID.omega, W0, 5e-6, amp, DELAYS) < 0.01 - - -def test_a_band_without_pairs_has_no_tilt_error(): - setup = _setup(geometry=GEOMETRY, polarization="perpendicular") - assert crystals.tilt_phase_error(setup, GRID.omega, W0, 100e-6, (1.0, 2.0)) == 0.0 + assert crystals.check_tilt(setup, GRID.omega, W0, 100e-6, amp, DELAYS) < 0.01 -def test_spectral_band_needs_light(): - with pytest.raises(ValueError, match="no positive intensity"): - crystals.spectral_band([1.0, 2.0], [0.0, 0.0]) - - -# -- guards ------------------------------------------------------------------------ def test_an_isotropic_slab_cannot_model_shg(): with pytest.raises(ValueError, match="dispersive propagation in an isotropic"): ForwardModel( @@ -284,8 +314,9 @@ def test_a_crystal_models_shg_only(): # -- the JAX models ----------------------------------------------------------------- -def test_jax_trace_matches_numpy(): - setup = _setup(geometry=GEOMETRY, polarization="parallel") +@pytest.mark.parametrize("plane", GEOMETRIES) +def test_jax_trace_matches_numpy(plane): + setup = _setup(**GEOMETRIES[plane]) thickness = 50e-6 ew = _pulse(GRID) delays = np.linspace(-20e-15, 20e-15, 7) @@ -320,9 +351,10 @@ def test_jax_crystal_refuses_slab_only_options(option): # -- the hand-derived adjoint --------------------------------------------------- -def test_adjoint_matches_finite_differences(): +@pytest.mark.parametrize("plane", GEOMETRIES) +def test_adjoint_matches_finite_differences(plane): rng = np.random.default_rng(11) - setup = _setup() + setup = _setup(**GEOMETRIES[plane]) thickness = 50e-6 ew = _pulse(GRID) + 0.05 * ( rng.standard_normal(GRID.n) + 1j * rng.standard_normal(GRID.n) @@ -378,10 +410,13 @@ def test_tilt_field_error_skips_absorbed_signal_frequencies(): phase_match_wavelength=800e-9, geometry=GEOMETRY, polarization="perpendicular", + delayed_beam="toward_axis", ) amp = np.abs(_pulse(GRID, gdd=0.0)) full = crystals.tilt_field_error( - _setup(geometry=GEOMETRY, polarization="perpendicular"), + _setup( + geometry=GEOMETRY, polarization="perpendicular", delayed_beam="toward_axis" + ), GRID.omega, W0, 100e-6, From e27d04be719f35f1c08ea17a4c286ec52af349e7 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 20:56:31 +0000 Subject: [PATCH 09/16] Address the crystal core's re-review Test the JAX hand adjoint with the arms' drift; pin the side flip to the delay mirror exactly on grid-aligned delays; reject a tilt beyond grazing, a non-finite thickness and an all-zero amplitude; write n_e'/n_s and the arms' delays explicitly; note what depth_points and the tilt reference leave out; correct two figures in the manual and a typo in the fragment. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- changelog.d/shg-crystal.added.md | 2 +- croak/crystals.py | 57 ++++++++++++++++++++++--------- docs/explanation/forward_model.md | 8 ++--- tests/test_crystals.py | 22 +++++++++++- tests/test_forward_crystal.py | 52 ++++++++++++++++++++++------ 5 files changed, 109 insertions(+), 32 deletions(-) diff --git a/changelog.d/shg-crystal.added.md b/changelog.d/shg-crystal.added.md index b8227ea..05b8962 100644 --- a/changelog.d/shg-crystal.added.md +++ b/changelog.d/shg-crystal.added.md @@ -1 +1 @@ -SHG in a Type I crystal: `croak.crystals.CrystalSetup` (cut angle with an external tilt or the wavelength the crystal was tuned to, the crossing geometry from `croak.geometry.TwoBeamGeometry`, and the fundamental's polarisation relative to the crossing plane), passed as `material` to the forward models for SHG, propagates the signal near 2ω0 as the extraordinary wave and so models phase matching, group-velocity mismatch and the ω/n generation prefactor. `croak.crystals.depth_points` gives the depth nodes the phase mismatch needs, With the beams crossing in the crystal's principal plane the signal's tilt makes the trace asymmetric in delay; the model includes it, to first order, as opposite delay drifts of the two arms (`delayed_beam` sets its sign, which flipping mirrors the trace in delay), and `check_tilt` warns where the remainder matters (#24). +SHG in a Type I crystal: `croak.crystals.CrystalSetup` (cut angle with an external tilt or the wavelength the crystal was tuned to, the crossing geometry from `croak.geometry.TwoBeamGeometry`, and the fundamental's polarisation relative to the crossing plane), passed as `material` to the forward models for SHG, propagates the signal near 2ω0 as the extraordinary wave and so models phase matching, group-velocity mismatch and the ω/n generation prefactor. `croak.crystals.depth_points` gives the depth nodes the phase mismatch needs. With the beams crossing in the crystal's principal plane the signal's tilt makes the trace asymmetric in delay; the model includes it, to first order, as opposite delay drifts of the two arms (`delayed_beam` sets its sign, which flipping mirrors the trace in delay), and `check_tilt` warns where the remainder matters (#24). diff --git a/croak/crystals.py b/croak/crystals.py index 88167a3..f20b0f6 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -59,7 +59,7 @@ :math:`\theta = \theta_c + \gamma_\mathrm{int}`. The mismatch in a tilted plate of thickness :math:`L` builds up along the face normal, which to first order is the mismatch along the beams over the effective path -:math:`L/(\cos\gamma_\mathrm{int} + (n_e'/n_e)\sin\gamma_\mathrm{int})` +:math:`L/(\cos\gamma_\mathrm{int} + (n_e'/n_s)\sin\gamma_\mathrm{int})` (:meth:`CrystalSetup.path_length`). :class:`CrystalSetup` takes either :math:`\gamma` or the wavelength the crystal was tuned to phase-match, from which :math:`\theta` is solved. Approximations: the refraction @@ -338,6 +338,11 @@ def __post_init__(self) -> None: "give exactly one of tilt (the external tilt) and " "phase_match_wavelength (the wavelength the crystal is tuned to)" ) + if self.tilt is not None and not abs(self.tilt) < 0.5 * math.pi: + raise ValueError( + f"the external tilt must lie strictly between -pi/2 and pi/2 rad, " + f"got {self.tilt!r}" + ) if not 0.0 <= self.cut_angle <= 0.5 * math.pi: raise ValueError( f"cut_angle must lie in [0, pi/2] rad, got {self.cut_angle!r}" @@ -432,11 +437,12 @@ def path_length(self, thickness: float, omega0: float) -> float: :math:`\Delta k_\perp L = \Delta k\, L_\mathrm{eff}` with .. math:: L_\mathrm{eff} = \frac{L}{\cos\gamma_\mathrm{int} - + (n_e'/n_e)\sin\gamma_\mathrm{int}}, + + (n_e'/n_s)\sin\gamma_\mathrm{int}}, - :math:`n_e' = \mathrm dn_e/\mathrm d\theta` at the signal carrier - :math:`2\omega_0` (derived in ``docs/explanation/forward_model.md``; it - agrees with an exact boundary-value solve to the mismatch's second order, + with :math:`n_s = n_e(\theta)` and :math:`n_e' = \mathrm dn_e/\mathrm + d\theta` at :math:`\theta` and the signal carrier :math:`2\omega_0` + (derived in ``docs/explanation/forward_model.md``; it agrees with an exact + boundary-value solve to the mismatch's second order, ``tests/test_crystals.py``). Without a tilt it is ``thickness``. """ gamma = self.internal_tilt(omega0) @@ -462,11 +468,14 @@ def arm_shift(self, omega0: float) -> float: :math:`\delta\theta = \pm(\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to the bisector, which changes its index by :math:`n_e'\delta\theta`. Its mismatch grows by :math:`\kappa(\omega_1-\omega_2)` with - :math:`\kappa = \pm(n_e'/n_e)\sin\alpha/c`, taken at the signal carrier. - Over the rest of the path :math:`P-z` that is the phase - :math:`e^{i\kappa\Omega(P-z)}` on the test arm and its inverse on the gate: - opposite delays, :math:`\mp\kappa(P-z)`, that drift with depth. The sign - is ``+`` with the delayed beam toward the optic axis. ``0`` out of the + :math:`\kappa = \pm(n_e'/n_s)\sin\alpha/c`, with :math:`n_s = n_e(\theta)`, + taken at the signal carrier. Over the rest of the path :math:`P-z` that is + the phase :math:`e^{i\kappa\Omega(P-z)}` on the test arm and its inverse on + the gate. With croak's convention (a factor :math:`e^{i\Omega\tau}` delays a + field by :math:`\tau`) the test arm is delayed by :math:`+\kappa(P-z)` and + the gate by :math:`-\kappa(P-z)`, so the gate-minus-test delay at depth + :math:`z` is :math:`\tau - 2\kappa(P-z)`. The sign of :math:`\kappa` is + ``+`` with the delayed beam toward the optic axis. ``0`` out of the principal plane, where the term is second order. """ if not self.in_principal_plane: @@ -663,7 +672,10 @@ def depth_points( :math:`n \ge \lceil\varphi\rceil + 3` (checked for :math:`0.5 \le \varphi \le 60` in ``tests/test_crystals.py``). :math:`\varphi` is the maximum over every pair of grid frequencies that lands on the signal grid, so the rule holds - wherever the retrieved field puts energy. + wherever the retrieved field puts energy. It leaves out the arms' delay drift + (:meth:`CrystalSetup.arm_shift`), which adds :math:`\kappa(\omega_1-\omega_2)` + to the mismatch: at most about one rad of :math:`\varphi` even for 500 µm at + a 5.7° half-angle, inside the rule's margin. Parameters ---------- @@ -709,13 +721,13 @@ def check_medium( Plate thickness (m). npoints : int Depth quadrature nodes the model will use. - quadrature : str, optional - The depth quadrature; a crystal's node rule is for ``"gausslegendre"`` - (default). omega : array_like Centred angular-frequency grid (rad/s). omega0 : float Pulse carrier (rad/s). + quadrature : str, optional + The depth quadrature; a crystal's node rule is for ``"gausslegendre"`` + (default). Raises ------ @@ -749,8 +761,10 @@ def check_medium( if not is_crystal: return material.internal_angle(omega0) # the carrier, the angle and the tilt are valid - if thickness < 0.0: - raise ValueError(f"the crystal thickness must be >= 0, got {thickness!r}") + if not (math.isfinite(thickness) and thickness >= 0.0): + raise ValueError( + f"the crystal thickness must be finite and >= 0, got {thickness!r}" + ) if not thickness: return if quadrature != "gausslegendre": @@ -870,6 +884,10 @@ def tilt_field_error( delays. ``0`` out of the principal plane (``polarization="parallel"``) or collinear. + For a tilted plate both sums use the mismatch along the beams over the + effective path (:meth:`CrystalSetup.path_length`), so the comparison is exact + for an untilted plate and first order in the tilt otherwise. + Scan the delays: the tilt's mismatch is odd in :math:`\omega_1-\omega_2`, so at zero delay, where the pairs :math:`(\omega_1,\omega_2)` and :math:`(\omega_2,\omega_1)` enter alike, much of its effect cancels. Delays @@ -897,11 +915,18 @@ def tilt_field_error( ------- float The relative field change. + + Raises + ------ + ValueError + If ``amplitude`` is zero everywhere. """ if setup.geometry is None or setup.polarization != "perpendicular" or not thickness: return 0.0 omega = np.asarray(omega, dtype=float) amplitude = np.abs(np.asarray(amplitude, dtype=float)) + if not np.max(amplitude) > 0.0: + raise ValueError("the spectral amplitude has no positive value") worst, peak = 0.0, 0.0 for tau in np.asarray(delays, dtype=float).ravel(): args = (setup, omega, omega0, thickness, amplitude, float(tau)) diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index 9472541..406449d 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -162,9 +162,9 @@ wavevectors are $k\cos\gamma_\mathrm{int}$; the signal keeps their transverse wavevector, so its direction $\psi$ solves $K(\psi)\sin\psi = k_t$ with $K = k_s(\theta_c+\psi)$. Expanding about $\psi = \gamma_\mathrm{int}$ to first order in the mismatch $\Delta k$ gives a normal mismatch -$\Delta k/(\cos\gamma_\mathrm{int} + (n_e'/n_e)\sin\gamma_\mathrm{int})$, so the model +$\Delta k/(\cos\gamma_\mathrm{int} + (n_e'/n_s)\sin\gamma_\mathrm{int})$, so the model integrates over the effective path -$P = L/(\cos\gamma_\mathrm{int} + (n_e'/n_e)\sin\gamma_\mathrm{int})$, with +$P = L/(\cos\gamma_\mathrm{int} + (n_e'/n_s)\sin\gamma_\mathrm{int})$, with $n_s = n_e(\theta)$ and $n_e' = \mathrm dn_e/\mathrm d\theta$ at the signal carrier. A test checks it against the exact solve (agreement within 0.3 % of $\Delta k L$ at a 10° tilt, where $L/\cos\gamma_\mathrm{int}$ is about 1 % off). Nothing is derived from the @@ -178,7 +178,7 @@ $\lceil\lvert\Delta k\rvert L/2\rceil + 3$ nodes; {func}`croak.crystals.depth_po takes the maximum over every pair of grid frequencies within the crystal's transparency range, and the models refuse fewer nodes. It grows with the grid's width: for 100 µm of BBO tuned to 800 nm, about 18 nodes on a 560–1440 nm grid and -about 50 on a grid twice as wide. +about 46 on a grid twice as wide. **The signal's tilt, and asymmetric SHG traces.** The signal of a pair $(\omega_1,\omega_2)$ (test, gate) inherits the transverse wavevector @@ -200,7 +200,7 @@ Two consequences follow: - **The trace is not symmetric in delay.** The drift distinguishes the two arms, so $I(\omega,\tau) \ne I(\omega,-\tau)$, unlike the ideal SHG FROG trace. For BBO at 800 nm crossing at 1.4° the term changes the signal by about 0.5 % for a - 12 fs pulse in 10 µm, 5 % in 100 µm, and 1 % for a 5 fs pulse in 10 µm. At zero + 12 fs pulse in 10 µm, 5 % in 100 µm, and 0.5 % for a 5 fs pulse in 10 µm. At zero delay its first-order effect cancels between the pairs $(\omega_1,\omega_2)$ and $(\omega_2,\omega_1)$, so it shows away from zero delay. - **Its sign depends on which beam is nearer the optic axis** diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 194d9d2..90c74bf 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -366,7 +366,11 @@ def test_setup_rejects_an_invalid_angle_or_carrier(kwargs, omega0, match): @pytest.mark.parametrize( ("thickness", "quadrature", "match"), - [(-1e-6, "gausslegendre", "thickness must be >= 0"), (50e-6, "uniform", "Gauss")], + [ + (-1e-6, "gausslegendre", "finite and >= 0"), + (math.nan, "gausslegendre", "finite and >= 0"), + (50e-6, "uniform", "Gauss"), + ], ) def test_check_medium_rejects_bad_crystal_inputs(thickness, quadrature, match): from croak.interactions import get_interaction @@ -375,3 +379,19 @@ def test_check_medium_rejects_bad_crystal_inputs(thickness, quadrature, match): crystals.check_medium( get_interaction("shg"), _tuned(), thickness, 99, GRID.omega, W0, quadrature ) + + +@pytest.mark.parametrize("tilt_deg", [90.0, -100.0]) +def test_setup_rejects_a_tilt_beyond_grazing(tilt_deg): + with pytest.raises(ValueError, match="external tilt"): + CrystalSetup(BBO, math.radians(29.2), tilt=math.radians(tilt_deg)) + + +def test_tilt_field_error_needs_light(): + setup = _tuned( + geometry=TwoBeamGeometry(5e-3, 0.1), + polarization="perpendicular", + delayed_beam="toward_axis", + ) + with pytest.raises(ValueError, match="no positive value"): + crystals.tilt_field_error(setup, GRID.omega, W0, 50e-6, np.zeros(GRID.n), [0.0]) diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py index ad629e6..d5c8a7e 100644 --- a/tests/test_forward_crystal.py +++ b/tests/test_forward_crystal.py @@ -21,7 +21,11 @@ from croak.constants import C from croak.crystals import CrystalApproximationWarning, CrystalSetup from croak.forward import ForwardModel -from croak.forward_jax import make_param_trace_fn, make_trace_fn +from croak.forward_jax import ( + make_forward_adjoint_fns, + make_param_trace_fn, + make_trace_fn, +) from croak.geometry import TwoBeamGeometry from croak.grid import Grid @@ -245,20 +249,17 @@ def test_arm_drift_captures_the_signal_tilt(side): def test_the_wrong_side_is_the_delay_mirror(): # Flipping the side is the same as mirroring the delay axis (swapping the arms - # of SHG), to quadrature accuracy; the two sides differ, so the data can tell. - delays = np.linspace(-30e-15, 30e-15, 13) + # of SHG); the two sides differ, so the data can tell. On delays that are whole + # multiples of the grid step the identity is exact to rounding: off them, pairs + # whose sum wraps round the grid pick up a phase that differs between tau and + # -tau, which breaks it at the 5e-5 level. + delays = GRID.dt * np.arange(-10, 11) ew = _pulse(GRID, fwhm=8e-15, gdd=40e-30) toward = _model(_setup(**PRINCIPAL, delayed_beam="toward_axis"), 100e-6, delays) away = _model(_setup(**PRINCIPAL, delayed_beam="away_from_axis"), 100e-6, delays) a = toward.trace(ew, normalize=False) b = away.trace(ew, normalize=False) - # The discrete grid is not exactly symmetric (an even N runs from -N/2 to N/2-1), - # so even a trace without the drift departs from its mirror at the grid edges; - # the side flip must match the mirror to that same level, here about 5e-5. - plain = _model(_setup(geometry=GEOMETRY, polarization="parallel"), 100e-6, delays) - c = plain.trace(ew, normalize=False) - grid_asymmetry = np.max(np.abs(c - c[:, ::-1])) / c.max() - assert np.max(np.abs(a - b[:, ::-1])) / a.max() < 2 * grid_asymmetry + np.testing.assert_allclose(a, b[:, ::-1], rtol=0, atol=1e-10 * a.max()) assert np.max(np.abs(a - b)) > 0.03 * a.max() @@ -426,3 +427,34 @@ def test_tilt_field_error_skips_absorbed_signal_frequencies(): error = crystals.tilt_field_error(setup, GRID.omega, W0, 100e-6, amp, DELAYS) # the absorbed bins lie in the far wings, so the error barely moves assert error == pytest.approx(full, rel=0.2) + + +@pytest.mark.parametrize("plane", GEOMETRIES) +def test_jax_hand_adjoint_matches_numpy(plane): + # The JAX twin of the hand adjoint, against the NumPy one (which the finite + # differences above pin), with and without the arms' delay drift. + rng = np.random.default_rng(5) + setup = _setup(**GEOMETRIES[plane]) + thickness = 50e-6 + npoints = crystals.depth_points(setup, GRID.omega, W0, thickness) + ew = _pulse(GRID) + psi_bar = rng.standard_normal(GRID.n) + 1j * rng.standard_normal(GRID.n) + tau = 6e-15 + model = _model(setup, thickness, np.array([tau])) + model.signal_single(ew, tau, record=True) + expected = model.adjoint_single(psi_bar, tau) + signal_tape, adjoint = make_forward_adjoint_fns( + GRID.omega, + [tau], + "shg", + material=setup, + thickness=thickness, + npoints=npoints, + omega0=W0, + ) + _, test, gate = signal_tape(ew, tau) + got = np.asarray(adjoint(psi_bar, test, gate, tau)) + # the same FFTs and products in float64 + np.testing.assert_allclose( + got, expected, rtol=1e-10, atol=1e-12 * np.abs(expected).max() + ) From 17e969362641862b1cb5e11a61beabd38d463381 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 21:01:26 +0000 Subject: [PATCH 10/16] Restore the 5 fs figure and state the arms' delays in the manual The 0.5 % came from delays too coarse for a 5 fs pulse; sampled finely it is about 1 %. The manual now gives which arm gets which delay, and tilt_field_error refuses an empty set of delays. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- croak/crystals.py | 12 ++++++++++-- docs/explanation/forward_model.md | 10 +++++++--- tests/test_crystals.py | 10 ++++++++++ 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/croak/crystals.py b/croak/crystals.py index f20b0f6..8f2fa52 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -919,7 +919,7 @@ def tilt_field_error( Raises ------ ValueError - If ``amplitude`` is zero everywhere. + If ``amplitude`` is zero everywhere or ``delays`` is empty. """ if setup.geometry is None or setup.polarization != "perpendicular" or not thickness: return 0.0 @@ -927,8 +927,11 @@ def tilt_field_error( amplitude = np.abs(np.asarray(amplitude, dtype=float)) if not np.max(amplitude) > 0.0: raise ValueError("the spectral amplitude has no positive value") + delays = np.asarray(delays, dtype=float).ravel() + if delays.size == 0: + raise ValueError("give at least one delay to evaluate") worst, peak = 0.0, 0.0 - for tau in np.asarray(delays, dtype=float).ravel(): + for tau in delays: args = (setup, omega, omega0, thickness, amplitude, float(tau)) model = _pair_signal(*args, tilted=False) exact = _pair_signal(*args, tilted=True) @@ -967,6 +970,11 @@ def check_tilt( float The relative field change of :func:`tilt_field_error`. + Raises + ------ + ValueError + As :func:`tilt_field_error`. + Warns ----- CrystalApproximationWarning diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index 406449d..9d44518 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -190,8 +190,11 @@ When the beams cross in the crystal's principal plane (the fundamental polarised perpendicular to the crossing plane), the tilt changes the signal's angle to the optic axis, so its index changes to first order, by $n_e'\psi$. The extra mismatch is $\kappa(\omega_1-\omega_2)$ with $\kappa = (n_e'/n_s)\sin\alpha/c$, and over the -remaining path it factorises into opposite delays of the two arms, -$\pm\kappa(P-z)$, that drift apart with depth. The model includes this +remaining path it factorises into opposite delays of the two arms that drift +apart with depth: in croak's convention (a factor $e^{i\Omega\tau}$ delays a field +by $\tau$) the test arm is delayed by $+\kappa(P-z)$ and the gate by +$-\kappa(P-z)$, so the gate-minus-test delay at depth $z$ is +$\tau - 2\kappa(P-z)$. The model includes this ({meth}`~croak.crystals.CrystalSetup.arm_shift`): about 0.57 fs per 100 µm per arm for BBO at 800 nm crossing at 1.4°. @@ -200,7 +203,8 @@ Two consequences follow: - **The trace is not symmetric in delay.** The drift distinguishes the two arms, so $I(\omega,\tau) \ne I(\omega,-\tau)$, unlike the ideal SHG FROG trace. For BBO at 800 nm crossing at 1.4° the term changes the signal by about 0.5 % for a - 12 fs pulse in 10 µm, 5 % in 100 µm, and 0.5 % for a 5 fs pulse in 10 µm. At zero + 12 fs pulse in 10 µm, 5 % in 100 µm, and about 1 % for a 5 fs pulse in 10 µm (on delays sampled finely enough to + catch its peak, about 1 fs apart). At zero delay its first-order effect cancels between the pairs $(\omega_1,\omega_2)$ and $(\omega_2,\omega_1)$, so it shows away from zero delay. - **Its sign depends on which beam is nearer the optic axis** diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 90c74bf..4cabaa5 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -395,3 +395,13 @@ def test_tilt_field_error_needs_light(): ) with pytest.raises(ValueError, match="no positive value"): crystals.tilt_field_error(setup, GRID.omega, W0, 50e-6, np.zeros(GRID.n), [0.0]) + + +def test_tilt_field_error_needs_a_delay(): + setup = _tuned( + geometry=TwoBeamGeometry(5e-3, 0.1), + polarization="perpendicular", + delayed_beam="toward_axis", + ) + with pytest.raises(ValueError, match="at least one delay"): + crystals.tilt_field_error(setup, GRID.omega, W0, 50e-6, np.ones(GRID.n), []) From edd43c9ac540209d2ff29244d2d01f8f71b4e17d Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Thu, 12 Nov 2026 21:12:50 +0000 Subject: [PATCH 11/16] Explain the arms' delay drift as the SH's walk-off The first-order signal-tilt term is the extraordinary SH walking off across the transverse delay gradient of the crossing beams. Say so in the manual and the module docstring, and stop describing walk-off as neglected: only the SH beam's sideways shift out of the overlap is. Refs #24 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- croak/crystals.py | 10 +++++++--- docs/explanation/forward_model.md | 23 ++++++++++++++++++++--- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/croak/crystals.py b/croak/crystals.py index 8f2fa52..58ca4d4 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -68,15 +68,19 @@ Validity -------- -* Type I only, fundamentals ordinary; no spatial walk-off of the beams (a thin - crystal, full collection). +* Type I only, fundamentals ordinary (they do not walk off). The SH's walk-off + enters only through the arms' delay drift below, its spatial picture; the SH + beam's sideways shift out of the fundamentals' overlap is neglected (a crystal + much thinner than the spot size over the walk-off angle; full collection). * The signal of a pair :math:`(\omega_1,\omega_2)` leaves at a small angle :math:`\delta\theta \approx (\omega_1-\omega_2)\sin\alpha/(\omega_s n_s)` to the bisector. When the beams cross in the crystal's principal plane (fundamental polarisation perpendicular to the crossing plane), that tilt changes :math:`n_e(\theta)` to first order. The model keeps that first-order term, as opposite delays of the two arms that drift with depth - (:meth:`CrystalSetup.arm_shift`), and neglects what is left; + (:meth:`CrystalSetup.arm_shift`); in space, it is the SH's walk-off carrying it + across the transverse delay gradient of the crossing beams. What is left is + neglected; :func:`tilt_field_error` computes the remainder's change to a pulse's signal, and :func:`check_tilt` warns above :data:`TILT_ERROR_WARN`. When the polarisation lies in the crossing plane, the principal plane is perpendicular to it and the diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index 9d44518..6601d9f 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -198,6 +198,19 @@ $\tau - 2\kappa(P-z)$. The model includes this ({meth}`~croak.crystals.CrystalSetup.arm_shift`): about 0.57 fs per 100 µm per arm for BBO at 800 nm crossing at 1.4°. +The same term has a picture in space. The crossing beams' wavefronts make the +delay between the arms vary across the focal spot, $\tau + 2x\sin\alpha/c$ (the +gradient behind the geometric delay smearing). The SH, an extraordinary wave, +carries its energy at the walk-off angle $\rho = -n_e'/n_s$ (68 mrad for BBO), so +SH made at depth $z$ leaves the crystal displaced sideways by $\rho(P-z)$, at a +point where the local delay differs by $2\rho\sin\alpha\,(P-z)/c = 2\lvert\kappa\rvert +(P-z)$. Light from every depth adds coherently at each exit point, each with its own +effective delay. The spectrometer sees it, though it records only the SH spectrum, +because the phase depends on $\omega_1-\omega_2$ rather than on $\omega_s$: it +changes how the pairs that make one signal frequency interfere. Crossing out of the +principal plane, the SH walks off along the direction in which the delay does not +vary, and the term vanishes. + Two consequences follow: - **The trace is not symmetric in delay.** The drift distinguishes the two arms, so @@ -221,9 +234,13 @@ each pair's signal in its own self-consistent direction, and 5-12 fs in up to 100 µm at 1.4°. Polarised in the crossing plane, the principal plane is perpendicular to the crossing plane and the first-order term vanishes. -**What is neglected.** The beams' spatial walk-off (the crystal is thin), Type II, -the remainder of the signal tilt above, and the dispersion of the refraction at the -entrance face. +**What is neglected.** The SH's walk-off is kept only through its effect on the +delay (above); its other consequence, the SH beam moving sideways out of the +fundamentals' overlap, is neglected (the crystal is much thinner than the focal +spot over the walk-off angle: 6.8 µm of walk-off in 100 µm against a spot of tens +of µm). The fundamentals are ordinary waves and do not walk off. Also neglected: +Type II, the remainder of the signal tilt above, and the dispersion of the +refraction at the entrance face. ```python import numpy as np From b919f55856e667f4be5533f824a8d8ea8ee2c9bc Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 09:02:45 +0000 Subject: [PATCH 12/16] Name the crystal module's validity section uniquely Two modules on the core API page had a section called Validity, which Sphinx rejects as a duplicate ID. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- croak/crystals.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/croak/crystals.py b/croak/crystals.py index 58ca4d4..3f5e613 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -66,8 +66,8 @@ uses :math:`n_o` at one wavelength (the phase-matched one, else the carrier), and the crossing geometry is taken at normal incidence. -Validity --------- +Validity of the crystal model +----------------------------- * Type I only, fundamentals ordinary (they do not walk off). The SH's walk-off enters only through the arms' delay drift below, its spatial picture; the SH beam's sideways shift out of the fundamentals' overlap is neglected (a crystal From e76618775090b0594dee6392005ec7764963ece2 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 09:38:52 +0000 Subject: [PATCH 13/16] Reference the arms' delay drift to mid-depth Referenced to the exit face, the drift offset the model's trace by kappa*P in delay, which a full-field simulation collecting the whole beam does not show (#28). The part of the walk-off common to every depth moves the whole SH beam sideways, which full collection cannot see; the plane-wave model drops the walk-off between depths, least on average about the mean generation depth, which is mid-depth for a uniform slab. The exact pair-sum reference re-references only the first-order drift, so tilt_field_error is not made smaller by the choice. A new test pins the trace's delay origin; the manual gives the argument, its assumptions and the full-field evidence, and the recomputed effect of the drift. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- changelog.d/shg-crystal.added.md | 2 +- croak/crystals.py | 44 ++++++++++++++++------- docs/explanation/forward_model.md | 58 ++++++++++++++++++++++++------- tests/test_forward_crystal.py | 41 +++++++++++++++++----- 4 files changed, 110 insertions(+), 35 deletions(-) diff --git a/changelog.d/shg-crystal.added.md b/changelog.d/shg-crystal.added.md index 05b8962..42801ff 100644 --- a/changelog.d/shg-crystal.added.md +++ b/changelog.d/shg-crystal.added.md @@ -1 +1 @@ -SHG in a Type I crystal: `croak.crystals.CrystalSetup` (cut angle with an external tilt or the wavelength the crystal was tuned to, the crossing geometry from `croak.geometry.TwoBeamGeometry`, and the fundamental's polarisation relative to the crossing plane), passed as `material` to the forward models for SHG, propagates the signal near 2ω0 as the extraordinary wave and so models phase matching, group-velocity mismatch and the ω/n generation prefactor. `croak.crystals.depth_points` gives the depth nodes the phase mismatch needs. With the beams crossing in the crystal's principal plane the signal's tilt makes the trace asymmetric in delay; the model includes it, to first order, as opposite delay drifts of the two arms (`delayed_beam` sets its sign, which flipping mirrors the trace in delay), and `check_tilt` warns where the remainder matters (#24). +SHG in a Type I crystal: `croak.crystals.CrystalSetup` (cut angle with an external tilt or the wavelength the crystal was tuned to, the crossing geometry from `croak.geometry.TwoBeamGeometry`, and the fundamental's polarisation relative to the crossing plane), passed as `material` to the forward models for SHG, propagates the signal near 2ω0 as the extraordinary wave and so models phase matching, group-velocity mismatch and the ω/n generation prefactor. `croak.crystals.depth_points` gives the depth nodes the phase mismatch needs. With the beams crossing in the crystal's principal plane the signal's tilt makes the trace asymmetric in delay; the model includes it, to first order, as opposite delay drifts of the two arms, referenced to mid-depth so that the trace keeps its delay origin (`delayed_beam` sets its sign, which flipping mirrors the trace in delay), and `check_tilt` warns where the remainder matters (#24). diff --git a/croak/crystals.py b/croak/crystals.py index 3f5e613..d074cbe 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -473,14 +473,18 @@ def arm_shift(self, omega0: float) -> float: the bisector, which changes its index by :math:`n_e'\delta\theta`. Its mismatch grows by :math:`\kappa(\omega_1-\omega_2)` with :math:`\kappa = \pm(n_e'/n_s)\sin\alpha/c`, with :math:`n_s = n_e(\theta)`, - taken at the signal carrier. Over the rest of the path :math:`P-z` that is - the phase :math:`e^{i\kappa\Omega(P-z)}` on the test arm and its inverse on - the gate. With croak's convention (a factor :math:`e^{i\Omega\tau}` delays a - field by :math:`\tau`) the test arm is delayed by :math:`+\kappa(P-z)` and - the gate by :math:`-\kappa(P-z)`, so the gate-minus-test delay at depth - :math:`z` is :math:`\tau - 2\kappa(P-z)`. The sign of :math:`\kappa` is - ``+`` with the delayed beam toward the optic axis. ``0`` out of the - principal plane, where the term is second order. + taken at the signal carrier. Referenced to mid-depth, that is the phase + :math:`e^{i\kappa\Omega(P/2-z)}` on the test arm and its inverse on the + gate. With croak's convention (a factor :math:`e^{i\Omega\tau}` delays a + field by :math:`\tau`) the test arm is delayed by :math:`+\kappa(P/2-z)` and + the gate by :math:`-\kappa(P/2-z)`, so the gate-minus-test delay at depth + :math:`z` is :math:`\tau - 2\kappa(P/2-z)`. Only the drift between depths + is observable when the whole beam is collected: the part common to every + depth moves the whole signal beam sideways, which a detector of the whole + beam cannot see, so the reference is the mean generation depth, which keeps + the trace's time zero (:doc:`/explanation/forward_model`). The sign of + :math:`\kappa` is ``+`` with the delayed beam toward the optic axis. ``0`` + out of the principal plane, where the term is second order. """ if not self.in_principal_plane: return 0.0 @@ -541,12 +545,15 @@ def arm_props( ``beta_in`` and ``omega`` in the order the caller works in (centred or DFT-bin). Each arm travels to depth ``z_q`` with ``beta_in``; with an :attr:`arm_shift` :math:`\kappa`, the test arm also carries - :math:`e^{i\kappa\Omega(P-z_q)}` and the gate its inverse. + :math:`e^{i\kappa\Omega(P/2-z_q)}` and the gate its inverse (the drift + referenced to mid-depth; :meth:`CrystalSetup.arm_shift`). """ base = np.exp(1j * np.outer(beta_in, nodes)) if self.arm_shift == 0.0: return base, base - drift = np.exp(1j * self.arm_shift * np.outer(omega, self.path_length - nodes)) + drift = np.exp( + 1j * self.arm_shift * np.outer(omega, 0.5 * self.path_length - nodes) + ) test = np.asarray(base * drift, dtype=np.complex128) return test, np.asarray(base / drift, dtype=np.complex128) @@ -829,7 +836,11 @@ def _pair_signal( model: each pair's signal along the bisector, with the arms' first-order delay drift. With ``tilted`` each pair's signal propagates in its own direction, found self-consistently with the index in that direction - (:func:`_signal_direction`). + (:func:`_signal_direction`). In both, the first-order part of the pair's + change of mismatch, :math:`\kappa(\omega_1-\omega_2)`, is referenced to + mid-depth, as the model's drift is (:meth:`CrystalSetup.arm_shift`); the rest, + which the model leaves out, keeps the exit-face reference, so that what the + comparison measures is not reduced by the choice of reference. """ prop = propagation(setup, omega, omega0, thickness) path = prop.path_length @@ -866,7 +877,11 @@ def _pair_signal( with np.errstate(divide="ignore", invalid="ignore"): depth = (np.exp(1j * a * path) - 1.0) / (1j * a) depth = np.where(np.abs(a * path) < 1e-12, path, depth) - psi[k] = amp[k] * np.sum(e[j] * e_tau[m] * np.exp(1j * bs * path) * depth) + # the first-order drift, referenced to mid-depth as in the model + shift = np.exp(-0.5j * prop.arm_shift * (w[j] - w[m]) * path) + psi[k] = amp[k] * np.sum( + e[j] * e_tau[m] * np.exp(1j * bs * path) * shift * depth + ) return np.fft.fftshift(psi) @@ -890,7 +905,10 @@ def tilt_field_error( For a tilted plate both sums use the mismatch along the beams over the effective path (:meth:`CrystalSetup.path_length`), so the comparison is exact - for an untilted plate and first order in the tilt otherwise. + for an untilted plate and first order in the tilt otherwise. Both reference the + first-order drift to mid-depth, as the model does, and the rest of each pair's + mismatch to the exit face, so the choice of reference does not reduce the + estimate. Scan the delays: the tilt's mismatch is odd in :math:`\omega_1-\omega_2`, so at zero delay, where the pairs :math:`(\omega_1,\omega_2)` and diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index 6601d9f..a822fed 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -189,14 +189,14 @@ $\psi = c k_x/(\omega_s n_s)$, the self-consistency entering only at second orde When the beams cross in the crystal's principal plane (the fundamental polarised perpendicular to the crossing plane), the tilt changes the signal's angle to the optic axis, so its index changes to first order, by $n_e'\psi$. The extra mismatch -is $\kappa(\omega_1-\omega_2)$ with $\kappa = (n_e'/n_s)\sin\alpha/c$, and over the -remaining path it factorises into opposite delays of the two arms that drift -apart with depth: in croak's convention (a factor $e^{i\Omega\tau}$ delays a field -by $\tau$) the test arm is delayed by $+\kappa(P-z)$ and the gate by -$-\kappa(P-z)$, so the gate-minus-test delay at depth $z$ is -$\tau - 2\kappa(P-z)$. The model includes this -({meth}`~croak.crystals.CrystalSetup.arm_shift`): about 0.57 fs per 100 µm per arm -for BBO at 800 nm crossing at 1.4°. +is $\kappa(\omega_1-\omega_2)$ with $\kappa = (n_e'/n_s)\sin\alpha/c$, and it +factorises into opposite delays of the two arms that drift apart with depth. In +croak's convention (a factor $e^{i\Omega\tau}$ delays a field by $\tau$), with the +drift referenced to mid-depth (below), the test arm is delayed by +$+\kappa(P/2-z)$ and the gate by $-\kappa(P/2-z)$, so the gate-minus-test delay +at depth $z$ is $\tau - 2\kappa(P/2-z)$. The model includes this +({meth}`~croak.crystals.CrystalSetup.arm_shift`): $\kappa$ is about 0.57 fs per +100 µm for BBO at 800 nm crossing at 1.4°. The same term has a picture in space. The crossing beams' wavefronts make the delay between the arms vary across the focal spot, $\tau + 2x\sin\alpha/c$ (the @@ -211,13 +211,45 @@ changes how the pairs that make one signal frequency interfere. Crossing out of principal plane, the SH walks off along the direction in which the delay does not vary, and the term vanishes. +**Where the drift is referenced.** The model treats each pair as plane waves, so a +pair's signal has the transverse wavevector $k_x = (\omega_1-\omega_2)\sin\alpha/c$, +and its first-order phase is the walk-off acting on that $k_x$. In real beams the +signal's transverse wavevector is $k_x + q$, where $q$, of order the inverse spot +size, comes from the beams' own angular spread, and the walk-off acts on $q$ too: +it contributes $e^{-iq\rho(P-z)} = e^{-iq\rho(z_\mathrm{ref}-z)}\,e^{-iq\rho(P-z_\mathrm{ref})}$ +for any reference depth $z_\mathrm{ref}$. The second factor is the same at every +depth: it moves the whole SH beam sideways, which a detector that collects the +whole beam cannot see (by Parseval's theorem, a phase that depends only on the +signal's transverse wavevector leaves the beam-integrated signal unchanged). The +first, the walk-off between depths, is what the plane-wave model leaves out with +$q$; averaged over the depth it is smallest when $z_\mathrm{ref}$ is the mean +generation depth, which for a uniform slab is mid-depth. croak therefore writes the +drift as $\kappa\Omega(P/2-z)$. The choice matters for the delay origin only: the +exit-face reference differs from it exactly by the delay shift +$\tau \to \tau - \kappa P$ and a linear spectral phase on the signal, so its trace +sits $\kappa P$ off-centre (−0.57 fs for 100 µm at 1.4° with the delayed beam toward +the optic axis, +0.57 fs away from it). + +A full-field simulation supports this choice (issue #28): two Gaussian beams of +20 µm waist crossing at the crystal's mid-plane in BBO, simulated in two dimensions +(x and t) with Luna.jl, with the signal collected over the whole beam. For a 10 fs +pulse with 30 fs² of GDD in 100 µm at 1.43°, and a 6 fs pulse with 20 fs³ of TOD +in 30 µm at 2.86°, the full-field traces are centred to 0.02 fs, and they match the +mid-depth-referenced model to 1.2 % and 0.2 % of the peak. The argument assumes +that the whole beam is collected, that generation is spread evenly over the depth, +and that the walk-off over the crystal, $\rho P$, is small against the spot size. A +spectrometer slit or an iris that passes only part of the beam can bring part of the +offset back, and strong phase mismatch weights the depths unevenly and moves the +mean generation depth; neither is modelled. A remaining offset is indistinguishable +from a mis-set delay origin, which `fit_tau0` absorbs. + Two consequences follow: - **The trace is not symmetric in delay.** The drift distinguishes the two arms, so $I(\omega,\tau) \ne I(\omega,-\tau)$, unlike the ideal SHG FROG trace. For BBO - at 800 nm crossing at 1.4° the term changes the signal by about 0.5 % for a - 12 fs pulse in 10 µm, 5 % in 100 µm, and about 1 % for a 5 fs pulse in 10 µm (on delays sampled finely enough to - catch its peak, about 1 fs apart). At zero + at 800 nm crossing at 1.4° the term changes the signal field by about 0.03 % + for a 12 fs pulse in 10 µm, 1.7 % in 100 µm, and 0.2 % for a 5 fs pulse in + 10 µm (4.6 % in 100 µm), relative to its peak, on delays 1 fs apart. At zero delay its first-order effect cancels between the pairs $(\omega_1,\omega_2)$ and $(\omega_2,\omega_1)$, so it shows away from zero delay. - **Its sign depends on which beam is nearer the optic axis** @@ -231,7 +263,9 @@ What remains is second order in the tilt. {func}`croak.crystals.tilt_field_error computes it for a given spectrum and set of delays, against an exact pair sum with each pair's signal in its own self-consistent direction, and {func}`croak.crystals.check_tilt` warns above 1 %. It is under 0.3 % for pulses of -5-12 fs in up to 100 µm at 1.4°. Polarised in the crossing plane, the principal +5-12 fs in up to 100 µm at 1.4°. In both sums the first-order drift is referenced +to mid-depth and the rest of each pair's mismatch to the exit face, so the +estimate is not made smaller by the choice of reference. Polarised in the crossing plane, the principal plane is perpendicular to the crossing plane and the first-order term vanishes. **What is neglected.** The SH's walk-off is kept only through its effect on the diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py index d5c8a7e..8fd2760 100644 --- a/tests/test_forward_crystal.py +++ b/tests/test_forward_crystal.py @@ -65,9 +65,10 @@ def _depth_integral(a, path): return np.where(np.abs(a * path) < 1e-12, path, out) -def _pair_sum(setup, thickness, ew, tau, beta_sig_pair=None): +def _pair_sum(setup, thickness, ew, tau, beta_sig_pair=None, drift=True): """Exact double sum over pairs, centred order; ``beta_sig_pair(j, m, k)`` may - replace the signal's propagation constant per pair.""" + replace the signal's propagation constant per pair. ``drift`` references the + first-order drift to mid-depth (off for a model without the drift).""" prop = crystals.propagation(setup, GRID.omega, W0, thickness) path = prop.path_length n = GRID.n @@ -85,7 +86,10 @@ def _pair_sum(setup, thickness, ew, tau, beta_sig_pair=None): model = b_sig[k] + prop.arm_shift * (w[j] - w[m]) bs = model if beta_sig_pair is None else beta_sig_pair(j, m, k) a = b_in[j] + b_in[m] - bs - h = np.exp(1j * bs * path) * _depth_integral(a, path) + # the first-order drift is referenced to mid-depth, as in the model + # (CrystalSetup.arm_shift); the rest of a pair's mismatch is not + mid = np.exp(-0.5j * prop.arm_shift * (w[j] - w[m]) * path) if drift else 1.0 + h = np.exp(1j * bs * path) * mid * _depth_integral(a, path) psi[k] = amp[k] * np.sum(e[j] * e_tau[m] * h) return scipy.fft.fftshift(psi) @@ -217,12 +221,12 @@ def f(p): PRINCIPAL = dict(geometry=GEOMETRY, polarization="perpendicular") -def _worst(setup, thickness, amp, beta_sig_pair): +def _worst(setup, thickness, amp, beta_sig_pair, drift=True): """Largest |model - reference| over DELAYS, relative to the reference's peak.""" reference = _tilted_signal(setup, thickness) pairs = [ ( - _pair_sum(setup, thickness, amp, t, beta_sig_pair), + _pair_sum(setup, thickness, amp, t, beta_sig_pair, drift), _pair_sum(setup, thickness, amp, t, reference), ) for t in DELAYS @@ -236,15 +240,34 @@ def test_arm_drift_captures_the_signal_tilt(side): # 12 fs in 100 um crossing at 1.43 degrees in the principal plane. Against each # pair's signal in its own self-consistent direction: with the arms' drift the # model is within 0.1 % (the residual is second order in the tilt); without it, - # about 5 % off. + # about 1.6 % off (the drift referenced to mid-depth, so no shift of time zero). setup = _setup(**PRINCIPAL, delayed_beam=side) amp = np.abs(_pulse(GRID, gdd=0.0)) with_drift = _worst(setup, 100e-6, amp, None) prop = crystals.propagation(setup, GRID.omega, W0, 100e-6) b_sig = scipy.fft.ifftshift(prop.beta_sig) - without = _worst(setup, 100e-6, amp, lambda j, m, k: b_sig[k]) + without = _worst(setup, 100e-6, amp, lambda j, m, k: b_sig[k], drift=False) assert with_drift < 1e-3 - assert without > 0.03 + assert without > 0.01 + + +@pytest.mark.parametrize("side", ["toward_axis", "away_from_axis"]) +def test_arm_drift_keeps_the_trace_time_zero(side): + # Pins the convention that the drift is referenced to mid-depth, so that the + # trace keeps its delay origin, as a full-field simulation collecting the + # whole beam finds (CrystalSetup.arm_shift; issue #28). Referenced to the exit + # face, the delay marginal's centroid sits at +kappa P (kappa P is -0.57 fs + # toward the axis, +0.57 fs away from it). The tolerance is set by this 12 fs + # pulse with 30 fs^2: its shape asymmetry leaves the centroid at 0.02 kappa P + # (a strongly chirped 5 fs pulse reaches about 0.2 kappa P). + setup = _setup(**PRINCIPAL, delayed_beam=side) + delays = GRID.dt * np.arange(-12, 13) + trace = _model(setup, 100e-6, delays).trace(_pulse(GRID), normalize=False) + marginal = trace.sum(axis=0) + centroid = np.sum(delays * marginal) / np.sum(marginal) + kappa_path = setup.arm_shift(W0) * setup.path_length(100e-6, W0) + assert abs(kappa_path) > 0.5e-15 + assert abs(centroid) < 0.1 * abs(kappa_path) def test_the_wrong_side_is_the_delay_mirror(): @@ -284,7 +307,7 @@ def test_tilt_field_error_vanishes_out_of_the_principal_plane(): def test_check_tilt_warns_above_one_percent(): # A 5 fs pulse, 300 um, crossing at 2.86 degrees: the second-order residual - # reaches about 3 %. + # reaches about 2 %. setup = _setup( geometry=TwoBeamGeometry(beam_separation=10e-3, focal_length=0.1), polarization="perpendicular", From 0ddef603131514060f4ec3214832963a96f1034d Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 09:44:55 +0000 Subject: [PATCH 14/16] State the full-field check at three crossing depths Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL --- docs/explanation/forward_model.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index a822fed..1c5a48c 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -231,11 +231,15 @@ sits $\kappa P$ off-centre (−0.57 fs for 100 µm at 1.4° with the delayed bea the optic axis, +0.57 fs away from it). A full-field simulation supports this choice (issue #28): two Gaussian beams of -20 µm waist crossing at the crystal's mid-plane in BBO, simulated in two dimensions +20 µm waist crossing in BBO, simulated in two dimensions (x and t) with Luna.jl, with the signal collected over the whole beam. For a 10 fs pulse with 30 fs² of GDD in 100 µm at 1.43°, and a 6 fs pulse with 20 fs³ of TOD in 30 µm at 2.86°, the full-field traces are centred to 0.02 fs, and they match the -mid-depth-referenced model to 1.2 % and 0.2 % of the peak. The argument assumes +mid-depth-referenced model to 1.2 % and 0.2 % of the peak, whether the beams +cross at the crystal's entrance face, its mid-plane or its exit face. (Over these +crystals the beams separate by little against their size, so this tells the +references apart rather than testing beams that separate in the crystal.) The +argument assumes that the whole beam is collected, that generation is spread evenly over the depth, and that the walk-off over the crystal, $\rho P$, is small against the spot size. A spectrometer slit or an iris that passes only part of the beam can bring part of the From a9b7b5f83c7d6f42e99c6498cecfd1d60573bfe8 Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 15:30:22 +0000 Subject: [PATCH 15/16] Check the arm-drift rate with no absolute tolerance kappa is about 6e-12 s/m, below pytest.approx's default absolute tolerance of 1e-12, so the relative tolerance was not what the test checked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- tests/test_crystals.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 4cabaa5..50c4745 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -291,7 +291,8 @@ def test_arm_shift_is_the_first_order_tilt_rate(): * math.sin(geometry.crossing_half_angle) / C ) - assert toward.arm_shift(W0) == pytest.approx(expected, rel=1e-12) + # abs=0: kappa is ~6e-12 s/m, below pytest.approx's default absolute tolerance + assert toward.arm_shift(W0) == pytest.approx(expected, rel=1e-12, abs=0) assert away.arm_shift(W0) == -toward.arm_shift(W0) # BBO at 800 nm, 1.43 degrees: -0.567 fs per 100 um (the explainer's number) assert toward.arm_shift(W0) * 100e-6 == pytest.approx(-0.567e-15, abs=0.001e-15) From 68006034536516a174e3cb6642aaac20a8edf26f Mon Sep 17 00:00:00 2001 From: chrisbrahms Date: Fri, 13 Nov 2026 18:24:32 +0000 Subject: [PATCH 16/16] Keep the signal-grid edge pairs independent of rounding The pair-mismatch estimate kept a pair when |w1 + w2| <= max|omega|, a strict float comparison at exactly the edge bins. The solver rebuilds its grid from the trace's frequency axis, whose spacing can differ from the session's in the last bit, so the two counted different pairs and the solver refused a node count the session had computed (25 against 27 for 200 um of BBO). Test the sum against the grid's own span with half a bin of tolerance. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX --- croak/crystals.py | 10 ++++++++-- tests/test_crystals.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/croak/crystals.py b/croak/crystals.py index d074cbe..b1d0467 100644 --- a/croak/crystals.py +++ b/croak/crystals.py @@ -648,9 +648,15 @@ def _pair_mismatch( if omega.size <= _PAIR_GRID else np.linspace(omega.min(), omega.max(), _PAIR_GRID) ) - half = float(np.max(np.abs(omega))) + # A sum lands on the signal grid when it lies within the grid's own span. The + # test allows half a bin either side: the edge pairs sum exactly onto the end + # bins, and a strict comparison would keep or drop them on a rounding error, so + # two copies of one grid that differ in the last bit of their spacing would ask + # for different node counts. + tolerance = 0.5 * float(omega[1] - omega[0]) o1, o2 = np.meshgrid(grid, grid) - keep = np.abs(o1 + o2) <= half + total = o1 + o2 + keep = (total >= omega.min() - tolerance) & (total <= omega.max() + tolerance) w1 = o1[keep] + omega0 w2 = o2[keep] + omega0 theta = setup.internal_angle(omega0) diff --git a/tests/test_crystals.py b/tests/test_crystals.py index 50c4745..61842b0 100644 --- a/tests/test_crystals.py +++ b/tests/test_crystals.py @@ -270,6 +270,21 @@ def test_depth_points_subsample_a_fine_grid(): ) +def test_signal_pairs_ignore_the_last_bit_of_the_spacing(): + # Regression: the solver rebuilds the grid from the trace's frequency axis, whose + # spacing can differ from the session's grid in its last bit. The pairs at the + # edge of the signal grid then fell either side of a strict comparison, and with + # the largest mismatch at that edge the solver asked for more depth nodes than + # the session had counted. Both copies must keep the same pairs. + setup = _tuned() + nudged = Grid(GRID.n, domega=float(np.nextafter(GRID.domega, np.inf))) + dk, *_ = crystals._pair_mismatch(setup, GRID.omega, W0) + dk_nudged, *_ = crystals._pair_mismatch(setup, nudged.omega, W0) + assert dk_nudged.size == dk.size + # the spacing differs by one ulp, so the mismatches agree to rounding + np.testing.assert_allclose(dk_nudged, dk, rtol=1e-9, atol=0) + + # -- the arms' delay drift -------------------------------------------------------- def test_arm_shift_is_the_first_order_tilt_rate(): # kappa = (n_e'/n_s) sin(alpha) / c at the signal carrier, signed by the side of