Examples#

The scripts in the repository’s examples/ folder are complete runs of the instrument. They are shown here, not run when the manual is built: each propagates real beams through a slab, which takes minutes to hours. Run one from a checkout with uv run python examples/<name>.py; each prints what it does and accepts --help.

A collection-window series#

tgfrog_window_series.py scans a 1 fs, 260 nm pulse through the boxcar instrument, collecting the transient-grating signal through six aperture diameters at sixteen slab thicknesses, and writes one scan file (Simulating a trace).

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

"""TG-FROG collection-window series — CPU example.

A 1 fs transform-limited DUV pulse at 260 nm from a hollow capillary, split into
three boxcar beamlets and focused into up to 40 um of UV fused silica; the
transient-grating signal is collected through six aperture diameters at 16
substrate thicknesses, scanned over delay. One HDF5 scan file is written.

The masks are rendered as the manual recommends (docs/windows.md): the input holes
as exact hard apertures antialiased over each momentum pixel (``apod="area"``), and the
collection windows as raised-cosine quadrature weights two momentum bins wide, which
leave the signal corner exactly dark at the entrance.

By default this runs a reduced *smoke* configuration (coarse transverse
grid, few delays) that exercises every code path. Pass ``--full`` for the
production grid (768 x 768 x 600: about six field volumes, 32 GiB; print the budget
with ``pnps budget``). The step target below is a conservative choice; certify it for
production with ``examples/calibrate_production.py``. ``--backend`` picks the solprop
backend (``auto`` prefers ``native`` when installed).

Run with:

    uv run python examples/tgfrog_window_series.py [--full] [--backend B]
"""

import argparse
import logging

import numpy as np

from pnps import Config, HE11Beam, WindowSpec
from pnps.beams import rcos_edge_default
from pnps.grids import space_grid, time_grid
from pnps.scan import run_scan

HOLE_DIAMS = [0.5e-3, 0.75e-3, 1.0e-3, 1.5e-3, 2.0e-3, 2.5e-3]
MASK_DIAM = 1.0e-3
MASK_SPACING = 1.0e-3
D = MASK_SPACING / 2 + MASK_DIAM / 2  # boxcar hole-centre offset
F_FOC = 0.1
LAM0 = 260.0e-9
LAM_LIMS = (143.0e-9, 600.0e-9)
# 250 fs holds most of the walked-off DUV spectrum without lapping the periodic
# window: 143 nm light trails the pulse by about 216 fs over 40 um of silica, and the
# lap budget absorbs only what would wrap onto the pulse (143-160 nm at the ends of the
# delay scan; docs/model.md).
TRANGE = 250.0e-15
R_MAX = 366.0e-6

# Save planes, the slab thicknesses of the window series.
ZSAVE_UM = (0, 1, 2, 3, 4, 6, 8, 9.5, 12, 16, 20, 24, 28, 32, 36, 40)
ZSAVE = np.array(ZSAVE_UM, dtype=float) * 1e-6


def make_config(full: bool) -> Config:
    n = 768 if full else 192
    # Two momentum bins of the grid, which the radius and not the sample count sets.
    edge = rcos_edge_default(
        time_grid(LAM0, LAM_LIMS, TRANGE), space_grid(R_MAX, n), F_FOC
    )
    return Config(
        lam0=LAM0,
        tau_fwhm=1.0e-15,
        energy=0.1e-6,
        thickness=40.0e-6,
        mask_diam=MASK_DIAM,
        mask_spacing=MASK_SPACING,
        beam=HE11Beam(a=125.0e-6, f_coll=5.0, f_foc=F_FOC),
        windows=tuple(
            WindowSpec(
                holex=-D,
                holey=-D,
                holediam=hd,
                zmask=F_FOC,
                apod="rcos",
                apod_param=edge,
                weighting="quadrature",
            )
            for hd in HOLE_DIAMS
        ),
        lam_lims=LAM_LIMS,
        trange=TRANGE,
        r_max=R_MAX,
        n_transverse=n,
        apod="area",
        apod_param=4.0,
        # Delays up to 40 fs fit in 75 % of the protected half-width.
        time_headroom=55.0e-15,
    )


