slurm_integration

nrxrdct.azimuthal.slurm_integration

nrxrdct.slurm_integration

Tools for distributing powder integration across SLURM HPC clusters.

Typical workflow

from nrxrdct.slurm_integration import launch, monitor, merge, check, repair

# 1. Submit integration jobs
result = launch(
    master_file = Path("master.h5"),
    output_file = Path("output.h5"),
    poni_file   = Path("calib.poni"),
    mask_file   = Path("mask.edf"),
    n_jobs      = 8,
    conda_env   = "nrxrdct",
)

# 2. Watch until done (blocking)
monitor(result["slurm_ids"], result["tmp_dir"], watch=True)

# 3. Assemble the output HDF5
merge(tmp_dir=result["tmp_dir"], output_file=Path("output.h5"))

# 4. Verify
check(tmp_dir=result["tmp_dir"], output_file=Path("output.h5"))

# 5. If anything is missing, resubmit
repair(tmp_dir=result["tmp_dir"], master_file=..., poni_file=..., mask_file=...)

check

check(tmp_dir: Path | None = None, output_file: Path | None = None) -> dict

Verify integration progress and/or merge completeness.

Parameters:
  • tmp_dir (Path, default: None ) –

    Tmp directory written by workers. If provided, counts completed .npy files and reports missing indices.

  • output_file (Path, default: None ) –

    Output HDF5 file. If provided, counts merged scan datasets.

Returns:
  • dict( dict ) –

    With keys 'n_total' (total expected scans), 'n_integrated' (.npy files present in tmp_dir), 'n_merged' (datasets present in output_file), 'missing_tmp' (indices not yet integrated), 'missing_h5' (indices not yet merged).

