Source code for pnps.beams

# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later

"""Beamlet construction: HE11 far field cut by chromatic boxcar-mask holes.

The transverse-momentum plane of the simulation *is* the collimated
mask plane: a k-space sample ``(kx, ky)`` at frequency ``omega`` maps to the
mask-plane position ``x = kx * zmask * c / omega`` (the focusing geometry's
angle-to-position mapping), so one physical hole is a different k-space
aperture at every frequency. This chromatic mapping is the entire vignetting
model, for the input holes here and for the collection windows in
:mod:`pnps.extraction`.

The input beam is the HE11 capillary mode imaged onto the focus; its far
field is the closed-form Hankel transform of the J0 core profile. Three
beamlets are cut at the corners ``(+d, +d)`` (gate 1), ``(+d, -d)`` (gate 2)
and ``(-d, +d)`` (test) of the boxcar, with ``d = spacing/2 + diam/2``; the
four-wave-mixing signal emerges at ``(-d, -d)``. The two gates always share
one delay, so they are summed once here.
"""

from dataclasses import dataclass
from typing import NamedTuple

import numpy as np
from jaxtyping import Bool, Complex, Float
from scipy.constants import c
from scipy.special import j0, j1, jn_zeros

from pnps.exceptions import InstrumentError
from pnps.flux import air_admittance, axial_admittance, launch_factor
from pnps.geometry import input_layout
from pnps.grids import SpaceGrid, TimeGrid
from pnps.pulse import energy_prefactor, planck_taper

__all__ = [
    "EDGE_SECOND_MOMENT",
    "Beam",
    "Beamlets",
    "GaussianBeam",
    "HE11Beam",
    "UniformBeam",
    "beamlets_from_fields",
    "build_beamlet_fields",
    "chromatic_mask",
    "he11_far_field",
    "illumination_scale",
    "quadrature_holediam",
    "rcos_edge_default",
    "tanh_apod_default",
    "transverse_factor",
]

#: Second radial moment of each antisymmetric edge profile, ``Int_0^inf t
#: phi(t) dt / w^2`` with t the distance past the nominal edge in units of the
#: profile parameter w. A profile with phi(t) + phi(-t) = 1 encloses
#: ``pi R^2 + 4 pi m2 w^2`` instead of ``pi R^2`` (the outward ring is longer
#: than the inward one), so this is exactly the correction
#: :func:`quadrature_holediam` removes. ``"hard"`` and ``"area"`` have no
#: transition and need no correction; ``"supergauss"`` is not antisymmetric
#: and has no such expansion, so it cannot be used as a quadrature weight.
EDGE_SECOND_MOMENT: dict[str, float] = {
    "hard": 0.0,
    "area": 0.0,
    "rcos": 0.25 - 2 / np.pi**2,
    "tanh": np.pi**2 / 48,
}

# First zero of J0: the HE11 transverse eigenvalue u11.
U11 = float(jn_zeros(0, 1)[0])


