Source code for pnps.pulse

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

"""Input pulse construction, spectral resampling, duration metrics and energy.

The 1-D pulse spectrum built here is the *shape* (amplitude and spectral
phase) of the input; its absolute scale is arbitrary because the beamlet
builder rescales the full 3-D field to the requested energy. The spectral
phase follows the FFT sign convention used throughout: a physical spectral
phase ``phi(omega)`` is applied as ``exp(-1j * phi)``, so positive GDD
(``phi2 > 0``) chirps the pulse in the normal-dispersion sense.
"""

import numpy as np
from jaxtyping import Complex, Float, Inexact
from scipy.constants import c, epsilon_0

from pnps.exceptions import PulseError
from pnps.grids import SpaceGrid, TimeGrid

__all__ = [
    "energy_prefactor",
    "energy_spectral",
    "energy_time",
    "fit_spectral_chirp",
    "gaussian_pulse_spectrum",
    "intensity_fwhm",
    "planck_taper",
    "resample_spectrum",
    "taylor_phase",
]

#: Target frequencies evaluated per block in :func:`resample_spectrum`. The
#: phase matrix is ``block x len(spectrum)`` complex, so this bounds the
#: temporary at a few tens of MB for the largest source grids used here.
_RESAMPLE_BLOCK = 64


def _planck_ramp(
    x: Float[np.ndarray, "*shape"], x0: float, x1: float
) -> Float[np.ndarray, "*shape"]:
    """C-infinity monotone ramp: 0 at ``x <= x0``, 1 at ``x >= x1``.

    Parameters
    ----------
    x : numpy.ndarray
        Abscissa, any shape and any unit.
    x0, x1 : float
        Start and end of the ramp, in the unit of ``x``, with ``x0 < x1``.

    Returns
    -------
    numpy.ndarray
        The ramp value in [0, 1], the shape of ``x``.
    """
    inside = (x > x0) & (x < x1)
    xs = np.where(inside, x, (x0 + x1) / 2)
    z = (x1 - x0) / (xs - x0) + (x1 - x0) / (xs - x1)
    ramp = 1.0 / (1.0 + np.exp(np.clip(z, -700, 700)))
    return np.where(x <= x0, 0.0, np.where(x >= x1, 1.0, ramp))