def main() -> None:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--full", action="store_true", help="production grid size")
    parser.add_argument(
        "--backend", default="auto", help="solprop backend registry name"
    )
    args = parser.parse_args()

    taus = (
        np.linspace(-24.0e-15, 24.0e-15, 16)
        if args.full
        else np.linspace(-18.0e-15, 18.0e-15, 5)
    )
    zsave = ZSAVE if args.full else ZSAVE[[0, 4, 10, 15]]
    name = "tgfrog_winseries_1fs_40umUVFS" + ("" if args.full else "_smoke")
    path = run_scan(
        make_config(args.full),
        taus,
        scan_name=name,
        zsave=zsave,
        h_target=0.5e-6,
        backend=args.backend,
    )
    print(f"scan written to {path}")


if __name__ == "__main__":
    main()

Certifying the step before a production scan#

calibrate_production.py runs the Richardson step calibration and the invariance battery on the production configuration of the window series (Accuracy: control, verification, and limits).

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

"""Certify the production configuration before a real scan.

Runs, on the production configuration of the window-series example:

1. the Richardson step calibration at tau = 0 (worst case: maximum beam
   overlap) and one large delay, over a halving sequence of step targets,
   with the observed convergence order (about 4 for the default low-storage
   RK4IP march, 5 for ``stepper="dopri5"``, once the steps are in the
   asymptotic regime);
2. the invariance battery: the trace observables must be insensitive to the
   absorber strength (gamma_max x0.5 / x2) and to enlarging the time window
   — if they are not, the absorbers or the window are shaping the physics
   and the configuration must not be trusted.

Intended for a large host (a few tens of propagation runs at production
size). Read the printed table, pick the largest h with D comfortably below
your accuracy target (e.g. D <= 5e-4 for 1e-3 trace fidelity), and use it as
the scan's ``h_target``. ``--backend`` picks the solprop backend.

Run with:

    uv run python examples/calibrate_production.py [--backend B]
"""

import argparse
import logging
from dataclasses import replace

import numpy as np
from tgfrog_window_series import ZSAVE, make_config

from pnps.calibrate import convergence_order, richardson_metric
from pnps.setup import build_setup
from pnps.simulate import simulate_delay_point

H_LIST = [2.0e-6, 1.0e-6, 0.5e-6]
TAU_LARGE = 20.0e-15


def observable_shift(res_a: dict, res_b: dict) -> float:
    """Worst peak-normalised change of any trace observable between two runs."""
    worst = 0.0
    for key in ("i_omega_win", "i_omega_reimaged", "i_omega_full"):
        a, b = res_a[key], res_b[key]
        peak = np.max(b, axis=-1, keepdims=True)
        worst = max(
            worst, float(np.max(np.abs(a - b) / np.where(peak > 0, peak, np.inf)))
        )
    return worst


