slurm_pole_figures

nrxrdct.texture.slurm_pole_figures

nrxrdct.texture.slurm_pole_figures

Tools for distributing pole-figure extraction (:mod:nrxrdct.texture.odf) across SLURM HPC clusters, for one or more hkl rings at once — each worker cake-integrates every frame once and extracts all requested rings from that single cake, so adding more hkls does not multiply the (expensive) integration cost.

Typical workflow

from nrxrdct.texture.slurm_pole_figures import launch, monitor, merge, check, repair

# 1. Submit extraction jobs for as many hkls as you want in one go
result = launch(
    master_file = Path("master.h5"),
    output_file = Path("pole_figures.h5"),
    poni_file   = Path("calib.poni"),
    mask_file   = Path("mask.edf"),
    hkls        = {"111": (4.0, 6.0), "200": (7.0, 9.0), "220": (11.0, 13.0)},
    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 (writes pole_figures/<hkl>/... for every hkl)
merge(tmp_dir=result["tmp_dir"], output_file=Path("pole_figures.h5"))

# 4. Verify (checks every hkl found in launch_meta.json by default)
check(tmp_dir=result["tmp_dir"], output_file=Path("pole_figures.h5"))

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

check

check(tmp_dir: Optional[Path] = None, output_file: Optional[Path] = None, hkl_labels: Optional[Union[str, List[str]]] = None) -> dict

Verify extraction progress and/or merge completeness, across every hkl launched (or an explicit subset via hkl_labels).

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

    Tmp directory written by workers. If provided, counts scans whose meta file and every hkl's .npy file are all present, and reports missing indices.

  • output_file (Path, default: None ) –

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

  • hkl_labels (str or list of str, default: None ) –

    Which hkls to check the merge completeness of. Defaults to every hkl found in tmp_dir's launch_meta.json; required (and must be explicit) if only output_file is given.

Returns:
  • dict( dict ) –

    With keys 'n_total', 'n_extracted', 'missing_tmp', and 'merge' — a dict mapping each checked hkl to {'n_merged', 'missing_h5'}.

Source code in src/nrxrdct/texture/slurm_pole_figures/check_output.py
def check(
    tmp_dir: Optional[Path] = None,
    output_file: Optional[Path] = None,
    hkl_labels: Optional[Union[str, List[str]]] = None,
) -> dict:
    """
    Verify extraction progress and/or merge completeness, across every hkl
    launched (or an explicit subset via *hkl_labels*).

    Args:
        tmp_dir (Path, optional): Tmp directory written by workers. If provided,
            counts scans whose meta file and every hkl's .npy file are all
            present, and reports missing indices.
        output_file (Path, optional): Output HDF5 file. If provided, counts
            merged scan datasets per hkl.
        hkl_labels (str or list of str, optional): Which hkls to check the
            merge completeness of. Defaults to every hkl found in
            *tmp_dir*'s launch_meta.json; required (and must be explicit) if
            only *output_file* is given.

    Returns:
        dict: With keys ``'n_total'``, ``'n_extracted'``, ``'missing_tmp'``,
            and ``'merge'`` — a dict mapping each checked hkl to
            ``{'n_merged', 'missing_h5'}``.
    """
    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_extracted": 0,
        "missing_tmp": [],
        "merge": {},
    }

    hkls_from_meta = None

    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"]
        hkls_from_meta = list(launch_meta["hkls"].keys())
        n_total = len(valid_entries)
        result["n_total"] = n_total

        extracted = set()
        for meta_path in tmp_dir.glob("scan_????.meta.json"):
            ii = int(meta_path.name.split("_")[1].split(".")[0])
            if all((tmp_dir / f"scan_{ii:04d}_{hkl}.npy").exists() for hkl in hkls_from_meta):
                extracted.add(ii)

        missing_tmp = sorted(set(range(n_total)) - extracted)
        result["n_extracted"] = len(extracted)
        result["missing_tmp"] = missing_tmp

        print(f"\n{'='*60}")
        print(f"  Extraction progress  ({tmp_dir.name})  [hkls: {hkls_from_meta}]")
        print(f"{'='*60}")
        print(f"  Expected    : {n_total}")
        print(f"  Extracted   : {len(extracted)}")
        print(f"  Remaining   : {len(missing_tmp)}")
        if missing_tmp:
            print(f"  Missing idx : {missing_tmp}")
        else:
            print(f"  ✓  All scans extracted — ready to merge.")

    if output_file is not None:
        output_file = Path(output_file)

        labels = hkl_labels if hkl_labels is not None else hkls_from_meta
        if labels is None:
            raise ValueError(
                "hkl_labels is required when checking output_file without tmp_dir."
            )
        if isinstance(labels, str):
            labels = [labels]

        if not output_file.exists():
            print(f"\n  ⚠  Output file not found: {output_file}")
            print(f"     Run merge() first.")
            return result

        with h5py.File(output_file, "r") as hout:
            for hkl in labels:
                group = f"pole_figures/{hkl}"
                n_total = result["n_total"]

                if group in hout:
                    merged = {
                        int(key.split("_")[1])
                        for key in hout[group].keys()
                        if key.startswith("scan_")
                    }
                else:
                    merged = set()

                if n_total == 0:
                    n_total = max(merged, default=-1) + 1
                missing_h5 = sorted(set(range(n_total)) - merged)

                result["merge"][hkl] = {"n_merged": len(merged), "missing_h5": missing_h5}

                has_azimuthal = f"{group}/azimuthal" in hout
                n_chi = hout[f"{group}/azimuthal"].shape[0] if has_azimuthal else None

                print(f"\n{'='*60}")
                print(f"  Merge completeness    ({output_file.name}) [{group}]")
                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 n_chi:
                    print(f"  Azimuthal : {n_chi} bins")

    print()
    return result

