Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion changelog.d/shg-crystal-integration.added.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
SHG retrievals through a Type I crystal everywhere a slab material is accepted: every solver, `retrieve_from_tracedata`, the bootstraps, the covariance and the thickness uncertainty take a `croak.crystals.CrystalSetup` as `material` (the thickness bootstrap gives each drawn thickness the depth nodes it needs). BBO is a built-in crystal (`croak.crystals.builtin_crystal`, optmat's Tamošauskas 2018 indices), so croak now needs `optmat[gas]>=0.10.0`, the first optmat release with BBO. Sessions describe the crystal (`crystal`, `cut_angle_deg`, `angle_mode`, `tilt_deg`, `phase_match_nm`, `polarization`, `delayed_beam`, `beam_separation_mm`), the GUI's Retrieve stage shows it as *Nonlinear crystal* and *Beam geometry* for SHG data, and the Synthetic stage can generate SHG traces through it. A crystal model refuses a marginal-corrected trace, which `TraceData.marginal_corrected` now records. A session's thickness uncertainty now raises a clear error when dispersive propagation is off, where it used to pass the unused slab material on. See [SHG FROG with a thick crystal](docs/howto/shg_crystal.md) (#24).
SHG retrievals through a Type I crystal everywhere a slab material is accepted: every solver, `retrieve_from_tracedata`, the bootstraps, the covariance and the thickness uncertainty take a `croak.crystals.CrystalSetup` as `material` (the thickness bootstrap gives each drawn thickness the depth nodes it needs). BBO is a built-in crystal (`croak.crystals.builtin_crystal`, optmat's Tamošauskas 2018 indices), so croak now needs `optmat[gas]>=0.10.0`, the first optmat release with BBO. Sessions describe the crystal (`crystal`, `cut_angle_deg`, `angle_mode`, `tilt_deg`, `phase_match_nm`, `polarization`, `delayed_beam`, `beam_separation_mm`), the GUI shows it as *Nonlinear crystal* and *Beam geometry* for SHG data, and the Synthetic stage can generate SHG traces through it. `TraceData.marginal_corrected` records whether the trace was marginal-corrected. A session's thickness uncertainty now raises a clear error when dispersive propagation is off, where it used to pass the unused slab material on. See [SHG FROG with a thick crystal](docs/howto/shg_crystal.md) (#24).
1 change: 1 addition & 0 deletions changelog.d/shg-marginal-crystal.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The marginal checks and the SHG marginal correction can predict the marginal through a Type I crystal: `croak.crystals.shg_marginal` gives the crystal model's delay-summed marginal, and `predicted_marginal`, `predicted_centroid` and `apply_marginal_correction` take a `croak.crystals.PhaseMatching` (crystal and thickness) with the pulse carrier. `load_and_clean(marginal_correct=True, marginal_crystal=...)` corrects a measured trace onto the crystal's marginal, removing the instrument's spectral response while keeping the phase matching for the crystal model, and records it as `TraceData.marginal_crystal`. A retrieval now refuses a corrected trace only when its medium differs from the one the correction used, instead of refusing every corrected trace with a crystal. Sessions correct through the retrieval's crystal, and the GUI shows the crystal and beam settings on the Data stage, where the Check step uses them. See [Marginal consistency checks](docs/howto/marginal_checks.md#through-an-shg-crystal) (#25).
129 changes: 129 additions & 0 deletions croak/crystals.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@
"TILT_ERROR_WARN",
"CrystalSetup",
"CrystalApproximationWarning",
"PhaseMatching",
"Propagation",
"UniaxialCrystal",
"builtin_crystal",
Expand All @@ -124,6 +125,7 @@
"extraordinary_index",
"phase_matching_angle",
"propagation",
"shg_marginal",
"tilt_field_error",
]

Expand Down Expand Up @@ -889,6 +891,133 @@ def _depth_points(
return math.ceil(phi) + 3


@dataclass(frozen=True)
class PhaseMatching:
"""A crystal of given thickness, as an SHG trace's frequency marginal sees it.

Attributes
----------
setup : CrystalSetup
The crystal, its angle and the beam geometry.
thickness : float
Plate thickness (m) along the face normal, ``>= 0``.
"""

setup: CrystalSetup
thickness: float

def __post_init__(self) -> None:
"""Validate the thickness."""
if not (math.isfinite(self.thickness) and self.thickness >= 0.0):
raise ValueError(
f"the crystal thickness must be finite and >= 0, got {self.thickness!r}"
)


def shg_marginal(
omega: ArrayLike,
spectrum: ArrayLike,
phase_matching: PhaseMatching,
omega0: float,
) -> NDArray[np.float64]:
r"""Frequency marginal of a crystal SHG trace, from the fundamental spectrum.

Summed over a delay range that holds the whole trace, the crystal model's SHG
trace (:class:`croak.forward.ForwardModel` with a :class:`CrystalSetup`) has the
phase-independent frequency marginal

.. math:: M(\omega_s) \propto a_s(\omega_s)^2 \sum_{\omega_1+\omega_2=\omega_s}
S(\omega_1)\,S(\omega_2)\,P^2\operatorname{sinc}^2\!\big(\Delta k\,P/2\big),

Parseval's theorem over delay turning the delay sum of :math:`|\psi|^2` into a
sum over component pairs. :math:`a_s` is the generation prefactor and :math:`P`
the path (:func:`propagation`); :math:`\Delta k = k_s(\omega_1+\omega_2) -
k_z(\omega_1) - k_z(\omega_2) - \kappa(\omega_1-\omega_2)` is the pair's
mismatch, with the arms' delay drift :math:`\kappa`
(:meth:`CrystalSetup.arm_shift`), and :math:`P^2\operatorname{sinc}^2` the
modulus squared of its depth integral, done analytically. The drift's sign does
not matter: the pairs :math:`(\omega_1,\omega_2)` and :math:`(\omega_2,\omega_1)`
enter with the same weight. Smearing along delay leaves the marginal unchanged.
At zero thickness the model has no depth integral, and this is :math:`a_s^2\,(S*S)`,
the thin-medium marginal times the prefactor.

It is the linear convolution: on a retrieval grid it differs from the model's
trace by the pairs that alias round the grid, which carry nothing when the grid
holds the trace.

Parameters
----------
omega : array_like
Absolute angular frequencies (rad/s) of ``spectrum``, uniform and ascending.
spectrum : array_like
Fundamental spectral intensity :math:`S(\omega)` per unit frequency
(``>= 0``).
phase_matching : PhaseMatching
The crystal and its thickness.
omega0 : float
Pulse carrier (rad/s), as the retrieval uses it: it refracts an explicit
tilt, and the path and the delay drift are taken there.

Returns
-------
numpy.ndarray
The marginal, unnormalised, on the ``2N - 1`` frequencies
``2 * omega[0] + k * (omega[1] - omega[0])``.

Raises
------
ValueError
If ``omega`` is not a uniform ascending axis of at least two points,
``spectrum`` has another shape, or either holds a non-finite value.
"""
omega = np.asarray(omega, dtype=float)
spectrum = np.asarray(spectrum, dtype=float)
if omega.ndim != 1 or omega.size < 2:
raise ValueError("omega must be a 1-D axis with at least 2 samples")
if spectrum.shape != omega.shape:
raise ValueError("spectrum and omega must have the same shape")
if not (np.all(np.isfinite(omega)) and np.all(np.isfinite(spectrum))):
raise ValueError("omega and spectrum must be finite")
spectrum = np.clip(spectrum, 0.0, None)
step = np.diff(omega)
if not (step[0] > 0.0 and np.allclose(step, step[0], rtol=1e-6, atol=0.0)):
raise ValueError("omega must be uniform and ascending")
domega = float(step[0])
n = omega.size
signal = 2.0 * omega[0] + domega * np.arange(2 * n - 1)
setup, thickness = phase_matching.setup, phase_matching.thickness
# The same propagation constants as the forward model, in its frame (the
# group-delay term beta_1 * Omega cancels in the mismatch, since the signal
# offset is the sum of the pair's offsets).
fundamental = propagation(setup, omega - omega0, omega0, thickness)
generated = propagation(setup, signal - 2.0 * omega0, omega0, thickness)
path = fundamental.path_length
kappa = fundamental.arm_shift
beta_in = fundamental.beta_in
offset = omega - omega0
out = np.zeros(signal.size)
for k in range(signal.size):
# pairs (j, k - j) with both members on the fundamental axis
j = np.arange(max(0, k - n + 1), min(k, n - 1) + 1)
m = k - j
weight = spectrum[j] * spectrum[m]
if not weight.any():
continue
mismatch = (
beta_in[j]
+ beta_in[m]
- generated.beta_sig[k]
- kappa * (offset[j] - offset[m])
)
# np.sinc(x) = sin(pi x) / (pi x). At zero thickness the model takes one
# node of unit weight (forward.quadrature_nodes_weights), not a zero path.
response = (
(path * np.sinc(mismatch * path / (2.0 * np.pi))) ** 2 if path > 0 else 1.0
)
out[k] = generated.sig_amp[k] ** 2 * float(np.sum(weight * response))
return out


def check_medium(
interaction: Interaction,
material: str | CrystalSetup | None,
Expand Down
Loading
Loading