Metadata-Version: 2.4
Name: ebsd-magus
Version: 2.0.0
Summary: Standalone workflow manager for EBSD simulations
License: MIT
License-File: LICENSE
Keywords: ebsd,workflow,snakemake
Author: Ulrich Kerzel
Author-email: ulrich.kerzel@rwth-aachen.de
Requires-Python: >=3.12,<4.0
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Requires-Dist: ase (>=3.22.1,<4.0.0)
Requires-Dist: gemmi (>=0.7.3,<0.8.0)
Requires-Dist: h5py (>=3.14.0,<4.0.0)
Requires-Dist: jinja2 (>=3.1.6,<4.0.0)
Requires-Dist: matplotlib (>=3.10.6,<4.0.0)
Requires-Dist: numpy (>=2.3.2,<3.0.0)
Requires-Dist: pandas (>=2.3.2,<3.0.0)
Requires-Dist: pyyaml (>=6.0.2,<7.0.0)
Requires-Dist: scikit-image (>=0.24.0,<0.25.0)
Requires-Dist: scipy (>=1.14.1,<2.0.0)
Requires-Dist: seaborn (>=0.13.2,<0.14.0)
Requires-Dist: snakemake (==9.13.7)
Requires-Dist: snakemake-executor-plugin-cluster-generic (==1.0.9)
Requires-Dist: tabulate (>=0.9.0,<0.10.0)
Project-URL: Repository, https://gitlab.git.nrw/rwth-sfb1394/sfb1394/ebsd/ebsdmagus
Description-Content-Type: text/markdown

# EBSDmagus

## Introduction
EBSDmagus orchestrates EMsoft-based EBSD simulations on HPC clusters. EMsoft provides the Monte Carlo and masterpattern solvers; EBSDmagus layers a Snakemake-directed DAG and a lightweight SQLite database on top to manage parameter sweeps, stage dependencies, SLURM submission, recovery, and analytics. Parameter sweeps quickly explode into dozens of jobs with ordering constraints (e.g., masterpattern depends on Monte Carlo outputs). Snakemake resolves these as a DAG, submits cluster-aware jobs, and EBSDmagus validates artifacts (NML/.h5/.done) and summarizes outcomes. The aim is reproducible, large-scale EBSD workflows—generate NMLs, queue jobs with appropriate resources, and track results end-to-end. Licensed under MIT.

