diff --git a/changelog.d/shg-crystal.added.md b/changelog.d/shg-crystal.added.md new file mode 100644 index 0000000..42801ff --- /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. 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 new file mode 100644 index 0000000..b1d0467 --- /dev/null +++ b/croak/crystals.py @@ -0,0 +1,1022 @@ +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}`. 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_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 +uses :math:`n_o` at one wavelength (the phase-matched one, else the carrier), and the +crossing geometry is taken at normal incidence. + +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 + 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`); 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 + 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_ERROR_WARN", + "CrystalSetup", + "CrystalApproximationWarning", + "Propagation", + "UniaxialCrystal", + "check_medium", + "check_tilt", + "depth_points", + "extraordinary_index", + "phase_matching_angle", + "propagation", + "tilt_field_error", +] + +#: 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 +#: 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"] +DelayedBeam = Literal["toward_axis", "away_from_axis"] + + +class CrystalApproximationWarning(UserWarning): + """What the crystal model leaves out of the signal's tilt matters.""" + + +@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. + 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( + n_o: ArrayLike, n_e: ArrayLike, theta: ArrayLike +) -> 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 : array_like + 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) + 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: 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) + + +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 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`` or ``delayed_beam`` 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 + delayed_beam: DelayedBeam | 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 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}" + ) + 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}" + ) + 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: + """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 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: + theta = phase_matching_angle( + self.crystal, self.phase_match_wavelength, self.crossing_half_angle + ) + 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).""" + 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 + # 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: + 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_s)\sin\gamma_\mathrm{int}}, + + 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) + 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).""" + if self.phase_match_wavelength is not None: + 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_s)\sin\alpha/c`, with :math:`n_s = n_e(\theta)`, + 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 + 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)]) + 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).""" + return math.asin(math.sin(gamma) / self._n_refraction(omega0)) + + +@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). + 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/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, 0.5 * self.path_length - nodes) + ) + test = np.asarray(base * drift, dtype=np.complex128) + return test, np.asarray(base / drift, dtype=np.complex128) + + +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) + # 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( + beta_in, + beta_sig, + sig_amp, + setup.path_length(float(thickness), omega0), + setup.arm_shift(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) + ) + # 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) + 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) + 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) + & crystal.transparent(w1) + & crystal.transparent(w2) + & crystal.transparent(w1 + w2) + ) + 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. 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 + ---------- + 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 check_medium( + interaction: Interaction, + material: str | CrystalSetup | None, + thickness: float, + npoints: int, + omega: ArrayLike, + omega0: float, + quadrature: str = "gausslegendre", +) -> 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). + quadrature : str, optional + The depth quadrature; a crystal's node rule is for ``"gausslegendre"`` + (default). + + 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`). + + Notes + ----- + 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: + 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: + return + material.internal_angle(omega0) # the carrier, the angle and the tilt are valid + 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": + 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: 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)" + ) + + +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). + """ + 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( + 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. 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`). 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 + 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 = 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]) + 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) + depth = np.where(np.abs(a * path) < 1e-12, 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) + + +def tilt_field_error( + setup: CrystalSetup, + omega: ArrayLike, + omega0: float, + thickness: float, + amplitude: ArrayLike, + delays: ArrayLike, +) -> float: + 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 (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. + + 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. 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 + :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 + ---------- + 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. + + Raises + ------ + ValueError + If ``amplitude`` is zero everywhere or ``delays`` is empty. + """ + 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") + 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 delays: + 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, + amplitude: ArrayLike, + delays: ArrayLike, +) -> float: + """Warn if what the model leaves of the signal's tilt matters for this pulse. + + 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`` (see :func:`tilt_field_error`). + delays : array_like + Delays (s) to evaluate (see :func:`tilt_field_error`). + + Returns + ------- + float + The relative field change of :func:`tilt_field_error`. + + Raises + ------ + ValueError + As :func:`tilt_field_error`. + + Warns + ----- + CrystalApproximationWarning + If it exceeds :data:`TILT_ERROR_WARN`. + """ + error = tilt_field_error(setup, omega, omega0, thickness, amplitude, delays) + if error > TILT_ERROR_WARN: + warnings.warn( + 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, + ) + return error diff --git a/croak/forward.py b/croak/forward.py index 5b8e5cb..2929404 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,43 @@ 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, + quadrature, + ) + 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. + # 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) + ) # Geometric smearing. The (p, delta) statistics are independent of depth — the # pulse-front tilts are set before the medium and the longitudinal walk-off @@ -214,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) @@ -351,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) @@ -362,7 +382,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..ec03c39 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, 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 + 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, 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, gate_prop, signal_prop, weights + + class _SignalConstants: """Static problem geometry shared by the JAX forward signal and its adjoint. @@ -142,6 +164,7 @@ class _SignalConstants: "n", "omega_bin", "input_prop", + "gate_prop", "signal_prop", "weights", "signal_map", @@ -152,27 +175,21 @@ 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, quadrature + ) 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, gate_prop, signal_prop, weights = _static_props( + material, omega, omega0, float(thickness), npoints, quadrature + ) self.inter = inter 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] @@ -193,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) @@ -226,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) @@ -236,7 +253,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 +306,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 +367,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 +528,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 +664,35 @@ 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, + quadrature, + ) + # 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 +756,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 +764,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 +798,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) @@ -780,25 +818,34 @@ 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). - 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, 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 + nodes0, _ = quadrature_nodes_weights(float(thickness), npoints, quadrature) remaining_c = jnp.asarray(float(thickness) - np.asarray(nodes0)) 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 @@ -808,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) @@ -1142,7 +1189,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..ed4fc88 --- /dev/null +++ b/croak/geometry.py @@ -0,0 +1,72 @@ +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 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. +""" + +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/docs/explanation/forward_model.md b/docs/explanation/forward_model.md index 05dd0a1..1c5a48c 100644 --- a/docs/explanation/forward_model.md +++ b/docs/explanation/forward_model.md @@ -108,9 +108,199 @@ 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, $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 +$\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}$. 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_s)\sin\gamma_\mathrm{int})$, so the model +integrates over the effective path +$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 +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 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 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 +$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 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 +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. + +**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 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, 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 +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 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** + (`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°. 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 +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 +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/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 new file mode 100644 index 0000000..61842b0 --- /dev/null +++ b/tests/test_crystals.py @@ -0,0 +1,423 @@ +"""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., 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 __future__ import annotations + +import math + +import numpy as np +import pytest +import scipy.optimize +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, strict=True)) + ) + + 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'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) + + +# -- 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) + + +@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(): + 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(): + # 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) + + +# -- 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 + ) + + +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 + # the delayed beam; independent of omega_s (it cancels). + geometry = TwoBeamGeometry(5e-3, 0.1) + 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 + ) + # 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) + + +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 + + +@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_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(): + # 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", "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 + + with pytest.raises(ValueError, match=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]) + + +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), []) diff --git a/tests/test_forward_crystal.py b/tests/test_forward_crystal.py new file mode 100644 index 0000000..8fd2760 --- /dev/null +++ b/tests/test_forward_crystal.py @@ -0,0 +1,483 @@ +"""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_forward_adjoint_fns, + 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, drift=True): + """Exact double sum over pairs, centred order; ``beta_sig_pair(j, m, k)`` may + 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 + 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 + # 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 + # 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) + + +# -- 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, plane): + setup = _setup(**GEOMETRIES[plane]) + 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])) + 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 + + +DELAYS = np.linspace(-24e-15, 24e-15, 9) +PRINCIPAL = dict(geometry=GEOMETRY, polarization="perpendicular") + + +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, drift), + _pair_sum(setup, thickness, amp, t, reference), + ) + for t in DELAYS + ] + worst = max(np.max(np.abs(a - b)) for a, b in pairs) + return worst / max(np.max(np.abs(b)) for _, b in pairs) + + +@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 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], drift=False) + assert with_drift < 1e-3 + 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(): + # Flipping the side is the same as mirroring the delay axis (swapping the arms + # 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) + 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() + + +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(): + 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(): + # A 5 fs pulse, 300 um, crossing at 2.86 degrees: the second-order residual + # reaches about 2 %. + 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(**PRINCIPAL, delayed_beam="toward_axis") + amp = np.abs(_pulse(GRID, gdd=0.0)) + assert crystals.check_tilt(setup, GRID.omega, W0, 100e-6, amp, DELAYS) < 0.01 + + +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 ----------------------------------------------------------------- +@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) + 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 --------------------------------------------------- +@pytest.mark.parametrize("plane", GEOMETRIES) +def test_adjoint_matches_finite_differences(plane): + rng = np.random.default_rng(11) + setup = _setup(**GEOMETRIES[plane]) + 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) + + +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)) + ) + + +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", + delayed_beam="toward_axis", + ) + amp = np.abs(_pulse(GRID, gdd=0.0)) + full = crystals.tilt_field_error( + _setup( + geometry=GEOMETRY, polarization="perpendicular", delayed_beam="toward_axis" + ), + 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) + + +@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() + ) 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)