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()),
}