For the EBSDmagus method and its supporting research records, see the
[journal article](https://www.sciencedirect.com/science/article/pii/S0927025626007688)
and the [Zenodo deposit](https://doi.org/10.5281/zenodo.22654863).

## Start here

- New to the project: read [Getting started](https://gitlab.git.nrw/rwth-sfb1394/sfb1394/ebsd/ebsdmagus/-/blob/v2.0.0/docs/getting_started.rst) first. It explains the
  Monte Carlo → masterpattern → screen-pattern chain, the role of
  `workflow.db`, and the normal `ebsdm prepare` → `ebsdm check` →
  `ebsdm submit` path.
- Running on a cluster that is not RWTH: read `docs/cluster_setup.rst` before
  submitting. RWTH examples are included as tested references, but partitions,
  accounts, shells, module names, and EMsoft paths are site-specific.
- Something went wrong: read `docs/troubleshooting.rst` before changing job
  statuses. It lists dry-run-first diagnostics, SLURM checks, artifact checks,
  and recovery commands.
- Developing the workflow internals: read `docs/technical_architecture.rst`.
  It explains Jinja templating, workflow generation, database helpers,
  Snakemake/SLURM contracts, artifact verification, and extension points.
- Choosing a workflow config or profile: read `docs/examples.rst`. It
  separates beginner examples, RWTH site examples, DAG demos, benchmark
  recipes, and archived validation fixtures.
- Using only conversion/inspection tools: see `docs/tools.rst`.
- Using the terminal UI: see `docs/gui.rst`.
- Upgrading from v1.3: see the [2.0.0 release notes](https://gitlab.git.nrw/rwth-sfb1394/sfb1394/ebsd/ebsdmagus/-/blob/v2.0.0/docs/release_v2.0.0.md).

Key point: `done` is a workflow state, not a scientific verdict. It means
the runtime checks found the expected outputs. Those checks are cheap and
structural: scheduler and executable status, the `.done` file, the expected
HDF5 paths, readable non-empty HDF5 files and the required datasets for each
stage. They do not judge EBSD signal quality, physical plausibility,
convergence or whether results are ready to publish. That still needs
review by a domain expert.

## Setup

### Requirements

Python ≥3.12,<4.0 and a working EMsoft install (`EMsoftinit` run; `$HOME/.config/EMsoft/EMsoftConfig.json` set with `EMdatapathname`, etc.). Use `EMOpenCLinfo` to pick GPU `platid/devid`.

### EMEBSD input note (`screen_pattern`)

The older EMsoft wiki example (<https://github.com/EMsoft-org/EMsoft/wiki/EBSD-Example>) shows `omega` in `&EBSDdata`, but current `EMEBSD` no longer accepts that key. Do not add `omega` to `sp_template.nml.j2`/screen-pattern inputs, or the run fails with `Cannot match namelist object name omega`.

### Install the CLI

Run `python -m pip install ebsd-magus==2.0.0` in an isolated environment. Use the checkout for the workflow examples and site profiles.

### Install from the checkout

Run `poetry install` (add `--with dev` if you want Sphinx docs).

### Profiles/config

Copy `user_profiles/default.yaml` → `user_profiles/<name>.yaml`, set paths/resources. When a tool passes an explicit config directory, profiles are resolved from that directory first; top-level `user_profiles/` remains a convenience fallback for implicit repo-root runs. The selected profile path is printed to stderr. `paths.repo_root` defaults to `${REPO_ROOT:-$HOME/Repositories/ebsdmagus}`; `paths.template_dir` defaults to packaged templates. Sample workflow configs live under `workflow_configs/`.

### Normal workflow commands

Edit a workflow YAML, then run:
```bash
poetry run ebsdm prepare --config workflow_configs/<run>.yaml --profile <site-or-user>
poetry run ebsdm check --preflight
poetry run ebsdm submit            # preview only
poetry run ebsdm submit --confirm  # submits to SLURM
poetry run ebsdm post-run-check    # read-only report after jobs finish
```
`prepare` reads the project identity from `workflow_config.project_name`,
writes a run-local Snakemake config under
`hpc_runs/<project>/config/snakemake_config.yaml`, and records the active
run in `.ebsdm_active_run.json`. A legacy `--project <project>` argument is
accepted only when it matches the YAML. Later `ebsdm` commands and the TUI
reuse the manifest so routine users do not need to know Snakemake
`--configfile` or cluster-generic adapter details.

### Crystal checks during preparation

`ebsdm prepare` checks every XTAL before it generates jobs. By default, it
stops if a stored coordinate lies outside the unit cell or an XTAL cannot
be read. For off-host staging, `--coordinate-check advisory` can continue
if the unavailable XTAL has no `crystal_references` entry. A known bad
coordinate still stops Prepare. A crystal reference starts a separate
comparison and can lead to a review request. The [Prepare guide](https://gitlab.git.nrw/rwth-sfb1394/sfb1394/ebsd/ebsdmagus/-/blob/v2.0.0/docs/getting_started.rst) explains
how to record a review and lists what the checks do not cover. `cif2xtal`
checks a CIF before it writes the XTAL and reports Accept, Stop or
Investigate. The [crystal review tutorial](https://gitlab.git.nrw/rwth-sfb1394/sfb1394/ebsd/ebsdmagus/-/blob/v2.0.0/docs/crystal_review_tutorial.rst)
walks through an example.

### TUI crystal review

Setup → Prepare runs the same checks and shows
their results before preparing. When Setup offers a review, enter a reason and
a new review file, or select an existing review. Cancel or Escape leaves
the active run unchanged, and Reassess only reads the inputs again. The
attempted campaign stays selected for a retry. A run prepared with a
review is marked as acknowledged, and its findings appear under **Active
crystal evidence (historical)**.

### Environment variables

Do not export `REPO_ROOT`,
`POETRY_ENV_PATH`, `WORKFLOW_PYTHON`, or `PYTHONPATH`. Invoke the wrapper as
`poetry run ebsdm ...`; it derives the current checkout and Poetry
interpreter, replaces stale ambient values for its child processes, and
leaves the parent shell unchanged. Select the cluster profile explicitly
with `prepare --profile <name-or-path>` and set the worker module script as
`paths.emsoft_module_script` in that profile. `USER_PROFILE` and
`EMSOFT_MODULE_SCRIPT` remain compatibility fallbacks for historical or raw
expert commands, not permanent `.zshrc` settings. See
`docs/cluster_setup.rst` for the environment that raw Snakemake commands need.

### Controller preflight before cluster submission

```bash
poetry run ebsdm check --preflight
```
This checks the database and rendered config recorded by `prepare`; it does
not guess a repo-root `workflow.db`. Direct `controller_preflight` and raw
Snakemake commands are retained for expert diagnostics and must name the
exact run paths.
The Snakemake `cluster-generic` worker handoff is version-sensitive; use the
Snakemake and `snakemake-executor-plugin-cluster-generic` versions pinned in
`pyproject.toml`/`poetry.lock` unless you have run the generated-jobscript
dump/replay gate for another version.
On clusters with site-specific shell startup or module initialization, run
controller-side commands through the shell recommended by the site. RWTH
example:
```bash
ssh hpc 'zsh -lic "<command>"'
```
For multi-line scripts sent over stdin on RWTH, keep the same login/module
setup and run the normal wrapper under zsh:
```bash
ssh hpc 'zsh -lic "zsh -s"' <<'REMOTE_SCRIPT'
cd ~/Repositories/ebsdmagus
poetry run ebsdm check --preflight
REMOTE_SCRIPT
```
Do not use plain `ssh hpc 'zsh -s'` for workflow-controller commands on
RWTH. It can bypass login module setup and bind the Poetry environment to
incompatible Python stdlib/library paths; one common symptom is a
`numpy`/`h5py` import crash.
Example RWTH controller module stack before running Snakemake:
```bash
module load GCC/13.3.0 OpenMPI/5.0.3 Python/3.12.3 SQLite/3.45.3 h5py/3.12.1
```
Keep this controller stack separate from `EMSOFT_MODULE_SCRIPT`, which is the
site-specific module/setup script sourced by worker jobs for EMsoft execution.

### Initialize DB (fresh)

```bash
poetry run ebsdm init-db --database workflow.db
```
This step is separate on purpose: `ebsdm prepare` refuses missing, unstamped, or
unusable DB files instead of silently creating a new SQLite database. The
underlying setup script defaults to SQLite `delete` journal mode for
shared/HPC filesystem safety. Use `--journal-mode wal` or
`EBSD_MAGUS_SQLITE_JOURNAL_MODE=wal` only when the DB filesystem has been
validated for SQLite WAL.

## Tests
- Run unit tests with coverage:
  ```bash
  poetry run pytest --cov=ebsd_magus --cov-report=term-missing
  ```

## Usage & Examples

### Console scripts

Run each with `poetry run <cmd>`: `generate-workflow`, `render-config`, `query-jobs`, `list-projects`, `find-jobs`, `explain-job-status`, `reset-failed-jobs`, `update-workflow-status`, `delete-workflow-jobs`, `export-workflow-to-csv`, `check-job-artifacts`, `verify-db`, `chain-validator`.

### Scientific config lint

`generate-workflow` prints warning-level lint for
obvious smoke-test or stage-key foot-guns before NML/DB writes. Add
`--strict-lint` when warnings should fail generation. This is pre-submit
plausibility lint, not artifact validation or proof of scientific quality.

### Tools (conversion/validation/metadata)

- Convert CIF→XTAL: `poetry run cif2xtal --cif tests/data/cif2xtal/YNi2.cif --output /tmp/YNi2.xtal`
- Convert VASP CONTCAR→CIF: `poetry run python -m ebsd_magus.tools.contcar2cif --poscar path/to/CONTCAR --symbols Nb,Ni,O`
- Verify XTAL vs reference h5dump: `poetry run python -m ebsd_magus.tools.verify_xtal_against_reference --xtal /tmp/YNi2.xtal --reference tests/data/cif2xtal/YNi2_h5dump.txt` (add `--allow-ragged-atomdata` if the recorded dump printed AtomData rows in multiple column blocks)
- Verify contcar2cif vs reference CIF: `poetry run python -m ebsd_magus.tools.verify_contcar_against_cif --poscar tests/data/contcar2cif/Mg_LavesPhaseStackingFaults_1.CONTCAR --reference tests/data/contcar2cif/Mg_LavesPhaseStackingFaults_1.cif`
- Extract XTAL metadata JSON, including the embedded per-atom Debye–Waller derivation record: `poetry run python -m ebsd_magus.tools.extract_xtal_metadata --input /tmp/YNi2.xtal --output /tmp/YNi2_meta.json`
  The report includes a stored-coordinate range check. Add
  `--coordinate-check required` to return exit status 2 for failed or
  unverified coordinate checks; advisory diagnostics are the default.
  This checks fractional-coordinate representation, not native multiplicity.
- Compare metadata JSON vs h5dump: `poetry run python -m ebsd_magus.tools.verify_xtal_metadata --json /tmp/YNi2_meta.json --reference tests/data/cif2xtal/YNi2_h5dump.txt` (also supports `--allow-ragged-atomdata`)
- Summarize CIF/XTAL/h5dump triplets: `poetry run python -m ebsd_magus.tools.summarize_cif_xtal_triplets --data-dir tests/data/cif2xtal` (add `--allow-ragged-atomdata` if a recorded h5dump prints AtomData rows split across multiple offsets and you’re OK padding the gaps with NaN).
- See `src/ebsd_magus/tools/README.md` (included in Sphinx docs) for full tool list and Debye–Waller overrides.

### Analytics (visualization/QA)

- Compare masterpatterns and plot diagnostics (diff/relative diff, edge diff, gradient ratio, entropy diff, FFT panels, SSIM map + low-SSIM overlay, hist/scatter, local mean/variance scatter, gradient-orientation histograms plus PSNR/SSIM/ESSIM metrics—see `docs/analysis.rst` for a glossary): `poetry run compare-masterpatterns --reference masterpattern/base.h5 --target masterpattern/bethe_sweep.h5 --output-dir reports/masterpattern --output-prefix yni2_bethe --reference-label "YNi2 8/20/50" --target-label "YNi2 100/100/50"`.

### Normal quick start

For a more beginner-friendly version of this sequence, see
`docs/getting_started.rst`.
1. Install deps (`poetry install`) and set the cluster exports if submitting.
2. Initialize the DB once for a fresh checkout:
   ```bash
   poetry run ebsdm init-db --database workflow.db
   ```
3. Create/adjust profile `user_profiles/<name>.yaml`; set paths/resources.
4. Edit workflow config `workflow_configs/<your_config>.yaml`.
5. Prepare the active run. The project name comes from the central campaign
   YAML:
   ```bash
   poetry run ebsdm prepare --config workflow_configs/<your_config>.yaml
   ```
6. Run read-only checks and a Snakemake dry-run:
   ```bash
   poetry run ebsdm check --preflight
   ```
7. Preview the exact submit command:
   ```bash
   poetry run ebsdm submit
   ```
8. Submit only after the preview is correct:
   ```bash
   poetry run ebsdm submit --confirm
   ```

### Expert/debug path

Use `generate-workflow`, `render-config`, `chain-validator`,
`workflow-controller-preflight`, and raw Snakemake only when you need to
inspect a specific layer. If you run raw Snakemake, pass the run-local
rendered config with `--configfile` and export the same absolute path as
`EBSD_MAGUS_SNAKEMAKE_CONFIG`; otherwise the Snakefile and cluster-generic
submit/status adapters can read different runtime configs. See
`docs/getting_started.rst` and `docs/cluster_setup.rst` for the full command.

### Other examples

```bash
# Verify DB against config (with artifact/NML checks)
poetry run verify-db --config workflow_configs/workflow_config.yaml --db workflow.db --check-artifacts --check-nml

# Update / delete / export jobs
poetry run update-workflow-status --db workflow.db --id 1 --status done
poetry run delete-workflow-jobs --db workflow.db --project MY_PROJ --stage masterpattern
poetry run export-workflow-to-csv --db workflow.db --out logs/jobs.csv

# Preview/reset failed jobs. Mutating resets require a selector or --all-failed.
poetry run reset-failed-jobs --db workflow.db --dry-run
poetry run reset-failed-jobs --db workflow.db --project MY_PROJ --stage monte_carlo
poetry run reset-failed-jobs --db workflow.db --all-failed

# Check artifacts / reconcile; preview first, then rerun without --dry-run
# only after the proposed DB changes match the scheduler and log evidence.
poetry run ebsdm post-run-check --html
poetry run ebsdm preview
poetry run ebsdm post-run-check --html
poetry run check-job-artifacts --project MY_PROJ --status pending submitted running --dry-run --verbose
poetry run reconcile-cluster-state --db workflow.db --project MY_PROJ --repo-root ${REPO_ROOT:-$HOME/Repositories/ebsdmagus} --emsoft-config $HOME/.config/EMsoft/EMsoftConfig.json --dry-run --verbose
```

- `ebsdm post-run-check --html` is the normal read-only first report after a run. `ebsdm preview` renders a small visual sample and a manifest; rerun the report to embed that exact selection. The preview command does not render every branch or orientation by default.
- `reconcile-cluster-state` cross-checks SLURM state vs. workflow.db to detect drift (e.g., jobs stuck/running in SLURM but marked done/failed in DB, or missing `.done`/`.h5`). Use `--dry-run` to review changes and then rerun without it to align DB statuses or clean up SLURM context.

### Find job IDs

To reset or cancel specific jobs, first find their IDs:
```bash
# List IDs with filters (project/stage/status/filename/xtal)
poetry run find-jobs --project MY_PROJ --status todo failed
# Wildcard filename search
poetry run find-jobs --filename-like "%mc0%"
```
Then reset a job back to todo:
```bash
poetry run update-workflow-status --db workflow.db --id <job_id> --status todo
```
`find-jobs` defaults to the configured database if `--db` is omitted.

### Bethe parameter sweeps
For background on excitation errors, strong/weak beam selection, and the physics behind these cutoffs, see `docs/bethe_parameters.md`.
- Masterpattern stages can now generate Bethe parameter NMLs (e.g., safe defaults or per-phase sweeps) directly from the workflow config. Add a `bethe_parameters` block under the `masterpattern` section:
  ```yaml
  masterpattern:
    filename_format: "{xtal}_{stage}_{project}_{dmin}_{npx}_{ekev}_{depthmax}_{mc_copy_id}_{bethe_label}"
    fixed:
      npx: 1000
      dmin: 0.02
      # ...
    bethe_parameters:
      enabled: true
      template: bethe_parameters_template.nml.j2
      filename_format: "{filename}_{bethe_label}_BetheParameters.nml"  # .nml appended if missing
      fixed:
        c1: 40.0
        c2: 50.0
        c3: 50.0
        sgdbdiff: 1.0
      sweep:
        c1: [8.0, 12.0]    # optional sweep keys/values
        c2: [18.0, 22.0]
  ```
- Each Monte Carlo/Masterpattern combination is crossed with every Bethe combo (respecting the block’s `variation_mode`, defaulting to the global mode). For every resulting job the generator:
  1. Renders `bethe_parameters_template.nml.j2` (override via `template`) with the chosen `c1/c2/c3/sgdbdiff`.
  2. Writes the file next to the Masterpattern NML using `filename_format` (available placeholders include any masterpattern params plus `filename`, `bethe_index`, `bethe_count`, `bethe_hash`, `bethe_label`).
  3. Sets `BetheParametersFile` inside the Masterpattern NML to the generated filename and records the sidecar path so Snakemake stages it alongside the main NML.
- When multiple Bethe combos are active, include `bethe_label`, `bethe_index`, or another varying placeholder in the masterpattern `filename_format` to avoid duplicate filenames. If the `bethe_parameters` block is omitted (or `enabled: false`), the workflow keeps the legacy behavior and respects any user-supplied `BetheParametersFile` string.

### Screen-pattern projections in YAML
- `screen_pattern` can now generate the EMsoft angle file directly from YAML so orientations/projections live in the workflow config (single source of truth), similar to Bethe sidecars.
- Add an optional `anglefile_generator` block under `screen_pattern`:
  ```yaml
  screen_pattern:
    fixed:
      anglefile: allEuler.txt  # fallback when generator is disabled
    anglefile_generator:
      enabled: true
      mode: eu                          # 'eu' (Euler triplets) or 'qu' (quaternions)
      filename_format: "{filename}_angles.txt"
      values:
        - [0.0, 20.0, 0.0]
        - [325.85, 89.60, 118.63]
  ```
- When enabled, the generator writes the angle text file next to the screen-pattern NML, sets `anglefile` in the NML to `screen_pattern/<generated-file>`, and records it as an auxiliary sidecar so Snakemake stages it on the compute node with the job NML.
- `values` must be numeric and match `mode`: 3 entries per row for `eu`, 4 entries per row for `qu`.

## Textual TUI (optional)
- Launch the terminal UI: `poetry run ebsdm-tui`.
- First-time setup: `poetry install --with tui` installs the Textual dependency so the TUI console script is available.
- If Textual is not installed, `ebsdm-tui` exits with an install hint instead
  of a raw import traceback. Non-TUI CLI workflows do not require Textual.
- Tabs: Setup (environment/config, DB init, generate workflow, render config), Monitoring/Projects/Jobs (filters for project/stage/status/filename-like), Validation (snakemake dry-run, verify-db, chain-validator, DAG generation), Submit (preview, dry-run execution, confirmed cluster submission), Recovery (check-job-artifacts, reset-failed-jobs, update/delete jobs, reconcile-cluster-state).
- Copy/paste/selection: mouse input stays with your terminal so you can highlight text (or use Ctrl+Shift+C / Ctrl+Shift+V) without needing a special Textual shortcut.
- Notes: job filters are shared across Monitoring/Recovery; check-job-artifacts updates `workflow.db` by default—add `--dry-run` in the UI to preview. Resetting failed jobs uses the active project/stage filters; resetting all failed jobs is only possible in the CLI with `reset-failed-jobs --all-failed`.

## Hints, debugging, further development

### Cluster env & submission stack

- `submit.py` is the single source of `sbatch` flags; the jobscript has no `#SBATCH`.
- Submission now fails fast if `REPO_ROOT`, `POETRY_ENV_PATH`, or `EMSOFT_MODULE_SCRIPT` are missing/invalid, so export them before running Snakemake.
- Run `"$WORKFLOW_PYTHON" -m ebsd_magus.workflow.snakemake_workflow.controller_preflight --db workflow.db` in the same shell before cluster submission to verify controller Python, SQLite, `yaml`, `h5py`, `snakemake`, exported workflow paths, and the read-only workflow DB schema stamp. Use `poetry run workflow-controller-preflight` only when Poetry is known to select this checkout's intended environment. On fresh cluster checkouts, export `PYTHONPATH=$REPO_ROOT/src` unless the pinned environment has this checkout installed editable.
- For non-RWTH clusters, adapt `user_profiles/<name>.yaml` and `EMSOFT_MODULE_SCRIPT` to the local partition/account/GPU/resource syntax and module names; see `docs/cluster_setup.rst`.
- Profile `emsoft_resources.<stage>.runtime` values must use numeric minutes or compact duration syntax such as `5m`, `2h`, or `1d`. Do not use `HH:MM:SS` values such as `00:05:00`; Snakemake rejected that form in RWTH tests.
- Optional live-HPC drift smoke: from a cluster checkout with SLURM tools available, set `EBSD_MAGUS_RUN_HPC_SMOKE=1` and run `"$WORKFLOW_PYTHON" -m pytest -q src/ebsd_magus/workflow/tests/snakemake_workflow/test_live_hpc_smoke.py`. The test is skipped by default, uses the `devel` partition unless `EBSD_MAGUS_HPC_SMOKE_PARTITION` is set, and checks the real Snakemake/SLURM worker handoff without running EMsoft.
- Jobscript is brace-free (`{properties}/{exec_job}` only) to avoid Python `.format` issues.
- `submit.py` exports `REPO_ROOT`, `POETRY_ENV_PATH`, `EMSOFT_MODULE_SCRIPT` to workers via `--export=ALL,...`.
- EM rule sets up modules via `EMSOFT_MODULE_SCRIPT`, logs module/GPU info, captures EM exit code, and only touches `.done` on success.
- **GPU resources are stage-specific:** Monte Carlo (`EMMCOpenCL`) needs GPUs, but Masterpattern (`EMEBSDmaster`) and Screen patterns (`EMEBSD`) are typically CPU-only. Configure `emsoft_resources.masterpattern.gres` / `emsoft_resources.screen_pattern.gres` as empty/omitted so SLURM doesn’t reserve a GPU for those stages.
- If outputs aren’t seen immediately, try `--latency-wait 30`.
- Prereqs enforced: submit waits for upstream stages (mc→mp→screen) to clear before submitting downstream jobs (waits up to ~12h, polling every 30s).

### Logs

SLURM out/err default to `$repo_root/slurm_logs` (or profile `paths.slurm_logs`). Snakemake logs: `.snakemake/log/<timestamp>.snakemake.log`.

### Troubleshooting EM runs

Tail slurm logs; confirm `.h5` (for monte_carlo) and `.done` appear; check module stack/GPU (`nvidia-smi`) in the log. If EM exits non-zero, the rule fails with the captured exit code.

### Resuming after interruption

- You can rerun the same Snakemake command with `--cluster-generic-status-cmd .../status.py`; it will keep existing pending/running jobs, report SLURM completions back to Snakemake, and only submit what’s still todo. A SLURM `COMPLETED` state alone does not mark the workflow DB row `done`: durable `done` is reserved for artifact-validated completion because scheduler success can race or outlive fileserver failures.
- If you intentionally include upstream `done` rows in a resumed/reuse job map, the worker status filter must still include active worker states. Use `SNK_STATUS_FILTER_OVERRIDE=todo,failed,submitted,pending,running,done`; do not use `todo,done`, because that hides the active worker row after submission.
- After a run finishes or after a controller/login-node outage, start with the read-only active-run report: `poetry run ebsdm post-run-check`. For targeted expert triage, use `poetry run workflow-recovery-snapshot --db workflow.db --project <proj> --repo-root "$REPO_ROOT"`. If it reports active SLURM jobs, do not start a duplicate controller.
- To refresh scheduler context before resuming, run `poetry run python src/ebsd_magus/workflow/snakemake_workflow/poll_cluster_jobs.py`. To reconcile artifact-backed completion, run `poetry run check-job-artifacts --db workflow.db --project <proj> --dry-run --verbose` and `poetry run reconcile-cluster-state --db workflow.db --project <proj> --dry-run --verbose`, then rerun the matching command without `--dry-run` only after checking logs.
- To inspect one row without changing state, run `poetry run explain-job-status --db workflow.db --job-hash <hash> --repo-root "$REPO_ROOT"`. It reports DB, scheduler, `.done`, validation sidecar, artifact, and derived explanation fields.
- If a job is stuck but still visible in SLURM, cancel it first (`scancel <id>`). Prefer scoped `reset-failed-jobs` after a terminal failed state; use direct `update-workflow-status` only as an advanced/manual DB operation after exporting or copying `workflow.db`.
- See `docs/troubleshooting.rst` for the recommended recovery steps and the difference between primary recovery tools, setup/migration scripts, and legacy/manual shell helpers.

### How EMsoft jobs run

- Controller shell: run Snakemake from the pinned workflow Python environment after `workflow-controller-preflight` passes. Required exports are `REPO_ROOT`, `POETRY_ENV_PATH`, and `EMSOFT_MODULE_SCRIPT`; `WORKFLOW_PYTHON` is derived from `POETRY_ENV_PATH/bin/python` when unset.
- Submission: `submit.py` owns all `sbatch` flags, validates required exported paths, records SLURM submission context in `workflow.db`, and exports the pinned workflow environment to the worker.
- Worker shell: the live backend remains the rendered jobscript plus `rules/emsoft.smk`. It preserves submitted env values across site shell/module startup, captures the workflow Python `PATH`/`LD_LIBRARY_PATH`, then sources `EMSOFT_MODULE_SCRIPT` for EMsoft binaries. RWTH uses zsh/Lmod; other clusters may use bash or another module setup.
- Inputs: Snakemake stages the job NML and any recorded auxiliary files into the stage directory under `EMdatapathname` from `EMsoftConfig.json`. The EMsoft executable is selected from the DB stage (`EMMCOpenCL`, `EMEBSDmaster`, or `EMEBSD`).
- Optional OpenCL probe: set `emsoft_resources.monte_carlo.opencl_probe: true` in a site profile to run `EMOpenCLinfo` on the worker after modules are loaded and before `EMMCOpenCL`. This is a GPU-stage diagnostic gate only; it is disabled by default and does not run for masterpattern/screen-pattern CPU stages.
- Exit/output rules: a non-zero EMsoft exit fails the rule and must not create `.done`. A zero exit still must pass runtime output validation against the declared DB output reference; missing, zero-byte, unreadable, or required-dataset-missing HDF5 artifacts fail. Legacy root-level master/screen outputs may be copied to the standard stage directory only after validation.
- Sentinel/logging: `.done` is touched only after EMsoft exits `0` and output validation succeeds. EMsoft sentinels live under `$REPO_ROOT/logs/emsoft/<filename>.done`, even when a profile uses a different `paths.log_dir` for housekeeping logs. Worker logs include workflow Python, module/GPU diagnostics, EMsoft command, exit code, and validation result. Recovery tools treat `.done` plus structurally valid HDF5 output as success; scientific quality checks belong to post-run QC, not to the scheduler.

### Docs

From the public checkout run `poetry install --with dev` and
`poetry run make -C docs html`. The build treats warnings as errors.
Read the Docs uses Python 3.12 and installs the checkout plus
`docs/requirements.txt` with pip.

### Development

Keep `sbatch` flags in submit.py, avoid reintroducing `${...}` in templates, and keep `REPO_ROOT`/`POETRY_ENV_PATH`/`EMSOFT_MODULE_SCRIPT` in worker environments.

### Path helpers

Resolve any repo-relative paths via `workflow/utils/pathing.py` (`resolve_path_safe`, `resolve_db_path`, `normalize_repo_placeholder`) to handle `${REPO_ROOT:-...}`, env vars, and relative bases consistently instead of re-implementing resolver logic.

### DB backend abstraction

Keep runtime DB operations backend-agnostic and route backend-specific session setup through `workflow_generator/database/session_init.py`; SQLite bootstrap/migration logic remains in `workflow/setup_workflow_db.sh`. The setup script sets the journal mode and defaults to `delete`; use WAL only on filesystems where it has been tested.

