diff --git a/README.md b/README.md index afa7d2a..91c7fac 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,15 @@ Minibutler is looking for new SwissFEL data and submitting analysis jobs to SLUR After installation (first clone this repository into the pgroup's `/work`, then `pip install -e . --user` in the project directory into the suitable python environment for analysis). -In `src` we have to adapt `calc_script.sh`, `calc_job.py` and `calculators.py` to the current pgroup, e.g. include special paths, SLURM reservations, etc. +The pgroup is only defined in `src/minibutler/config.py`, all paths are derived from it there. By default it is guessed from the location of the repository (via `cristallina.utils.heuristic_extract_pgroup`), so there is nothing to change for a new pgroup. Other adaptations, e.g. SLURM reservations or the calculations themselves, go into `calc_script.sh` and `calculators.py`. -We can then start minibutler with a given directory to watch for new runs: +We can then start minibutler, which watches `/sf/cristallina/data//raw` for new runs: ```` -minibutler --watch-path /sf/cristallina/data/p19150/raw +minibutler +```` +or with an explicitly given pgroup and/or directory to watch: +```` +minibutler --pgroup p19150 --watch-path /sf/cristallina/data/p19150/raw ```` As soon as the files of a new run appear on the filesystem the `scheduled_jobs` from the `calculator.py` module are submitted for execution. diff --git a/src/minibutler/butler.py b/src/minibutler/butler.py index a1d2a79..6d9c165 100644 --- a/src/minibutler/butler.py +++ b/src/minibutler/butler.py @@ -6,6 +6,7 @@ import time import sys from pathlib import Path +from . import config from .calc_job import submit_scheduled_jobs # Our own script directory @@ -167,11 +168,16 @@ def main(): parser = argparse.ArgumentParser( description="Butler to monitor directories for new experimental runs and submit processing jobs." ) + parser.add_argument( + "--pgroup", + default=None, + help="The pgroup of the experiment (e.g. p23102). If not given, it is guessed from the repository location.", + ) parser.add_argument( "--watch-path", type=Path, - required=True, - help=f"Path to monitor for new run directories (e.g: /sf/cristallina/data/p22760/raw)", + default=None, + help="Path to monitor for new run directories (default: /sf/cristallina/data//raw)", ) parser.add_argument( "--process-all", @@ -188,6 +194,10 @@ def main(): args = parser.parse_args() + config.set_pgroup(args.pgroup) + logger.info(f"Using pgroup {config.PGROUP}") + watch_path = args.watch_path or Path(config.RAW_PATH) + reprocess_runs = None if args.reprocess: reprocess_runs = set() @@ -200,7 +210,7 @@ def main(): pipe_path = setup_reprocessing_pipe() run_watcher( - watch_path=args.watch_path, process_all_runs=args.process_all, reprocess_runs=reprocess_runs, pipe_path=pipe_path, + watch_path=watch_path, process_all_runs=args.process_all, reprocess_runs=reprocess_runs, pipe_path=pipe_path, ) diff --git a/src/minibutler/calc_job.py b/src/minibutler/calc_job.py index e2bad5c..6070744 100644 --- a/src/minibutler/calc_job.py +++ b/src/minibutler/calc_job.py @@ -1,25 +1,17 @@ -import sys import argparse import subprocess from pathlib import Path from loguru import logger +from minibutler import config from minibutler.calculators import Calculators, scheduled_jobs, verify_scheduled_jobs # Our own script directory SCRIPT_DIR = Path(__file__).parent.resolve() -# specific to this beamtime and analysis setup -analysis_setup_path_name = "/sf/cristallina/data/p23031/work/analysis_beamtime" -if analysis_setup_path_name not in sys.path: - sys.path.append(analysis_setup_path_name) - -try: - import setup.roi_peaks as rois_module -except ImportError as e: - logger.error(f"Could not import ROI definitions: {e}") - rois_module = None +# ROI definitions, imported in main() once the pgroup and thereby the analysis setup path is known +rois_module = None # Collect all ROIs defined in the rois_module # This assumes that the ROIs are defined as instances of cr.utils.ROI @@ -51,32 +43,30 @@ def submit_calc_job(func_name: str, run_numbers: list, roi_names: list = None) - # Prepare the command to submit the job # Assuming 'calc_script.sh' is the script that runs the calculation - # and it accepts --func, run_number, and roi as arguments. - if roi_names is None: - result = subprocess.run( - ["sbatch", "calc_script.sh", "--func", func_name, "--run", str(run_number)], - capture_output=True, - text=True, - check=False, - cwd=SCRIPT_DIR, - ) - else: - result = subprocess.run( - [ - "sbatch", - "calc_script.sh", - "--func", - func_name, - "--run", - str(run_number), - "--rois", - " ".join(roi_names), - ], - capture_output=True, - text=True, - check=False, - cwd=SCRIPT_DIR, - ) + # and it accepts --pgroup, --func, run_number, and roi as arguments. + # The log path is given here as #SBATCH lines in calc_script.sh cannot use variables. + Path(config.LOG_DIR).mkdir(parents=True, exist_ok=True) + command = [ + "sbatch", + f"--output={config.LOG_DIR}/calc_%j_%N.log", + "calc_script.sh", + "--pgroup", + config.PGROUP, + "--func", + func_name, + "--run", + str(run_number), + ] + if roi_names is not None: + command += ["--rois", " ".join(roi_names)] + + result = subprocess.run( + command, + capture_output=True, + text=True, + check=False, + cwd=SCRIPT_DIR, + ) if result.returncode != 0: logger.error(f"Error submitting job: {result.stderr}") @@ -98,6 +88,12 @@ def main(): parser = argparse.ArgumentParser() + parser.add_argument( + "--pgroup", + default=None, + help="The pgroup of the experiment (e.g. p23102). If not given, it is guessed from the repository location.", + ) + # Add the -f/--func argument: valid choices are function _names_ from calc_funcs parser.add_argument( "-f", @@ -127,6 +123,14 @@ def main(): args = parser.parse_args() + config.set_pgroup(args.pgroup) + + global rois_module + try: + import setup.roi_peaks as rois_module + except ImportError as e: + logger.error(f"Could not import ROI definitions: {e}") + # Resolve the chosen function object using its name: func = calc_funcs[args.func] run = int(args.run) diff --git a/src/minibutler/calc_script.sh b/src/minibutler/calc_script.sh index 83d7301..0b9b85f 100755 --- a/src/minibutler/calc_script.sh +++ b/src/minibutler/calc_script.sh @@ -18,7 +18,7 @@ #SBATCH --cpus-per-task=8 # Number of CPU cores per task #SBATCH --mem-per-cpu=18G #SBATCH --time=00:59:00 # Time limit hrs:min:sec -#SBATCH --output=/sf/cristallina/data/p23102/work/minibutler/logs/calc_%j_%N.log # Standard output and error log +# --output (log file) is passed by calc_job.py as it depends on the pgroup #SBATCH --constraint="cpu_xeon|cpu_epyc9334" # exclude AMD Epyc 7453 nodes due to missing AVX512 for bitshuffle @@ -43,8 +43,8 @@ source /sf/cristallina/applications/conda/envs/miniconda/etc/profile.d/conda.sh conda activate /sf/cristallina/applications/it/envs/analysis-stable -# to our calc script folder (where calc_job.py is located) -cd /sf/cristallina/data/p23102/work/minibutler/src/minibutler +# to our calc script folder (where calc_job.py is located), from where sbatch was called +cd "$SLURM_SUBMIT_DIR" python calc_job.py "$@" diff --git a/src/minibutler/calculators.py b/src/minibutler/calculators.py index d71ae5f..4e63059 100644 --- a/src/minibutler/calculators.py +++ b/src/minibutler/calculators.py @@ -1,4 +1,3 @@ -import sys import time from loguru import logger @@ -14,17 +13,10 @@ except ImportError as e: logger.error(f"Could not import RSM module: {e}") RSM = None +from minibutler import config + jungfrau_utils.verbose = False -# specific to this beamtime and analysis setup -analysis_setup_path_name = "/gfa/.mounts/sf_cristallina/data/p23102/work/" -if analysis_setup_path_name not in sys.path: - sys.path.append(analysis_setup_path_name) - -# BASE_DATA_PATH = "/sf/cristallina/data/p23102/" -# for testing: -BASE_DATA_PATH = "/sf/cristallina/data/p23102/raw/" - class Calculators: """ Class containing methods for calculations that can be called externally. @@ -60,7 +52,7 @@ class Calculators: @staticmethod def calc_1p5M_stacks_fluorescence(run_number, rois=None, preview=False, detector=cr.channels.JF): - scan = cu.scan_info(run_number, use_uscan=True, base_path=BASE_DATA_PATH) + scan = cu.scan_info(run_number, use_uscan=True, base_path=config.RAW_PATH) stacks, IO_norms = cr.analysis.calculate_JF_stacks(scan, lower_cutoff_threshold=5.4, upper_cutoff_threshold=6.85, @@ -71,7 +63,7 @@ class Calculators: @staticmethod def calc_1p5M_stacks_bragg(run_number, rois=None, preview=False, detector=cr.channels.JF): - scan = cu.scan_info(run_number, use_uscan=True, base_path=BASE_DATA_PATH) + scan = cu.scan_info(run_number, use_uscan=True, base_path=config.RAW_PATH) stacks, IO_norms = cr.analysis.calculate_JF_stacks(scan, lower_cutoff_threshold=7.0, exclude_steps=None, @@ -82,7 +74,7 @@ class Calculators: def calc_1p5M_stacksv2(run_number, rois=None, preview=False, detector=cr.channels.JF): while True: - scan = cr.utils.scan_info(run_number, use_uscan=True, base_path=BASE_DATA_PATH) + scan = cr.utils.scan_info(run_number, use_uscan=True, base_path=config.RAW_PATH) if scan.finished: break time.sleep(5) @@ -94,7 +86,7 @@ class Calculators: @staticmethod def calc_8M_stacks(run_number, rois=None, preview=False, detector=cr.channels.JF_8M): - scan = cu.scan_info(run_number, use_uscan=True, base_path=BASE_DATA_PATH) + scan = cu.scan_info(run_number, use_uscan=True, base_path=config.RAW_PATH) stacks, IO_norms = cr.analysis.calculate_JF_stacks( scan, lower_cutoff_threshold=10, exclude_steps=None, recompute=False, detector=detector ) diff --git a/src/minibutler/config.py b/src/minibutler/config.py new file mode 100644 index 0000000..5e57ae1 --- /dev/null +++ b/src/minibutler/config.py @@ -0,0 +1,50 @@ +""" +Single source of truth for the pgroup and all paths derived from it. + +Call set_pgroup() once at program start. Afterwards access the values as +config.PGROUP, config.RAW_PATH, ... (not via `from config import RAW_PATH`, +as that would copy the value before it is set). +""" + +import re +import sys +from pathlib import Path + +import cristallina.utils as cu + +PGROUP = None # e.g. "p23102" +PGROUP_PATH = None # /sf/cristallina/data/p23102 +RAW_PATH = None # /sf/cristallina/data/p23102/raw/ +WORK_PATH = None # /sf/cristallina/data/p23102/work +LOG_DIR = None # /sf/cristallina/data/p23102/work/minibutler/logs +ANALYSIS_SETUP_PATH = None # /sf/cristallina/data/p23102/work/analysis_beamtime + + +def set_pgroup(pgroup: str | None = None) -> str: + """ + Set the pgroup and all derived paths. + + pgroup: e.g. "p23102". If None, it is guessed from the location of this repository, + which is expected to be cloned into the pgroup's work directory. + """ + global PGROUP, PGROUP_PATH, RAW_PATH, WORK_PATH, LOG_DIR, ANALYSIS_SETUP_PATH + + if pgroup is None: + pgroup = "p" + cu.heuristic_extract_pgroup(str(Path(__file__).resolve())) + + if not re.fullmatch(r"p\d{5}", pgroup): + raise ValueError(f"Invalid pgroup '{pgroup}', expected 'p' followed by 5 digits (e.g. p23102).") + + PGROUP = pgroup + PGROUP_PATH = f"/sf/cristallina/data/{PGROUP}" + RAW_PATH = f"{PGROUP_PATH}/raw/" + WORK_PATH = f"{PGROUP_PATH}/work" + LOG_DIR = f"{WORK_PATH}/minibutler/logs" + ANALYSIS_SETUP_PATH = f"{WORK_PATH}/analysis_beamtime" + + # specific to this beamtime and analysis setup + for path in (WORK_PATH, ANALYSIS_SETUP_PATH): + if path not in sys.path: + sys.path.append(path) + + return PGROUP