# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Delay-scan driver: a plain loop with per-point writes and resume.
The simplest thing that scales: one process scans (a shard of) the delay axis and writes
each point into its own HDF5 file immediately after computing it. Interrupted scans
resume by skipping already-written points. One bridge to solprop
(:func:`pnps.bridge.build_bridge`) is built per process and reused for every delay
point, so the problem is translated and the backend allocated once. For several nodes,
run one process per shard (``shard=(i, n)`` computes delay indices ``i::n``) and merge
with :func:`pnps.io_h5.merge_shards`. :func:`run_separation_scan` is the same loop for
the transient-grating separation (:mod:`pnps.separation`).
"""
import logging
import time
from collections.abc import Sequence
from pathlib import Path
import h5py
import numpy as np
from jaxtyping import Float, Int
from pnps.bridge import build_bridge
from pnps.exceptions import ConfigError, ScanError
from pnps.io_h5 import create_scan_file, point_done, scan_grid_metadata, write_point
from pnps.pulse import energy_prefactor
from pnps.separation import FIELD_PART, PARTS, Separation, part_trace_names
from pnps.setup import Config, Setup, build_setup
from pnps.simulate import (
_check_delay, # pyright: ignore[reportPrivateUsage] - the one delay guard
run_delay_point,
)
__all__ = ["run_scan", "run_separation_scan"]
logger = logging.getLogger(__name__)
[docs]
def run_scan( # noqa: PLR0913, PLR0917 - the scan, its file and the engine overrides
cfg: Config,
taus: Float[np.ndarray, " n_delays"],
scan_name: str,
zsave: Float[np.ndarray, " n_z"],
h_target: float,
out_dir: str | Path = ".",
shard: tuple[int, int] | None = None,
indices: Sequence[int] | None = None,
skip_existing: bool = True,
backend: str = "auto",
) -> Path:
"""Run a delay scan and write ``<scan_name>_collected.h5``.
Parameters
----------
cfg : Config
The simulation configuration.
taus : numpy.ndarray
The full delay axis in s (identical across shards).
scan_name : str
Base name of the output file.
zsave : numpy.ndarray
Save positions in m, see
:func:`pnps.simulate.simulate_delay_point`.
h_target : float
Largest step of the replayed schedule in m — calibrate with
:mod:`pnps.calibrate` before a production scan.
out_dir : str or pathlib.Path
Directory for the output file.
shard : tuple of (int, int) or None
``(i, n)``: compute only delay indices ``i::n`` and write to
``<scan_name>_collected.shard<i>.h5``. None computes everything
into the collected file directly.
indices : sequence of int or None
Compute only these delay indices, leaving the rest of the file
zero. The delay axis is still written in full, so the result is a
partial scan on the production sampling rather than a different
scan — which is what a validation subset has to be if it is to be
compared against a reference cell for cell. Cannot be combined
with ``shard``.
skip_existing : bool
Skip delay points whose slice in the target file is already
non-zero (resume after interruption).
backend : str
The solprop backend registry name (``"auto"``, which is
``"native"``; ``"native"``; ``"numpy_ref"``). The backends agree to a stated
floating-point bound rather than bit-for-bit, so a scan should not mix
them; the recorded metadata names the one used.
Returns
-------
pathlib.Path
The file written by this process.
"""
taus = np.asarray(taus, dtype=float)
zsave = np.asarray(zsave, dtype=float)
path, chosen = _target(len(taus), scan_name, Path(out_dir), shard, indices)
if path.exists() and _field_part(path):
raise ScanError(
f"{path} holds a separated field part ({_field_part(path)}), not a scan"
)
setup = build_setup(cfg)
_check_delays(setup, taus, chosen)
with build_bridge(setup, zsave, h_target, backend=backend) as bridge:
create_scan_file(
path,
taus,
len(zsave),
setup.tgrid.nt,
len(setup.windows),
scan_grid_metadata(setup, zsave, h_target, bridge.metadata),
)
todo = [i for i in chosen if not (skip_existing and point_done(path, int(i)))]
logger.info(
"scan %s on %s: %d/%d points to compute -> %s",
scan_name,
bridge.metadata["backend"],
len(todo),
len(taus),
path,
)
for i in todo:
t0 = time.monotonic()
result = run_delay_point(bridge, float(taus[i]))
write_point(path, int(i), result)
logger.info(
"point %d (τ = %.2f fs) done in %.1f s; gd-band power %.2e",
int(i),
taus[i] * 1e15,
time.monotonic() - t0,
float(result["gd_band_power"].max()),
)
return path
[docs]
def run_separation_scan( # noqa: PLR0913, PLR0917 - run_scan's arguments
cfg: Config,
taus: Float[np.ndarray, " n_delays"],
scan_name: str,
zsave: Float[np.ndarray, " n_z"],
h_target: float,
out_dir: str | Path = ".",
shard: tuple[int, int] | None = None,
indices: Sequence[int] | None = None,
skip_existing: bool = True,
backend: str = "auto",
) -> Path:
"""Run a transient-grating separation over a delay axis.
Writes ``<scan_name>_collected.h5`` (or one shard of it) in the layout of
:func:`run_scan`, its ``Iω_*`` traces holding the transient-grating field alone
(:mod:`pnps.separation`) and ``/grid/field_part`` saying so. Beside them it
records the whole nonlinear field's and the remainder's window traces
(:func:`pnps.separation.part_trace_names`) and ``/grid/energy_prefactor``, which
turns a trace summed over frequency into joules. The bridge reduces on the host
whatever the configuration asks for; each process propagates the three
delay-free subsets once and four subsets per delay. A file that is not a
separation is never written into.
Parameters
----------
cfg : Config
The simulation configuration: the ``"tg"`` layout, with
``exact_windows``.
taus : numpy.ndarray
The full delay axis in s (identical across shards).
scan_name : str
Base name of the output file; give it a name of its own, apart from the
scan of the same configuration.
zsave : numpy.ndarray
Save positions in m, see :func:`pnps.simulate.simulate_delay_point`.
h_target : float
Largest step of the replayed schedule in m.
out_dir : str or pathlib.Path
Directory for the output file.
shard : tuple of (int, int) or None
``(i, n)``: compute only delay indices ``i::n``, as :func:`run_scan`.
indices : sequence of int or None
Compute only these delay indices, as :func:`run_scan`.
skip_existing : bool
Skip delay points already written (resume).
backend : str
The solprop backend registry name.
Returns
-------
pathlib.Path
The file written by this process.
Raises
------
ScanError
For a bad shard or indices, or a target file that is not a separation.
ConfigError
If the configuration has no exact windows or not the ``"tg"`` layout.
"""
if cfg.geometry != "tg" or not cfg.exact_windows:
raise ConfigError(
"the separation needs the three-arm 'tg' layout and Config.exact_windows"
)
taus = np.asarray(taus, dtype=float)
zsave = np.asarray(zsave, dtype=float)
path, chosen = _target(len(taus), scan_name, Path(out_dir), shard, indices)
if path.exists() and _field_part(path) != FIELD_PART:
raise ScanError(
f"{path} exists and is not a transient-grating separation: give the "
"separation a scan name of its own"
)
setup = build_setup(cfg)
_check_delays(setup, taus, chosen)
with build_bridge(
setup, zsave, h_target, backend=backend, reduction="host"
) as bridge:
separation = Separation(bridge)
n_windows = len(setup.windows)
meta = scan_grid_metadata(setup, zsave, h_target, bridge.metadata)
meta["field_part"] = FIELD_PART
meta["field_part_subsets"] = (
"N(123) - N(12) - N(13) - N(23) + N(1) + N(2) + N(3), on N before the "
"windows; 1, 2 = gates, 3 = test"
)
meta["energy_prefactor"] = energy_prefactor(setup.tgrid, setup.sgrid)
create_scan_file(path, taus, len(zsave), setup.tgrid.nt, n_windows, meta)
parts = [name for part in PARTS for name in part_trace_names(n_windows, part)]
with h5py.File(path, "r+") as f:
for name in parts:
if name not in f:
f.create_dataset(
name,
shape=(len(taus), len(zsave), setup.tgrid.nt),
dtype="f8",
chunks=(1, len(zsave), setup.tgrid.nt),
)
todo = [i for i in chosen if not (skip_existing and point_done(path, int(i)))]
logger.info(
"separation %s on %s: %d/%d points to compute -> %s",
scan_name,
bridge.metadata["backend"],
len(todo),
len(taus),
path,
)
for i in todo:
t0 = time.monotonic()
result = separation.point(float(taus[i]))
_write_parts(path, int(i), result)
# The transient grating last: its Iω_win marks the point done.
write_point(path, int(i), result)
logger.info(
"point %d (τ = %.2f fs) separated in %.1f s; last plane, energy per "
"window (J): transient grating %s, remainder %s",
int(i),
taus[i] * 1e15,
time.monotonic() - t0,
np.array2string(result["energy_win"][-1], precision=3),
np.array2string(result["energy_win_remainder"][-1], precision=3),
)
return path
def _target(
n_delays: int,
scan_name: str,
out_dir: Path,
shard: tuple[int, int] | None,
indices: Sequence[int] | None,
) -> tuple[Path, Int[np.ndarray, " n_chosen"]]:
"""Return the file a scan process writes and the delay indices it computes.
Raises
------
ScanError
For both ``shard`` and ``indices``, empty or out-of-range indices, or a shard
index outside ``[0, n)``.
"""
if shard is not None and indices is not None:
raise ScanError(
"give either shard or indices, not both: a shard is a stride "
"through the whole axis and indices are a chosen subset of it"
)
if shard is None:
path = out_dir / f"{scan_name}_collected.h5"
if indices is None:
return path, np.arange(n_delays)
chosen = np.asarray(indices, dtype=int)
if chosen.size == 0:
raise ScanError("indices is empty: nothing to compute")
if np.any((chosen < 0) | (chosen >= n_delays)):
raise ScanError(
f"indices out of range for a {n_delays}-delay axis: "
f"{sorted(set(chosen[(chosen < 0) | (chosen >= n_delays)]))}"
)
return path, chosen
i_shard, n_shard = shard
if not 0 <= i_shard < n_shard:
raise ScanError(f"shard index {i_shard} not in [0, {n_shard})")
path = out_dir / f"{scan_name}_collected.shard{i_shard}.h5"
return path, np.arange(i_shard, n_delays, n_shard)
def _field_part(path: Path) -> str:
"""Return a scan file's ``/grid/field_part``, empty for a whole-field scan."""
with h5py.File(path, "r") as f:
if "grid/field_part" not in f:
return ""
return str(f["grid/field_part"].asstr()[()]) # type: ignore[union-attr]
def _write_parts(
path: Path, index: int, result: dict[str, Float[np.ndarray, "*_"]]
) -> None:
"""Write one separated point's further parts (:data:`pnps.separation.PARTS`)."""
with h5py.File(path, "r+") as f:
for part in PARTS:
win = result[f"i_omega_win_{part}"]
axis = result[f"i_omega_reimaged_{part}"]
names = part_trace_names(win.shape[1], part)
for j in range(win.shape[1]):
f[names[2 * j]][index] = win[:, j] # type: ignore[index]
f[names[2 * j + 1]][index] = axis[:, j] # type: ignore[index]
def _check_delays(
setup: Setup,
taus: Float[np.ndarray, " n_delays"],
chosen: Int[np.ndarray, " n_chosen"],
) -> None:
"""Refuse a scan any of whose chosen delays the delay point would refuse.
The same guard as each point's (:func:`pnps.simulate.run_delay_point`), run before
the backend is built, so that a refused delay stops the scan before its first
point rather than at it.
Raises
------
ConfigError
If light that wraps the time window could act at one of the delays.
"""
for i in chosen:
_check_delay(setup, float(taus[i]))