# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""HDF5 scan file, in the layout the Croak retrieval package reads.
One scan produces one ``<scan_name>_collected.h5``. Datasets are written in C
order with the delay first and the frequency fastest on disk, ``(N_tau, nz,
N_omega)``, so a reader in a column-major language sees ``(N_omega, nz, N_tau)``.
Conventions carried in ``/grid``:
- ``omega`` is the absolute angular frequency axis in FFT order — readers
must not assume monotonicity;
- ``delay_convention = "gate"``: the test arm was advanced by ``exp(+1j
omega tau)``; do not reverse the delay axis;
- spectra are in the state's unnormalised-FFT units (scaling as the fourth
power of the transverse sample count at fixed extent).
Resume marker: datasets are created zero-filled, and an all-zero delay slice
means "not yet computed". Sharding for
multi-process/multi-GPU scans writes ``<scan_name>_collected.shard<i>.h5``
files with identical layout, merged by :func:`merge_shards`.
"""
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal
import h5py
import numpy as np
from jaxtyping import Complex, Float, Inexact
from scipy.constants import c
from pnps.exceptions import ScanError
from pnps.geometry import signal_centre
from pnps.grids import TimeGrid
from pnps.input_pulse import InputPulse
from pnps.materials import SILICA_BUNDLE
from pnps.setup import Setup
#: Oversampling factor of the ``To``/``Ito*`` time-domain truth arrays.
OVERSAMPLE = 8
#: The ``/grid`` keys that describe the engine a file was produced with
#: (:attr:`pnps.bridge.Bridge.metadata` supplies exactly these).
ENGINE_KEYS = (
"backend",
"stepper",
"pnps_engine",
"solprop_tableau",
"frame_pinned",
"gamma_k_applied",
"evanescent_clamp",
"index_model",
"measure",
"reduction",
)
__all__ = [
"ENGINE_KEYS",
"OVERSAMPLE",
"SimulatedScan",
"beamlet_truth",
"create_scan_file",
"delivered_energy",
"engine_metadata",
"load_simulated_scan",
"merge_shards",
"oversampled_time_axis",
"point_done",
"scan_grid_metadata",
"temporal_truth",
"trace_names",
"write_point",
]
[docs]
def trace_names(n_windows: int) -> list[str]:
"""Dataset names for the per-window traces.
The first window has no suffix; later ones get ``_2``, ``_3``, ...
Parameters
----------
n_windows : int
Number of collection windows, >= 1.
Returns
-------
list of str
``2 * n_windows`` names: for each window, the k-integrated trace
followed by its reimaged partner.
"""
names = []
for j in range(n_windows):
suffix = "" if j == 0 else f"_{j + 1}"
names.append(f"Iω_win{suffix}")
names.append(f"Iω_win{suffix}_reimaged")
return names
[docs]
def beamlet_truth(
i_beamlet: Float[np.ndarray, " n_omega"], e_in: Complex[np.ndarray, " n_omega"]
) -> tuple[Float[np.ndarray, " n_omega"], Complex[np.ndarray, " n_omega"]]:
"""Complex beamlet spectrum: vignetted amplitude carrying the input phase.
The input-mask hole is a real amplitude filter and the illumination
profile is real, so a beamlet's spectrum is the input spectrum times a
real non-negative chromatic vignetting factor: its spectral phase is
*exactly* the input phase, and only the amplitude changes. The amplitude
is recovered from the recorded beamlet power spectrum.
Where the input spectrum is below ``1e-12`` of its peak the phase is not
meaningfully defined, and both returned arrays are zeroed there — so
``|e_beamlet|**2`` equals the returned power spectrum everywhere, which
the raw ``i_beamlet`` would not (it is a k-space sum and stays non-zero
in bins where the input has effectively vanished).
Parameters
----------
i_beamlet : numpy.ndarray
Beamlet power spectrum on the frequency grid, shape ``(nt,)``.
e_in : numpy.ndarray
Complex input pulse spectrum on the same grid.
Returns
-------
tuple of numpy.ndarray
``(i_beamlet_defined, e_beamlet)``, satisfying
``abs(e_beamlet)**2 == i_beamlet_defined``.
"""
i_in = np.abs(e_in) ** 2
defined = i_in > i_in.max() * 1e-12
phase = np.where(defined, e_in / np.sqrt(np.where(defined, i_in, 1.0)), 0.0)
i_defined = np.where(defined, np.maximum(i_beamlet, 0.0), 0.0)
return i_defined, np.sqrt(i_defined) * phase
[docs]
def delivered_energy(setup: Setup) -> float:
"""Three-arm post-hole pulse energy of a built setup, in J.
``Config.energy`` is the *pre-mask* energy of all three arms together;
what the slab actually receives is whatever the input holes pass. That
fraction is **not** grid-invariant: the pre-mask normalisation divides by
the illumination's energy over the whole momentum grid, and the HE11 far
field's tails are not fully contained, so a finer grid captures more of
them and delivers slightly less through the holes. The delivered energy
is therefore recorded per file rather than quoted as a constant of the
instrument (a stored constant is only meaningful at the sample count it
was measured on).
Parameters
----------
setup : Setup
The configuration; the energy is computed once, when it is built
(:func:`pnps.form_input.beamlet_diagnostics`).
Returns
-------
float
Energy of the gate pair plus the test arm in J.
"""
return float(setup.beamlets.delivered_energy)
[docs]
def oversampled_time_axis(
t: Float[np.ndarray, " n_t"], oversample: int = OVERSAMPLE
) -> Float[np.ndarray, " n_t_fine"]:
"""Refine ``t`` by ``oversample`` into the ``To`` axis, same span and centring.
Parameters
----------
t : numpy.ndarray
Centred native time axis, shape ``(nt,)``, in s.
oversample : int
Refinement factor.
Returns
-------
numpy.ndarray
Shape ``(oversample * nt,)``, in s.
"""
n = len(t) * oversample
return (np.arange(n) - n / 2) * (t[1] - t[0]) / oversample
[docs]
def temporal_truth(
e_omega: Inexact[np.ndarray, " n_omega"], oversample: int = OVERSAMPLE
) -> tuple[Float[np.ndarray, " n_t"], Float[np.ndarray, " n_t_fine"]]:
"""Temporal intensity of a spectrum, natively and oversampled.
``It`` is ``|ifft(E)|^2`` on the native time axis. ``Ito`` is the same
envelope evaluated on the ``oversample``-times finer axis, by zero-padding
the spectrum in the middle (the exact band-limited interpolation, since
the envelope is band-limited by construction) and rescaling by
``oversample^2`` so that the two share one intensity scale.
Parameters
----------
e_omega : numpy.ndarray
Complex spectrum on the FFT-ordered frequency axis, shape ``(nt,)``.
oversample : int
Refinement factor for the second output.
Returns
-------
tuple of numpy.ndarray
``(It, Ito)`` with shapes ``(nt,)`` and ``(oversample * nt,)``.
Examples
--------
Both arrays describe one envelope, so their peaks agree:
>>> import numpy as np
>>> spectrum = np.fft.fft(np.exp(-((np.arange(64) - 32.0) ** 2) / 8))
>>> it, ito = temporal_truth(spectrum)
>>> bool(abs(it.max() / ito.max() - 1) < 1e-12)
True
"""
n = len(e_omega)
m = oversample * n
padded = np.zeros(m, dtype=complex)
padded[: n // 2] = e_omega[: n // 2]
padded[m - n // 2 :] = e_omega[n // 2 :]
return (
np.abs(np.fft.ifft(e_omega)) ** 2,
oversample**2 * np.abs(np.fft.ifft(padded)) ** 2,
)
def _input_pulse_metadata(
pulse: InputPulse, tgrid: TimeGrid, e_in: Complex[np.ndarray, " n_omega"]
) -> dict[str, Any]:
"""``/grid`` provenance for an injected input field.
``input_band`` is the source file's own support; ``input_band_nm`` is the
wavelength range the simulation grid ends up carrying, which is narrower
whenever the source extends beyond the simulation window (the input
band-limit of :func:`pnps.setup.build_setup` rolls that content off).
``input_energy_fraction`` is what survived both the resampling and that
band-limit, ``sum |E|^2 domega`` on the simulation grid over the same on
the source grid: a number below one is the price of the finite window,
not a resampling error.
Parameters
----------
pulse : InputPulse
The prepared source pulse.
tgrid : TimeGrid
The simulation's temporal grid.
e_in : numpy.ndarray
The injected complex spectrum on ``tgrid.omega``, shape
``(tgrid.nt,)``.
Returns
-------
dict
The ``input_*`` provenance entries for the ``/grid`` group.
"""
omega_lo, omega_hi = pulse.support
carried = np.abs(e_in) > 0
lam = 2 * np.pi * c / tgrid.omega[carried & (tgrid.omega > 0)]
delta_omega = 2 * np.pi / (tgrid.nt * tgrid.delta_t)
return {
"input_source": pulse.source,
"input_source_md5": pulse.md5,
"input_history": "; ".join(pulse.history),
"input_tshift": pulse.tshift,
"input_norm": pulse.norm,
"input_resampling": "exact-dft",
"input_band": np.array([omega_lo, omega_hi]),
"input_band_nm": np.array([lam.min() * 1e9, lam.max() * 1e9]),
"input_energy_fraction": (
float(np.sum(np.abs(e_in) ** 2) * delta_omega) / pulse.energy
),
}
[docs]
def create_scan_file(
path: str | Path,
taus: Float[np.ndarray, " n_delays"],
n_z: int,
n_omega: int,
n_windows: int,
grid_meta: dict,
) -> None:
"""Create the collected file with zero-filled full-size datasets.
Idempotent: an existing file is left untouched (resume relies on this).
Parameters
----------
path : str or pathlib.Path
Target file path.
taus : numpy.ndarray
The full delay axis in s.
n_z, n_omega, n_windows : int
Dataset dimensions.
grid_meta : dict
The ``/grid`` metadata from :func:`scan_grid_metadata`.
"""
path = Path(path)
if path.exists():
return
with h5py.File(path, "w") as f:
f["scanorder"] = ["τ"]
f["scanvariables/τ"] = np.asarray(taus, dtype=float)
shape = (len(taus), n_z, n_omega)
chunks = (1, n_z, n_omega)
for name in [*trace_names(n_windows), "Iω_full", "Iω_beam"]:
f.create_dataset(name, shape=shape, dtype="f8", chunks=chunks)
f.create_dataset(
"Iω_lap_lost",
shape=(len(taus), n_omega),
dtype="f8",
chunks=(1, n_omega),
)
grid = f.create_group("grid")
for key, val in grid_meta.items():
grid[key] = val
[docs]
def point_done(path: str | Path, index: int) -> bool:
"""Whether delay point ``index`` already holds data (resume marker).
Parameters
----------
path : str or pathlib.Path
The collected or shard file (must exist).
index : int
Position on the delay axis.
Returns
-------
bool
True if the point's ``Iω_win`` slice is not all zero.
"""
with h5py.File(path, "r") as f:
return bool(np.any(f["Iω_win"][index])) # type: ignore[index]
[docs]
def write_point(
path: str | Path, index: int, result: dict[str, Float[np.ndarray, "*_"]]
) -> None:
"""Write one delay point's results into the collected file.
Parameters
----------
path : str or pathlib.Path
The collected file (must exist).
index : int
Position on the delay axis.
result : dict
Output of :func:`pnps.simulate.simulate_delay_point` for one delay:
``i_omega_win``/``i_omega_reimaged`` of shape ``(nz, n_windows,
nt)``, ``i_omega_full`` and ``i_omega_beam`` of shape ``(nz, nt)``, and
``lap_lost`` of shape ``(nt,)``.
"""
n_windows = result["i_omega_win"].shape[1]
with h5py.File(path, "r+") as f:
for j in range(n_windows):
suffix = "" if j == 0 else f"_{j + 1}"
f[f"Iω_win{suffix}"][index] = result["i_omega_win"][:, j, :] # type: ignore[index]
f[f"Iω_win{suffix}_reimaged"][index] = result["i_omega_reimaged"][:, j, :] # type: ignore[index]
f["Iω_full"][index] = result["i_omega_full"] # type: ignore[index]
f["Iω_beam"][index] = result["i_omega_beam"] # type: ignore[index]
f["Iω_lap_lost"][index] = result["lap_lost"] # type: ignore[index]
f.flush()
[docs]
def merge_shards(target: str | Path, shard_paths: Sequence[str | Path]) -> int:
"""Copy every computed delay slice from shard files into ``target``.
All files must share the layout (created from the same configuration).
Returns the number of slices copied. Slices that are all-zero in a shard
(not computed there) are skipped; a slice already present in the target
is overwritten only by a computed shard slice.
Parameters
----------
target : str or pathlib.Path
The collected file to merge into (must exist).
shard_paths : sequence of str or pathlib.Path
The shard files to copy from.
Returns
-------
int
The number of delay slices copied, summed over shards.
"""
copied = 0
with h5py.File(target, "r+") as out:
# h5py.Group is not a dict: iterating it directly is typed as
# yielding str | None, while .keys() yields proper names.
names = [n for n in out.keys() if n.startswith("Iω")] # noqa: SIM118 — see above
for shard in shard_paths:
with h5py.File(shard, "r") as f:
marker = np.asarray(f["Iω_win"])
for i in range(marker.shape[0]):
if not np.any(marker[i]):
continue
for name in names:
out[name][i] = f[name][i] # type: ignore[index]
copied += 1
return copied
[docs]
@dataclass(frozen=True)
class SimulatedScan:
"""A scan file read back: the trace, its axes and the truths recorded with it.
Attributes
----------
omega : numpy.ndarray
Absolute angular frequency in rad/s, ascending, shape ``(n_omega,)``.
omega0 : float
Carrier angular frequency in rad/s.
t : numpy.ndarray
Centred time axis in s, shape ``(n_t,)``.
tau : numpy.ndarray
The delay axis in s, shape ``(n_delays,)``.
trace : numpy.ndarray
The trace in frequency order: ``(n_delays, n_omega)`` for one plane, or
``(n_delays, n_z, n_omega)`` for every plane.
zsave : numpy.ndarray
The save positions in m, shape ``(n_z,)``.
z_index : int or None
The plane the trace is taken at, or None for every plane.
window_key : str
The dataset the trace was read from (``"Iω_win"``, ``"Iω_full"``, ...).
i_omega : numpy.ndarray
The input spectrum, in frequency order.
i_t : numpy.ndarray
The input temporal intensity on ``t``.
tau_fwhm : float
The input pulse's intensity FWHM in s.
i_omega_beamlet : numpy.ndarray
The vignetted beamlet spectrum (the gate's), in frequency order.
i_t_beamlet : numpy.ndarray
The beamlet temporal intensity on ``t``.
to : numpy.ndarray
The oversampled time axis in s.
i_to : numpy.ndarray
The oversampled input intensity on ``to``.
i_to_beamlet : numpy.ndarray
The oversampled beamlet intensity on ``to``.
lap_lost : numpy.ndarray or None
The energy per bin the lap budget removed at each delay, in frequency order,
``(n_delays, n_omega)``, in the trace's units
(:func:`pnps.simulate.run_delay_point`); None in a file written without it.
With the last plane of ``"Iω_beam"`` it gives a band's share
(:func:`pnps.absorber.lap_loss_share`).
metadata : dict
Every scalar and string of ``/grid``, by key.
"""
omega: Float[np.ndarray, " n_omega"]
omega0: float
t: Float[np.ndarray, " n_t"]
tau: Float[np.ndarray, " n_delays"]
trace: Float[np.ndarray, "n_delays *planes n_omega"]
zsave: Float[np.ndarray, " n_z"]
z_index: int | None
window_key: str
i_omega: Float[np.ndarray, " n_omega"]
i_t: Float[np.ndarray, " n_t"]
tau_fwhm: float
i_omega_beamlet: Float[np.ndarray, " n_omega"]
i_t_beamlet: Float[np.ndarray, " n_t"]
to: Float[np.ndarray, " n_t_fine"]
i_to: Float[np.ndarray, " n_t_fine"]
i_to_beamlet: Float[np.ndarray, " n_t_fine"]
lap_lost: Float[np.ndarray, "n_delays n_omega"] | None
metadata: dict[str, Any]
[docs]
def load_simulated_scan(
path: str | Path,
window_key: str = "Iω_win",
*,
z_index: int | Literal["all"] = -1,
z_thickness: float | None = None,
) -> SimulatedScan:
"""Read a scan file back, with the frequency axis in ascending order.
Parameters
----------
path : str or pathlib.Path
The ``<scan_name>_collected.h5`` file.
window_key : str, optional
The trace dataset: ``"Iω_win"`` (the default, the first window),
``"Iω_win_reimaged"``, ``"Iω_win_2"``, ..., ``"Iω_full"``, the whole signal
region (``Iω_win / Iω_full`` is the collection efficiency), or ``"Iω_beam"``,
the whole beam.
z_index : int or "all", optional
The save plane, by index (negative counts from the last, the default), or
``"all"`` for every plane.
z_thickness : float or None, optional
Select the plane nearest this slab thickness in m instead; it takes
precedence over `z_index`.
Returns
-------
SimulatedScan
The trace, its axes and the recorded truths.
Raises
------
ScanError
If the file has no ``/grid`` or delay axis, no such trace, or the plane is
out of range.
"""
with h5py.File(path, "r") as f:
if "grid" not in f or "scanvariables/τ" not in f:
raise ScanError(f"{path} is not a scan file: no /grid or /scanvariables/τ")
if window_key not in f:
names = [str(k) for k in f.keys()] # noqa: SIM118 - h5py's typed keys
available = sorted(k for k in names if k.startswith("Iω"))
raise ScanError(f"{path} has no trace {window_key!r}; it has {available}")
grid = f["grid"]
assert isinstance(grid, h5py.Group)
def read(key: str) -> np.ndarray:
return np.asarray(grid[key])
data = np.asarray(f[window_key]) # (n_delays, n_z, n_omega)
if data.ndim != 3:
raise ScanError(
f"{window_key!r} is not a trace over the save planes; "
"a per-point record is read as an attribute (lap_lost)"
)
tau = np.asarray(f["scanvariables/τ"], dtype=float)
metadata: dict[str, Any] = {}
for key in [str(k) for k in grid.keys()]: # noqa: SIM118 - h5py's typed keys
value = np.asarray(grid[key])
if value.ndim == 0:
item = value.item()
metadata[key] = item.decode() if isinstance(item, bytes) else item
zsave = read("zsave").astype(float)
order = np.argsort(read("ω"))
if z_thickness is not None:
plane: int | None = int(np.argmin(np.abs(zsave - z_thickness)))
elif z_index == "all":
plane = None
else:
if not -len(zsave) <= z_index < len(zsave):
raise ScanError(
f"z_index {z_index} out of range for {len(zsave)} planes"
)
plane = int(z_index) % len(zsave)
trace = data[..., order] if plane is None else data[:, plane, order]
return SimulatedScan(
omega=read("ω")[order].astype(float),
omega0=float(read("ω0")),
t=read("t").astype(float),
tau=tau,
trace=trace.astype(float),
zsave=zsave,
z_index=plane,
window_key=window_key,
i_omega=read("Iω")[order].astype(float),
i_t=read("It").astype(float),
tau_fwhm=float(read("τfwhm")),
i_omega_beamlet=read("Iω_beamlet")[order].astype(float),
i_t_beamlet=read("It_beamlet").astype(float),
to=read("To").astype(float),
i_to=read("Ito").astype(float),
i_to_beamlet=read("Ito_beamlet").astype(float),
lap_lost=(
np.asarray(f["Iω_lap_lost"])[:, order].astype(float)
if "Iω_lap_lost" in f
else None
),
metadata=metadata,
)