Source code in src/nrxrdct/azimuthal/slurm_integration/check_output.py
def check(
    tmp_dir: Path | None = None,
    output_file: Path | None = None,
) -> dict:
    """
    Verify integration progress and/or merge completeness.

    Args:
        tmp_dir (Path, optional): Tmp directory written by workers. If provided,
            counts completed .npy files and reports missing indices.
        output_file (Path, optional): Output HDF5 file. If provided, counts
            merged scan datasets.

    Returns:
        dict: With keys ``'n_total'`` (total expected scans),
            ``'n_integrated'`` (.npy files present in tmp_dir),
            ``'n_merged'`` (datasets present in output_file),
            ``'missing_tmp'`` (indices not yet integrated),
            ``'missing_h5'`` (indices not yet merged).
    """
    if tmp_dir is None and output_file is None:
        raise ValueError("Provide at least one of tmp_dir or output_file.")

    result = {
        "n_total": 0,
        "n_integrated": 0,
        "n_merged": 0,
        "missing_tmp": [],
        "missing_h5": [],
        "nan_scans": [],
    }

    # ── Read total expected scans from launch_meta.json ───────────────────────
    if tmp_dir is not None:
        tmp_dir = Path(tmp_dir)
        meta_sidecar = tmp_dir / "launch_meta.json"
        if not meta_sidecar.exists():
            raise FileNotFoundError(
                f"launch_meta.json not found in {tmp_dir}. " "Was launch() called?"
            )
        with open(meta_sidecar) as f:
            launch_meta = json.load(f)

        valid_entries = launch_meta["valid_entries"]
        n_total = len(valid_entries)
        result["n_total"] = n_total

        # Count completed scans — a scan is done when both .npy and .meta.json
        # exist. Also count misnamed files from the previous bug.
        integrated = set()
        for p in tmp_dir.glob("scan_????.npy"):
            ii = int(p.stem.split("_")[1])
            if (tmp_dir / f"scan_{ii:04d}.meta.json").exists():
                integrated.add(ii)
        # Count misnamed files (scan_XXXX.npy.tmp.npy) from previous bug
        for p in tmp_dir.glob("scan_????.npy.tmp.npy"):
            ii = int(p.name.split("_")[1].split(".")[0])
            metas = list(tmp_dir.glob(f"scan_{ii:04d}.meta.meta.json.tmp")) + list(
                tmp_dir.glob(f"scan_{ii:04d}.meta.json.tmp")
            )
            if metas:
                integrated.add(ii)

        # ── NaN check — load each .npy and flag scans with NaN rows ──────────
        nan_scans = []
        for ii in sorted(integrated):
            npy_path = tmp_dir / f"scan_{ii:04d}.npy"
            if not npy_path.exists():
                # misnamed file — skip NaN check, merge will rename it
                continue
            try:
                sinogram = np.load(npy_path)
                nan_rows = int(np.all(np.isnan(sinogram), axis=1).sum())
                if nan_rows > 0:
                    nan_scans.append((ii, nan_rows, sinogram.shape[0]))
            except Exception as e:
                print(f"  ⚠  scan_{ii:04d}: could not load for NaN check — {e}")

        # Remove NaN scans from integrated set and delete their tmp files
        # so repair() will reintegrate them
        if nan_scans:
            print(
                f"\n  ⚠  {len(nan_scans)} scans have NaN frames — "
                f"deleting and flagging for reintegration:"
            )
            for ii, nan_rows, n_frames in nan_scans:
                print(f"     scan_{ii:04d}: {nan_rows}/{n_frames} NaN frames")
                integrated.discard(ii)
                for f in [
                    tmp_dir / f"scan_{ii:04d}.npy",
                    tmp_dir / f"scan_{ii:04d}.meta.json",
                ]:
                    if f.exists():
                        f.unlink()

        missing_tmp = sorted(set(range(n_total)) - integrated)

        result["n_integrated"] = len(integrated)
        result["missing_tmp"] = missing_tmp
        result["nan_scans"] = nan_scans

        print(f"\n{'='*60}")
        print(f"  Integration progress  ({tmp_dir.name})")
        print(f"{'='*60}")
        print(f"  Expected    : {n_total}")
        print(f"  Integrated  : {len(integrated)}")
        print(f"  NaN scans   : {len(nan_scans)}  (deleted, will be reintegrated)")
        print(f"  Remaining   : {len(missing_tmp)}")
        if missing_tmp:
            print(f"  Missing idx : {missing_tmp}")
        else:
            print(f"  ✓  All scans integrated and NaN-free — ready to merge.")

    # ── Check HDF5 merge completeness ─────────────────────────────────────────
    if output_file is not None:
        output_file = Path(output_file)
        if not output_file.exists():
            print(f"\n  ⚠  Output file not found: {output_file}")
            print(f"     Run merge() first.")
            return result

        try:
            with h5py.File(output_file, "r") as hout:
                if "meta/valid_entries" not in hout:
                    print(
                        f"\n  ⚠  'meta/valid_entries' missing from {output_file.name}"
                    )
                    return result

                n_total = len(hout["meta/valid_entries"])
                result["n_total"] = max(result["n_total"], n_total)

                merged = {
                    ii for ii in range(n_total) if f"integrated/scan_{ii:04d}" in hout
                }
                missing_h5 = sorted(set(range(n_total)) - merged)

                result["n_merged"] = len(merged)
                result["missing_h5"] = missing_h5

                has_radial = "integrated/radial" in hout
                radial_info = (
                    (
                        hout["integrated/radial"].shape[0],
                        hout["integrated/radial"].attrs.get("unit", "?"),
                    )
                    if has_radial
                    else None
                )

        except OSError as e:
            print(f"\n  ✗  Cannot open {output_file.name}: {e}")
            print(f"     The file may be corrupted. Run rebuild().")
            return result

        print(f"\n{'='*60}")
        print(f"  Merge completeness    ({output_file.name})")
        print(f"{'='*60}")
        print(f"  Expected  : {n_total}")
        print(f"  Merged    : {len(merged)}")
        print(f"  Missing   : {len(missing_h5)}")
        if missing_h5:
            print(f"  Missing idx : {missing_h5}")
        else:
            print(f"  ✓  All scans merged.")
        if radial_info:
            print(f"  Radial    : {radial_info[0]} pts, unit={radial_info[1]}")

    print()
    return result

launch

launch(master_file: Path, output_file: Path, poni_file: Path, mask_file: Path, rot: ndarray | None = None, n_jobs: int = 8, n_points: int = 1000, n_workers: int = 16, batch_size: int = 32, unit: str = '2th_deg', method: str = 'standard', percentile: tuple = (10, 90), thres: float = 3.0, max_iter: int = 5, partition: str = 'cpu', time: str = '04:00:00', mem: str = '32G', cpus: int = 16, gpu: bool = False, env_activate: Path | None = None, conda_env: str | None = None) -> dict

