Repository navigation
Model SHG in a Type I crystal in the forward models - #31
chrisbrahms wants to merge 19 commits into
Conversation
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
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
left a comment
There was a problem hiding this comment.
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
| 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 |
There was a problem hiding this comment.
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.
| """ | ||
| if thickness == 0.0: | ||
| return 1 | ||
| dk, *_ = _pair_mismatch(setup, np.asarray(omega, dtype=float), omega0) |
There was a problem hiding this comment.
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.
| "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: |
There was a problem hiding this comment.
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__.
| 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 |
There was a problem hiding this comment.
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.
| 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)` |
There was a problem hiding this comment.
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.
| 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)) |
There was a problem hiding this comment.
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.
| 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( |
There was a problem hiding this comment.
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.
| ValueError | ||
| If ``amplitude`` is zero everywhere or ``delays`` is empty. | ||
| """ | ||
| if setup.geometry is None or setup.polarization != "perpendicular" or not thickness: |
There was a problem hiding this comment.
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.
| 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): |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
_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.
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
|
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.
The drift in φ. Done as you suggested. 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. Nits. Both done.
Independent test reference. Done.
|
Derivation note: the effective path and the drift's signThe 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 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 γ So Δk_⊥ L = Δk L_eff, with L_eff = L / (cos γ + (n_e′/n_s) sin γ). This is What it assumes:
2. The drift rate κ = s (n_e′/n_s) sin α / c, and its signHere 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 For the test crystal (α = 1.43°, 800 nm), n_e′ < 0, so κ < 0 with the gate toward the axis. That matches 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 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 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:
|
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):
croak.crystalsand the forward models ← this PRThis 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 ontomain.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.UniaxialCrystalholds any pair of ordinary and extraordinary index functions, with an optional transparency range.CrystalSetuptakes 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.propagationgives 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_pointsgives 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.ForwardModel,maketraceand the JAX trace functions accept aCrystalSetupasmaterialfor 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.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_errorandcheck_tiltestimate what the first-order treatment leaves out and warn above 1 %.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 checkon the final commit: lint, format, pyright (0 errors), codespell, changelog check, and the full suite with 100 % statement and branch coverage.uv run poe docsbuilds without warnings.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