[docs] def planck_taper( x: Float[np.ndarray, "*shape"], left0: float, left1: float, right1: float, right0: float, ) -> Float[np.ndarray, "*shape"]: """Planck-taper window: 0 outside ``(left0, right0)``, 1 in ``[left1, right1]``. A C-infinity bump [McKechan2010]_ used here to band-limit the *input* spectrum to the simulation window once at setup — its smoothness means the hard grid-boundary truncation never rings into the time domain. It is never applied during propagation. Parameters ---------- x : numpy.ndarray Abscissa, any shape and any unit. left0, left1, right1, right0 : float The window's corners in the unit of ``x``, with ``left0 < left1 <= right1 < right0``: it rises over ``(left0, left1)`` and falls over ``(right1, right0)``. Returns ------- numpy.ndarray The window value in [0, 1], the shape of ``x``. References ---------- .. [McKechan2010] D. J. A. McKechan, C. Robinson and B. S. Sathyaprakash, Class. Quantum Grav. 27, 084020 (2010), eq. (7). """ return _planck_ramp(x, left0, left1) * (1.0 - _planck_ramp(x, right1, right0))
[docs] def taylor_phase( omega: Float[np.ndarray, "*shape"], lam0: float, cep: float = 0.0, gd: float = 0.0, gdd: float = 0.0, tod: float = 0.0, ) -> Float[np.ndarray, "*shape"]: """Taylor spectral phase about the carrier ``omega_c = 2*pi*c/lam0``. Parameters ---------- omega : numpy.ndarray Absolute angular frequency axis in rad/s. lam0 : float Expansion wavelength in m. cep, gd, gdd, tod : float Phase orders 0..3 in s^0..s^3: carrier-envelope phase, group delay, group-delay dispersion, third-order dispersion. Returns ------- numpy.ndarray ``phi(omega) = cep + gd*dw + gdd*dw^2/2 + tod*dw^3/6`` with ``dw = omega - omega_c``. """ dw = omega - 2 * np.pi * c / lam0 return cep + gd * dw + gdd * dw**2 / 2 + tod * dw**3 / 6
[docs] def gaussian_pulse_spectrum( tgrid: TimeGrid, tau_fwhm: float, gdd: float = 0.0, tod: float = 0.0, lam0: float | None = None, ) -> Complex[np.ndarray, " n_omega"]: """Spectrum of a Gaussian pulse with optional GDD/TOD chirp. The transform-limited envelope has intensity FWHM ``tau_fwhm`` and peaks at grid time t = 0 (the centre sample). The chirp is applied as a multiplicative spectral phase ``exp(-1j * phi)``. Parameters ---------- tgrid : TimeGrid The temporal grid the pulse lives on. tau_fwhm : float Intensity FWHM of the transform-limited pulse in s. gdd, tod : float Group-delay dispersion (s^2) and third-order dispersion (s^3) about the pulse carrier. lam0 : float or None Pulse carrier wavelength in m; defaults to the grid reference. A different carrier appears as an envelope frequency offset. Returns ------- numpy.ndarray Complex spectrum on ``tgrid.omega``, arbitrary overall scale. """ lam0 = tgrid.lam0 if lam0 is None else lam0 # sigma of the INTENSITY profile: I(t) = exp(-t^2 / (2 sigma^2)). sigma = tau_fwhm / (2 * np.sqrt(2 * np.log(2))) envelope = np.exp(-(tgrid.t**2) / (4 * sigma**2)) # field = sqrt(intensity) offset = 2 * np.pi * c / lam0 - tgrid.omega0 # envelope carrier offset et = envelope * np.exp(1j * offset * tgrid.t) e_omega = np.fft.fft(et) phi = taylor_phase(tgrid.omega, lam0, gdd=gdd, tod=tod) return e_omega * np.exp(-1j * phi)
[docs] def fit_spectral_chirp( omega: Float[np.ndarray, " n_omega"], e_omega: Complex[np.ndarray, " n_omega"], lam0: float, threshold: float = 1e-3, ) -> tuple[float, float]: """Fit (GDD, TOD) from a stored complex spectrum by a weighted cubic. The spectral phase is unwrapped over the bins carrying more than ``threshold`` of the peak spectral power, fitted with a cubic weighted by the spectral amplitude, and reported in the package's convention (phase applied as ``exp(-1j phi)`` with ``phi = gdd dw^2/2 + tod dw^3/6``), so a positive GDD is normal dispersion. Constant and linear terms — carrier- envelope phase and any residual time offset — are absorbed by the fit and not reported. Two details are load-bearing. The stored pulse peaks at the centre sample of its time grid, so the FFT-ordered spectrum carries an exact ``(-1)^k`` ramp — very nearly pi radians per bin, which defeats any unwrap; it is removed exactly first. And ``threshold`` is part of the measurement, not a detail: on a structured spectrum with deep minima, raising it from 1e-3 to 1e-2 discards the wings that constrain the curvature and can move the fitted GDD by a factor of two. Parameters ---------- omega : numpy.ndarray Absolute angular frequency axis in rad/s, any order. e_omega : numpy.ndarray Complex spectrum on ``omega`` in the storage convention. lam0 : float Wavelength the Taylor expansion is taken about, in m. threshold : float Fraction of the peak spectral power a bin must carry to enter the fit. Returns ------- tuple of (float, float) ``(gdd, tod)`` in s^2 and s^3. Raises ------ PulseError If fewer than four bins pass the threshold (a cubic needs four). """ e_omega = e_omega * (-1.0) ** np.arange(len(e_omega)) order = np.argsort(omega) om, e = omega[order], e_omega[order] weight = np.abs(e) ** 2 selected = weight > threshold * weight.max() if np.count_nonzero(selected) < 4: raise PulseError( f"only {np.count_nonzero(selected)} bins carry more than " f"{threshold:g} of the peak power; a cubic fit needs four" ) phase = np.unwrap(np.angle(e[selected])) dw = om[selected] - 2 * np.pi * c / lam0 coef = np.polynomial.polynomial.polyfit(dw, phase, 3, w=np.sqrt(weight[selected])) return float(-2.0 * coef[2]), float(-6.0 * coef[3])
[docs] def resample_spectrum( spectrum: Inexact[np.ndarray, " n_time"], omega_ref: float, delta_t: float, omega: Float[np.ndarray, " n_omega"], ) -> Complex[np.ndarray, " n_omega"]: """Evaluate an FFT-ordered spectrum at arbitrary frequencies, exactly. The samples of a spectrum on a uniform frequency grid determine a unique trigonometric polynomial in frequency, whose coefficients are the conjugate-domain (time) samples obtained by one inverse FFT. Evaluating that polynomial at arbitrary frequencies is *exact* interpolation for any signal contained in the implied time window, at any ratio of grid spacings. Linear or spline interpolation of the sampled values is not: on a delayed trace the spectrum carries fringes of period ``2 pi / tau`` (about twenty bins at 13 fs), where linear interpolation errs by ~1% of the fringe amplitude, and on a phase-wrapped complex field it fails outright. The conjugate-domain coefficients are indexed by *signed* lags, so the interpolant is the one appropriate to a signal centred on zero lag. Two kinds of input satisfy that: a power spectrum, whose conjugate domain is the field autocorrelation (peaked at zero lag by construction), and the centred-time transform ``sum_n E(t_n) exp(-1j omega t_n)`` of a field peaked at ``t = 0``. A spectrum carrying this package's storage ramp (see :func:`gaussian_pulse_spectrum`) must have it removed first. Parameters ---------- spectrum : numpy.ndarray Spectral samples in FFT order, shape ``(n,)``; real or complex. omega_ref : float Absolute angular frequency of element 0, in rad/s (the carrier for a baseband envelope grid, 0 for a one-sided absolute axis). delta_t : float Time step of the conjugate grid in s, i.e. the sample spacing implied by the spectrum's own frequency spacing ``2 pi / (n * delta_t)``. omega : numpy.ndarray Absolute angular frequencies to evaluate at, in rad/s, any order. Returns ------- numpy.ndarray Complex values at ``omega``, shape ``omega.shape``. For a real input spectrum the imaginary part is round-off and callers may drop it. Examples -------- Evaluating at the grid's own frequencies returns the samples: >>> import numpy as np >>> s = np.fft.fft(np.exp(-((np.arange(32) - 16.0) ** 2) / 8)) >>> w = 2 * np.pi * np.fft.fftfreq(32, 1.0) >>> bool(np.allclose(resample_spectrum(s, 0.0, 1.0, w), s)) True """ n = len(spectrum) coeffs = np.fft.ifft(spectrum) # Signed lags: element j of the inverse transform belongs to lag j for # j < n/2 and to lag j - n above, which is the centred lag window. lags = np.rint(np.fft.fftfreq(n, 1.0 / n)) * delta_t out = np.empty(len(omega), dtype=complex) for start in range(0, len(omega), _RESAMPLE_BLOCK): block = omega[start : start + _RESAMPLE_BLOCK] - omega_ref out[start : start + _RESAMPLE_BLOCK] = ( np.exp(-1j * np.outer(block, lags)) @ coeffs ) return out
def _half_maximum_crossing( t: Float[np.ndarray, " n_t"], intensity: Float[np.ndarray, " n_t"], i: int, j: int ) -> float: """Interpolate the time where the segment from sample i to j crosses half peak. Parameters ---------- t : numpy.ndarray Monotonically increasing time axis, shape ``(n_t,)``, in s. intensity : numpy.ndarray Non-negative intensity samples on ``t``. i, j : int Indices of the two samples bracketing the crossing. Returns ------- float The linearly interpolated crossing time, in the unit of ``t``. """ half = 0.5 * float(np.max(intensity)) y0, y1 = float(intensity[i]), float(intensity[j]) return float(t[i] + (half - y0) * (t[j] - t[i]) / (y1 - y0))
[docs] def intensity_fwhm( t: Float[np.ndarray, " n_t"], intensity: Float[np.ndarray, " n_t"] ) -> float: """Full width at half maximum of a sampled intensity profile. The half-maximum crossings are found on the outermost samples above half the peak and placed by linear interpolation between the bracketing samples, so the result is not quantised to the sample spacing. On an 8x-oversampled envelope grid that leaves an error of order ``(delta_t)^2`` times the profile's curvature at the crossing — below 1e-4 fs for a femtosecond pulse — but the estimate does assume a single connected region above half maximum: for a profile with a satellite above half the peak it measures the outermost crossings, which is the width of the whole structure, not of the main peak. Parameters ---------- t : numpy.ndarray Monotonically increasing time axis, shape ``(n,)``, in s. intensity : numpy.ndarray Non-negative intensity samples on ``t``. Returns ------- float FWHM in the units of ``t``. Raises ------ PulseError If the profile is not positive, or its half-maximum region touches an end of the axis (the crossing is then off-grid and the width is not measurable). Examples -------- >>> import numpy as np >>> t = np.linspace(-5, 5, 2001) >>> round(intensity_fwhm(t, np.exp(-t**2 / 2)), 4) # 2 sqrt(2 ln 2) 2.3548 """ peak = float(np.max(intensity)) if not peak > 0: raise PulseError("intensity profile is not positive") above = np.flatnonzero(intensity >= 0.5 * peak) first, last = int(above[0]), int(above[-1]) if first == 0 or last == len(t) - 1: raise PulseError( "the half-maximum region reaches the end of the time axis: " "widen the window before measuring a duration" ) return _half_maximum_crossing(t, intensity, last, last + 1) - ( _half_maximum_crossing(t, intensity, first - 1, first) )
[docs] def energy_time( et: Complex[np.ndarray, "*batch n_y n_x n_t"], tgrid: TimeGrid, sgrid: SpaceGrid ) -> Float[np.ndarray, "*batch"] | float: """Pulse energy of a real-space/time field ``E(..., y, x, t)`` in J. ``(c epsilon_0 / 2) * dx * dy * dt * sum(|E|^2)`` for a field in V/m. The three field axes are reduced; a leading batch axis survives. Parameters ---------- et : numpy.ndarray Field ``(..., n_y, n_x, n_t)`` in V/m, with any leading batch axes. tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. Returns ------- numpy.ndarray or float The energy in J, one value per leading batch index (a float for a single field). """ prefac = c * epsilon_0 / 2 * sgrid.delta_x**2 * tgrid.delta_t return prefac * np.sum(np.abs(et) ** 2, axis=(-3, -2, -1))
[docs] def energy_prefactor(tgrid: TimeGrid, sgrid: SpaceGrid) -> float: """Factor turning ``sum |E|^2`` of the spectral state into joules. The state is the unnormalised 3-D FFT of the field in V/m, so by Parseval the time-domain energy functional applies directly once divided by the total sample count. Parameters ---------- tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. Returns ------- float ``c eps_0 / 2 * dx^2 * dt / (n^2 nt)``, in J per (V/m)^2. """ n_total = sgrid.n * sgrid.n * tgrid.nt return c * epsilon_0 / 2 * sgrid.delta_x**2 * tgrid.delta_t / n_total
[docs] def energy_spectral( e: Complex[np.ndarray, "*batch n_y n_x n_omega"], tgrid: TimeGrid, sgrid: SpaceGrid ) -> Float[np.ndarray, "*batch"] | float: """Pulse energy of the spectral state ``E(..., ky, kx, omega)`` in J. A leading batch axis survives. See :func:`energy_prefactor` for the normalisation. Parameters ---------- e : numpy.ndarray Spectral state ``(..., n_y, n_x, n_omega)``, complex: the unnormalised 3-D FFT of the field in V/m, with any leading batch axes. tgrid, sgrid : TimeGrid, SpaceGrid The simulation grids. Returns ------- numpy.ndarray or float The energy in J, one value per leading batch index (a float for a single state). """ return energy_prefactor(tgrid, sgrid) * np.sum(np.abs(e) ** 2, axis=(-3, -2, -1))