Validate master file, write launch_meta.json, and submit N SLURM jobs.

Workers write results to /_tmp/. Call merge() after all jobs finish to assemble the output HDF5.

Returns

dict with keys 'slurm_ids', 'tmp_dir', 'n_scans'.

Source code in src/nrxrdct/azimuthal/slurm_integration/launch_jobs.py
def launch(
    master_file: Path,
    output_file: Path,
    poni_file: Path,
    mask_file: Path,
    rot: np.ndarray | None = None,
    n_jobs: int = 8,
    n_points: int = 1000,
    n_workers: int = 16,
    batch_size: int = 32,
    unit: str = "2th_deg",
    method: str = "standard",
    percentile: tuple = (10, 90),
    thres: float = 3.0,
    max_iter: int = 5,
    # SLURM
    partition: str = "cpu",
    time: str = "04:00:00",
    mem: str = "32G",
    cpus: int = 16,
    gpu: bool = False,
    # Environment
    env_activate: Path | None = None,
    conda_env: str | None = None,
) -> dict:
    """
    Validate master file, write launch_meta.json, and submit N SLURM jobs.

    Workers write results to <output_file.parent>/<output_file.stem>_tmp/.
    Call merge() after all jobs finish to assemble the output HDF5.

    Returns
    -------
    dict with keys 'slurm_ids', 'tmp_dir', 'n_scans'.
    """
    from nrxrdct.azimuthal.slurm_integration.integrate_worker import INTEGRATION_METHODS

    if method not in INTEGRATION_METHODS:
        raise ValueError(f"method must be one of {INTEGRATION_METHODS}, got '{method}'")

    master_file = Path(master_file)
    output_file = Path(output_file)
    poni_file = Path(poni_file)
    mask_file = Path(mask_file)
    percentile_str = f"{percentile[0]},{percentile[1]}"

    # tmp dir lives next to the output file, named after it
    tmp_dir = output_file.parent / (output_file.stem + "_tmp")
    tmp_dir.mkdir(parents=True, exist_ok=True)
    log_dir = output_file.parent / "slurm_logs"
    log_dir.mkdir(exist_ok=True)

    # ── 1. Validate ───────────────────────────────────────────────────────────
    print("=" * 60)
    print("Step 1 — Validating master file entries")
    print("=" * 60)
    valid_entries, bad_entries, dty_values = _validate_entries(master_file)
    if not valid_entries:
        raise RuntimeError("No valid entries found in master file.")

    # ── 2. Rotation angles ────────────────────────────────────────────────────
    if rot is None:
        with h5py.File(master_file, "r") as hin:
            rot = hin[f"{valid_entries[0]}/measurement/rot"][:]

    # ── 3. Compute radial axis + cake_mask, write output file skeleton ────────
    print("\n" + "=" * 60)
    print("Step 2 — Computing radial axis")
    print("=" * 60)
    mask = fabio.open(mask_file).data
    with h5py.File(master_file, "r") as hin:
        first_image = hin[f"{valid_entries[0]}/measurement/eiger"][0].astype(np.float32)
    tt, _, _ = azimuthal_integration_1d(
        image=first_image,
        poni_file=poni_file,
        npt=n_points,
        mask=mask,
        unit=unit,
    )
    mascake = (
        cake_integration(
            np.ones_like(first_image) * 10,
            poni_file,
            npt_rad=n_points,
            mask=mask,
        )[0]
        > 0
    )
    print(f"✓  Radial axis computed: {n_points} points, unit={unit}")

    # ── 4. Write launch_meta.json sidecar ─────────────────────────────────────
    print("\n" + "=" * 60)
    print("Step 3 — Writing launch metadata")
    print("=" * 60)
    launch_meta = {
        "valid_entries": valid_entries,
        "bad_entries": bad_entries,
        "dty_values": dty_values,
        "rot": rot.tolist(),
        "radial": tt.tolist(),
        "cake_mask": mascake.tolist(),
        "unit": unit,
        "n_points": n_points,
        "master_file": str(master_file),
        "output_file": str(output_file),
        "poni_file": str(poni_file),
        "mask_file": str(mask_file),
        "method": method,
        # SLURM settings — reused by repair()
        "partition": partition,
        "time": time,
        "mem": mem,
        "cpus": cpus,
        "gpu": gpu,
        "env_activate": str(env_activate) if env_activate else None,
        "conda_env": conda_env,
        # Integration settings — reused by repair()
        "batch_size": batch_size,
        "percentile": f"{percentile[0]},{percentile[1]}",
        "thres": thres,
        "max_iter": max_iter,
    }
    sidecar_path = tmp_dir / "launch_meta.json"
    sidecar_path.write_text(json.dumps(launch_meta, indent=2))
    print(f"✓  launch_meta.json → {sidecar_path}")

    # ── 5. Split & submit ─────────────────────────────────────────────────────
    print("\n" + "=" * 60)
    print("Step 4 — Splitting work and submitting jobs")
    print("=" * 60)
    chunks = _split_indices(len(valid_entries), n_jobs)
    slurm_ids = []
    for job_id, indices in enumerate(chunks):
        sid = _submit_job(
            job_id,
            indices,
            master_file=master_file,
            tmp_dir=tmp_dir,
            poni_file=poni_file,
            mask_file=mask_file,
            n_points=n_points,
            n_workers=n_workers,
            batch_size=batch_size,
            unit=unit,
            method=method,
            percentile=percentile_str,
            thres=thres,
            max_iter=max_iter,
            partition=partition,
            time=time,
            mem=mem,
            cpus=cpus,
            gpu=gpu,
            env_activate=env_activate,
            conda_env=conda_env,
            log_dir=log_dir,
        )
        slurm_ids.append(sid)

    print(f"\n✓  {len(slurm_ids)} jobs submitted — IDs: {', '.join(slurm_ids)}")
    print(f"   Tmp dir : {tmp_dir}/")
    print(f"   Logs    : {log_dir}/")
    print(
        f"\n   Monitor : nrxrdct-slurm monitor --slurm-ids {','.join(slurm_ids)} "
        f"--tmp-dir {tmp_dir} --watch"
    )
    print(
        f"   Merge   : nrxrdct-slurm merge --tmp-dir {tmp_dir} "
        f"--output-file {output_file}"
    )

    return {"slurm_ids": slurm_ids, "tmp_dir": tmp_dir, "n_scans": len(valid_entries)}