[docs] @dataclass(frozen=True) class HE11Beam: """HE11 capillary output collimated and refocused. Attributes ---------- a : float Capillary core radius in m. f_coll : float Collimating focal length in m. f_foc : float Focusing focal length in m. """ a: float f_coll: float f_foc: float
[docs] @property def a_scaled(self) -> float: """Effective core radius at the focus, ``a * f_foc / f_coll``, in m. Returns ------- float The core radius scaled by the imaging magnification, in m. """ return self.a * self.f_foc / self.f_coll
[docs] @dataclass(frozen=True) class GaussianBeam: """A Gaussian beam focused to a waist, cut by the same mask holes. The illumination is the far field of a focal-plane Gaussian of 1/e^2 intensity radius ``w0``: ``exp(-r^2 / w0^2)`` in field, whose transverse spectrum is ``exp(-k^2 w0^2 / 4)``. Like :class:`HE11Beam` it is the same in momentum for every frequency (one focal spot), and the chromatic mask holes cut the three beamlets from it. It is not three mask-free Gaussian beams tilted by one achromatic wavevector: the instrument stays the physical one, a single beam behind a boxcar mask. Attributes ---------- w0 : float 1/e^2 intensity radius of the focal spot in m. f_foc : float Focusing focal length in m (sets the chromatic mask mapping). """ w0: float f_foc: float
[docs] @dataclass(frozen=True) class UniformBeam: """Ideal-instrument control: uniform illumination of the mask plane. The far-field profile is frequency-independent and flat, so each arm's delivered focal k-content is exactly the (apodised) hole disc itself — the ideal top-hat that idealised collection models assume. Tilt geometry, native phases and the chromatic hole mapping are unchanged. With this beam the "pre-mask energy" normalisation of :func:`pnps.form_input.build_input_former` is box-limited rather than physical; control runs should rescale to a recorded delivered energy. Attributes ---------- f_foc : float Focusing focal length in m (sets the chromatic mask mapping). """ f_foc: float
#: The illuminating beam: an HE11 capillary mode, a Gaussian focus, or the #: ideal-instrument control of uniform illumination. Beam = HE11Beam | GaussianBeam | UniformBeam
[docs] def he11_far_field( k_perp: Float[np.ndarray, "*shape"], a_scaled: float ) -> Float[np.ndarray, "*shape"]: """Closed-form far field of the HE11 (J0) mode profile. The Hankel transform of ``J0(u11 r / a)`` truncated at ``r = a``: ``A(k) = -a^2 u11 J1(u11) J0(a k) / (a^2 k^2 - u11^2)`` The singularity of the denominator at ``a k = u11`` is removable (``J0(u11) = 0``); the limit ``a^2 J1(u11)^2 / 2`` is substituted where a grid sample lands on it. Parameters ---------- k_perp : numpy.ndarray Transverse momentum magnitude in rad/m. a_scaled : float Effective core radius in m. Returns ------- numpy.ndarray Real far-field amplitude (arbitrary scale), same shape as ``k_perp``. """ ak = a_scaled * k_perp den = ak**2 - U11**2 on_ring = np.abs(den) < 1e-9 * U11**2 den_safe = np.where(on_ring, 1.0, den) amp = -(a_scaled**2) * U11 * j1(U11) * j0(ak) / den_safe return np.where(on_ring, a_scaled**2 * j1(U11) ** 2 / 2, amp)
def _mask_plane_radius( # noqa: PLR0913, PLR0917 - the k sample, frequency and hole geometry ky: Float[np.ndarray, " n_y"], kx: Float[np.ndarray, " n_x"], omega: Float[np.ndarray, " n_omega"], holex: float, holey: float, zmask: float, offset_ky: float = 0.0, offset_kx: float = 0.0, ) -> tuple[Float[np.ndarray, "n_y n_x n_omega"], Bool[np.ndarray, " n_omega"]]: """Mask-plane distance from the hole centre, and the positive-omega mask. The optional momentum offsets shift the sample point inside its own k pixel; :func:`chromatic_mask` uses them to average a hole edge over the pixel area. Non-positive frequencies are reported separately rather than guarded here: the angle-to-position mapping diverges there. Parameters ---------- ky, kx : numpy.ndarray Transverse momentum axes in rad/m, shapes ``(n_y,)`` and ``(n_x,)``. omega : numpy.ndarray Absolute angular frequency axis in rad/s, shape ``(n_omega,)``. holex, holey : float Hole centre in the mask plane in m. zmask : float Distance from the mask plane to the focus in m. offset_ky, offset_kx : float Momentum offsets added to every sample, in rad/m. Returns ------- r : numpy.ndarray Mask-plane distance from the hole centre in m, shape ``(n_y, n_x, n_omega)``; meaningless where ``omega <= 0``. positive : numpy.ndarray Boolean mask ``omega > 0``, shape ``(n_omega,)``. """ positive = omega > 0 omega_safe = np.where(positive, omega, 1.0) factor = zmask * c / omega_safe # angle-to-position mapping, (nt,) x = (kx[None, :, None] + offset_kx) * factor[None, None, :] y = (ky[:, None, None] + offset_ky) * factor[None, None, :] return np.hypot(x - holex, y - holey), positive
[docs] def chromatic_mask( # noqa: PLR0913, PLR0917 - the k sample, frequency and hole geometry ky: Float[np.ndarray, " n_y"], kx: Float[np.ndarray, " n_x"], omega: Float[np.ndarray, " n_omega"], holex: float, holey: float, holediam: float, zmask: float, apod: str, apod_param: float, ) -> Float[np.ndarray, "n_y n_x n_omega"]: """Hole mask on the ``(ky, kx, omega)`` grid. Each sample maps to the mask-plane position ``x = kx * zmask * c / omega`` (likewise y); the mask is the hole transmission at that position. Non-positive frequencies get zero transmission (the mapping diverges there and those bins carry no physical field). A hole is a *discontinuous* function of position, so how its edge is rendered onto the k grid is a modelling choice with measurable consequences. ``"hard"`` point-samples the discontinuity: by the sampling/periodisation duality that is exactly the *wrapped* focal field, and the Airy tails that wrap round the periodic grid show up as a percent-level ripple. The smooth profiles suppress the wrap by making the focal field decay before the grid edge, at the price of no longer being the nominal aperture. ``"area"`` is the middle course: it is the exact hard aperture averaged over each pixel, so it is unbiased and parameter-free. Parameters ---------- ky, kx, omega : numpy.ndarray Grid axes: transverse momenta in rad/m, absolute angular frequency in rad/s. ``"area"`` additionally requires both momentum axes to be uniformly spaced (the pixel size is taken from the first two samples); every other profile accepts arbitrary sample positions. holex, holey : float Hole centre in the mask plane in m. holediam : float Hole diameter in m. zmask : float Distance from the mask plane to the focus in m (the focal length of the focusing optic for input and collection masks alike). apod : str Edge profile, with ``r`` the mask-plane radius and ``D`` the hole diameter: - ``"hard"``: ``r <= D/2``; - ``"supergauss"``: ``exp(-(2r/D)^p)``; - ``"tanh"``: ``(1 - tanh((r - D/2)/w))/2``; - ``"rcos"``: raised cosine ``(1 - sin(pi t / 2))/2`` with ``t = clip((r - D/2)/w, -1, 1)`` — like ``"tanh"`` but of *compact* support, so the mask is exactly zero beyond ``D/2 + w``; - ``"planck"``: 1 inside ``D/2`` and falling to 0 at ``D/2 + w`` with the C-infinity Planck taper (:func:`pnps.pulse.planck_taper`): an edge *outside* the nominal hole (a padding of ``1 + 2w/D`` on the diameter), so it is not a quadrature weight; - ``"area"``: the fraction of each k pixel lying inside the hole, evaluated by ``p x p`` supersampling. Parameter-free and unbiased, but ``p^2`` times the arithmetic of the others — intended for the input holes, which are built once per setup, not for collection windows evaluated inside the propagation loop. apod_param : float Supergaussian order ``p``; tanh, raised-cosine or Planck width ``w`` in m; or, for ``"area"``, the supersampling factor ``p`` (a positive integer, 4 is ample). See :func:`tanh_apod_default` and :func:`rcos_edge_default` for the conventional widths. Returns ------- numpy.ndarray Real mask of shape ``(len(ky), len(kx), len(omega))`` in [0, 1]. Raises ------ InstrumentError For an unknown ``apod``, or a non-integral ``"area"`` supersampling factor. Examples -------- The raised cosine has compact support, unlike the tanh it replaces: >>> import numpy as np >>> from scipy.constants import c >>> omega = np.array([2 * np.pi * c / 260e-9]) >>> k = np.array([0.0, 4e5]) >>> m = chromatic_mask(k, k, omega, 0.0, 0.0, 1e-3, 0.1, "rcos", 1e-5) >>> float(m[0, 0, 0]), float(m[1, 1, 0]) (1.0, 0.0) """ if apod == "area": sub = round(apod_param) if sub < 1 or abs(apod_param - sub) > 1e-9: raise InstrumentError( f"apod='area' needs a positive integer supersampling factor, " f"got apod_param={apod_param!r}" ) delta_kx = float(kx[1] - kx[0]) delta_ky = float(ky[1] - ky[0]) # Pixel-centred offsets: sub samples spanning (-1/2, +1/2) of a pixel. offsets = (np.arange(sub) + 0.5) / sub - 0.5 covered = np.zeros((len(ky), len(kx), len(omega))) positive = omega > 0 for off_y in offsets: for off_x in offsets: r, _ = _mask_plane_radius( ky, kx, omega, holex, holey, zmask, off_y * delta_ky, off_x * delta_kx, ) # fmt: skip covered = covered + np.where(r <= holediam / 2, 1.0, 0.0) return np.where(positive[None, None, :], covered / sub**2, 0.0) r, positive = _mask_plane_radius(ky, kx, omega, holex, holey, zmask) if apod == "hard": mask = np.where(r <= holediam / 2, 1.0, 0.0) elif apod == "supergauss": mask = np.exp(-((2 * r / holediam) ** apod_param)) elif apod == "tanh": mask = (1 - np.tanh((r - holediam / 2) / apod_param)) / 2 elif apod == "rcos": t = np.clip((r - holediam / 2) / apod_param, -1.0, 1.0) mask = (1 - np.sin(np.pi * t / 2)) / 2 elif apod == "planck": # Flat to the hole radius and zero one width outside it (radii are # non-negative, so the taper's rising side is never reached). edge = holediam / 2 mask = planck_taper(r, -edge - apod_param, -edge, edge, edge + apod_param) else: raise InstrumentError( f"apod must be one of " f"{[*sorted(EDGE_SECOND_MOMENT), 'planck', 'supergauss']}, got {apod!r}" ) return np.where(positive[None, None, :], mask, 0.0)
def _mask_plane_pixel(tgrid: TimeGrid, sgrid: SpaceGrid, zmask: float) -> float: """Width of one k pixel projected into the mask plane at the carrier, in m. Parameters ---------- tgrid : TimeGrid The time grid; its carrier ``omega0`` is snapped to the nearest grid frequency. sgrid : SpaceGrid The transverse grid, which sets the k pixel ``2 pi / (n delta_x)``. zmask : float Distance from the mask plane to the focus in m. Returns ------- float Mask-plane pixel width in m. """ delta_k = 2 * np.pi / (sgrid.n * sgrid.delta_x) omega0 = tgrid.omega[np.argmin(np.abs(tgrid.omega - tgrid.omega0))] return delta_k * zmask * c / omega0
[docs] def tanh_apod_default(tgrid: TimeGrid, sgrid: SpaceGrid, zmask: float) -> float: """Conventional tanh smoothing width: 3 mask-plane pixels at the carrier. ``3 * delta_k * zmask * c / omega0``, with ``omega0`` snapped to the nearest grid frequency (inherited convention). Parameters ---------- tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. zmask : float Mask-plane distance from the focus in m. Returns ------- float Tanh edge width ``w`` in m, for :func:`chromatic_mask`. """ return 3 * _mask_plane_pixel(tgrid, sgrid, zmask)
[docs] def rcos_edge_default( tgrid: TimeGrid, sgrid: SpaceGrid, zmask: float, pixels: float = 2.0 ) -> float: """Raised-cosine edge half-width, in mask-plane m, for ``pixels`` k pixels. Two pixels is the recommended collection-window setting: wide enough that the sampled profile is smooth (so the quadrature carries no Gauss-circle staircase) and narrow enough that the compact support clears the input arms across the whole simulation band. Parameters ---------- tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. zmask : float Mask-plane distance from the focus in m. pixels : float Edge half-width in k pixels at the carrier. Returns ------- float Half-width in m. """ return pixels * _mask_plane_pixel(tgrid, sgrid, zmask)
[docs] def quadrature_holediam(holediam: float, apod: str, apod_param: float) -> float: """Edge diameter whose weight encloses exactly the nominal hole area. An antisymmetric edge profile (``phi(t) + phi(-t) = 1``) samples the aperture without bias in one dimension, but in two dimensions the ring just outside the nominal radius is longer than the ring just inside, so a profile of width ``w`` encloses ``pi R^2 + 4 pi m2 w^2`` with ``m2`` from :data:`EDGE_SECOND_MOMENT`. Shrinking the edge radius to ``sqrt(R^2 - 4 m2 w^2)`` cancels that term exactly, leaving an error of order ``(w/R)^4``. Parameters ---------- holediam : float Nominal hole diameter in m. apod : str Edge profile; must be antisymmetric (not ``"supergauss"``). apod_param : float Edge width in m (ignored for ``"hard"`` and ``"area"``). Returns ------- float Corrected diameter in m, to pass to :func:`chromatic_mask`. Raises ------ InstrumentError If the profile has no antisymmetric expansion, or the correction would consume the whole aperture (edge far too wide for the hole). Examples -------- >>> round(quadrature_holediam(1e-3, "hard", 0.0), 12) 0.001 """ if apod not in EDGE_SECOND_MOMENT: raise InstrumentError( f"apod={apod!r} is not an antisymmetric edge profile and cannot be " f"used as a quadrature weight; use one of {sorted(EDGE_SECOND_MOMENT)}" ) radius_sq = (holediam / 2) ** 2 - 4 * EDGE_SECOND_MOMENT[apod] * apod_param**2 if radius_sq <= 0: raise InstrumentError( f"edge width {apod_param:.3g} m is too wide for a {holediam:.3g} m " "hole: the second-moment correction consumes the whole aperture" ) return 2 * float(np.sqrt(radius_sq))
[docs] class Beamlets(NamedTuple): """Diagnostics of the input beamlets, recorded in every scan file. The beamlet *fields* are never stored: the input state is formed on the fly for each delay (:func:`pnps.form_input.form_input`), so a setup holds only what the scan file records about them. :func:`pnps.form_input.beamlet_diagnostics` computes these in one pass without a field-sized buffer, and :func:`beamlets_from_fields` computes the same numbers from materialised arms -- the reference the fast pass is tested against. Attributes ---------- i_omega_beamlet : numpy.ndarray k-integrated power spectrum of one gate beamlet, ``sum eta |E|^2 / n^2``, shape ``(nt,)`` -- the vignetted "pulse that is retrieved" (the mask and the launch factor are real, so its spectral phase is the input phase). i_omega_beamlet_reimaged : numpy.ndarray On-axis power spectrum of the same beamlet: the focal-centre pixel of its 2-D inverse FFT paired with its magnetic closure, ``Re(A conj(G))`` with ``A = sum (-1)^(iy+ix) E / n^2`` and ``G`` the same sum of ``conj(y) E``, shape ``(nt,)``. This is the partner of ``i_omega_reimaged`` in :mod:`pnps.extraction`, and it is *not* proportional to ``i_omega_beamlet``: the focal spot area scales as ``omega^-2``, so the two differ by a factor ``omega^2`` -- nearly an order of magnitude across a DUV band. Compare a re-imaged trace against this one and a k-integrated trace against ``i_omega_beamlet``. delivered_energy : float Three-arm post-hole pulse energy in J, see :func:`pnps.io_h5.delivered_energy`. """ i_omega_beamlet: Float[np.ndarray, " n_omega"] i_omega_beamlet_reimaged: Float[np.ndarray, " n_omega"] delivered_energy: float
[docs] def transverse_factor(sgrid: SpaceGrid, beam: Beam) -> Complex[np.ndarray, "n_y n_x"]: """Transverse factor of the unmasked input beam, ``(n, n)`` complex. The far-field profile of the illumination times the phase ramps that move the beam from the FFT corner (DC at index 0) to the centre of the real-space grid. The full illumination is this times the 1-D pulse spectrum times one energy normalisation — it is never intrinsically 3-D, which is what lets :mod:`pnps.form_input` form the input state on the fly instead of storing the masked beamlet fields. Parameters ---------- sgrid : SpaceGrid The transverse grid. beam : HE11Beam, GaussianBeam or UniformBeam Input beam geometry. Returns ------- numpy.ndarray Complex ``(ky, kx)`` factor. """ k_perp = np.hypot(sgrid.kx[:, None], sgrid.kx[None, :]) # (ky, kx) match beam: case UniformBeam(): profile = np.ones_like(k_perp) case GaussianBeam(): profile = np.exp(-((k_perp * beam.w0 / 2) ** 2)) case _: profile = he11_far_field(k_perp, beam.a_scaled) shift = sgrid.n * sgrid.delta_x / 2 ramp = np.exp(-1j * sgrid.kx * shift) return profile * ramp[:, None] * ramp[None, :]
[docs] def illumination_scale( tgrid: TimeGrid, sgrid: SpaceGrid, transverse: Complex[np.ndarray, "n_y n_x"], e_omega: Complex[np.ndarray, " n_omega"], energy: float, ) -> float: """Energy normalisation of the separable illumination, without the 3-D array. :func:`build_beamlet_fields` gets the same number from the assembled 3-D array; this computes it from the two factors, so the on-the-fly input former, which never forms the array, can still normalise. The pre-mask beam is in air, so its energy is its axial flux in air, ``sum_omega |e|^2 sum_k cos(theta_air) |t|^2``, one pass over the momentum plane per frequency the spectrum occupies. Parameters ---------- tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. transverse : numpy.ndarray The ``(n, n)`` factor from :func:`transverse_factor`. e_omega : numpy.ndarray 1-D input spectrum on ``tgrid.omega`` (arbitrary scale). energy : float Target pre-mask energy in J, all three arms together. Returns ------- float The real factor normalising ``transverse * e_omega`` to ``energy``. """ profile = np.abs(transverse) ** 2 spectrum = np.abs(e_omega) ** 2 kperp2 = sgrid.kx[:, None] ** 2 + sgrid.kx[None, :] ** 2 weighted = sum( float(spectrum[k]) * float(np.sum(air_admittance(kperp2, float(tgrid.omega[k])) * profile)) for k in np.flatnonzero(spectrum) ) return float(np.sqrt(energy / (energy_prefactor(tgrid, sgrid) * weighted)))
[docs] def build_beamlet_fields( # noqa: PLR0913, PLR0917 - grids, beam, mask and pulse tgrid: TimeGrid, sgrid: SpaceGrid, beam: Beam, e_omega: Complex[np.ndarray, " n_omega"], energy: float, mask_diam: float, mask_spacing: float, apod: str = "area", apod_param: float = 4.0, geometry: str = "tg", *, k2: Complex[np.ndarray, " n_omega"], ) -> tuple[ Complex[np.ndarray, "n_y n_x n_omega"], Complex[np.ndarray, "n_y n_x n_omega"], Complex[np.ndarray, "n_y n_x n_omega"], ]: """Materialise the three beamlet slots in the spectral state layout. This is the NumPy reference rendering of the input, used by the tests to check the on-the-fly former (:mod:`pnps.form_input`), which is what a run uses. It allocates three field-sized arrays, so it is for small grids. The full (unmasked) HE11 beam is the separable product of the far-field profile, the 1-D pulse spectrum, and the phase ramps that centre the beam on the spatial grid; it is normalised to ``energy`` *before* masking, so ``energy`` is the pre-mask energy of all the arms together (inherited convention -- each beamlet carries whatever its hole passes). That energy is the beam's axial flux in air, and the masked arms are carried into the slab at constant flux (:func:`pnps.flux.launch_factor`). Parameters ---------- tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. beam : HE11Beam, GaussianBeam or UniformBeam Input beam geometry (UniformBeam gives the flat-illumination ideal-instrument control). e_omega : numpy.ndarray 1-D input pulse spectrum on ``tgrid.omega`` (arbitrary scale). energy : float Pre-mask pulse energy in J. mask_diam, mask_spacing : float Hole diameter and edge-to-edge spacing in m. apod : str Input-hole apodisation, see :func:`chromatic_mask`. apod_param : float Apodisation parameter for the input holes. geometry : {"tg", "sd"}, optional The beam layout (:func:`pnps.geometry.input_layout`). k2 : numpy.ndarray The slab's material wavenumber squared, ``(nt,)``, complex, zero off the band (:func:`pnps.materials.silica_k2`). Returns ------- tuple of numpy.ndarray ``(e_g1, e_g2, e_test)``, each ``(n, n, nt)`` complex, at zero delay: for TG gate 1 at ``(+d, +d)``, gate 2 at ``(+d, -d)`` and the test arm at ``(-d, +d)``; for SD the probe, zeros, and the gate. """ transverse = transverse_factor(sgrid, beam) base = transverse[:, :, None] * np.asarray(e_omega)[None, None, :] kperp2 = (sgrid.kx[:, None] ** 2 + sgrid.kx[None, :] ** 2)[:, :, None] omega = tgrid.omega[None, None, :] # Normalised from the assembled array, not by illumination_scale's form over the # factors: this is the reference path. air = air_admittance(kperp2, omega) total = energy_prefactor(tgrid, sgrid) * float(np.sum(air * np.abs(base) ** 2)) base = base * np.sqrt(energy / total) base = base * launch_factor(k2[None, None, :], kperp2, omega) layout = input_layout(geometry, mask_diam, mask_spacing) def mask(hx: float, hy: float) -> Float[np.ndarray, "n_y n_x n_omega"]: """Input-hole mask centred at ``(hx, hy)`` in the mask plane. Parameters ---------- hx, hy : float Hole centre in the mask plane in m. Returns ------- numpy.ndarray Real mask of shape ``(n_y, n_x, n_omega)`` in [0, 1]. """ return chromatic_mask( sgrid.kx, sgrid.kx, tgrid.omega, hx, hy, mask_diam, beam.f_foc, apod, apod_param, ) # fmt: skip g1, g2, test = ( base * mask(hx, hy) if weight else np.zeros_like(base) for (hx, hy), weight in zip(layout.holes, layout.weights, strict=True) ) return g1, g2, test
[docs] def beamlets_from_fields( e_g1: Complex[np.ndarray, "n_y n_x n_omega"], e_g2: Complex[np.ndarray, "n_y n_x n_omega"], e_test: Complex[np.ndarray, "n_y n_x n_omega"], tgrid: TimeGrid, sgrid: SpaceGrid, *, k2: Complex[np.ndarray, " n_omega"], ) -> Beamlets: """Compute the beamlet diagnostics from materialised arms. The reference for :func:`pnps.form_input.beamlet_diagnostics`. Every quantity is measured by the slab's axial flux: ``|E|^2`` is weighted by the admittance's real part ``eta``, and the on-axis spectrum pairs the amplitude with its magnetic closure. Parameters ---------- e_g1, e_g2, e_test : numpy.ndarray The arms from :func:`build_beamlet_fields`. tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. k2 : numpy.ndarray The slab's material wavenumber squared, ``(nt,)``, complex. Returns ------- Beamlets The power spectra of gate 1 and the three-arm delivered energy. """ n = sgrid.n kperp2 = (sgrid.kx[:, None] ** 2 + sgrid.kx[None, :] ** 2)[:, :, None] y = axial_admittance(k2[None, None, :], kperp2, tgrid.omega[None, None, :]) eta = np.real(y) i_omega_beamlet = np.sum(eta * np.abs(e_g1) ** 2, axis=(0, 1)) / n**2 # On-axis focal amplitude of the same arm, by the same exact identity the # extraction uses for the collected signal: for an even grid the centre pixel of # the 2-D inverse FFT is the (-1)^(iy+ix)-weighted mean. sign = (-1.0) ** (np.arange(n)[:, None] + np.arange(n)[None, :]) centre = np.sum(sign[:, :, None] * e_g1, axis=(0, 1)) / n**2 closure = np.sum(sign[:, :, None] * np.conj(y) * e_g1, axis=(0, 1)) / n**2 prefactor = energy_prefactor(tgrid, sgrid) delivered = prefactor * float(np.sum(eta * np.abs(e_g1 + e_g2) ** 2)) + ( prefactor * float(np.sum(eta * np.abs(e_test) ** 2)) ) return Beamlets( i_omega_beamlet=i_omega_beamlet, i_omega_beamlet_reimaged=np.real(centre * np.conj(closure)), delivered_energy=delivered, )