Source code for pnps.cli

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

"""The ``pnps`` command: run, merge and budget a scan from a run file.

``pnps scan RUN.toml`` runs the scan a run file (:mod:`pnps.runfile`) describes, or one
shard of it with ``--shard I/N`` (delay indices ``I::N``), resuming any point already
written. ``pnps separate RUN.toml`` runs the transient-grating separation of the same
scan (:func:`pnps.scan.run_separation_scan`), with the same options; give it a run file
with a scan name of its own. ``pnps merge RUN.toml --shards N`` folds the ``N`` shard
files into the collected file. ``pnps budget RUN.toml`` prints the run's memory before
it is launched (:func:`pnps.memory.memory_budget`). ``python -m pnps`` is the same
command.

On a Slurm cluster, one shard per array task::

    #SBATCH --array=0-7
    pnps scan run.toml --shard ${SLURM_ARRAY_TASK_ID}/8

then, once every task has finished, ``pnps merge run.toml --shards 8``.
"""

import argparse
import logging
import shutil
import sys
from collections.abc import Sequence

from pnps.exceptions import PnpsError, ScanError
from pnps.io_h5 import merge_shards
from pnps.memory import memory_budget
from pnps.runfile import load_run
from pnps.scan import run_scan, run_separation_scan
from pnps.setup import build_setup

__all__ = ["main"]

logger = logging.getLogger(__name__)


def _shard(text: str) -> tuple[int, int]:
    """Parse ``I/N`` into a shard.

    Parameters
    ----------
    text : str
        The command-line value.

    Returns
    -------
    tuple of int
        ``(I, N)``.

    Raises
    ------
    argparse.ArgumentTypeError
        If the value is not two integers separated by ``/``.
    """
    try:
        index, count = (int(part) for part in text.split("/"))
    except ValueError as error:
        raise argparse.ArgumentTypeError(f"expected I/N, got {text!r}") from error
    return index, count


def _parser() -> argparse.ArgumentParser:
    """Return the command's argument parser.

    Returns
    -------
    argparse.ArgumentParser
        The ``scan``, ``separate``, ``merge`` and ``budget`` subcommands.
    """
    parser = argparse.ArgumentParser(
        prog="pnps", description="Run, merge and budget PNPS trace scans."
    )
    commands = parser.add_subparsers(dest="command", required=True)
    scan = commands.add_parser("scan", help="run a scan, or one shard of it")
    scan.add_argument("run", help="the run file (TOML)")
    scan.add_argument("--shard", type=_shard, help="compute delay indices I::N")
    scan.add_argument("--indices", type=int, nargs="+", help="only these delays")
    scan.add_argument("--backend", help="override the run file's solprop backend")
    scan.add_argument(
        "--recompute", action="store_true", help="recompute points already written"
    )
    separate = commands.add_parser(
        "separate", help="separate the transient grating, or one shard of it"
    )
    separate.add_argument("run", help="the run file (TOML)")
    separate.add_argument("--shard", type=_shard, help="compute delay indices I::N")
    separate.add_argument("--indices", type=int, nargs="+", help="only these delays")
    separate.add_argument("--backend", help="override the run file's solprop backend")
    separate.add_argument(
        "--recompute", action="store_true", help="recompute points already written"
    )
    merge = commands.add_parser("merge", help="fold the shard files together")
    merge.add_argument("run", help="the run file (TOML)")
    merge.add_argument("--shards", type=int, required=True, help="how many shards")
    budget = commands.add_parser("budget", help="print the run's memory budget")
    budget.add_argument("run", help="the run file (TOML)")
    budget.add_argument("--backend", help="override the run file's solprop backend")
    return parser


def _scan(args: argparse.Namespace) -> int:
    """Run the ``scan`` or the ``separate`` subcommand.

    Parameters
    ----------
    args : argparse.Namespace
        The parsed arguments.

    Returns
    -------
    int
        The exit status, 0.
    """
    run = load_run(args.run)
    run.out_dir.mkdir(parents=True, exist_ok=True)
    driver = run_separation_scan if args.command == "separate" else run_scan
    path = driver(
        run.config,
        run.scan.taus,
        run.scan.name,
        run.scan.zsave,
        run.scan.h_target,
        out_dir=run.out_dir,
        shard=args.shard,
        indices=args.indices,
        skip_existing=not args.recompute,
        backend=args.backend or run.scan.backend,
    )
    sys.stdout.write(f"{path}\n")
    return 0


def _merge(args: argparse.Namespace) -> int:
    """Run the ``merge`` subcommand.

    Parameters
    ----------
    args : argparse.Namespace
        The parsed arguments.

    Returns
    -------
    int
        The exit status, 0.

    Raises
    ------
    ScanError
        If a shard file is missing.
    """
    run = load_run(args.run)
    shards = [
        run.out_dir / f"{run.scan.name}_collected.shard{i}.h5"
        for i in range(args.shards)
    ]
    missing = [str(path) for path in shards if not path.exists()]
    if missing:
        raise ScanError(f"missing shard files: {missing}")
    target = run.out_dir / f"{run.scan.name}_collected.h5"
    if not target.exists():
        # The first shard carries the whole layout and /grid.
        shutil.copyfile(shards[0], target)
    copied = merge_shards(target, shards)
    sys.stdout.write(f"{target}: {copied} delay points from {len(shards)} shards\n")
    return 0


def _budget(args: argparse.Namespace) -> int:
    """Run the ``budget`` subcommand.

    Parameters
    ----------
    args : argparse.Namespace
        The parsed arguments.

    Returns
    -------
    int
        The exit status, 0.
    """
    run = load_run(args.run)
    budget = memory_budget(
        build_setup(run.config),
        run.scan.zsave,
        run.scan.h_target,
        backend=args.backend or run.scan.backend,
    )
    sys.stdout.write(budget.report() + "\n")
    return 0


[docs] def main(argv: Sequence[str] | None = None) -> int: """Run the ``pnps`` command. Parameters ---------- argv : sequence of str or None, optional The arguments; None takes ``sys.argv[1:]``. Returns ------- int The exit status: 0, or 1 after printing a package error. """ args = _parser().parse_args(argv) logging.basicConfig( level=logging.INFO, format="%(asctime)s %(name)s %(message)s", stream=sys.stderr ) commands = {"scan": _scan, "separate": _scan, "merge": _merge, "budget": _budget} try: return commands[args.command](args) except PnpsError as error: sys.stderr.write(f"pnps: {error}\n") return 1