def main() -> None:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--backend", default="auto", help="solprop backend")
    backend = parser.parse_args().backend
    config = make_config(full=True)
    setup = build_setup(config)

    print("== Richardson calibration, tau = 0 ==")
    metrics, orders = convergence_order(setup, 0.0, ZSAVE, H_LIST, backend=backend)
    for h, d in zip(H_LIST, metrics, strict=True):
        print(f"  h = {h * 1e6:5.2f} um : D(h) = {d:.3e}")
    print(f"  observed orders: {np.round(orders, 2)} (expect ~5)")

    print(f"== Spot check at tau = {TAU_LARGE * 1e15:.0f} fs ==")
    d_large = richardson_metric(setup, TAU_LARGE, ZSAVE, H_LIST[-1], backend=backend)
    print(f"  D({H_LIST[-1] * 1e6:.2f} um) = {d_large:.3e}")

    h_ref = H_LIST[-1]
    reference = simulate_delay_point(setup, 0.0, ZSAVE, h_target=h_ref, backend=backend)
    print("== Invariance battery (worst observable shift vs reference) ==")
    for label, cfg in [
        ("gamma_max x 0.5", replace(config, gamma_max=config.gamma_max / 2)),
        ("gamma_max x 2.0", replace(config, gamma_max=config.gamma_max * 2)),
        ("trange + 30%", replace(config, trange=config.trange * 1.3)),
    ]:
        varied = simulate_delay_point(
            build_setup(cfg), 0.0, ZSAVE, h_target=h_ref, backend=backend
        )
        if varied["i_omega_win"].shape == reference["i_omega_win"].shape:
            shift = observable_shift(varied, reference)
            print(f"  {label:15s}: {shift:.3e}")
        else:
            # A changed trange changes nt and therefore the bin spacing of
            # the unnormalised-FFT units: integrated spectra must be
            # compared as densities (sum x d_omega, i.e. sum / nt at equal
            # delta_t), or the nt ratio masquerades as a physics shift.
            a = varied["i_omega_win"].sum(axis=-1) / varied["i_omega_win"].shape[-1]
            b = (
                reference["i_omega_win"].sum(axis=-1)
                / reference["i_omega_win"].shape[-1]
            )
            print(f"  {label:15s}: {float(np.max(np.abs(a / b - 1))):.3e} (integrated)")


if __name__ == "__main__":
    main()

Injecting a pulse from a file#

injected_pulse.py writes a chirped, off-centre Gaussian to a source file, prepares it and runs a smoke scan with it (Input pulses).

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

"""Inject a pulse from a file into the window-series instrument.

Writes a chirped, off-centre Gaussian to a source file in the layout
``pnps.input_pulse`` reads (an ascending one-sided ``rfft`` axis of absolute angular
frequency, the spectrum stored as the DFT of a centred field array), prepares it as the
manual describes (docs/input-pulses.md) and runs a smoke scan with it. It prints the
centring shift, which undoes the source's offset (plus the small move of the intensity
peak its chirp causes), and the chirp of the input truth the scan file records, which
must be the source's.

Run with:

    uv run python examples/injected_pulse.py [--backend B]
"""

import argparse
import logging
from dataclasses import replace
from pathlib import Path

import h5py
import numpy as np
from scipy.constants import c
from tgfrog_window_series import make_config

from pnps.input_pulse import centre_pulse, load_input_pulse, normalise_peak
from pnps.pulse import fit_spectral_chirp, taylor_phase
from pnps.scan import run_scan

LAM0 = 260e-9
TAU_FWHM = 2e-15
GDD = 1.0e-30  # s^2
TOD = 0.5e-45  # s^3
OFFSET = 5e-15  # where the pulse peaks on the source's own time axis, s


def write_source(path: Path) -> None:
    """Write a chirped Gaussian at ``OFFSET`` in the source-file layout."""
    n_bins, window = 6145, 2.0e-12  # a 2 ps source window, up to about 98 nm
    omega = np.arange(n_bins) * (2 * np.pi / window)
    sigma_t = TAU_FWHM / (2 * np.sqrt(2 * np.log(2)))
    amplitude = np.exp(-((omega - 2 * np.pi * c / LAM0) ** 2) * sigma_t**2)
    phase = taylor_phase(omega, LAM0, gdd=GDD, tod=TOD) + omega * OFFSET
    # The stored spectrum is the DFT of the centred field array: the extra (-1)^j.
    ramp = (-1.0) ** np.arange(n_bins)
    with h5py.File(path, "w") as f:
        f["ω"] = omega
        f["Eω"] = amplitude * np.exp(-1j * phase) * ramp


