Source code for croak.crystals

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"]


[docs] class CrystalApproximationWarning(UserWarning): """What the crystal model leaves out of the signal's tilt matters."""
[docs] @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
[docs] 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
[docs] 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)
[docs] 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))
[docs] @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
[docs] 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
[docs] 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
[docs] 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)) )
[docs] 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))
[docs] 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))
[docs] @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
[docs] 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)
[docs] 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
[docs] 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
[docs] 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)
[docs] 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
[docs] 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