launch

launch(master_file: Path, output_file: Path, poni_file: Path, mask_file: Path, hkls: Dict[str, Tuple[float, float]], background_ranges: Optional[Dict[str, Tuple[Tuple[float, float], Tuple[float, float]]]] = None, n_jobs: int = 8, npt_rad: int = 1000, npt_azim: int = 360, n_workers: Optional[int] = None, batch_size: int = 32, camera_name: str = 'eiger', monitor_name: str = 'fpico6', translation_motor: str = 'dty', rotation_motor: str = 'rot', partition: str = 'nice', time: str = '04:00:00', mem: str = '32G', cpus: int = 16, gpu: bool = False, env_activate: Optional[Path] = None, conda_env: Optional[str] = None) -> dict

Validate master file, write launch_meta.json, and submit N SLURM jobs that extract pole-figure profiles for one or more hkl rings.

Each worker cake-integrates every frame once and extracts all requested rings from that single cake, so adding more hkls does not multiply the (expensive) integration cost the way calling :func:launch once per hkl would.

Workers write results to <output_file.parent>/<output_file.stem>_tmp/. Call :func:nrxrdct.texture.slurm_pole_figures.merge after all jobs finish to assemble the output HDF5.

Parameters:
  • master_file (Path) –

    HDF5 master file containing all scan entries.

  • output_file (Path) –

    Destination HDF5 file for pole-figure data; used to derive the tmp directory name.

  • poni_file (Path) –

    pyFAI .poni calibration file.

  • mask_file (Path) –

    Detector mask file (fabio-readable).

  • hkls (dict) –

    Maps hkl label to its (low, high) 2theta window, e.g. {"111": (4.0, 6.0), "200": (7.0, 9.0)}. Each label becomes an HDF5 group name under pole_figures/.

  • background_ranges (dict, default: None ) –

    Maps hkl label to ((low1, high1), (low2, high2)) flanking 2theta windows for background subtraction. Labels not present get no background subtraction; pass None (default) to skip it for every hkl.

  • n_jobs (int, default: 8 ) –

    Number of SLURM jobs to submit (default 8).

  • npt_rad (int, default: 1000 ) –

    Radial bins used internally by CAKE integration (default 1000).

  • npt_azim (int, default: 360 ) –

    Number of azimuthal (chi) bins (default 360).

  • n_workers (int, default: None ) –

    Integration threads per scan; auto-scaled from available RAM when None (default None).

  • batch_size (int, default: 32 ) –

    Frames streamed from HDF5 per batch in the worker (default 32).

  • camera_name (str, default: 'eiger' ) –

    Detector dataset name under measurement/ (default "eiger").

  • monitor_name (str, default: 'fpico6' ) –

    Monitor dataset name under measurement/ used for normalisation (default "fpico6").

  • translation_motor (str, default: 'dty' ) –

    Translation-motor name read from instrument/positioners/ (default "dty").

  • rotation_motor (str, default: 'rot' ) –

    Rotation-motor dataset name under measurement/ (default "rot").

  • partition (str, default: 'nice' ) –

    SLURM partition (default "nice").

  • time (str, default: '04:00:00' ) –

    SLURM wall-time limit (default "04:00:00").

  • mem (str, default: '32G' ) –

    SLURM memory request (default "32G").

  • cpus (int, default: 16 ) –

    CPUs per task (default 16).

  • gpu (bool, default: False ) –

    Request a GPU node (default False).

  • env_activate (Path, default: None ) –

    Shell activate script sourced before the worker command.

  • conda_env (str, default: None ) –

    Conda environment used via conda run (alternative to env_activate).