def main() -> None:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--backend", default="auto", help="solprop backend")
    args = parser.parse_args()

    source = Path("injected_source.h5")
    write_source(source)
    pulse = load_input_pulse(source)
    pulse, shift = centre_pulse(pulse)
    pulse = normalise_peak(pulse)
    # The chirp moves the intensity peak a little off the offset itself.
    print(
        f"centring shift {shift * 1e15:+.4f} fs (source offset {OFFSET * 1e15:.1f} fs)"
    )

    cfg = replace(make_config(full=False), input_pulse=pulse)
    path = run_scan(
        cfg,
        np.linspace(-6e-15, 6e-15, 3),
        scan_name="injected_smoke",
        zsave=np.array([0.0, 20e-6, 40e-6]),
        h_target=0.5e-6,
        backend=args.backend,
    )
    with h5py.File(path, "r") as f:
        omega = np.asarray(f["grid/ω"])
        e_in = np.asarray(f["grid/Eω_re"]) + 1j * np.asarray(f["grid/Eω_im"])
    gdd, tod = fit_spectral_chirp(omega, e_in, LAM0)
    print(f"input truth: GDD {gdd * 1e30:.4f} fs^2 (source {GDD * 1e30:.4f}), "
          f"TOD {tod * 1e45:.4f} fs^3 (source {TOD * 1e45:.4f})")  # fmt: skip
    print(f"scan written to {path}")


if __name__ == "__main__":
    main()

The mask-edge study#

mask_study.py reproduces the numbers behind the choice of mask and window edges (Masks and collection windows, The physical and numerical model).

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

"""Evidence for the mask-edge choices: aperture, dark corner, spectral ripple.

Reproduces the numbers quoted in the *Mask discretisation and the collection
observables* section of ``docs/model.md``. Three questions are asked of each
candidate rendering of a collection window, on the production transverse
grid:

*aperture* — against a flat field the collected energy is just the enclosed
area, so its ratio to ``pi R^2`` is the effective aperture the observable
actually implements.

*dark corner* — how much of the z = 0 input (three arms, no signal generated
yet) the window collects. A physical hard hole collects exactly none: the
nearest arm edge lies 250 um outside even the largest window. Anything
collected is the rendering's own tails.

*ripple* — the collected value must be a smooth function of frequency, since
the chromatic mapping and the field both are. Any bin-scale structure is
quadrature error from a hole spanning few momentum bins. The probe is the
first-Born TG source ``e_g2 conj(e_g1) e_test``, so the momentum structure
in the signal corner is realistic rather than assumed.

Run (a few minutes on a laptop CPU):

    uv run python examples/mask_study.py
"""

import argparse

import numpy as np
from scipy.constants import c

from pnps.beams import chromatic_mask, quadrature_holediam
from pnps.extraction import WindowSpec
from pnps.grids import space_grid

# The production boxcar geometry: 1 mm holes on a 1 mm gap, 100 mm focusing.
F_FOC = 0.1
HOLE_DIAM = 1e-3
HOLE_OFFSET = 1e-3  # mask_spacing / 2 + mask_diam / 2
WINDOW_DIAMS = (0.5e-3, 1.0e-3, 2.5e-3)
GATE1 = (HOLE_OFFSET, HOLE_OFFSET)
GATE2 = (HOLE_OFFSET, -HOLE_OFFSET)
TEST = (-HOLE_OFFSET, HOLE_OFFSET)
SIGNAL_CORNER = (-HOLE_OFFSET, -HOLE_OFFSET)
# Supersampling for the pixel-area renderings; 6x6 is well converged.
AREA_SUBSAMPLES = 6.0


def corner_window(
    apod: str, apod_param: float, weighting: str = "amplitude"
) -> WindowSpec:
    """A signal-corner window with the given edge treatment.

    ``holediam`` is left at zero and filled in per window later; only the
    edge treatment varies between candidates.
    """
    return WindowSpec(
        holex=SIGNAL_CORNER[0],
        holey=SIGNAL_CORNER[1],
        holediam=0.0,
        zmask=F_FOC,
        apod=apod,
        apod_param=apod_param,
        weighting="quadrature" if weighting == "quadrature" else "amplitude",
    )