repair

repair(tmp_dir: Path, master_file: Path | None = None, poni_file: Path | None = None, mask_file: Path | None = None, *, output_file: Path | None = None, n_jobs: int = 1, watch: bool = False, interval: int = 30, **kwargs) -> dict

Resubmit SLURM jobs for any scans missing from the tmp directory.

All integration and SLURM settings are read from launch_meta.json so you don't need to repeat them. Pass **kwargs to override any individual setting (e.g. partition, mem, n_workers).

Parameters:
  • tmp_dir (Path) –

    Tmp directory from the original launch().

  • master_file (Path, default: None ) –

    Override master HDF5 (default: from launch_meta).

  • poni_file (Path, default: None ) –

    Override calibration file (default: from launch_meta).

  • mask_file (Path, default: None ) –

    Override mask file (default: from launch_meta).

  • output_file (Path, default: None ) –

    Only used to check merge status if provided.

  • n_jobs (int, default: 1 ) –

    Number of repair jobs. Defaults to 1.

  • watch (bool, default: False ) –

    Block until repair jobs finish.

  • interval (int, default: 30 ) –

    Polling interval in seconds when watch=True.

  • **kwargs –

    Override any setting from launch_meta (partition, mem, etc.).

Source code in src/nrxrdct/azimuthal/slurm_integration/check_output.py
def repair(
    tmp_dir: Path,
    master_file: Path | None = None,
    poni_file: Path | None = None,
    mask_file: Path | None = None,
    *,
    output_file: Path | None = None,
    n_jobs: int = 1,
    watch: bool = False,
    interval: int = 30,
    **kwargs,
) -> dict:
    """
    Resubmit SLURM jobs for any scans missing from the tmp directory.

    All integration and SLURM settings are read from launch_meta.json so
    you don't need to repeat them. Pass **kwargs to override any individual
    setting (e.g. partition, mem, n_workers).

    Args:
        tmp_dir (Path): Tmp directory from the original launch().
        master_file (Path, optional): Override master HDF5 (default: from launch_meta).
        poni_file (Path, optional): Override calibration file (default: from launch_meta).
        mask_file (Path, optional): Override mask file (default: from launch_meta).
        output_file (Path, optional): Only used to check merge status if provided.
        n_jobs (int): Number of repair jobs. Defaults to 1.
        watch (bool): Block until repair jobs finish.
        interval (int): Polling interval in seconds when watch=True.
        **kwargs: Override any setting from launch_meta (partition, mem, etc.).
    """
    from .launch_jobs import _split_indices, _submit_job

    tmp_dir = Path(tmp_dir)
    result = check(tmp_dir=tmp_dir, output_file=output_file)

    missing = result["missing_tmp"]
    if not missing:
        print("✓  Nothing to repair — all scans present in tmp dir.")
        return result

    print(f"\n🔧  Repairing {len(missing)} missing scans across {n_jobs} job(s)...")

    with open(tmp_dir / "launch_meta.json") as f:
        lm = json.load(f)

    # Resolve paths — kwargs override launch_meta, launch_meta overrides defaults
    _master_file = Path(kwargs.pop("master_file", master_file or lm["master_file"]))
    _poni_file = Path(kwargs.pop("poni_file", poni_file or lm["poni_file"]))
    _mask_file = Path(kwargs.pop("mask_file", mask_file or lm["mask_file"]))
    _env_activate = kwargs.pop("env_activate", lm.get("env_activate"))
    _env_activate = Path(_env_activate) if _env_activate else None

    # All settings fall back to what was used at launch time
    settings = dict(
        n_points=lm.get("n_points", 1000),
        n_workers=lm.get("cpus", 16),
        batch_size=lm.get("batch_size", 32),
        unit=lm.get("unit", "2th_deg"),
        method=lm.get("method", "standard"),
        percentile=lm.get("percentile", "10,90"),
        thres=lm.get("thres", 3.0),
        max_iter=lm.get("max_iter", 5),
        partition=lm.get("partition", "cpu"),
        time=lm.get("time", "04:00:00"),
        mem=lm.get("mem", "32G"),
        cpus=lm.get("cpus", 16),
        gpu=lm.get("gpu", False),
        conda_env=lm.get("conda_env", None),
    )
    # Apply user overrides
    settings.update(kwargs)

    log_dir = Path(lm["output_file"]).parent / "slurm_logs"
    log_dir.mkdir(exist_ok=True)
    base_id = len(sorted(log_dir.glob("job_*.sh")))

    chunks = _split_indices(len(missing), min(n_jobs, len(missing)))
    chunks = [[missing[i] for i in chunk] for chunk in chunks]

    slurm_ids = []
    for offset, chunk in enumerate(chunks):
        sid = _submit_job(
            base_id + offset,
            chunk,
            master_file=_master_file,
            tmp_dir=tmp_dir,
            poni_file=_poni_file,
            mask_file=_mask_file,
            n_points=settings["n_points"],
            n_workers=settings["n_workers"],
            batch_size=settings["batch_size"],
            unit=settings["unit"],
            method=settings["method"],
            percentile=settings["percentile"],
            thres=settings["thres"],
            max_iter=settings["max_iter"],
            partition=settings["partition"],
            time=settings["time"],
            mem=settings["mem"],
            cpus=settings["cpus"],
            gpu=settings["gpu"],
            env_activate=_env_activate,
            conda_env=settings["conda_env"],
            log_dir=log_dir,
        )
        slurm_ids.append(sid)

    print(
        f"\n✓  {len(slurm_ids)} repair job(s) submitted — IDs: {', '.join(slurm_ids)}"
    )

    if watch:
        from .monitor import monitor as _monitor

        _monitor(
            slurm_ids=slurm_ids,
            tmp_dir=tmp_dir,
            watch=True,
            interval=interval,
        )

    result["repair_job_ids"] = slurm_ids
    return result