Returns:
  • dict( dict ) –

    With keys 'slurm_ids', 'tmp_dir', 'n_scans', 'hkls'.

Source code in src/nrxrdct/texture/slurm_pole_figures/launch_jobs.py
def launch(
    master_file: Path,
    output_file: Path,
    poni_file: Path,
    mask_file: Path,
    hkls: Dict[str, Tuple[float, float]],
    background_ranges: Optional[Dict[str, Tuple[Tuple[float, float], Tuple[float, float]]]] = None,
    n_jobs: int = 8,
    npt_rad: int = 1000,
    npt_azim: int = 360,
    n_workers: Optional[int] = None,
    batch_size: int = 32,
    camera_name: str = "eiger",
    monitor_name: str = "fpico6",
    translation_motor: str = "dty",
    rotation_motor: str = "rot",
    # SLURM
    partition: str = "nice",
    time: str = "04:00:00",
    mem: str = "32G",
    cpus: int = 16,
    gpu: bool = False,
    # Environment
    env_activate: Optional[Path] = None,
    conda_env: Optional[str] = None,
) -> dict:
    """
    Validate master file, write launch_meta.json, and submit N SLURM jobs
    that extract pole-figure profiles for one or more hkl rings.

    Each worker cake-integrates every frame once and extracts all requested
    rings from that single cake, so adding more hkls does not multiply the
    (expensive) integration cost the way calling :func:`launch` once per hkl
    would.

    Workers write results to ``<output_file.parent>/<output_file.stem>_tmp/``.
    Call :func:`nrxrdct.texture.slurm_pole_figures.merge` after all jobs finish
    to assemble the output HDF5.

    Args:
        master_file (Path): HDF5 master file containing all scan entries.
        output_file (Path): Destination HDF5 file for pole-figure data; used to
            derive the tmp directory name.
        poni_file (Path): pyFAI ``.poni`` calibration file.
        mask_file (Path): Detector mask file (fabio-readable).
        hkls (dict): Maps hkl label to its ``(low, high)`` 2theta window, e.g.
            ``{"111": (4.0, 6.0), "200": (7.0, 9.0)}``. Each label becomes an
            HDF5 group name under ``pole_figures/``.
        background_ranges (dict, optional): Maps hkl label to
            ``((low1, high1), (low2, high2))`` flanking 2theta windows for
            background subtraction. Labels not present get no background
            subtraction; pass ``None`` (default) to skip it for every hkl.
        n_jobs (int, optional): Number of SLURM jobs to submit (default 8).
        npt_rad (int, optional): Radial bins used internally by CAKE integration
            (default 1000).
        npt_azim (int, optional): Number of azimuthal (chi) bins (default 360).
        n_workers (int, optional): Integration threads per scan; auto-scaled from
            available RAM when ``None`` (default ``None``).
        batch_size (int, optional): Frames streamed from HDF5 per batch in the
            worker (default 32).
        camera_name (str, optional): Detector dataset name under ``measurement/``
            (default ``"eiger"``).
        monitor_name (str, optional): Monitor dataset name under ``measurement/``
            used for normalisation (default ``"fpico6"``).
        translation_motor (str, optional): Translation-motor name read from
            ``instrument/positioners/`` (default ``"dty"``).
        rotation_motor (str, optional): Rotation-motor dataset name under
            ``measurement/`` (default ``"rot"``).
        partition (str, optional): SLURM partition (default ``"nice"``).
        time (str, optional): SLURM wall-time limit (default ``"04:00:00"``).
        mem (str, optional): SLURM memory request (default ``"32G"``).
        cpus (int, optional): CPUs per task (default 16).
        gpu (bool, optional): Request a GPU node (default ``False``).
        env_activate (Path, optional): Shell activate script sourced before the
            worker command.
        conda_env (str, optional): Conda environment used via ``conda run``
            (alternative to *env_activate*).

    Returns:
        dict: With keys ``'slurm_ids'``, ``'tmp_dir'``, ``'n_scans'``, ``'hkls'``.
    """
    if not hkls:
        raise ValueError("hkls must contain at least one hkl label.")

    master_file = Path(master_file)
    output_file = Path(output_file)
    poni_file = Path(poni_file)
    mask_file = Path(mask_file)

    tmp_dir = output_file.parent / (output_file.stem + "_tmp")
    tmp_dir.mkdir(parents=True, exist_ok=True)
    log_dir = output_file.parent / "slurm_logs_texture"
    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, camera_name, monitor_name, translation_motor
    )
    if not valid_entries:
        raise RuntimeError("No valid entries found in master file.")

    # ── 2. Write launch_meta.json sidecar ─────────────────────────────────────
    print("\n" + "=" * 60)
    print("Step 2 — Writing launch metadata")
    print("=" * 60)
    print(f"  hkls: {list(hkls.keys())}")
    launch_meta = {
        "valid_entries": valid_entries,
        "bad_entries": bad_entries,
        "dty_values": dty_values,
        "hkls": {hkl: list(tth_range) for hkl, tth_range in hkls.items()},
        "background_ranges": (
            {hkl: [list(bg[0]), list(bg[1])] for hkl, bg in background_ranges.items()}
            if background_ranges is not None
            else {}
        ),
        "npt_rad": npt_rad,
        "npt_azim": npt_azim,
        "master_file": str(master_file),
        "output_file": str(output_file),
        "poni_file": str(poni_file),
        "mask_file": str(mask_file),
        "camera_name": camera_name,
        "monitor_name": monitor_name,
        "translation_motor": translation_motor,
        "rotation_motor": rotation_motor,
        # 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,
        # Worker settings — reused by repair()
        "n_workers": n_workers,
        "batch_size": batch_size,
    }
    sidecar_path = tmp_dir / "launch_meta.json"
    sidecar_path.write_text(json.dumps(launch_meta, indent=2))
    print(f"✓  launch_meta.json → {sidecar_path}")

    # ── 3. Split & submit ─────────────────────────────────────────────────────
    print("\n" + "=" * 60)
    print("Step 3 — 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,
            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-texture monitor --slurm-ids {','.join(slurm_ids)} "
        f"--tmp-dir {tmp_dir} --watch"
    )
    print(
        f"   Merge   : nrxrdct-slurm-texture merge --tmp-dir {tmp_dir} "
        f"--output-file {output_file}"
    )

    return {
        "slurm_ids": slurm_ids,
        "tmp_dir": tmp_dir,
        "n_scans": len(valid_entries),
        "hkls": list(hkls.keys()),
    }