def candidates(pixel: float) -> list[WindowSpec]:
    """Window renderings to compare, with edge widths scaled to the pixel size."""
    return [
        corner_window("tanh", 3 * pixel),
        corner_window("tanh", 1 * pixel),
        *(
            corner_window("rcos", bins * pixel, "quadrature")
            for bins in (1.0, 2.0, 3.0)
        ),
        corner_window("area", AREA_SUBSAMPLES, "quadrature"),
        corner_window("hard", 0.0, "quadrature"),
    ]


def label(spec: WindowSpec, pixel: float) -> str:
    """Human-readable name: the weighting, the profile, and its width."""
    kind = "w" if spec.weighting == "quadrature" else "W^2"
    if spec.apod in ("hard", "area"):
        return f"{kind} = {spec.apod}"
    return f"{kind} = {spec.apod} {(spec.apod_param or 0.0) / pixel:.0f} bins"


def energy_weight(
    spec: WindowSpec, holediam: float, kx: np.ndarray, omega: np.ndarray
) -> np.ndarray:
    """The array multiplying ``|E|^2`` in the collected-energy observable.

    A quadrature weight enters once (and its edge radius carries the
    second-moment correction); an amplitude filter enters squared.
    """
    param = spec.apod_param or 0.0
    if spec.weighting == "quadrature":
        holediam = quadrature_holediam(holediam, spec.apod, param)
        power = 1
    else:
        power = 2
    mask = chromatic_mask(
        kx, kx, omega, spec.holex, spec.holey, holediam, spec.zmask, spec.apod, param
    )
    return np.asarray(mask**power)[:, :, 0]


def input_arms(kx: np.ndarray, omega: np.ndarray) -> np.ndarray:
    """The three z = 0 input arms, rendered as the accurate input mask does."""
    arms = [
        chromatic_mask(kx, kx, omega, hx, hy, HOLE_DIAM, F_FOC, "area", AREA_SUBSAMPLES)
        for hx, hy in (GATE1, GATE2, TEST)
    ]
    return arms[0] + arms[1] + arms[2]


def born_signal(kx: np.ndarray, omega: np.ndarray) -> np.ndarray:
    """First-Born TG source power in the signal corner.

    ``P(x) = e_g2(x) conj(e_g1(x)) e_test(x)``, transformed back to
    momentum. No centring ramps are applied: they would only translate the
    source, which the power spectrum does not see.
    """
    fields = [
        np.fft.ifft2(
            chromatic_mask(
                kx, kx, omega, hx, hy, HOLE_DIAM, F_FOC, "area", AREA_SUBSAMPLES
            ).astype(complex),
            axes=(0, 1),
        )
        for hx, hy in (GATE1, GATE2, TEST)
    ]
    source = fields[1] * np.conj(fields[0]) * fields[2]
    return np.asarray(np.abs(np.fft.fft2(source, axes=(0, 1))) ** 2)[:, :, 0]


def report_aperture_and_darkness(
    specs: list[WindowSpec], kx: np.ndarray, omega0: float, pixel: float, delta_k: float
) -> None:
    """Print the enclosed aperture and the z = 0 leakage of each rendering."""
    om = np.array([omega0])
    factor = F_FOC * c / omega0  # k -> mask-plane position
    power_in = np.asarray(input_arms(kx, om) ** 2)[:, :, 0]
    power_in = power_in / power_in.max()
    head = "".join(f"{d * 1e3:>12.2f} mm" for d in WINDOW_DIAMS)
    print(f"\n{'window rendering':22s}{head}  |{head}")
    print(f"{'':22s}{'--- aperture / nominal ---':^42s}  "
          f"|{'--- dark corner at z = 0 ---':^42s}")  # fmt: skip
    for spec in specs:
        aperture, leak = [], []
        for diam in WINDOW_DIAMS:
            w = energy_weight(spec, diam, kx, om)
            exact = np.pi * (diam / 2 / factor) ** 2 / delta_k**2
            aperture.append(w.sum() / exact)
            leak.append((w * power_in).sum())
        cells = "".join(f"{a:15.5f}" for a in aperture)
        print(f"{label(spec, pixel):22s}{cells}  |"
              + "".join(f"{v:15.3e}" for v in leak))  # fmt: skip


