Skip to content

Model SHG in a Type I crystal in the forward models - #31

Open
chrisbrahms wants to merge 19 commits into
LupoLab:mainfrom
chrisbrahms:feature/shg-crystal-core
Open

chrisbrahms wants to merge 19 commits into
LupoLab:mainfrom
chrisbrahms:feature/shg-crystal-core

Conversation

@chrisbrahms

@chrisbrahms chrisbrahms commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Important

This PR is part of a stack. Each PR builds on the one before it. Review and merge them in this order (stack note added by Claude):

  1. Model SHG in a Type I crystal in the forward models #31: SHG crystal core: croak.crystals and the forward models ← this PR
  2. Thread the SHG crystal through the solvers, sessions and GUI, with BBO #37: threading through solvers, sessions and GUI; BBO
  3. Two-beam delay smearing for SHG FROG #38: two-beam SHG delay smearing
  4. Predict and correct the SHG marginal through a crystal #39: SHG marginal through a crystal

This PR's base is main; the later PRs each show only their own changes. Merge the PRs bottom-up. After each merge, retarget the next PR onto main.

What changed

The first part of #24: SHG in a Type I (oo→e) uniaxial crystal, through the NumPy and JAX forward models.

  • croak.crystals.
    • UniaxialCrystal holds any pair of ordinary and extraordinary index functions, with an optional transparency range.
    • CrystalSetup takes the cut angle with either an external tilt or the wavelength the crystal was tuned to phase-match (the tilt is then solved). It also takes the crossing geometry and the fundamental's polarisation relative to the crossing plane.
    • propagation gives the fundamental's (ordinary, longitudinal) and the signal's (extraordinary, at the internal angle) propagation constants, the ω/n generation prefactor and the path through a tilted plate.
    • depth_points gives the depth nodes the phase mismatch needs, and the models refuse fewer.
  • croak.geometry.TwoBeamGeometry. It is the one source of the crossing angle: beam separation and focal length, and later the beam diameter for smearing.
  • The forward models. ForwardModel, maketrace and the JAX trace functions accept a CrystalSetup as material for SHG, with separate fundamental and signal propagators. The refusal of a material for SHG is lifted only for a crystal; PG and SD are unchanged.
  • Beams crossing in the crystal's principal plane. The signal's tilt changes its index to first order. The model keeps that term as opposite delay drifts of the two arms (CrystalSetup.arm_shift), with the delayed beam's side as a parameter (delayed_beam); the two sides mirror the trace in delay. The drift is referenced to mid-depth, so the trace keeps its delay origin (Reference the principal-plane delay drift to mid-depth? croak's crystal trace is offset by κP from a full-field simulation #28). tilt_field_error and check_tilt estimate what the first-order treatment leaves out and warn above 1 %.
  • Docs. The forward-model manual has a new section on SHG in a Type I crystal. It covers the two propagation constants, the generation prefactor, depth resolution, the signal's tilt and its walk-off picture, and where the drift is referenced, with the argument and its assumptions. The tutorial and the interactions page point to it, and there is a changelog fragment.

Not in this PR: threading the crystal through the solvers, session and GUI, BBO from optmat (PR 3b), and two-beam SHG delay smearing (PR 4). Both follow as stacked PRs once this is in. Fitting the crystal's thickness stays refused for SHG (#26).

