# 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
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 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