def report_ripple(
    specs: list[WindowSpec], kx: np.ndarray, lam0: float, pixel: float, points: int
) -> None:
    """Print the bin-scale ripple each rendering imposes on a smooth signal.

    Ratios are taken against the first candidate (a deliberately
    over-smoothed tanh, which has no ripple of its own) so the strong
    physical variation of the source across the band divides out; a
    low-order polynomial then removes what smooth trend remains.
    """
    lams = np.linspace(0.8 * lam0, 1.2 * lam0, points)
    collected: dict[tuple[int, float], list[float]] = {}
    for lam in lams:
        om = np.array([2 * np.pi * c / lam])
        probe = born_signal(kx, om)
        for j, spec in enumerate(specs):
            for diam in WINDOW_DIAMS:
                weight = energy_weight(spec, diam, kx, om)
                collected.setdefault((j, diam), []).append(
                    float((weight * probe).sum())
                )
    head = "".join(f"{d * 1e3:>13.2f} mm" for d in WINDOW_DIAMS)
    print(f"\n{'window rendering':22s}{head}")
    print(f"{'':22s}{'--- spectral ripple, peak-to-peak ---':^48s}")
    for j, spec in enumerate(specs):
        row = []
        for diam in WINDOW_DIAMS:
            values = np.array(collected[(j, diam)]) / np.array(collected[(0, diam)])
            trend = np.polyval(np.polyfit(lams, values, 5), lams)
            row.append(float(np.ptp(values - trend) / np.median(values)))
        print(f"{label(spec, pixel):22s}" + "".join(f"{v:16.2e}" for v in row))


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--n", type=int, default=768, help="transverse samples")
    parser.add_argument("--r-max", type=float, default=366e-6, help="containment, m")
    parser.add_argument("--lam0", type=float, default=260e-9, help="carrier, m")
    parser.add_argument("--scan", type=int, default=81, help="ripple scan points")
    args = parser.parse_args()

    sgrid = space_grid(args.r_max, args.n)
    kx = np.asarray(sgrid.kx)
    delta_k = float(sgrid.kx[1] - sgrid.kx[0])
    omega0 = 2 * np.pi * c / args.lam0
    pixel = delta_k * F_FOC * c / omega0  # one momentum bin, in mask-plane m
    print(
        f"n = {args.n}, r_max = {args.r_max:.4g} m: one momentum bin is "
        f"{pixel * 1e6:.1f} um in the mask plane at {args.lam0 * 1e9:.0f} nm"
    )

    specs = candidates(pixel)
    report_aperture_and_darkness(specs, kx, omega0, pixel, delta_k)
    report_ripple(specs, kx, args.lam0, pixel, args.scan)


if __name__ == "__main__":
    main()

A run file and a Slurm job#

The same window series as a TOML run file, for the pnps command, and a Slurm array job that scans it in shards (Run files, the command line and clusters).

# The window-series instrument at the production pixel size: 260 nm, 1 fs, HE11
# illumination, six collection windows, 40 um of fused silica, delays of +-40 fs.
# Run it with `pnps budget`, then `pnps scan` (see docs/clusters.md).