repair

repair(tmp_dir: Path, master_file: Optional[Path] = None, poni_file: Optional[Path] = None, mask_file: Optional[Path] = None, *, output_file: Optional[Path] = 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 hkls, extraction settings, and SLURM settings are read from launch_meta.json so you don't need to repeat them. Pass **kwargs to override any individual SLURM setting (e.g. partition, mem).

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 SLURM setting from launch_meta (partition, mem, etc.).

Source code in src/nrxrdct/texture/slurm_pole_figures/check_output.py
def repair(
    tmp_dir: Path,
    master_file: Optional[Path] = None,
    poni_file: Optional[Path] = None,
    mask_file: Optional[Path] = None,
    *,
    output_file: Optional[Path] = 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 hkls, extraction settings, and SLURM settings are read from
    launch_meta.json so you don't need to repeat them. Pass **kwargs to
    override any individual SLURM setting (e.g. partition, mem).

    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 SLURM setting from launch_meta (partition, mem, etc.).
    """
    from .launch_jobs import _split_indices, _submit_job

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

    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 (hkls: {list(lm['hkls'])}) "
          f"across {n_jobs} job(s)...")

    _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

    settings = dict(
        partition=lm.get("partition", "nice"),
        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),
    )
    settings.update(kwargs)

    log_dir = Path(lm["output_file"]).parent / "slurm_logs_texture"
    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,
            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