Source code for pnps.input_pulse

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

"""Data-driven input pulse: inject a stored complex spectrum as the source field.

The synthetic pulse of :func:`pnps.pulse.gaussian_pulse_spectrum` is a
convenience, not a requirement: the illumination profile and the chromatic
input holes are *real*, frequency-dependent amplitude factors applied to one
1-D reference spectrum (see :func:`pnps.beams.build_beamlet_fields`), so any
measured or separately simulated field composes exactly. This module reads
such a field from an HDF5 file, prepares it, and puts it on the simulation's
frequency axis.

Notes
-----
**Conventions.**

A source file stores the *discrete Fourier transform of a field array*: a complex
spectrum ``E[j]`` on an ascending, uniform, absolute angular-frequency axis ``omega[j] =
j * delta_omega`` (a one-sided ``rfft`` axis, as ``numpy.fft.rfft`` gives for a real
field), whose inverse DFT is the analytic field sampled on the *centred* time axis
``t[n] = (n - N/2) * delta_t`` with ``N = 2 * (M - 1)`` and ``delta_t = 2 * pi / (N *
delta_omega)``. That is the same layout this package uses for its own state, and reading
the file on the file's own ``t`` axis is what makes the reported centring shift a
physically meaningful number rather than a wrapped one.

The steps, in the order they must be applied:

1. :func:`load_input_pulse` — read ``omega`` and the complex spectrum;
2. :func:`spectral_window` — optional smooth band-pass, to drop content the
   experiment (or the simulation) does not carry;
3. :func:`centre_pulse` — **required**: move the pulse's temporal peak to
   ``t = 0``. A pulse sitting far from its grid's time origin carries a
   spectral phase rotating by up to pi per sample; the resampling of step 5
   is then interpolating a phase-wrapped field, which no interpolation
   scheme can do. It is also what puts the pulse at the centre of the
   simulation's time window instead of at its edge;
4. :func:`normalise_peak` — optional; the beamlet builder rescales the
   assembled 3-D beam to the requested energy, so only the *shape* of the
   injected spectrum matters and its absolute scale is free;
5. :func:`injected_spectrum` — evaluate the pulse on a :class:`pnps.grids.TimeGrid`
   by exact DFT interpolation (:func:`pnps.pulse.resample_spectrum`), zero
   outside the source's support, and return it in the storage convention of
   :func:`pnps.pulse.gaussian_pulse_spectrum`.

Steps 1-4 are pure functions returning new :class:`InputPulse` objects and
accumulating a human-readable ``history``; step 5 is what
:func:`pnps.setup.build_setup` calls when ``Config.input_pulse`` is set.

**Why exact DFT interpolation and not a spline.**

The source grid and the simulation grid are not commensurate (here 1.72 THz
against 24.2 THz of angular-frequency spacing), so the field must be
*interpolated* in frequency. The samples of a spectrum on a uniform grid determine a
unique trigonometric polynomial — the transform of the field samples in the conjugate
time domain — and evaluating that polynomial is exact, not approximate, for any field
contained in the source's time window. Interpolating real and imaginary parts separately
with a spline is not: it is accurate only where the complex spectrum turns slowly
between samples, which a chirped or off-centre pulse violates. Measured on a simulated
resonant-dispersive-wave field, the exact interpolant reproduces the source energy to
2e-11 when the target time window is long enough to hold the whole source period.
"""

import hashlib
from dataclasses import dataclass, replace
from pathlib import Path

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

from pnps.exceptions import PulseError, PulseFileError
from pnps.grids import TimeGrid
from pnps.pulse import resample_spectrum

__all__ = [
    "MAX_PEAK_OFFSET_FRACTION",
    "PEAK_OVERSAMPLE",
    "InputPulse",
    "centre_pulse",
    "injected_spectrum",
    "load_input_pulse",
    "normalise_peak",
    "peak_time",
    "spectral_window",
]

#: Oversampling factor used to locate the temporal peak in :func:`peak_time`.
#: The parabolic vertex refines below the sample spacing, so 8 is ample: on
#: the source grid used here it puts the peak time within ~1e-4 fs.
PEAK_OVERSAMPLE = 8