[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
time_headroom = 55e-15

[config.beam]
type = "HE11Beam"
a = 125e-6
f_coll = 5.0
f_foc = 0.1

# Raised-cosine edges 0.1 mm wide (solprop's limit is w <= D/4), as quadrature
# weights, so solprop's statistics reduce them (reduction = "auto").
[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 0.5e-3
zmask = 0.1
apod = "rcos"
apod_param = 0.1e-3
weighting = "quadrature"

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 1e-3
zmask = 0.1
apod = "rcos"
apod_param = 0.1e-3
weighting = "quadrature"

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 2e-3
zmask = 0.1
apod = "rcos"
apod_param = 0.1e-3
weighting = "quadrature"

[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
out_dir = "scans"
backend = "auto"
#!/bin/bash
# SPDX-FileCopyrightText: 2026 John C. Travers and contributors
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# One shard of a scan per array task; merge once every task has finished:
#
#     sbatch --array=0-7 scan.sbatch window_series.toml 8
#     pnps merge window_series.toml --shards 8
#
# Size the job first with `pnps budget window_series.toml`: the peak is the memory to
# ask for. On a CPU node of several NUMA domains, prefer one task per domain, each
# confined to its cores by Slurm, over one task per node.
#SBATCH --job-name=pnps
#SBATCH --cpus-per-task=32
#SBATCH --mem=40G
#SBATCH --time=24:00:00

set -euo pipefail
RUN=$1
SHARDS=$2
export SOLPROP_THREADS=${SLURM_CPUS_PER_TASK}
# Use the profile `solprop calibrate` kept for this node type (run it once, with the
# same thread budget, before submitting), rather than measuring in every task.
export SOLPROP_CALIBRATION=use
# Leave OpenMP's own variables (OMP_PROC_BIND, OMP_PLACES, OMP_WAIT_POLICY) unset:
# solprop chooses them. Binding the threads pins the main thread to one CPU, and the
# run then uses about one core of the task (see the manual's clusters page).
pnps scan "${RUN}" --shard "${SLURM_ARRAY_TASK_ID}/${SHARDS}"

A transient-grating separation#

The FROG2 campaign’s common instrument as a separation run file, for pnps separate (Separating the transient grating): the Iω_win* traces of its file hold the transient-grating field alone, beside the whole nonlinear field’s and the remainder’s. The same Slurm script runs it with pnps separate in place of pnps scan, given about 160 GB of host memory per task.

# The transient-grating separation (pnps separate) of the FROG2 campaign's common
# instrument (S1): an ideal 1 fs Gaussian at 260 nm from a hollow capillary (HE11),
# three 1 mm boxcar holes on a 1 mm gap focused by f = 100 mm into 40 um of fused
# silica, 1 nJ before the mask, six exact hard-disc windows from 0.5 to 2.5 mm at the
# signal corner. Three planes, at which h = 0.5 um meets the campaign's step target,
# and 27 delays: -10 to 10 fs in steps of 1 fs, and the quarter steps between 0 and
# 2 fs that resolve one fringe period. The scan name is the separation's own.
[config]
lam0 = 260e-9
tau_fwhm = 1e-15
energy = 1e-9
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
time_headroom = 55e-15
exact_windows = true

[config.beam]
type = "HE11Beam"
a = 125e-6
f_coll = 5.0
f_foc = 0.1

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 0.5e-3
zmask = 0.1

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 0.75e-3
zmask = 0.1

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 1.0e-3
zmask = 0.1

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 1.5e-3
zmask = 0.1

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 2.0e-3
zmask = 0.1

[[config.windows]]
holex = -1e-3
holey = -1e-3
holediam = 2.5e-3
zmask = 0.1

[scan]
name = "s1_tg"
taus = [-10e-15, -9e-15, -8e-15, -7e-15, -6e-15, -5e-15, -4e-15, -3e-15, -2e-15, -1e-15, 0.0, 0.25e-15, 0.5e-15, 0.75e-15, 1e-15, 1.25e-15, 1.5e-15, 1.75e-15, 2e-15, 3e-15, 4e-15, 5e-15, 6e-15, 7e-15, 8e-15, 9e-15, 10e-15]
zsave = [4e-6, 9.5e-6, 40e-6]
h_target = 0.5e-6
out_dir = "scans"
backend = "auto"