# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run files: a configuration and its scan, in TOML, for the command line and records.
A run file holds two tables:
- ``[config]``: the fields of :class:`pnps.setup.Config`, with the beam as a table
carrying its ``type`` (``"HE11Beam"``, ``"GaussianBeam"`` or ``"UniformBeam"``),
the collection windows as an array of tables (:class:`pnps.extraction.WindowSpec`
fields), and an optional injected input pulse as a recipe (``[config.input_pulse]``:
the source file, its keys, and the spectral window, centring and normalisation to
apply, as :mod:`pnps.input_pulse` does them);
- ``[scan]``: the delay axis ``taus`` and the save positions ``zsave`` (lists in s and
m, or ``{start, stop, num}`` tables for evenly spaced ones), the step ``h_target``,
the scan ``name``, the output directory ``out_dir`` and the solprop ``backend``.
Paths in a run file are relative to the file's own directory. Fields left out take
their defaults. :func:`dump_run` writes a run file :func:`load_run` reads back exactly.
Notes
-----
A small run file:
.. code-block:: toml
[config]
lam0 = 260e-9
tau_fwhm = 1e-15
energy = 1e-7
thickness = 40e-6
mask_diam = 1e-3
mask_spacing = 1e-3
lam_lims = [143e-9, 600e-9]
trange = 250e-15
r_max = 366e-6
n_transverse = 768
[config.beam]
type = "HE11Beam"
a = 125e-6
f_coll = 5.0
f_foc = 0.1
[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 1e-3
zmask = 0.1
[scan]
name = "window_series"
taus = {start = -40e-15, stop = 40e-15, num = 161}
zsave = {start = 0.0, stop = 40e-6, num = 17}
h_target = 0.5e-6
"""
import math
import tomllib
from collections.abc import Mapping
from dataclasses import MISSING, dataclass, fields, replace
from pathlib import Path
from typing import Any
import numpy as np
from jaxtyping import Float
from pnps.beams import Beam, GaussianBeam, HE11Beam, UniformBeam
from pnps.exceptions import ConfigError
from pnps.extraction import WindowSpec
from pnps.input_pulse import (
InputPulse,
centre_pulse,
load_input_pulse,
normalise_peak,
spectral_window,
)
from pnps.setup import Config
__all__ = ["PulseRecipe", "RunFile", "ScanSpec", "dump_run", "load_run"]
_BEAMS: dict[str, type[HE11Beam] | type[GaussianBeam] | type[UniformBeam]] = {
"HE11Beam": HE11Beam,
"GaussianBeam": GaussianBeam,
"UniformBeam": UniformBeam,
}
[docs]
@dataclass(frozen=True)
class PulseRecipe:
"""How to build an injected input pulse from its source file.
Attributes
----------
file : str
The source file, relative to the run file's directory or absolute.
omega_key, e_omega_key : str
Its frequency and complex-spectrum datasets.
window : tuple of float or None
``(lam_min, lam_max)`` in m for :func:`pnps.input_pulse.spectral_window`, or
None for no window.
wfrac_blue, wfrac_red : float
The window's edge fractions.
centre : bool
Centre the pulse in time (:func:`pnps.input_pulse.centre_pulse`).
normalise : bool
Normalise its peak (:func:`pnps.input_pulse.normalise_peak`).
"""
file: str
omega_key: str = "ω"
e_omega_key: str = "Eω"
window: tuple[float, float] | None = None
wfrac_blue: float = 0.05
wfrac_red: float = 0.03
centre: bool = True
normalise: bool = True
[docs]
def build(self, base: Path) -> InputPulse:
"""Load the source and apply the recipe's steps, in order.
Parameters
----------
base : pathlib.Path
The directory a relative ``file`` is taken from.
Returns
-------
InputPulse
The prepared pulse.
"""
pulse = load_input_pulse(base / self.file, self.omega_key, self.e_omega_key)
if self.window is not None:
pulse = spectral_window(
pulse,
*self.window,
wfrac_blue=self.wfrac_blue,
wfrac_red=self.wfrac_red,
)
if self.centre:
pulse, _ = centre_pulse(pulse)
return normalise_peak(pulse) if self.normalise else pulse
[docs]
@dataclass(frozen=True)
class ScanSpec:
"""The scan a run file asks for.
Attributes
----------
name : str
The scan name; files are ``<out_dir>/<name>_collected[.shard<i>].h5``.
taus : numpy.ndarray
The delay axis in s.
zsave : numpy.ndarray
The save positions in m.
h_target : float
The largest step of the replayed schedule, m.
out_dir : str
The output directory, relative to the run file's directory or absolute.
backend : str
The solprop backend registry name.
"""
name: str
taus: Float[np.ndarray, " n_delays"]
zsave: Float[np.ndarray, " n_z"]
h_target: float
out_dir: str = "."
backend: str = "auto"
[docs]
@dataclass(frozen=True)
class RunFile:
"""A configuration, its scan and the recipe of its input pulse.
Attributes
----------
config : Config
The configuration, with its input pulse built when there is a recipe.
scan : ScanSpec
The scan.
input_pulse : PulseRecipe or None
How the input pulse was built, or None for the synthetic Gaussian.
base : pathlib.Path
The directory relative paths are taken from.
"""
config: Config
scan: ScanSpec
input_pulse: PulseRecipe | None = None
base: Path = Path()
[docs]
@property
def out_dir(self) -> Path:
"""Return the output directory, resolved against :attr:`base`.
Returns
-------
pathlib.Path
Where the scan files go.
"""
return self.base / self.scan.out_dir
def _axis(value: object, name: str) -> Float[np.ndarray, " n"]:
"""Read an axis: a list of values, or a ``{start, stop, num}`` table.
Parameters
----------
value : object
The TOML value.
name : str
The key, for the error message.
Returns
-------
numpy.ndarray
The axis, float.
Raises
------
ConfigError
If the value is neither form.
"""
if isinstance(value, list):
return np.asarray(value, dtype=float)
if isinstance(value, dict) and set(value) == {"start", "stop", "num"}:
return np.linspace(
float(value["start"]), float(value["stop"]), int(value["num"])
)
raise ConfigError(f"[scan] {name} must be a list or a {{start, stop, num}} table")
def _construct(cls: type, table: Mapping[str, Any], where: str) -> Any:
"""Construct a dataclass from a table, naming any unknown or missing key.
Parameters
----------
cls : type
The dataclass.
table : Mapping
Its fields' values.
where : str
The table's name, for the error message.
Returns
-------
object
The instance.
Raises
------
ConfigError
For a key the dataclass has no field for, or a required field left out.
"""
names = {f.name for f in fields(cls)}
unknown = sorted(set(table) - names)
if unknown:
raise ConfigError(f"{where} has unknown keys {unknown}")
required = sorted(
f.name
for f in fields(cls)
if f.default is MISSING and f.default_factory is MISSING and f.name not in table
)
if required:
raise ConfigError(f"{where} is missing {required}")
return cls(**table)
def _beam(table: Mapping[str, Any]) -> Beam:
"""Read the beam table.
Parameters
----------
table : Mapping
``type`` and the beam's fields.
Returns
-------
HE11Beam, GaussianBeam or UniformBeam
The beam.
Raises
------
ConfigError
For an unknown beam type.
"""
kind = table.get("type")
if kind not in _BEAMS:
raise ConfigError(f"[config.beam] type must be one of {sorted(_BEAMS)}")
rest = {k: v for k, v in table.items() if k != "type"}
return _construct(_BEAMS[kind], rest, "[config.beam]")
def _tuples(table: Mapping[str, Any]) -> dict[str, Any]:
"""Return a table with its lists as tuples, as the frozen dataclasses hold them.
Parameters
----------
table : Mapping
A TOML table.
Returns
-------
dict
The same, lists made tuples.
"""
return {k: tuple(v) if isinstance(v, list) else v for k, v in table.items()}
[docs]
def load_run(path: str | Path) -> RunFile:
"""Read a run file.
Parameters
----------
path : str or pathlib.Path
The TOML file.
Returns
-------
RunFile
The configuration (with its input pulse built), the scan and the recipe.
Raises
------
ConfigError
If a table is missing, or holds an unknown key, a missing required field or
an unreadable axis.
"""
path = Path(path)
with path.open("rb") as stream:
data = tomllib.load(stream)
for table in ("config", "scan"):
if table not in data:
raise ConfigError(f"{path} has no [{table}] table")
config = dict(data["config"])
recipe_table = config.pop("input_pulse", None)
recipe = (
None
if recipe_table is None
else _construct(PulseRecipe, _tuples(recipe_table), "[config.input_pulse]")
)
if "beam" not in config:
raise ConfigError("[config] is missing ['beam']")
config["beam"] = _beam(config["beam"])
config["windows"] = tuple(
_construct(WindowSpec, w, "[[config.windows]]")
for w in config.get("windows", [])
)
cfg = _construct(Config, _tuples(config), "[config]")
scan_table = dict(data["scan"])
for axis in ("taus", "zsave"):
if axis in scan_table:
scan_table[axis] = _axis(scan_table[axis], axis)
scan = _construct(ScanSpec, scan_table, "[scan]")
base = path.parent
if recipe is not None:
cfg = replace(cfg, input_pulse=recipe.build(base))
return RunFile(config=cfg, scan=scan, input_pulse=recipe, base=base)
def _toml_float(number: float) -> str:
"""Return a float as TOML, exactly.
Parameters
----------
number : float
The value.
Returns
-------
str
``repr`` for a finite value, TOML's ``nan``, ``inf`` or ``-inf`` otherwise.
"""
if math.isnan(number):
return "nan"
if math.isinf(number):
return "inf" if number > 0 else "-inf"
return repr(number)
def _toml_value(value: object) -> str:
"""Return one value as TOML.
Parameters
----------
value : object
A bool, int, float, str, or a sequence of those.
Returns
-------
str
Its TOML text; floats are written exactly (``repr``).
Raises
------
ConfigError
For a value TOML cannot hold.
"""
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, int | np.integer):
return str(int(value))
if isinstance(value, float | np.floating):
return _toml_float(float(value))
if isinstance(value, str):
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped}"'
if isinstance(value, tuple | list | np.ndarray):
return "[" + ", ".join(_toml_value(v) for v in value) + "]"
raise ConfigError(f"{type(value).__name__} cannot be written to a run file")
def _table(name: str, values: Mapping[str, object], *, array: bool = False) -> str:
"""Return a TOML table (or array-of-tables element), None values left out.
Parameters
----------
name : str
The table's dotted name.
values : Mapping
Its keys and values.
array : bool, optional
Write it as an element of an array of tables.
Returns
-------
str
The table's text.
"""
header = f"[[{name}]]" if array else f"[{name}]"
lines = [header]
lines += [f"{k} = {_toml_value(v)}" for k, v in values.items() if v is not None]
return "\n".join(lines) + "\n"
[docs]
def dump_run(run: RunFile, path: str | Path) -> None:
"""Write a run file that :func:`load_run` reads back exactly.
Parameters
----------
run : RunFile
The run; its configuration's input pulse must come from its recipe.
path : str or pathlib.Path
The TOML file to write.
Raises
------
ConfigError
If the configuration carries an input pulse without a recipe (its arrays
have no place in a run file).
"""
cfg = run.config
if cfg.input_pulse is not None and run.input_pulse is None:
raise ConfigError(
"the configuration's input pulse has no recipe; give the run a "
"PulseRecipe naming its source file"
)
plain = {
f.name: getattr(cfg, f.name)
for f in fields(cfg)
if f.name not in ("beam", "windows", "input_pulse")
}
beam = {"type": type(cfg.beam).__name__} | {
f.name: getattr(cfg.beam, f.name) for f in fields(cfg.beam)
}
parts = [_table("config", plain), _table("config.beam", beam)]
parts += [
_table(
"config.windows",
{f.name: getattr(w, f.name) for f in fields(w)},
array=True,
)
for w in cfg.windows
]
if run.input_pulse is not None:
recipe = run.input_pulse
parts.append(
_table(
"config.input_pulse",
{f.name: getattr(recipe, f.name) for f in fields(recipe)},
)
)
scan = run.scan
parts.append(_table("scan", {f.name: getattr(scan, f.name) for f in fields(scan)}))
Path(path).write_text("\n".join(parts), encoding="utf-8")