#: Fraction of the simulation's time window within which an injected pulse's
#: peak must sit for :func:`injected_spectrum` to accept it. A quarter window
#: is generous — the pulse also has to fit inside ``Config.time_headroom``
#: alongside the delay scan — while still catching the failure this guard
#: exists for: a field injected without :func:`centre_pulse`, which lands at
#: the window edge rather than its centre.
MAX_PEAK_OFFSET_FRACTION = 0.25


[docs] @dataclass(frozen=True, eq=False) class InputPulse: """A stored complex spectrum to be used as the simulation's source field. Equality and hashing are by identity (``eq=False``): the object holds arrays, and it is carried inside the hashable :class:`pnps.setup.Config`. Attributes ---------- omega : numpy.ndarray Ascending, uniformly spaced, absolute angular-frequency axis in rad/s. It must be a contiguous run of bins of a one-sided ``rfft`` axis, i.e. every ``omega[j]`` an integer multiple of the spacing. e_omega : numpy.ndarray Complex spectrum on ``omega``, as stored: the DFT of the field array whose inverse transform is the analytic field on the centred time axis ``(n - N/2) * delta_t`` (see the module docstring). Absolute scale is arbitrary. source : str Provenance: where the field came from (a file name). md5 : str MD5 checksum of the source file, hex-encoded. history : tuple of str The preparation steps applied so far, in order, each a short human-readable record. Written into the scan file so a trace says how its input was built. tshift : float Cumulative time shift applied by :func:`centre_pulse`, in s (positive = the pulse arrived late and was advanced). norm : float Cumulative amplitude factor divided out by :func:`normalise_peak`. """ omega: Float[np.ndarray, " n_bins"] e_omega: Complex[np.ndarray, " n_bins"] source: str = "" md5: str = "" history: tuple[str, ...] = () tshift: float = 0.0 norm: float = 1.0 def __post_init__(self) -> None: """Check that the axis and the spectrum are 1-D and of one length.""" if self.omega.ndim != 1 or self.e_omega.ndim != 1: raise PulseError("omega and e_omega must be 1-D") if len(self.omega) != len(self.e_omega): raise PulseError( f"omega has {len(self.omega)} samples, e_omega has {len(self.e_omega)}" ) if len(self.omega) < 8: raise PulseError( f"an input pulse needs >= 8 samples, got {len(self.omega)}" ) steps = np.diff(self.omega) if np.any(steps <= 0): raise PulseError("omega must be strictly ascending") spacing = float(np.mean(steps)) if np.max(np.abs(steps - spacing)) > 1e-6 * spacing: raise PulseError( "omega must be uniformly spaced (exact DFT interpolation is " "defined by the grid spacing); largest deviation " f"{np.max(np.abs(steps - spacing)) / spacing:.3e} of a step" ) # Every bin must be an integer multiple of the spacing: only then is # the axis a run of bins of a one-sided rfft axis, which fixes the # implied time grid (delta_t, N) the interpolation is built on. offset = self.omega[0] / spacing if abs(offset - round(offset)) > 1e-6: raise PulseError( f"omega[0] = {self.omega[0]:.6e} rad/s is not an integer " f"multiple of the spacing {spacing:.6e}: the axis is not part " "of a one-sided rfft axis, so the implied time grid is undefined" ) if round(offset) < 0: raise PulseError("omega must be non-negative")
[docs] @property def delta_omega(self) -> float: """Angular-frequency sample spacing in rad/s. Returns ------- float The uniform spacing of :attr:`omega`, in rad/s. """ return float((self.omega[-1] - self.omega[0]) / (len(self.omega) - 1))
[docs] @property def n_bins(self) -> int: """Length of the full one-sided axis this pulse is a run of bins of. Returns ------- int Bin count of the one-sided axis from 0 to ``omega[-1]``. """ return round(self.omega[-1] / self.delta_omega) + 1
[docs] @property def n_time(self) -> int: """Sample count of the implied source time grid, ``2 * (n_bins - 1)``. Returns ------- int The source time-grid length ``N``. """ return 2 * (self.n_bins - 1)
[docs] @property def delta_t(self) -> float: """Time step of the implied source time grid in s. Returns ------- float ``2 * pi / (n_time * delta_omega)``, in s. """ return 2 * np.pi / (self.n_time * self.delta_omega)
[docs] @property def support(self) -> tuple[float, float]: """Angular-frequency range carrying non-zero amplitude, in rad/s. Every preparation step here is multiplicative, so exact zeros in the source survive: this is the band the source file actually defines, and :func:`injected_spectrum` puts exact zeros outside it rather than letting the interpolant invent values there. Returns ------- tuple of (float, float) Lowest and highest angular frequency with non-zero amplitude, in rad/s. Raises ------ PulseError If the spectrum is identically zero. """ nonzero = np.flatnonzero(np.abs(self.e_omega) > 0) if len(nonzero) == 0: raise PulseError("input pulse spectrum is identically zero") return float(self.omega[nonzero[0]]), float(self.omega[nonzero[-1]])
[docs] @property def energy(self) -> float: """``sum |E|^2 * delta_omega``: energy in the spectrum's own units. Returns ------- float The spectral energy, in the source file's units of ``|E|^2`` times rad/s (only ratios of it are meaningful). """ return float(np.sum(np.abs(self.e_omega) ** 2) * self.delta_omega)
[docs] def padded(self) -> Complex[np.ndarray, " n_time"]: """Embed the spectrum in its full one-sided axis, zero-filled. Length :attr:`n_time`: the one-sided bins followed by zeros for the negative frequencies, i.e. an FFT-ordered spectrum of an analytic field with reference frequency 0. Returns ------- numpy.ndarray Complex FFT-ordered spectrum, shape ``(n_time,)``. """ first = round(self.omega[0] / self.delta_omega) out = np.zeros(self.n_time, dtype=complex) out[first : first + len(self.e_omega)] = self.e_omega return out
[docs] def time_axis(self, oversample: int = 1) -> Float[np.ndarray, " n_t_fine"]: """Centred time axis of the implied source grid, refined ``oversample`` x. Parameters ---------- oversample : int Refinement factor of the sample spacing, >= 1. Returns ------- numpy.ndarray Times ``(n - N/2) * delta_t / oversample`` in s, shape ``(n_time * oversample,)``. """ n = self.n_time * oversample return (np.arange(n) - n / 2) * self.delta_t / oversample
def _md5(path: Path) -> str: """MD5 checksum of a file, hex-encoded, read in chunks. A provenance fingerprint, not a security measure: it answers "is this the same source field the trace was made from", and MD5 is widely available to check it with. Parameters ---------- path : pathlib.Path The file to fingerprint. Returns ------- str The 32-character hexadecimal MD5 digest. """ digest = hashlib.md5() with path.open("rb") as handle: for block in iter(lambda: handle.read(1 << 20), b""): digest.update(block) return digest.hexdigest()
[docs] def load_input_pulse( path: str | Path, omega_key: str = "ω", e_omega_key: str = "Eω" ) -> InputPulse: """Read an input pulse from an HDF5 file. Parameters ---------- path : str or pathlib.Path The HDF5 file. omega_key, e_omega_key : str Dataset names of the absolute angular-frequency axis (rad/s) and the complex spectrum on it. Returns ------- InputPulse With ``source`` and ``md5`` filled in for provenance. Raises ------ PulseFileError If either key does not name a dataset, or the spectrum is not complex. PulseError If the axis fails the grid requirements of :class:`InputPulse`. """ path = Path(path) with h5py.File(path, "r") as f: for key in (omega_key, e_omega_key): if not isinstance(f.get(key), h5py.Dataset): raise PulseFileError(f"{path.name}: {key!r} is not a dataset") omega = np.asarray(f[omega_key], dtype=float) # type: ignore[arg-type] raw = np.asarray(f[e_omega_key]) # type: ignore[arg-type] if not np.iscomplexobj(raw): raise PulseFileError( f"{path.name}: {e_omega_key!r} is {raw.dtype}, not complex — an " "input pulse needs amplitude and phase" ) return InputPulse( omega=omega, e_omega=np.asarray(raw, dtype=complex), source=path.name, md5=_md5(path), history=(f"load({omega_key}, {e_omega_key})",), )
[docs] def spectral_window( pulse: InputPulse, lam_min: float, lam_max: float, wfrac_blue: float = 0.05, wfrac_red: float = 0.03, ) -> InputPulse: """Smooth tanh band-pass of a stored pulse, ``(lam_min, lam_max)`` in m. Unity well inside the band, rolling off with tanh edges of width ``wfrac_blue * omega(lam_min)`` on the blue side and ``wfrac_red * omega(lam_max)`` on the red. Use it to remove content the instrument being modelled does not carry — for a simulated dispersive-wave field, say, the residual near-infrared driver remnant that survived the filter chain and would otherwise dominate the chi3 interaction. The windowed field is the ground truth a retrieval is compared against, so the window belongs to the run's provenance and is recorded in ``history``. Parameters ---------- pulse : InputPulse The pulse to window. lam_min, lam_max : float Band-pass edges in m. wfrac_blue, wfrac_red : float Edge widths as a fraction of the corresponding edge frequency. Returns ------- InputPulse A new pulse; the input is unchanged. Raises ------ PulseError If ``lam_min >= lam_max`` or an edge width is not positive. """ if not lam_min < lam_max: raise PulseError(f"need lam_min < lam_max, got {lam_min}, {lam_max}") if wfrac_blue <= 0 or wfrac_red <= 0: raise PulseError("edge widths must be positive") omega_red = 2 * np.pi * c / lam_max omega_blue = 2 * np.pi * c / lam_min window = ( 0.25 * (1 + np.tanh((pulse.omega - omega_red) / (wfrac_red * omega_red))) * (1 + np.tanh((omega_blue - pulse.omega) / (wfrac_blue * omega_blue))) ) return replace( pulse, e_omega=pulse.e_omega * window, history=( *pulse.history, ( f"tanh_window({lam_min * 1e9:.1f}-{lam_max * 1e9:.1f} nm, " f"wfrac {wfrac_blue:g}/{wfrac_red:g})" ), ), )
[docs] def peak_time(pulse: InputPulse, oversample: int = PEAK_OVERSAMPLE) -> float: """Time of the temporal intensity peak on the source's centred axis, in s. The analytic field is evaluated on an ``oversample``-times finer axis by zero-padding the spectrum (the exact band-limited interpolation), and the peak is refined below that spacing by the vertex of the parabola through the largest sample and its neighbours. Neighbours are taken cyclically, so a pulse sitting at the wrap point of the source window is handled. Parameters ---------- pulse : InputPulse The pulse whose peak is sought. oversample : int Temporal refinement factor for the search. Returns ------- float Peak time in s, on the axis ``(n - N/2) * delta_t``. """ buffer = np.zeros(pulse.n_time * oversample, dtype=complex) padded = pulse.padded() buffer[: len(padded)] = padded intensity = np.abs(np.fft.ifft(buffer)) ** 2 n = len(intensity) axis = pulse.time_axis(oversample) peak = int(np.argmax(intensity)) left, centre, right = ( intensity[(peak - 1) % n], intensity[peak], intensity[(peak + 1) % n], ) curvature = left - 2 * centre + right offset = 0.0 if curvature == 0 else 0.5 * (left - right) / curvature return float(axis[peak] + offset * pulse.delta_t / oversample)
[docs] def centre_pulse( pulse: InputPulse, oversample: int = PEAK_OVERSAMPLE ) -> tuple[InputPulse, float]: """Advance the pulse so its intensity peak sits at ``t = 0``. A pure linear spectral phase is physically irrelevant, but numerically it is what decides whether the field can be resampled at all (see the module docstring) and where in the simulation's time window the pulse lands — a pulse left at the window edge is the failure this step exists to prevent. The shift is applied as ``exp(+1j * omega * tshift)``, which advances the field by ``tshift``. Parameters ---------- pulse : InputPulse The pulse to centre. oversample : int Temporal refinement of the peak search, see :func:`peak_time`. Returns ------- tuple of (InputPulse, float) The centred pulse and the shift applied, in s. """ tshift = peak_time(pulse, oversample) centred = replace( pulse, e_omega=pulse.e_omega * np.exp(1j * pulse.omega * tshift), tshift=pulse.tshift + tshift, history=(*pulse.history, f"centre(tshift={tshift * 1e15:+.6f} fs)"), ) return centred, tshift
[docs] def normalise_peak(pulse: InputPulse) -> InputPulse: """Scale the spectrum to unit peak amplitude, recording the factor. The beamlet builder normalises the assembled 3-D beam to the configured pre-mask energy, so the injected spectrum's absolute scale is free; fixing the peak at 1 makes the recorded input truth ``Iω`` an O(1) quantity whatever units the source file used. The factor divided out is kept in ``norm`` so the source amplitude is recoverable. Parameters ---------- pulse : InputPulse The pulse to normalise. Returns ------- InputPulse A new pulse with ``max |e_omega| == 1``; the input is unchanged. Raises ------ PulseError If the spectrum is identically zero. """ peak = float(np.abs(pulse.e_omega).max()) if peak == 0.0: raise PulseError("input pulse spectrum is identically zero") return replace( pulse, e_omega=pulse.e_omega / peak, norm=pulse.norm * peak, history=(*pulse.history, f"normalise(peak={peak:.6e})"), )
[docs] def injected_spectrum( tgrid: TimeGrid, pulse: InputPulse ) -> Complex[np.ndarray, " n_omega"]: """Evaluate a prepared input pulse on the simulation's frequency axis. Exact DFT interpolation of the source spectrum (see the module docstring), zeroed outside the source's :attr:`InputPulse.support`, and returned in the same convention as :func:`pnps.pulse.gaussian_pulse_spectrum`: the FFT of the analytic envelope on the centred time axis, so ``ifft`` of the result is the envelope with the pulse at ``t = 0``. The pulse must have been centred (:func:`centre_pulse`) first, and this is checked rather than assumed: the interpolation is only meaningful for a field sitting at the origin of the source's time window, and an uncentred field would be injected at the edge of the simulation's. Parameters ---------- tgrid : TimeGrid The simulation's temporal grid; its ``omega`` axis is the target. pulse : InputPulse A prepared (windowed, centred) input pulse. Returns ------- numpy.ndarray Complex spectrum on ``tgrid.omega``, shape ``(tgrid.nt,)``. Raises ------ PulseError If the source's support does not overlap the simulation's frequency axis at all, or if the pulse has not been centred. """ window = tgrid.nt * tgrid.delta_t offset = peak_time(pulse) if abs(offset) > MAX_PEAK_OFFSET_FRACTION * window: raise PulseError( f"the input pulse peaks {offset * 1e15:+.3f} fs from its time " f"origin, more than {MAX_PEAK_OFFSET_FRACTION:g} of the " f"simulation's {window * 1e15:.1f} fs window: it would be injected " "at the edge of that window, and its spectral phase turns too fast " "to resample. Run centre_pulse first." ) omega_lo, omega_hi = pulse.support inside = (tgrid.omega >= omega_lo) & (tgrid.omega <= omega_hi) if not np.any(inside): raise PulseError( f"the input pulse's support ({2 * np.pi * c / omega_hi * 1e9:.1f}-" f"{2 * np.pi * c / omega_lo * 1e9:.1f} nm) does not overlap the " "simulation's frequency axis" ) # Multiplying by (-1)^j turns the stored DFT of the field array into the # centred-time transform sum_n E(t_n) exp(-i omega t_n), whose # conjugate-domain content sits at zero lag for a centred pulse -- the # convention resample_spectrum interpolates in. ramp_source = (-1.0) ** np.arange(pulse.n_time) values = resample_spectrum( pulse.padded() * ramp_source, 0.0, pulse.delta_t, tgrid.omega ) ramp_target = (-1.0) ** np.arange(tgrid.nt) return np.where(inside, values, 0.0) * ramp_target