Verification

  • uv run poe check on the final commit: lint, format, pyright (0 errors), codespell, changelog check, and the full suite with 100 % statement and branch coverage.
  • uv run poe docs builds without warnings.
  • Tests (all with a synthetic BBO-like Sellmeier pair; no new dependency):
    • the n_e(θ) limits and derivative;
    • the solved tilt phase-matches its wavelength;
    • both models against an exact double sum over component pairs (analytic depth integral), for both geometries;
    • the exact marginal identity, M(Ω) = |a_s|² Σ S S sinc²(ΔkL/2);
    • the depth-node rule;
    • NumPy against JAX;
    • the zero-thickness limit (the ideal trace times the prefactor);
    • the hand-derived adjoint against finite differences, and against JAX;
    • the drift's sign (flipping it mirrors the trace in delay);
    • that the principal-plane trace keeps its delay origin (fails with an exit-face reference);
    • every refusal and error path.
  • Against a full-field simulation (Luna.jl, 2-D x–t, the full χ(2) field of two crossing Gaussian beams in BBO, the signal summed 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³ in 30 µm at 2.86°, the model matches to 1.2 % and 0.2 % of the trace peak. That is with the delay smearing averaged in, for beams crossing at the entrance face, mid-plane or exit face. Out of the principal plane the traces are symmetric, as the model predicts. Run, not public.
  • Two rounds of independent review on each block (the crystal numerics, the forward models, the drift's reference), with the findings fixed.

Coefficient checks: the tests use a synthetic Sellmeier pair (Tamošauskas et al. 2018's BBO coefficients, as printed) only as a realistic test crystal; no physical constant is transcribed into the package by this PR.

Related

Part of #24. Closes #28. Follow-ups: #25 (crystal-aware marginal check), #26 (fitting the crystal), #27 (remaining differences against a full-field simulation). Independent of #29.

🤖 Generated with Claude Code

https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX

chrisbrahms and others added 15 commits November 12, 2026 17:05
croak.crystals supplies separate propagation constants for the ordinary
fundamentals (with the crossing angle) and the extraordinary signal near
2*omega0, and the omega_s/n_s generation prefactor; keeping the carrier
wavevectors, the depth sum carries the exact phase mismatch. The crystal
is given by its cut angle and an external tilt, or the wavelength it is
tuned to. croak.geometry holds the two-beam geometry, the one source of
the crossing angle. Both forward models take a CrystalSetup for SHG and
check the depth resolution and the neglected signal tilt.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
The exact double sum over component pairs with the depth integral done
analytically, the Parseval form of the frequency marginal (pair sinc^2),
the zero-thickness limit, NumPy against JAX, the hand adjoint, the guards,
and the neglected signal tilt against a per-pair reference.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
The worst pair over the whole grid sits at its edges, where there is no
light, and overstated the error some 200-fold. tilt_phase_error takes the
fundamental's band (spectral_band), and check_tilt warns once the band is
known; the forward models, which do not know the field, no longer warn.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
- Integrate over the effective path of a tilted plate,
  L / (cos g + (n_e'/n_e) sin g), the first-order normal mismatch; tested
  against an exact normal-component solve.
- A crystal's transparency range: outside it the signal is absorbed and
  pairs do not drive the depth-node count.
- Guards: omega0 > 0, a reachable tilt, an internal angle in 0-90 degrees,
  thickness >= 0, Gauss-Legendre quadrature.
- check_tilt computes the neglected signal tilt's actual change to the
  signal over a set of delays (tilt_field_error, by the exact pair sum)
  and warns above 1 %; at zero delay its first-order effect cancels.
- Independent tests of the crossing wavevector, a tilted forward model and
  the masks; docs and comments corrected.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Crossing in the crystal's principal plane, the signal of a pair (w1, w2)
leaves at an angle psi to the bisector, solving (w_s/c) n_e(theta + psi)
sin(psi) = k_x; its index changes to first order, adding the mismatch
kappa (w1 - w2), kappa = (n_e'/n_s) sin(alpha) / c. That factorises into
opposite delays of the two arms that drift with depth, now carried by
separate test and gate propagators in both forward models and the
adjoint. The trace is then asymmetric in delay; CrystalSetup.delayed_beam
sets the sign, which flipping mirrors the trace in delay. The reference
for check_tilt solves the signal's direction self-consistently and
measures what is left (second order). The phase bound and band helper
are gone.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Test the JAX hand adjoint with the arms' drift; pin the side flip to the
delay mirror exactly on grid-aligned delays; reject a tilt beyond grazing,
a non-finite thickness and an all-zero amplitude; write n_e'/n_s and the
arms' delays explicitly; note what depth_points and the tilt reference
leave out; correct two figures in the manual and a typo in the fragment.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
The 0.5 % came from delays too coarse for a 5 fs pulse; sampled finely it
is about 1 %. The manual now gives which arm gets which delay, and
tilt_field_error refuses an empty set of delays.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
The first-order signal-tilt term is the extraordinary SH walking off
across the transverse delay gradient of the crossing beams. Say so in the
manual and the module docstring, and stop describing walk-off as
neglected: only the SH beam's sideways shift out of the overlap is.

Refs LupoLab#24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Two modules on the core API page had a section called Validity, which
Sphinx rejects as a duplicate ID.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Referenced to the exit face, the drift offset the model's trace by kappa*P
in delay, which a full-field simulation collecting the whole beam does not
show (LupoLab#28). The part of the walk-off common to every depth moves the whole
SH beam sideways, which full collection cannot see; the plane-wave model
drops the walk-off between depths, least on average about the mean
generation depth, which is mid-depth for a uniform slab.

The exact pair-sum reference re-references only the first-order drift, so
tilt_field_error is not made smaller by the choice. A new test pins the
trace's delay origin; the manual gives the argument, its assumptions and
the full-field evidence, and the recomputed effect of the drift.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxMiUXc12ViRwSf2cyL
kappa is about 6e-12 s/m, below pytest.approx's default absolute tolerance
of 1e-12, so the relative tolerance was not what the test checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX
@chrisbrahms chrisbrahms added enhancement New feature or request area: forward model Forward models, interactions, dispersion, smearing and collection labels Nov 13, 2026
@read-the-docs-community

read-the-docs-community Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

@codecov

codecov Bot commented Nov 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

The pair-mismatch estimate kept a pair when |w1 + w2| <= max|omega|, a strict
float comparison at exactly the edge bins. The solver rebuilds its grid from the
trace's frequency axis, whose spacing can differ from the session's in the last
bit, so the two counted different pairs and the solver refused a node count the
session had computed (25 against 27 for 200 um of BBO). Test the sum against the
grid's own span with half a bin of tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX

@jtravs jtravs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the crystal core. Nothing here makes a trace wrong for the setups the tests cover: the frame terms cancel in the mismatch, the gate arm uses gate_prop in both the forward map and the hand adjoint, and the slab-only paths are refused for a crystal. The inline comments are, in order of weight: input validation in croak.crystals (three), the depth-node rule (two), then cleanups and one test-independence point.

The numbers quoted inline were reproduced by running this branch's code with the BBO-like test crystal. I did not run the full suite, and did not re-derive the effective-path formula or the drift's sign convention.

🤖 Generated with Claude Code

Comment thread croak/crystals.py Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

depth_points doesn't validate thickness. It's public, but a negative thickness gives a negative path and a negative count: depth_points(setup, GRID.omega, W0, -100e-6) returns -11. NaN fails inside math.ceil with an unrelated message. Only check_medium checks thickness, and only on the model path. Suggest raising ValueError for a non-finite or negative thickness here.

Comment thread croak/crystals.py Outdated
"""
if thickness == 0.0:
return 1
dk, *_ = _pair_mismatch(setup, np.asarray(omega, dtype=float), omega0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No transparent pairs gives a cryptic error, or a silent zero trace. When no pair lies inside transparency, _pair_mismatch returns empty arrays and np.max raises NumPy's zero-size array to reduction operation maximum which has no identity. That names neither the crystal nor the range. Example: transparency=(1.5e-6, 2e-6) with an 800 nm carrier, which then fails inside ForwardModel(...). At thickness=0 the same setup passes check_medium, propagation zeroes sig_amp everywhere, and the model returns an all-zero trace without a word. A clear ValueError (the grid and carrier lie outside the crystal's transparency range) would cover both.

Comment thread croak/crystals.py
"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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validate phase_match_wavelength and transparency at construction. AGENTS.md: "Validate inputs at public boundaries. Never let NaN or Inf propagate silently." phase_match_wavelength=0.0 is accepted here. It fails later in phase_matching_angle with "runs from nan to nan", after divide-by-zero RuntimeWarnings. A reversed UniaxialCrystal(transparency=(2e-6, 1e-6)) is accepted and silently marks every frequency absorbed. Suggest checking finite and > 0 here, and 0 < lo < hi in UniaxialCrystal.__post_init__.

Comment thread croak/crystals.py
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The node rule over-allocates by about 1.5–1.8× at large φ, and the models refuse the smaller counts that already suffice. I scanned the smallest Gauss–Legendre count with error ≤ 1e-6·L for every φ′ in [0, φ]:

φ needed ceil(φ)+3
20 18 23
40 30 43
60 41 63
120 74 123
250 142 253

Forward and adjoint cost scale with Q, so a 1.5 fs grid with 500 µm at 5.7° (249 nodes where about 140 would do) pays roughly 1.8× on every solver iteration. Since check_medium raises below the rule, a user can't opt out. A tighter rule (about φ/2 plus a slowly growing margin), validated by the existing parametrised test_depth_rule_resolves_the_oscillation with φ extended upward, would keep the guarantee. Not blocking; could be a follow-up issue.

Comment thread croak/crystals.py Outdated
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)`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The drift's contribution to φ depends on the grid. The claim of "at most about one rad … even for 500 µm at a 5.7° half-angle" holds only on a ~3 fs grid, because the drift grows with the span of ω1−ω2. φ from _pair_mismatch, without and with κ(ω1−ω2):

  • 3 fs grid, 500 µm, 5.7°: 73.3 → 74.7 rad
  • 1.5 fs grid, 500 µm, 5.7°: 245.6 → 257.6 rad, so 249 nodes returned where the rule itself asks for 261
  • 1.5 fs grid, 100 µm, 1.43°: 48.5 → 49.0 rad, so 52 returned vs 53

The rule's slack (previous comment) absorbs it in practice: the quadrature error is still about 4e-15. But the stated guarantee doesn't strictly hold. _pair_mismatch already returns w1 and w2, so adding setup.arm_shift(omega0) * (w1 - w2) to dk would make it exact for free and remove the caveat.

Comment thread croak/crystals.py Outdated
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hoist the delay-independent work out of the loop. _pair_signal runs twice per delay, and each call recomputes propagation(), _group_delay, and (through internal_angle from propagation, path_length and arm_shift) several brentq solves of the phase-matching angle at xtol 1e-14. The tilted branch also re-evaluates both Sellmeier indices per bin. None of this depends on τ. Computing it once and passing it in would make the cost the N² pair sum the docstring states. Relatedly, a ForwardModel construction solves the same angle about 8 times. Computing θ once per (setup, omega0) and passing it down would tidy both.

Comment thread croak/crystals.py Outdated
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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: these lines repeat path_length's n_e′/n_s computation exactly. A private _index_slope_ratio(omega0) used by both keeps the effective path and the drift from drifting apart, e.g. if the evaluation wavelength ever changes.

Comment thread croak/crystals.py Outdated
ValueError
If ``amplitude`` is zero everywhere or ``delays`` is empty.
"""
if setup.geometry is None or setup.polarization != "perpendicular" or not thickness:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this re-spells in_principal_plane. if not setup.in_principal_plane or not thickness: keeps the estimate tied to the same condition arm_shift uses.

Comment thread croak/forward_jax.py Outdated
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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: instead of a second closure with a different signature (thk unused in one branch, input_prop in the other), have props return (input_prop, gate_prop, signal_prop, weights). The focal and smearing call sites of props use only input_prop. That's fine today because they're refused for SHG, but a 4-tuple makes the gate arm impossible to forget when SHG smearing lands (PR 4).

return np.where(np.abs(a * path) < 1e-12, path, out)


def _pair_sum(setup, thickness, ew, tau, beta_sig_pair=None, drift=True):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_pair_sum copies crystals._pair_signal(tilted=False) almost line for line. It builds on the same crystals.propagation() and arm_shift. So the "exact" comparisons check the FFT and quadrature plumbing, but a wrong sign or factor in beta_sig, sig_amp or arm_shift would pass on both sides. Those are covered elsewhere (test_crystal_propagation_carries_the_exact_mismatch, the prefactor test, the sign and mirror tests), so this isn't a gap in itself. Still, either reuse _pair_signal here, or build the reference from the index functions directly (_k_fundamental/_k_signal and an independently written κ) to make it independent.

chrisbrahms and others added 3 commits November 17, 2026 10:59
Address the review of LupoLab#31: reject an invalid transparency range,
phase-match wavelength or thickness, and a grid the crystal is opaque
over (even at zero thickness), with a clear message. Add the drift
kappa(w1 - w2) to the mismatch the node rule takes its maximum over, so
the rule's guarantee holds on wide grids. Solve the carrier angle once
and share the index slope between the effective path and the drift, and
precompute the delay-independent parts of the pair sum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX
A 4-tuple (input, gate, signal, weights) in place of a second closure,
so a future SHG smearing path cannot leave out the gate arm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX
The reference no longer reuses croak.crystals.propagation, _group_delay
or arm_shift, so a wrong sign or factor there fails the comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WM2AxPM9w8Mg7mfKikaeCX
@chrisbrahms

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Drafted by Claude (AI) on behalf of the author. The changes are in da1da60..59880ad; an independent derivation of the two pieces you did not re-derive (the effective path and the drift's sign) follows in the next comment.

Input validation (three comments). Done.

  • UniaxialCrystal rejects a transparency that is not finite with 0 < lo < hi.
  • CrystalSetup rejects a phase_match_wavelength that is not finite and > 0.
  • depth_points rejects a negative or non-finite thickness, sharing one check with check_medium.
  • A grid with no pair inside the transparency range now raises a ValueError that names the crystal, its range and the grid's span. check_medium runs that check at zero thickness too, so the silent all-zero trace is gone.

The drift in φ. Done as you suggested. _pair_mismatch adds κ(ω₁−ω₂), so the node rule's guarantee now holds on wide grids. I removed the docstring's "about one rad" claim. A new test pins the 500 µm / 5.7° / 1.5 fs case.

The node rule. I reproduced your table exactly (18/30/41/74/142 nodes at φ = 20/40/60/120/250) and opened #36 for a tighter rule. The forward-model explanation page links it.

Hoisting. Done. _PairSum, built once per tilt_field_error call, holds everything that does not depend on the delay: the propagation, the frame's group delay, the angle and the indices at every signal bin. The carrier's angle and the index slope are solved once into a private _Carrier and shared by propagation, path_length, arm_shift and the node rule. Building a ForwardModel now solves the angle twice instead of about eight times.

Nits. Both done. _slope is the single evaluation of n_e′/n_s used by both the effective path and the drift. tilt_field_error now tests in_principal_plane.

props as a 4-tuple. Done. The slab-only call sites (focal, smeared) unpack the gate propagator and say why they don't use it.

Independent test reference. Done. _pair_sum is now built from the crystal's index functions: the wavevector along the bisector, the signal index, the prefactor, and the frame's group delay and κ by finite differences. Only the internal angle and the effective path come from the library, and both are tested on their own. As a check, flipping the sign of κ in the library now fails 6 tests in test_forward_crystal.py.

uv run poe check passes (1997 passed, 100% coverage) and uv run poe docs builds cleanly.

@chrisbrahms

Copy link
Copy Markdown
Contributor Author

Derivation note: the effective path and the drift's sign

The review said it did not re-derive these two, so here they are, for checking. Both agree with the code at the head of this PR. Drafted by Claude (AI); please check it rather than take it on trust.

Conventions (from croak/crystals.py). θ is the internal angle between the bisector and the optic axis. θ = θ_c + γ_int, with a positive tilt increasing θ. n_s = n_e(θ), and n_e′ = dn_e/dθ, both taken at the signal carrier 2ω₀. For a negative uniaxial crystal n_e′ < 0. The bisector mismatch is Δk = k_s − k_z(ω₁) − k_z(ω₂).

1. Effective path, L_eff = L / (cos γ + (n_e′/n_s) sin γ)

Take x along the face and z along the face normal. The fundamentals' mean wavevector lies along the bisector, at angle γ (= γ_int) to the normal. The sum of the fundamentals' bisector components is k_s0 − Δk, where k_s0 = (ω_s/c) n_s.

The face fixes the transverse component, so the driven signal has K_x = (k_s0 − Δk) sin γ. The signal is a free extraordinary wave at angle γ + δ to the normal. Its magnitude is k_s0 + k_s′δ, with k_s′ = (ω_s/c) n_e′.

Matching the transverse components to first order:

δ (k_s0 cos γ + k_s′ sin γ) = −Δk sin γ.

The phase that builds up over the plate is the mismatch of the normal components:

Δk_⊥ = (k_s0 + k_s′δ) cos(γ+δ) − (k_s0 − Δk) cos γ
= Δk cos γ + δ (k_s′ cos γ − k_s0 sin γ)
= Δk · k_s0 / (k_s0 cos γ + k_s′ sin γ).

So Δk_⊥ L = Δk L_eff, with L_eff = L / (cos γ + (n_e′/n_s) sin γ). This is CrystalSetup.path_length.

What it assumes:

  • It is first order in Δk. The error is O(Δk²) and vanishes at phase matching; the existing test against an exact boundary-value solve checks this.
  • It takes n_e′/n_s at 2ω₀ rather than at each ω_s. That neglects a correction of order Δk · sin γ times the ratio's relative change across the band, which is small for the few-degree tilts in use.
  • It ignores the crossing's own transverse components. Their cross term with γ is second order, and their first-order part is the drift in section 2.

2. The drift rate κ = s (n_e′/n_s) sin α / c, and its sign

Here s = +1 when the delayed (gate) beam crosses on the optic-axis side, and α is the external half-angle.

From wavevectors (as coded). Take x as transverse, positive towards a larger angle to the optic axis. With the gate on the axis side, the test beam carries +ω₁ sin α / c and the gate −ω₂ sin α / c (the tangential component is conserved through an untilted face). So the signal has K_x = s(ω₁−ω₂) sin α / c and runs at δθ = K_x/k_s to the bisector. Its index changes by n_e′ δθ. Its bisector component, k_s cos δθ, changes only at second order. Δk therefore grows by κ(ω₁−ω₂) with κ as above, which is arm_shift and the k_x sign in _pair_signal.

For the test crystal (α = 1.43°, 800 nm), n_e′ < 0, so κ < 0 with the gate toward the axis. That matches test_arm_shift_is_the_first_order_tilt_rate: κ·100 µm = −0.567 fs.

Independently, in real space. κ(ω₁−ω₂) = (n_e′/n_s) K_x is linear in K_x. A phase linear in K_x is a transverse shift. Stationary phase on exp(i k_z(K_x)(L−z) + i K_x X) puts the signal generated at depth z at exit position X = x₀ + ρ(L−z). Here ρ = −n_e′/n_s > 0 is the signal's e-ray walk-off, about 3.9° at these parameters. So the drift is the signal's walk-off.

The crossing turns a transverse shift into a delay. The transverse wavevector is fixed at ω sin α / c inside the crystal, so the gate-minus-test delay at transverse position x is τ − 2s x sin α / c. No group-index factor enters, because ∂k_x/∂ω = sin α / c exactly. The light reaching the exit at X from depth z was generated at x₀ = X − ρ(L−z).

Collecting the whole beam (integrating over X), the depth-dependent part of the delay seen there is

+2sρ(L−z) sin α / c = −2κ(L−z),

which is the arm_shift docstring's τ − 2κ(L−z) before re-referencing. Both routes give the same magnitude and sign.

The mid-depth reference. Splitting (L−z) = L/2 + (L/2 − z), the L/2 part is the same for every depth. It is a transverse translation of the whole signal beam by ρL/2, which a detector collecting the whole beam cannot see. That leaves e^{iκΩ(P/2−z)} on the test arm and its inverse on the gate, as in Propagation.arm_props.

Whether dropping the common part is right for croak's plane-wave pair sum is a modelling question, not a step of the derivation. #28 settles it by comparison with a full-field simulation, not by this argument.

What section 2 assumes:

  • It is first order in α and in the walk-off.
  • It treats an untilted plate. With a tilt, the conserved tangential component is along the face rather than perpendicular to the bisector, a relative correction of O(γ²).
  • It uses n_e′/n_s at 2ω₀, as in section 1.
  • The neglected second-order remainder of the signal's tilt is what tilt_field_error estimates.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: forward model Forward models, interactions, dispersion, smearing and collection enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Reference the principal-plane delay drift to mid-depth? croak's crystal trace is offset by κP from a full-field simulation

2 participants