diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ddef136..253f705 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -6,7 +6,7 @@ on: pull_request: workflow_dispatch: -# Least-privilege default: neither job here needs to write anything. +# Least-privilege default: no job here needs to write anything. permissions: contents: read @@ -19,11 +19,30 @@ defaults: run: shell: bash +# Test matrix: one job per pixi environment x (linux, windows). The +# suites are pytest marker selections (pyproject.toml) bound to pixi tasks +# (pixi.toml): `core` runs the engine-free suites in the default env with the +# core guard on (tests/conftest.py), `gsasii` and `easydiffraction` run their +# engine's suite in its env. Only `topas_exec` is absent: it needs tc.exe and +# stays a manual gate step on the TOPAS machine. Every job is gated to the +# upstream repository: CI runs with the PR to NSLS2/PowderLine, not on +# forks, and each job's command is proven locally first: +# pixi run test · pixi run -e gsasii test-gsasii · pixi run -e easydiffraction test-easydiffraction · pixi run docs +# setup-pixi caches .pixi/envs per lock-file hash and environment; the cache +# is written only on pushes to main so PRs read it and the gsasii env (the +# slow pixi-build one) is built once per lock change. + jobs: - test: - # Run on pull requests, direct pushes to main, and manual dispatch in the upstream repository. + core: + # The no-plugin guarantee: schema layer, registry, CLI, TOPAS input generation, + # without any engine installed or importable. if: github.repository == 'NSLS2/PowderLine' - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 30 steps: - uses: actions/checkout@v4 with: @@ -31,8 +50,57 @@ jobs: - uses: prefix-dev/setup-pixi@a0af7a228712d6121d37aba47adf55c1332c9c2e # v0.9.4 with: pixi-version: v0.83.0 - - name: Run tests + environments: default + cache: true + cache-write: ${{ github.event_name == 'push' && github.ref_name == 'main' }} + - name: Engine-free suites (core + topas_gen, core guard on) run: pixi run test + - name: Generated field tables and support matrix are current + run: pixi run fields-check + + gsasii: + # GSAS-II suite incl. the slow regressions against the committed references. + if: github.repository == 'NSLS2/PowderLine' + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: prefix-dev/setup-pixi@a0af7a228712d6121d37aba47adf55c1332c9c2e # v0.9.4 + with: + pixi-version: v0.83.0 + environments: gsasii + cache: true + cache-write: ${{ github.event_name == 'push' && github.ref_name == 'main' }} + - name: GSAS-II suite + run: pixi run -e gsasii test-gsasii + + easydiffraction: + # easydiffraction suite (native runs and goldens; no GSAS-II in this env). + if: github.repository == 'NSLS2/PowderLine' + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: prefix-dev/setup-pixi@a0af7a228712d6121d37aba47adf55c1332c9c2e # v0.9.4 + with: + pixi-version: v0.83.0 + environments: easydiffraction + cache: true + cache-write: ${{ github.event_name == 'push' && github.ref_name == 'main' }} + - name: easydiffraction suite + run: pixi run -e easydiffraction test-easydiffraction docs: # Build-only check that the docs still compile warning-free diff --git a/.gitignore b/.gitignore index a4ed1cf..8ba4b1f 100644 --- a/.gitignore +++ b/.gitignore @@ -40,4 +40,7 @@ examples/**/output/**/*.bak*.gpx # Stray Fortran scratch files (e.g. GSAS-II fort.NN reflection dumps) fort.* -.vscode/* \ No newline at end of file +.vscode/* + +# Maintainers' local probe scripts (never part of the package or the suite) +probes/ diff --git a/.powderline_config.yaml.example b/.powderline_config.yaml.example index 73a663f..e2ee95e 100644 --- a/.powderline_config.yaml.example +++ b/.powderline_config.yaml.example @@ -1,16 +1,22 @@ # PowderLine Configuration File -# Copy this file to .powderline_config.yaml and add your API keys -# The actual config file (.powderline_config.yaml) is not tracked by git +# Copy this file to .powderline_config.yaml. It is not tracked by git. -# Materials Project API Configuration -materials_project: - api_key: "YOUR_API_KEY_HERE" - # Get your free API key at: https://next-gen.materialsproject.org/api - # Alternatively, set the MP_API_KEY environment variable - # (a real key set here takes precedence over the environment variable) +# ─── TOPAS (topas.* recipes) ──────────────────────────────────────────────── +# A run that executes TOPAS needs both values declared, here or with the CLI's +# --topas-dir / --topas-version: `dir` is the folder holding tc.exe and +# `version` the installed TOPAS version, which must equal the recipe's +# engine_version (TOPAS 6 is the supported version). PowderLine never guesses +# where TOPAS is: with no `dir` it only writes the INP (generate-only). +# Uncomment to use. +# `timeout` stops a tc.exe run after that many seconds (default 3600; 0 = no +# limit), so a TOPAS waiting for input (a licence dialog) cannot hang a run. +# topas: +# dir: "C:/TOPAS6" +# version: 6 +# timeout: 3600 # ─── GSAS-II simulation defaults ───────────────────────────────────────────── -# Simulations (mp-simulate) run through the GSAS-II engine: all parameters +# Simulation recipes built by SimulationRecipeBuilder run through the GSAS-II engine: all parameters # below follow GSAS-II conventions and units. TOPAS is NOT used here — it has # different conventions for polarization, axial divergence, and the # instrumental broadening parameters. @@ -24,8 +30,9 @@ simulation_defaults: instrument_defaults: wavelength: 0.4133 # Angstroms (lambda = 12.398 / E[keV]; 0.4133 A = 30 keV) polarization: 0.99 # GSAS-II 'Polariz.' - zero_shift: 0.0 # degrees 2theta (GSAS-II 'Zero') - axial_divergence: 0.001 # GSAS-II 'SH/L' + zero_shift: 0.0 # centidegrees 2theta (GSAS-II 'Zero') + axial_divergence: 0.002 # GSAS-II 'SH/L'; 0.002 is GSAS-II's own floor + # (smaller values are rejected) # Thompson-Cox-Hastings pseudo-Voigt instrumental broadening # (GSAS-II U, V, W, X, Y, Z; reasonable high-resolution synchrotron values) @@ -41,8 +48,8 @@ simulation_defaults: phase_defaults: scale: 1.0 - # Structural fallbacks — applied ONLY when the structure source (e.g. - # Materials Project, CIF) does not provide a value; a warning is printed + # Structural fallbacks — applied ONLY when the structure source (the + # structure dict given to the builder) does not provide a value; a warning is printed # whenever a fallback is used Uiso: 0.01 # isotropic displacement, Angstrom^2 occupancy: 1.0 # site occupancy fraction diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..26cd373 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,261 @@ +# AGENTS.md — PowderLine + +Guidance for coding agents (and a quick orientation for human contributors). +Tool-specific files (`CLAUDE.md`) only point here. + +Automated powder X-ray diffraction refinement driven from a JSON "recipe". +PowderLine is the application layer over interchangeable refinement engines: +a recipe names **one engine and one workflow** in its `schema_name` +(`gsasii.rietveld`, `gsasii.spf`, `topas.rietveld`, `topas.spf`, +`easydiffraction.rietveld`), is written in that engine's own conventions and +units, and `powderline.run()` / the `powderline` CLI hand it to that engine's +**gateway** and return standardized tables with uniform fit statistics. +Nothing is translated between engines. Example-driven: real refinement cases +drive schema evolution and are the regression references. + +**Authoritative sources for a change:** `docs/policies.md` (versioning, +deliberate changes, frozen code, engine pins, review, "ask, don't +assume"), `docs/SCHEMA_HISTORY.md` (schema facts), `docs/engine-behavior.md` +(what the engines do and PowderLine's policy), `docs/known_issues.md` +(`KI-NN`). Maintainers who work with the private design records (the devkit) +also follow the devkit's own agent guidance. **If a decision is not written down, +stop and ask the maintainer; do not infer it from the code or from another +engine.** + +## Architecture (`src/powderline/`) + +Core (engine-free; `import powderline` imports no engine): +- `__init__.py` — the public API, `__all__`: `run`, `validate`, `ValidationResult`, + `load_recipe_asset`, `support_matrix`, `PowderLineError`, + `GatewayNotInstalledError`, `EngineNotAvailableError`, `EngineVersionError`, + `EngineExecutionError`, `ExecutionBackendError`. +- `api.py` — `validate(recipe)` → `ValidationResult(recipe=, + warnings=[...])` through the gateway's engine-free schema layer; + `run(recipe, output_dir, *, verbose, validate_only, **engine_options)` + dispatches on `schema_name` (`.` → `registry.get(engine)`); + engine options are the gateway's explicit keywords (gsasii `execution_mode`; + topas `topas_dir`, `topas_version`, `topas_timeout`); `allow_unsupported_engine_version` is + refused (test-only, on the gateway's own `run`). +- `kicker.py` — the one CLI: `powderline [--output DIR] + [--validate-only] [--verbose] [--use-server|--no-server] [--server-timeout SECONDS] + [--topas-dir DIR] [--topas-version V] [--topas-timeout SECONDS]` and `powderline --doctor` (`doctor.py`: gateways, + engine versions vs pins, server state; non-zero on a stale install, KI-13); + `pixi run kicker` / `pixi run doctor` run the same `main`. Refuses + templates; an engine flag for another engine's recipe exits 1. +- `registry.py` — gateways from the `powderline.gateways` entry-point group + (lazy `ep.load`), the frozen `Gateway` dataclass (`name`, `capabilities`, + `validate`, `run`), `register_gateway` escape hatch, `check_engine_version`. + Entry points only; no in-code fallback (KI-13). +- `schema_core.py` — core schema **0.1.0**: `CoreRecipe` frame + (`schema_name`, `core_schema_version`, `engine_schema_version`, `metadata` + ≤ 1 MiB, `payload`), `RefinableParameter` `[value, flag]` / + `BoundedRefinableParameter` `[value, flag, min, max]`, `XRDData`, `FitRange`, + `ChebyshevBackground`, the phase block `Phase[P]` (`space_group` canonical + gemmi name, `unit_cell`, `atoms`; every symmetry rule: cell check, special + positions, tie groups and flags, derived values held exactly), `CoreName`, + `collect_warnings`, `parameters_requested`, `fit_limits_on_data`, and the + engine schema building blocks (`EngineRecipe`, `recipe_validator`, + `refined_flags`, `custom_error`/`raise_problems`, `omit_absent`, + `absent_not_null`, `unique_phase_names`, `fit_window`, `fit_range_problems`, + `outside_window_problems`, `refined_flag_problems`, `unit_schema`) every + gateway schema is composed from. Every + model `extra='forbid'`; units in `json_schema_extra={"unit": ...}`. +- `symmetry.py` (gemmi), `compat.py` (declared schema compatibility, + `support_matrix()`), `fitstats.py` (uniform Rwp/Rexp/GoF/χ²_red), `reports.py` + (standardized report writers), `recipes.py`, `exceptions.py` (also + `WARNING_CODES`: every warning code with owner and level, asserted against + `src/` and the engine-behaviour table), + `config_loader.py` (simulation defaults), `_status.py`. +- `results.py` — the run-result envelope (`ENVELOPE_VERSION`, `REASONS`, the + failed/generated envelopes, `raise_if_failed`); `roundtrip.py` — the output + recipe (`output_recipe`, `output_recipe_valid`, `parameter_dispositions`; + tie propagation, KI-04); `doctor.py` — the `--doctor` report (KI-13). + +Gateways (`src/powderline/gateways//`), each a **schema layer** +(`schema.py`: the engine schema 0.1.0 on core 0.1.0, `DECLARATIONS`, +`SCHEMA_NAMES`, `validate_recipe`; imports no engine) plus a **runtime +layer** (`gateway.py` factory `get_gateway()` with `capabilities()`, +`validate()`, `run()`, `ENGINE_VERSION_SPEC`, `ENV`/`INSTALL_COMMAND`; engine +imported lazily from `run()`): +- `gsasii/` (GSAS-II `==5.7.9`, env `gsasii`): the **frozen** setup/execution + code `helpers.py`, `project.py`, `setters.py`, `executors.py`, + `extractors.py`, `constraints.py` (moved verbatim from `kicker.py` at the + verified baseline `daace24`; code-hashed); non-frozen `routing.py`, `fit_report.py` + (uniform statistics, `engine_details`, convergence, divergence = failure), + `sites.py` (GSAS-II's reading of each site vs core's), `report_rows.py`, + `paths.py` (GSAS-II parameter names → recipe paths for the output recipe), + `console.py` (the engine's console tail into a failed envelope, KI-05), + `scattering.py` (GSAS-II's ion table, `La3+` → `La+3`); + `server.py` / `client.py` (persistent FastAPI server + `GSASClient`, the + `auto`/`server` execution modes; per-user state dir, token-signed requests + and responses, `POWDERLINE_NO_SERVER=1` disables it — v0.1.2, KI-14; output files travel + back inside the response, no shared filesystem — KI-12); `simulation_builder.py` + (a crystal-structure dict → a `gsasii.rietveld` simulation recipe; the Materials Project + fetch/export tool that used it left PowderLine in 0.2.0; RandomXRD carries its own). +- `topas/` (TOPAS 6; recipes state `engine_version: "6"`, runs need the + installed version declared): `native_writer.py` (model → INP + `.xye`; + limits on data points; `= p/q;` constants), `native_run.py` (run `tc.exe`, + strict file reads, the background-only second run, result), `peak_list.py`, + `runner.py`, `scattering.py` (TOPAS 6's ion table, `La3+` → `occ La+3`). + No Python engine: generate-only + without `tc.exe`. +- `easydiffraction/` (`==0.21.1`, env `easydiffraction`, Python ≥ 3.12): + `native_builder.py`, `native_run.py`, `space_group_table.py`, + `space_group_support.py` (per-calculator verified settings), `scattering.py` + (CrysPy's ion table). + +Docs: `docs/schemas.md`, `docs/fields.md` (generated tables), `docs/input-guidance.md`, +`docs/engine-behavior.md`, `docs/policies.md`, `docs/migration-0.1-to-0.2.md`, +`docs/support-matrix.md`, `docs/cross-engine-comparison.md`, `docs/DEVELOPMENT.md` +("Adding a refinement engine"). Scripts: `scripts/gen_schema_field_tables.py` +(field tables + support matrix → `docs/_generated/`), `scripts/cross_engine_comparison.py`, +`scripts/convert_recipe_026.py` (0.26.0 → `gsasii.*` migration tool; +fixtures `tests/data/convert_026/`), `scripts/update_code_hash.py`. + +## Key commands (pixi) + +Environments: `default` = core only (validate anything, run nothing); +`gsasii`, `easydiffraction`, `all` (both engines), `dev` (all + docs/test +tooling). `pixi install -e `. +- `pixi run kicker --validate-only` — any env; engine-free. +- `pixi run -e gsasii kicker ` — run a `gsasii.*` recipe + (`--use-server`/`--no-server`, `--output DIR`, `--verbose`); + `pixi run -e easydiffraction kicker ` for `easydiffraction.*`; + `pixi run kicker --topas-version 6 [--topas-dir DIR] + [--topas-timeout SECONDS]` for `topas.*` (runs `tc.exe` on Windows; when no + `tc.exe` is found the run is generate-only: the INP and `.xye` are written, + the result has status `generated` and the CLI exits 0). + After `pixi reinstall powderline` the installed command is `powderline …`. +- `pixi run test` — the engine-free suites (`core or topas_gen`, any env); + `pixi run -e gsasii test-gsasii`, `pixi run -e easydiffraction + test-easydiffraction` per engine; `pixi run test-topas` — `topas_gen` + + `topas_exec` (the exec tests run `tc.exe` only when `POWDERLINE_TOPAS_DIR` + and `POWDERLINE_TOPAS_VERSION` are set, on the TOPAS Windows machine; else + they skip); `pixi run test-all` — everything (`dev`). +- `pixi run -e gsasii gsas-server start|status|stop|restart|logs` — the + persistent GSAS-II server (task in the `gsasii` feature; without `-e` pixi + reports it ambiguous). +- `pixi run docs` / `pixi run docs-clean` — Sphinx HTML with `-W` (zero warnings). +- `PYTHONPATH=src python scripts/gen_schema_field_tables.py [--check]` — after + editing a schema module or a gateway's declarations (regenerates + `docs/_generated/fields_*.md`, `support_matrix.md`); `pixi run fields-check` + runs the `--check` form (fails when the committed fragments are stale). +- `pixi reinstall powderline --all` — after editing `[project.entry-points]` + or `[project.scripts]` in `pyproject.toml`: entry-point metadata is written + at install time, per env; the registry finds nothing until the editable + package is re-installed (KI-13). +- `pixi run update-code-hash` — regenerate `src/powderline/_code_hash.json` + after a **signed** edit to a frozen gsasii module (guarded by `tests/test_code_hash.py`). + +## Frozen GSAS-II code (the rule stays) + +`src/powderline/gateways/gsasii/{helpers,project,setters,executors,extractors,constraints}.py` +are **move-only**: they do GSAS-II's project-dictionary work exactly as the +pre-refactor code did. Never change what they do to the GSAS-II project dict. +Additive or input-side edits — and output-side control flow that leaves the +project-dictionary work untouched (the failure propagation, the checks +before any result table is written) — go **only** through the maintainers' +signed-off record of frozen-code edits, each entry with its proof, then +`pixi run update-code-hash`. An agent never makes such an edit on its own: +propose it to the maintainer. New behaviour goes in +the non-frozen modules (`fit_report.py`, `sites.py`, `routing.py`, +`gateway.py`). Restart the GSAS-II server after any edit it runs (the client +compares the server's source-tree hash with its own and refuses a stale one). + +## Engines / environment notes + +- `GSAS-II` is built as a **conda package via `pixi-build`** from the + `tacaswell/GSAS-II@enh/pixi_pkg` fork (pinned to a commit in `pixi.toml`, + feature `gsasii`); it resolves to **v5.7.9**, which the gateway's + `ENGINE_VERSION_SPEC` checks at run time. easydiffraction is pinned + `==0.21.1`; gemmi `==0.7.5` (the canonical space-group names depend on it). + Moving a pin is a deliberate change with a compatibility run + (`docs/policies.md`): GSAS-II (or scipy/BLAS) changes shift refined values + at the last digit, so `refined_parameters.csv` and the unit-cell reports are + compared within tolerance (`docs/regression-tolerance.md`; + `tests/subprocess_utils.py` `refined_params_match` / `unit_cell_match`) and + peak lists by row count. TOPAS and easydiffraction goldens live under + `tests/data/{topas,easydiffraction}/native/golden/` (TOPAS's by version, + `golden/6/`); TOPAS runs only in the `topas_exec` tests on the TOPAS machine + (goldens from the TOPAS machine). +- The schema layer of every gateway, `powderline.api` and `powderline.kicker` + import no engine — enforced by subprocess tests that block the engine + imports. Keep it that way: engine imports live inside `run()`-time code. +- Platforms: `linux-64`, `win-64`, `osx-arm64`. **All functionality must work + on Linux and Windows** (sole exception: TOPAS *execution* needs `tc.exe` on + win-64). Avoid Unix-only shell syntax in pixi tasks — tasks set `PYTHONPATH` + through the task-level `env` dict; see `docs/cross-platform-guide.md`. +- **Testing caveat**: some `test_esd_extraction` / `test_example_*_regression` + cases require a working GSAS-II refinement; they can fail for environment + reasons unrelated to a given change. Compare against the baseline rather + than assuming a failure is new. + +## Conventions + +- Parameters are lists: `[value, refine_flag]` in `gsasii.*`, + `[value, refine_flag, min, max]` in `topas.*` and `easydiffraction.*`; the + flag is a JSON boolean; `null` bounds mean open. Blocks that may be left out + are left out, never `null`; unknown keys are errors. +- **Validation never changes a recipe beyond its stated tolerance, and never + silently**: anything an engine would silently alter is a validation error + naming the value to write; a value stated within tolerance of its exact + symmetry-derived form is *held* in that form and reported + (`symmetry_value_derived`, level `info`); documented defaults (gsasii + size/strain 10 µm / 0, background none, 5 cycles) and informative findings + are structured warnings `{code, message, field_path[, level]}` (`level` is + `"warning"` when absent, or `"info"`). +- Space groups are gemmi's canonical names (`"P m -3 m"`, `"F d -3 m:2"`); + every member of a symmetry tie group is stated, with the same flag. +- Results: uniform `rwp`/`r_exp`/`gof`/`chi2_red` from core `fitstats` over the + window's weighted points; the engine's own values and + `parameters_requested`/`parameters_varied` under `engine_details`; every + result carries `status` (`ok` / `generated`), `converged`, `output_recipe` + + `output_recipe_valid` + `parameter_dispositions` (KI-04: the resolved + recipe with refined values written back, built by `powderline.roundtrip`) and + `envelope_version` (no `success` key: `status` is the outcome); **every failure + raises**: `EngineExecutionError` (the engine ran and failed) or + `ExecutionBackendError` (it did not run), with `.reason` from + `powderline.results.REASONS` and `.result` the failed envelope (the + GSAS-II server speaks the same envelope). +- Output uses fixed filenames (`refined_parameters.csv`, + `_unit_cell_report.csv`, `_peak_list_report.csv`, + `fit_profile.txt`, `output_recipe.json`, `parameter_dispositions.csv`; + gsasii `dummy.gpx`/`dummy.lst`; topas `.inp` etc.). + `unit_cell_data`/`peak_list_data` from `run()` are dicts keyed by phase name. + `powderline.run()` removes PowderLine's own fixed-name files from the output + directory before every run (`reports.clear_fixed_outputs`) — only once the + recipe has validated and the engine is importable, so a typo or a wrong + environment costs nothing — and, when a run fails, writes the failed envelope + to `failure.json` beside the engine's own files; no result table is written + for a failed run on any engine. +- Known, deliberately-deferred behaviours are registered with stable `KI-NN` + ids in `docs/known_issues.md` — check it before "fixing" a quirk; engine + quirks and PowderLine's policy are on `docs/engine-behavior.md`. +- Every intentional behaviour change is a deliberate change (recorded, + reviewed, in the CHANGELOG); regression references under + `examples/**/output/` **are** tracked and move only with an equivalence + record — do not gitignore or regenerate them casually. +- Don't commit secrets: `.powderline_config.yaml` is gitignored. +- `_dev/` is a reserved, gitignored path (the maintainers' private design + records). Never `git add` it or anything under it. +- Never commit TOPAS's own files (console text, `tc.log`, `TOPAS.INC`, + `ATMSCAT.CPP`): they are licensed with TOPAS. + +## Working rules for coding agents (NSLS-II) + +PowderLine follows the NSLS-II policy for AI coding assistants: + +- A human is responsible for every change, reviews every line, and confirms + that the tests passed. AI output gets no shortcut through review. +- Agents work on a feature branch, commit **unsigned** if they commit at all, + and **never** sign, push, tag, force-push or rewrite published history; the + maintainer signs and pushes. +- Commit messages follow Conventional Commits and end with one trailer line + per model that contributed: `Assisted-by: :` (e.g. + `Assisted-by: claude-code:claude-opus-5-5`). Never `Co-authored-by` for + an AI, never `Signed-off-by` on a human's behalf. +- Never put secrets, tokens or credentials in the repository or in a + prompt; `.powderline_config.yaml` is gitignored for that reason. +- Re-run every reported test count yourself before stating it, and compare + against the baseline rather than assuming a failure is new. +- Before calling documentation complete, grep for the old wording. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..416486b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,279 @@ +# Changelog + +All notable changes to the PowderLine **package** are recorded here. The format +follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and PowderLine +versions follow [Semantic Versioning](https://semver.org/). + +The recipe **schemas** are versioned separately from the package and have their +own history, [`docs/SCHEMA_HISTORY.md`](docs/SCHEMA_HISTORY.md). + +## [Unreleased] + +## [0.2.0] - 2026-11-04 + +PowderLine 0.2.0 is a clean break from the unified recipe schema 0.26.0: a +recipe names one engine and is written in that engine's own conventions, and +nothing is translated between engines. Recipes written for 0.1.x do not +validate; see the [migration guide](docs/migration-0.1-to-0.2.md). Known +limitations are listed in the [known-issues register](docs/known_issues.md). + +### Highlights + +- **One recipe, one engine:** `gsasii.*`, `topas.*` and `easydiffraction.*` + recipes, each in its engine's own names and units, through one API and one CLI. +- **New schemas, starting at 0.1.0:** a core schema plus one schema per engine + replace the single 0.1–0.26.0 schema ([schemas](docs/schemas.md)). +- **Validation states what the engine computes:** symmetry, engine floors and + silent defaults become errors or structured warnings, never silent changes. +- **Uniform fit statistics:** `rwp`, `r_exp`, `gof`, `chi2_red` are computed by + PowderLine over the fit window, the same way for every engine. +- **The output recipe:** every result carries the recipe with refined values + written back, ready to validate and run again (KI-04). +- **Ionic scattering types and March–Dollase preferred orientation**, and every + failure raises an exception with a reason and a `failure.json` record. + +### Upgrading + +- Read the [migration guide](docs/migration-0.1-to-0.2.md): a 0.26.0 recipe + (`GSASII_Rietveld` / `GSASII_SPF`) is refused at `schema_name`. +- Convert gsasii recipes with `python scripts/convert_recipe_026.py IN.json -o + OUT.json`; it reports every change and stops where 0.1.1's refinement cannot + be stated. TOPAS and easydiffraction recipes are written natively. +- API and CLI: `run()` has no `engine=`; failures raise instead of returning + `success: False`; results have `status`, not `success` / `error`; `topas-kicker` + is gone (use `powderline`); engine modules moved under `powderline.gateways`. +- Environments: the default pixi environment is core-only; install an engine + with `pixi install -e gsasii`, `-e easydiffraction` (was `easydiff`), `-e all` + or `-e dev`, then run `pixi reinstall powderline --all` and `powderline --doctor`. +- `rwp` is now PowderLine's uniform Rwp over the fit window, not the engine's + own value (GSAS-II's wR is under `engine_details`); compare old values with care. + +### Added + +- Engine schemas `gsasii.rietveld` / `gsasii.spf` (GSAS-II 5.7.9), + `topas.rietveld` / `topas.spf` (TOPAS 6) and `easydiffraction.rietveld` + (easydiffraction 0.21.1), on a shared core phase block ([fields](docs/fields.md)). +- Declared schema compatibility: each gateway states the core and engine schema + versions it accepts, `validate()` enforces them, and `powderline.support_matrix()` + lists them ([support matrix](docs/support-matrix.md)). +- `powderline.validate()`, engine-free, returning `ValidationResult(recipe, + warnings)`; an invalid recipe raises pydantic's `ValidationError` listing every + problem at its field path. +- Structured warnings `{code, message, field_path, level}` in validation output + and results (`level` `"warning"` or `"info"`); info `symmetry_value_derived` + records a value held in its exact symmetry-derived form. +- The output recipe (KI-04): `output_recipe`, `output_recipe_valid` and + `parameter_dispositions` in every result and validate-only summary, written to + `output_recipe.json` and `parameter_dispositions.csv`. +- `metadata.powderline_provenance` in the output recipe and `failure.json`, + naming the PowderLine version, the engine and its version; gsasii + `engine_details` gains `engine_version`. +- `powderline.recipes.block` / `with_block` move core blocks (`xrd_data`, + `fit_range`, a phase) between recipes, e.g. to chain a sequential refinement. +- A `gsasii.spf` result carries `peak_fit`: every parameter the peak fit varied, + with value and ESD, by GSAS-II's own name. +- Ionic `scattering_types` (CIF spelling, e.g. `La3+`) per atom label in the + gsasii and easydiffraction (`cryspy`) phase blocks, checked against each + engine's ion table ([input guidance](docs/input-guidance.md); EB-94–EB-96). +- March–Dollase `preferred_orientation` (`hkl`, `ratio`) in the gsasii and + easydiffraction (`cryspy`) phase blocks (EB-97, EB-98). +- TOPAS accepts ionic `scattering_types` (TOPAS 6's table, 113 ions, written as + `La+3` in `occ`) and March–Dollase `preferred_orientation` (the `PO` macro; + TOPAS's default lower limit on r, 0.0001). +- `powderline --doctor` (`pixi run doctor`): gateways found, engine versions + against their pins and the GSAS-II server's state; non-zero exit on a stale + install (KI-13). +- A failed run writes its failure envelope to `failure.json` in the output + directory, and a failed `gsasii.*` run carries GSAS-II's console tail (KI-05). +- TOPAS time limit: `--topas-timeout SECONDS`, config `topas.timeout` or the + `topas_timeout` option (default 3600 s per `tc.exe` run, 0 = none); past it + `tc.exe` is stopped and the run raises `ExecutionBackendError(reason="timeout")`. + The second run that only evaluates the background (`y_bkg`) does not fail a + finished fit: stopped at the limit, it leaves the column empty with + `topas_background_not_calculated`. +- `scripts/convert_recipe_026.py`, the 0.26.0 → `gsasii.*` converter. +- Examples: per-engine recipes under `examples//{topas,easydiffraction}/`, + `example_LaB6_temperature_series` (sequential refinement), `example_LaB6_ionic` + and `example_LaB6_textured`, with easydiffraction references. +- Documentation: [schemas](docs/schemas.md), [fields](docs/fields.md), [input + guidance](docs/input-guidance.md), [engine behaviour](docs/engine-behavior.md), + [cross-engine comparison](docs/cross-engine-comparison.md), [policies](docs/policies.md). +- Engine citations in `CITATION.cff` and on the [citing page](docs/citing.md) (#12). + +### Changed + +- The recipe schema is split: the single 0.1–0.26.0 schema is replaced by a + core schema and one schema per engine, each starting at **0.1.0** and told + apart by `schema_name`; the 0.x bump rule is in [policies](docs/policies.md). +- A recipe names its engine and workflow in `schema_name` (`.`) + and states that engine's own terms and units; unknown keys are errors at + every level. +- The public API is `run`, `validate`, `ValidationResult`, `load_recipe_asset`, + `support_matrix` and the exceptions; `run()` dispatches on `schema_name` and + takes engine options as keywords; `import powderline` imports no engine. +- One CLI, `powderline `, installed with the package, serves every + schema (`--output`, `--validate-only`, `--verbose`, `--use-server` / `--no-server`, + `--topas-dir`, `--topas-version`, `--topas-timeout`); `--validate-only` writes nothing. +- Every failure raises `EngineExecutionError` (the engine ran and failed) or + `ExecutionBackendError` (it did not run), with `.reason` and `.result`, the + failed envelope; the exceptions pickle. +- Every result carries `status` (`ok`, or `generated` for a TOPAS run without + `tc.exe`), `converged`, `simulation_mode` and `envelope_version`; a statistic + without degrees of freedom is `None`, never NaN. +- `rwp`, `r_exp`, `gof` and `chi2_red` are PowderLine's uniform statistics over + the weighted points of the fit window; the engine's own values move to + `engine_details` (LaB6: 6.5345 vs GSAS-II 6.5346). +- The fit window is exactly min ≤ 2θ ≤ max on the data points; a window with no + weighted point is an error. A converted gsasii recipe fits one point fewer when + its maximum falls between data points (EB-54). +- gsasii defaults are stated and warned about: size/strain left out means + 10 µm / 0 microstrain (was GSAS-II's 1 µm / 1000), background left out means + none (was 1.0), and refinement cycles left out mean 5, each with a warning. +- New gsasii validation errors where GSAS-II used a floor silently or failed at + run time: SH/L < 0.002, background or Peak List peaks below the floors, `scale` + < 0, wavelength or size ≤ 0, and more (EB-35, EB-37, EB-38, EB-53). +- Space groups are gemmi's canonical names (`"P m -3 m"`, `"F d -3 m:2"`); gsasii + refuses origin choice 1 and the settings GSAS-II cannot express (EB-03, EB-41). +- Refine flags and values must match the symmetry: a tie group is stated whole + with one flag, a symmetry-fixed parameter is not refined, and a stated + multiplicity must equal the derived one. +- A `topas.*` recipe whose total TCHZ peak width is not positive somewhere in + the fit window is a validation error (TOPAS writes no results there); a + negative Lorentzian part X·tanθ + Y/cosθ with a positive total width runs as + written. +- A `gsasii.*` refinement that GSAS-II aborted (no step lowered χ²) raises a + `diverged` failure instead of returning its rejected pattern (EB-99). +- A failed run leaves only the engine's own files and `failure.json`: a gsasii + run no longer writes result tables before PowderLine's checks. +- `powderline.run()` removes PowderLine's own fixed-name outputs from the output + directory before every run, so a reused directory holds one run's results; + only once the recipe has validated and the engine is importable, so an + invalid recipe or a run in an environment without the engine leaves the + previous results in place. +- Every engine writes the same seven unit-cell report rows, `cell_a` … + `cell_gamma`, `cell_volume`; a gsasii simulation writes ESD `0.0` (was empty). +- The GSAS-II server needs no shared filesystem: output files come back inside + the signed response (KI-12); it runs one job at a time and a stale server is + detected and refused. Waiting for its answer has no time limit by default + (as in-process); `--server-timeout SECONDS` / the `server_timeout` option set + one (past it `ExecutionBackendError` `timeout`, no in-process fallback). +- TOPAS runs only from a declared directory (`--topas-dir` or `topas.dir`); + without one a run writes the INP and data and stops (`status: generated`). + `topas.*` recipes state `engine_version: "6"` and the installed version is + declared the same way (`"6"`, not `"6.0"`); TOPAS 7 is not supported. +- TOPAS execution is verified on TOPAS 6: the reference fixtures are reproduced + byte for byte (KI-16). +- easydiffraction recipes state the calculator (`cryspy` or `crysfml`) and the + engine's own instrument terms; anisotropic ADPs work with CrysPy (EB-23). +- Modules moved, without shims: `powderline.topas` → `powderline.gateways.topas`, + `powderline.easydiff` → `powderline.gateways.easydiffraction`; `powderline.symmetry` + raises `SymmetryError`. +- pixi environments: the default is core-only; engines live in `gsasii`, + `easydiffraction`, `all` and `dev`; a run in an environment without its engine + raises `EngineNotAvailableError` naming the install command. +- Pins: GSAS-II 5.7.9 and easydiffraction 0.21.1, checked at run time + (`EngineVersionError`); gemmi `==0.7.5`; pixi ≥ 0.82.1. +- The regression references under `examples/*/output/` were regenerated once on + the new path and gain `output_recipe.json` and `parameter_dispositions.csv`; + the LaB6 examples drop their undeterminable background peak. +- The simulation recipe builder writes SH/L 0.002 (GSAS-II's floor) and emits a + `gsasii.rietveld` 0.1.0 recipe. + +### Removed + +- The unified 0.26.0 schema and the cross-engine translation layer + (`powderline.schema`, the legacy TOPAS writer and easydiffraction builder). +- From the API: `run(engine=...)`, `RecipeModel`, `validate_simulation_mode_parameters`, + `powderline.engine`, top-level `GSASClient` and the shims `powderline.constraints`, + `powderline.gsas_client`, `powderline.gsas_server`. +- The `topas-kicker` console script and pixi task. +- The result keys `success`, `error` and `traceback`, the reason + `output_not_visible`, and `GSASClient.run_simulation`. +- gsasii fields with no effect: `refinement_algorithm`, the `null` instrument and + phase forms, parameter bounds, `payload.asset_path` and `Iparm2`. +- The Materials Project simulation tool (`mp-simulate`) and its configuration; + the simulation recipe builder stays. +- The `easydiff` pixi environment (now `easydiffraction`) and GSAS-II in the + default environment. +- The TOPAS 7.25 references under `examples/*/output/topas/` and + `example_LaB6_easydiff`. +- The pre-refactor TOPAS helpers (`topas/conversions.py`, `runner.run_topas`, + `RunResult`) and symmetry API (`cell_constraints`, `site_dof`, `adp_dof`, + `check_uij`). +- The unused dependencies `h5py`, `pybaselines` and `xmltodict`. + +### Fixed + +- A gsasii run no longer computes 4× the intensity for some 2-fold sites in R32, + R-3m and R-3c, nor crashes on a site GSAS-II cannot name; both are errors + naming a position to state (EB-40, EB-05). +- A diverged gsasii refinement (non-finite pattern) no longer returns success + with Rwp 100 % and a NaN profile (EB-52). +- easydiffraction: 0.1.1's wrong polarization (p = P, not 1 − P), swapped + Lorentzian X/Y, FCJ S/L and H/L, and 2θ rounded to 4 decimals are gone (EB-72, + EB-75, EB-76). +- The simulation recipe builder counted a site *multiplicity* times and used + origin choice 1 coordinates as origin 2 (EB-03); its grid now includes + `max_2theta`. +- `powderline.symmetry` handles the monoclinic groups Pm, Pc, Cm and Cc in every + setting, and classifies trigonal and hexagonal sites correctly. +- An exception while easydiffraction builds the project is + `EngineExecutionError(reason="engine_crashed")`, like one in the fit. +- A TOPAS `output_missing` failure carries its envelope: the files kept, + `tc_path`, the exit code and any console text. +- A TOPAS output folder outside the Windows ANSI code page is run through the + folder's 8.3 short path (file names kept), or refused with a clear message + before `tc.exe` starts. +- The TOPAS at-limit warning tolerates TOPAS stopping just past a bound or a fit + window edge. +- A timed-out GSAS-II server request is a `timeout` failure and no longer falls + back in-process into the same directory; a bad port, a busy port or a Windows + sharing violation is reported instead of crashing. +- Recipe and `.powderline_config.yaml` files are read as UTF-8; malformed JSON + or YAML is an error naming the file (the CLI says "Cannot read recipe"). + +### Security + +- The GSAS-II server no longer writes into a client-chosen directory; the client + writes returned files by bare name only, size-capped; a request body read + before the signature check is capped at 4 KiB except on `/simulate` (KI-12). +- `pip >= 26.2.2` and refreshed `ca-certificates` / `certifi` after the emSign + CA incident; pixi ≥ 0.82.1 is required. + +## [0.1.2] - 2026-10-10 + +Tagged on `main` after the refactor branch was cut; merged into the 0.2.0 +branch on 2026-10-14 (the server and client live at +`src/powderline/gateways/gsasii/server.py` / `client.py` there; the +known-issue entry is `KI-14` on 0.2.0 because `KI-13` was already taken). + + +### Fixed +- GSAS-II server made per-user and token-authenticated: per-user state + directory, loopback bind on an ephemeral port, bearer token on every route, + `POWDERLINE_NO_SERVER` to disable the server (#10). + +## [0.1.1] - 2026-09-24 + +The pre-refactor baseline; unified recipe schema 0.26.0. + + +### Added +- easydiffraction engine (`engine="easydiffraction"`, optional `easydiff` pixi + environment) with the SH/L → Thompson-Cox-Hastings/FCJ profile mapping (#2). +- Documentation published on GitHub Pages (#4–#7). + +### Fixed +- GSAS-II's refinement failure message is surfaced instead of a silent + no-Rwp result; `run()` normalisation no longer crashes on null tables from + server failure responses (#3). + +## [0.1.0] - 2026-08-17 + +Initial public release. + +[Unreleased]: https://github.com/NSLS2/PowderLine/compare/v0.2.0...HEAD +[0.2.0]: https://github.com/NSLS2/PowderLine/compare/v0.1.2...v0.2.0 +[0.1.2]: https://github.com/NSLS2/PowderLine/compare/v0.1.1...v0.1.2 +[0.1.1]: https://github.com/NSLS2/PowderLine/compare/v0.1.0...v0.1.1 +[0.1.0]: https://github.com/NSLS2/PowderLine/releases/tag/v0.1.0 diff --git a/CITATION.cff b/CITATION.cff index cc4de8c..f5c1f90 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -16,7 +16,8 @@ authors: affiliation: "Brookhaven National Laboratory" license: BSD-3-Clause repository-code: "https://github.com/NSLS2/PowderLine" -version: 0.1.2 +version: 0.2.0 +date-released: "2026-11-04" identifiers: - type: doi value: "10.48550/arXiv.2608.17009" @@ -42,8 +43,10 @@ preferred-citation: - type: doi value: "10.48550/arXiv.2608.17009" description: "arXiv preprint" -# Refinement engines PowderLine drives. Please cite the engine you used in -# addition to PowderLine (see the "Citation" section of README.md). +# The refinement engines PowderLine drives and the libraries its results +# depend on. Please cite the engine you used in addition to PowderLine (see +# the "Citation" section of README.md and docs/citing.md). Versions are the +# ones PowderLine 0.2.0 pins or locks. references: - type: article title: "GSAS-II: the genesis of a modern open-source all purpose crystallography software package" @@ -54,10 +57,12 @@ references: given-names: "Robert B." journal: "Journal of Applied Crystallography" volume: 46 + issue: "2" start: 544 end: 549 year: 2013 doi: "10.1107/S0021889813003531" + notes: "GSAS-II, the engine of the gsasii.* schemas (GSAS-II 5.7.9)." - type: article title: "A scripting interface for GSAS-II" authors: @@ -71,10 +76,12 @@ references: given-names: "Brian H." journal: "Journal of Applied Crystallography" volume: 51 + issue: "4" start: 1244 end: 1250 year: 2018 doi: "10.1107/S1600576718008075" + notes: "GSASIIscriptable, through which PowderLine drives GSAS-II." - type: article title: "TOPAS and TOPAS-Academic: an optimization program integrating computer algebra and crystallographic objects written in C++" authors: @@ -82,13 +89,16 @@ references: given-names: "Alan A." journal: "Journal of Applied Crystallography" volume: 51 + issue: "1" start: 210 end: 218 year: 2018 doi: "10.1107/S1600576718000183" + notes: "TOPAS, the engine of the topas.* schemas (TOPAS 6)." - type: software title: "easydiffraction" - version: "0.20.1" + version: "0.21.1" + date-released: "2026-09-22" authors: - family-names: "Sazonov" given-names: "Andrew" @@ -99,5 +109,59 @@ references: - family-names: "Seth" given-names: "Mridul" year: 2026 - doi: "10.5281/zenodo.21999827" + doi: "10.5281/zenodo.22905049" repository-code: "https://github.com/easyscience/diffraction-lib" + notes: "The engine of the easydiffraction.* schema. The project asks for the version used to be cited; all versions: doi:10.5281/zenodo.16806521." + - type: article + title: "Local magnetic anisotropy by polarized neutron powder diffraction: Application of magnetically induced preferred crystallite orientation" + authors: + - family-names: "Kibalin" + given-names: "Iurii A." + - family-names: "Gukasov" + given-names: "Arsen" + journal: "Physical Review Research" + volume: 1 + issue: "3" + start: "033100" + year: 2019 + doi: "10.1103/PhysRevResearch.1.033100" + notes: "CrysPy's preferred citation. CrysPy (0.13.0 in PowderLine's lock file) is easydiffraction's cryspy calculator." + - type: article + title: "Crystallographic Fortran 90 Modules Library (CrysFML): a simple toolbox for crystallographic computing programs" + authors: + - family-names: "Rodríguez-Carvajal" + given-names: "Juan" + - family-names: "González-Platas" + given-names: "Javier" + journal: "IUCr Commission on Crystallographic Computing Newsletter" + issue: "1" + start: 50 + end: 58 + year: 2003 + url: "https://www.iucr.org/resources/commissions/computing/newsletters/1/crysfml" + notes: "The publication by which the CrysFML library is cited in the literature (CrysFML2008 is its Fortran 2008 successor). Cite it with the entry below when the recipe names the crysfml calculator." + - type: software + title: "CrysFML2008 (Python package crysfml)" + version: "0.8.0" + authors: + - family-names: "Rodríguez-Carvajal" + given-names: "Juan" + - family-names: "González-Platas" + given-names: "Javier" + - family-names: "Ayape Katcho" + given-names: "Nebil" + repository-code: "https://code.ill.fr/scientific-software/CrysFML2008" + url: "https://github.com/easyscience/deps-pycrysfml" + notes: "The crystallographic Fortran library behind easydiffraction's crysfml calculator; version 0.8.0 of the Python package in PowderLine's lock file." + - type: article + title: "GEMMI: A library for structural biology" + authors: + - family-names: "Wojdyr" + given-names: "Marcin" + journal: "Journal of Open Source Software" + volume: 7 + issue: "73" + start: 4200 + year: 2022 + doi: "10.21105/joss.04200" + notes: "gemmi 0.7.5 supplies the canonical space-group names and symmetry operations every PowderLine recipe is checked against." diff --git a/CLAUDE.md b/CLAUDE.md index 3874fe4..3fc4066 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,133 +1,6 @@ -# CLAUDE.md — PowderLine +# CLAUDE.md -Automated powder X-ray diffraction refinement driven from a JSON "recipe". PowderLine -is the application layer over interchangeable refinement engines: a recipe (schema -**0.26.0**) describes the refinement, and `powderline.run()` drives GSAS-II by default — -or TOPAS / easydiffraction via `engine=` — and returns standardized tables. -Example-driven: real refinement cases drive schema evolution. +The guidance for coding agents in this repository is in `AGENTS.md` (tool-neutral); Claude Code reads it +through the import below. Edit `AGENTS.md`, not this file. -## Architecture (`src/powderline/`) - -Core engine: -- `kicker.py` — the refinement engine: recipe loading/validation, GSAS-II project setup, - all parameter setters, execution, and output extraction. Intentionally monolithic. -- `schema.py` — Pydantic models; `EXPECTED_SCHEMA_VERSION = "0.26.0"`, - `schema_name ∈ {GSASII_Rietveld, GSASII_SPF}`. Schema changelog: `docs/SCHEMA_HISTORY.md`. -- `constraints.py` — per-parameter refine-flag → GSAS-II lumped-flag / Hold-constraint - translation (the schema-0.26 refine-semantics); imported by `kicker.py`. -- `gsas_server.py` / `gsas_client.py` — persistent FastAPI server keeping GSAS-II in memory + - HTTP client with in-process subprocess fallback (backends for `run()` `server`/`auto` modes). -- `config_loader.py`, `mp_interface.py`, `mp_simulate.py`, `simulation_builder.py`, - `pattern_exporter.py` — Materials Project simulation pipeline (`pixi run mp-simulate`). - -TOPAS v7 INP generation (`src/powderline/topas/`, **imports zero GSAS-II**): -- `conversions.py` — pure unit math + TOPAS equation-string builders. -- `symmetry.py` — gemmi-backed cell rules + site-symmetry DOF analysis. -- `writer.py` — recipe → `.inp` + `.xye` (`render_topas` pure; `write_topas_inp` - does I/O). Handles `GSASII_Rietveld` (incl. `Uaniso` u11..u23) and `GSASII_SPF` - (single-peak fitting). **Permissive**: TOPAS does not arbitrate recipe - correctness, so symmetry-breaking refine flags **warn + emit**, never raise; - hard errors are reserved for untranslatable input (unknown schema/space group, - rhombohedral `:R`, SPF `use_instrument_profile`). Emits a structured - `_results.csv` `out` block + a `param_index` for the round-trip. - `errors.py` holds `TopasTranslationError`. -- `roundtrip.py` — parse TOPAS `_results.csv` (single source; no `.OUT` - fallback) → standardized `refined_parameters.csv` + `_unit_cell_report.csv` - + `fit_profile.txt` + `_peak_list_report.csv` (GSAS-II schema). -- `runner.py` — discover `tc.exe` (`--topas-dir`/`--topas-version`/config) and run - it with an injectable subprocess (Windows-only execution, Linux-testable). -- `kicker.py` — end-to-end CLI: `pixi run topas-kicker ` generates - INP+xye, runs TOPAS if found, and parses results into standardized tables; - degrades to generate-only when tc.exe is absent. Flags: `--output DIR`, - `--run`/`--no-run`, `--topas-dir`/`--topas-version`, `--validate-only`, - `--parse-results `. -- `engine.py` (TOPAS adapter) + `src/powderline/engine.py` (dispatcher) — power - `powderline.run(recipe, output_dir, engine="gsasii"|"topas"|"easydiffraction")`. - `engine="topas"` returns the same result dict as GSAS-II (plus - `rwp`/`r_exp`/`gof`) and imports no GSAS-II; `engine="gsasii"` (default) is a - transparent pass-through to the GSAS-II `kicker.run` (imported lazily). - -easydiffraction engine (`src/powderline/easydiff/`, **imports zero GSAS-II**; -requires the optional `easydiff` pixi environment — easydiffraction needs -Python ≥3.12): -- `conversions.py` — GSAS-II↔easydiffraction unit/convention math (U/V/W σ² - centideg² ↔ Caglioti FWHM² deg², X/Y/Zero centideg↔deg, Rwp fraction↔percent, - lowercase datablock slugs, fit-range/weight masking). -- `policy.py` — the pre-flight "honesty rule": fixed-unmappable recipe features - are dropped with a recorded warning; anything *flagged for refinement* that - can't be represented raises `errors.EasyDiffractionTranslationError`. Also - validates space groups via `topas.symmetry.cell_constraints`. Powers - `validate_only` with **no easydiffraction import**. -- `builder.py` — recipe dict → easydiffraction `Project` + a manifest mapping - every freed parameter back to GSAS-II naming/units (`scale_to_recipe`); cell - symmetry enforced via gemmi `cell_constraints` (library does NOT police it). -- `engine.py` — adapter: build → lmfit fit (or `calculate()` for simulation) → - same standardized result dict + report files as the other engines. v1 refines - cell/scale/wavelength/Chebyshev-background/U-V-W-X-Y/zero; atom-level flags, - Kα doublets, refined Z/polarization/axial-divergence/background-peaks and SPF - are rejected loudly. Nonzero SH/L auto-selects the TCH profile with fixed FCJ - asymmetry (CrysFML calculator; hkl lists harvested post-fit via CrysPy). Rwp is - still NOT comparable to GSAS-II (no background peaks; profile details differ): - LaB6 9.63% vs 6.01% (head-to-head demo lives in the private PowderLine-devkit, - `dossiers/easydiffraction/example_engine_comparison/`). - -The 6-name public API is in `src/powderline/__init__.py` `__all__`: -`run`, `validate`, `load_recipe_asset`, `validate_simulation_mode_parameters`, -`RecipeModel`, `GSASClient`. - -## Key commands (pixi) - -- `pixi run kicker ` — run a refinement (`--validate-only`, `--verbose`, - `--output DIR`, `--use-server`/`--no-server`). -- `pixi run topas-kicker ` — generate a TOPAS v7 `.inp` + `.xye` - (`--output DIR`, `--validate-only`, `--verbose`); no GSAS-II required. -- `pixi install -e easydiff` then `pixi run -e easydiff python ...` — the - optional easydiffraction environment (Python ≥3.12 + easydiffraction + GSAS-II; - the default env is untouched). The GSAS-II-vs-easydiffraction head-to-head demo - is a dev artifact and lives in the private PowderLine-devkit - (`dossiers/easydiffraction/example_engine_comparison/`). -- `pixi run test` — full pytest suite (run from the repo root). -- `pixi run gsas-server start|status|stop|restart` — manage the persistent GSAS-II server. -- `pixi run mp-simulate --material-id mp-2680` — simulate a pattern from - Materials Project (`--formula`, `--wavelength`, `--no-server`, `--keep-recipe`). -- `pixi run docs` / `pixi run docs-clean` — build / clean the Sphinx HTML docs. -- `pixi run update-code-hash` — regenerate `src/powderline/_code_hash.json` after - editing `kicker.py` (guarded by `tests/test_code_hash.py`). - -## GSAS-II / environment notes - -- `gsas-ii` is built as a **conda package via `pixi-build`** from the - `tacaswell/GSAS-II@enh/pixi_pkg` fork (adds the conda recipe); it currently - resolves to **v5.7.9** and installs on all platforms. Don't bump the rev - casually: GSAS-II (or scipy/BLAS) changes can shift refinement results, so - re-run the regression suite when you do. Because exact refined values drift - at the last digit across builds/OSes, `refined_parameters.csv` and the - unit-cell reports are compared within tolerance (see - `docs/regression-tolerance.md`; `tests/subprocess_utils.py` - `refined_params_match` / `unit_cell_match`), and peak lists by row count. - The TOPAS path imports zero GSAS-II even where GSAS-II is installed — that - guarantee is enforced by subprocess tests that block the `GSASII` import. -- Platforms: `linux-64`, `win-64`, `osx-arm64`. **All functionality must work - on Linux and Windows** (sole exception: TOPAS *execution* needs `tc.exe` on - win-64; TOPAS input generation runs everywhere). Avoid Unix-only shell - syntax in pixi tasks — see `docs/cross-platform-guide.md`. -- After editing engine code, restart the GSAS-II server - (`pixi run gsas-server restart`) — it caches loaded code. After editing - `kicker.py`, also run `pixi run update-code-hash`. -- **Testing caveat**: some `test_esd_extraction` / `test_example_*_regression` cases require - a working GSAS-II refinement to produce output files; they can fail for environment - reasons unrelated to a given change. When checking a change, compare against the baseline - rather than assuming a failure is new. - -## Conventions - -- Refinement parameters are 4-element lists: `[value, refine_flag, min, max]`. -- Refinement output uses fixed filenames (`dummy.gpx`, `dummy.lst`, `refined_parameters.csv`, - `_unit_cell_report.csv`, …). `unit_cell_data`/`peak_list_data` from `run()` are dicts - keyed by phase name. -- Known, deliberately-deferred behaviors are registered with stable `KI-NN` ids in - `docs/known_issues.md` — check it before "fixing" a quirk. -- Don't commit secrets: `.powderline_config.yaml` is gitignored. -- `examples/**/output/` **is** tracked (regression references) — do not gitignore it. -- `_dev/` is a reserved, gitignored path (maintainers' private workspace). Never - `git add` it or anything under it. +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6f9cba6..b51b213 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,10 +8,16 @@ guides. ```bash git clone https://github.com/NSLS2/PowderLine.git cd PowderLine -pixi install # installs everything, including GSAS-II -pixi run test # full suite — run it before and after your change +pixi install -e dev # every engine + docs/test tooling (GSAS-II is built as a conda package) +pixi run test # full suite (dev env) — run it before and after your change +pixi run docs # Sphinx with -W; zero warnings is the standard ``` +The default environment is core-only (it validates recipes for every engine +and runs none); `pixi install -e gsasii` / `-e easydiffraction` install one +engine. After pulling a change to `pyproject.toml`'s entry points, run +`pixi reinstall powderline --all`. + [pixi](https://pixi.sh) is the only tool you install yourself. See the [README](README.md) for platforms and the [Quickstart](docs/quickstart.md) for a first refinement run. @@ -19,8 +25,14 @@ a first refinement run. ## Where things are - **[docs/DEVELOPMENT.md](docs/DEVELOPMENT.md)** — developer guide: - architecture, domain concepts, GSAS-II integration, how to add a refinement - parameter, and a `## Contributing` section with expectations for changes. + architecture (core + gateways), the schema layer, **how to add a refinement + engine or a capability**, GSAS-II integration, workflow. +- **[docs/policies.md](docs/policies.md)** — what binds every change: + versioning and declared compatibility, deliberate behaviour changes, the + frozen GSAS-II modules, engine-version pins, review, "ask, don't + assume". +- **[docs/engine-behavior.md](docs/engine-behavior.md)** — what each engine + does with a recipe and PowderLine's policy toward it. - **[docs/known_issues.md](docs/known_issues.md)** — the known-issues register (`KI-NN` ids, referenced from code and docs): check it before "fixing" a quirk. See also [docs/regression-tolerance.md](docs/regression-tolerance.md) @@ -29,30 +41,10 @@ a first refinement run. - **[examples/CONTRIBUTING_EXAMPLES.md](examples/CONTRIBUTING_EXAMPLES.md)** — how to contribute a new example recipe (examples drive schema evolution). -## Development workflow & the devkit - -Design dossiers, implementation plans/specs, AI-agent context, publication -benchmarks, and private regression data live in a **separate private repo, -[NSLS2/PowderLine-devkit](https://github.com/NSLS2/PowderLine-devkit)** — not in -this repo. Maintainers doing substantial feature work check it out as a -gitignored `_dev/` subdirectory of a PowderLine working tree: - -```bash -cd PowderLine -git clone git@github.com:NSLS2/PowderLine-devkit.git _dev # request access first -git config core.hooksPath scripts/hooks # enable the guard (below) -``` +## Design records -One working tree then holds code + dev artifacts, while this repo tracks only -code. The devkit is private; request access from the maintainers. - -**Where a file belongs (the contract the pre-commit guard enforces):** - -| Content | Home | -|---|---| -| Code, tests, user-facing docs (`docs/*.md/.rst`), public example references | **this repo** | -| Design dossiers, implementation plans/specs, engine/backend surveys, agent scratch | **devkit** (`_dev/dossiers/`) | -| Benchmarks, private/unpublishable regression data, full agent context | **devkit** | +Maintainers keep design records in a separate private repository. +`_dev/` is reserved and gitignored; never commit it. Dev-doc scaffold paths (`docs/superpowers/`, `docs/plans/`, `docs/specs/`, `docs/dev/`), `.gpx` binaries, `fort.*` scratch, and `_dev/` are all rejected by @@ -68,8 +60,28 @@ the pre-commit guard so they never reach `main`. - Run `pixi run test` before opening a PR. Some regression cases need a working GSAS-II refinement — compare failures against a baseline run, don't assume they're yours. -- After editing `src/powderline/kicker.py`: run `pixi run update-code-hash` and - `pixi run gsas-server restart`. +- The frozen GSAS-II modules + (`src/powderline/gateways/gsasii/{helpers,project,setters,executors,extractors,constraints}.py`) + change only through the maintainers' signed-off record of frozen-code + edits; after such an edit run `pixi run update-code-hash`. Restart the GSAS-II server after + editing anything it runs (`pixi run -e gsasii gsas-server restart`). +- After editing a schema module or a gateway's version declarations, run + `PYTHONPATH=src python scripts/gen_schema_field_tables.py` and commit the + regenerated `docs/_generated/` fragments. +- If a decision is not written down (policies page, schema history), ask the maintainer rather than inferring it. - `examples/**/output/` is tracked on purpose (regression references) — don't regenerate it casually. - Questions and bug reports: open a GitHub issue. + +## Changelog + +[CHANGELOG.md](CHANGELOG.md) follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). + +- Every user-visible change adds a bullet under `## [Unreleased]`, in the + right section: `Added`, `Changed`, `Deprecated`, `Removed`, `Fixed` or + `Security`. Internal work (tests, CI, refactoring that changes nothing a + user sees) gets no bullet. +- A bullet is one to three lines, written for users, and links the + documentation page, `KI-NN` / `EB-NN` id or pull request where useful. +- No internal ids: no branch names, private design-record or review ids, and + no names of people in decisions. diff --git a/README.md b/README.md index f8d19cc..dd32838 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,10 @@ [![Docs](https://img.shields.io/badge/docs-live-blue)](https://nsls2.github.io/PowderLine/) Automated powder X-ray diffraction refinement. You describe a refinement in a -JSON "recipe"; PowderLine runs it through a refinement engine — -[GSAS-II](https://gsasii.github.io/) by default, or Bruker TOPAS v7 or the -open-source easydiffraction — and returns standardized result tables. +JSON "recipe"; PowderLine runs it through the refinement engine the recipe +names — [GSAS-II](https://gsasii.github.io/), Bruker TOPAS 6, or the +open-source [easydiffraction](https://easydiffraction.org) — and returns +standardized result tables. **Documentation:** [nsls2.github.io/PowderLine](https://nsls2.github.io/PowderLine/) · **New here? Start with the [Quickstart](docs/quickstart.md).** @@ -13,40 +14,49 @@ open-source easydiffraction — and returns standardized result tables. PowderLine gives you a programmatic, reproducible way to run Rietveld refinements and single-peak fits without hand-driving the underlying refinement software. -- **Two workflow types:** Rietveld refinement (`GSASII_Rietveld`) and single-peak - fitting (`GSASII_SPF`). +- **One recipe = one engine.** A recipe's `schema_name` names the engine and + workflow (`gsasii.rietveld`, `gsasii.spf`, `topas.rietveld`, `topas.spf`, + `easydiffraction.rietveld`) and is written in that engine's own + conventions and units; nothing is translated between engines. - **Refine what you need:** unit cell, atom coordinates, occupancies, isotropic and - anisotropic displacement parameters, background, and peak broadening — each - parameter individually flagged. -- **Three engines, one recipe:** GSAS-II by default, Bruker TOPAS v7 - (`engine="topas"`), or open-source easydiffraction - (`engine="easydiffraction"`) — the TOPAS and easydiffraction paths import - zero GSAS-II. -- **Materials Project integration:** simulate a pattern from a crystal structure. -- **Standardized outputs:** fixed-filename CSV/TXT reports plus a GSAS-II `.gpx`. + anisotropic displacement parameters, background, peak broadening and + March–Dollase preferred orientation, with ionic scattering types per atom — + each parameter individually flagged, and checked against the space-group + symmetry before any engine runs. +- **Honest statistics:** every engine returns the same uniform Rwp / Rexp / + GoF over the same data points, with the engine's own values kept alongside. +- **Strict validation, engine-free:** a recipe validates in a core-only + environment; every problem is reported at its field, and engine quirks are + refused or warned about, never papered over. +- **Standardized outputs:** fixed-filename CSV/TXT reports plus each engine's + native artifacts (the GSAS-II `.gpx`, the TOPAS `.inp` and output files). ## 1. Install PowderLine uses [pixi](https://pixi.sh) for reproducible conda environments. -GSAS-II is installed **automatically** by `pixi install` (it ships as a conda -package — no separate GSAS-II install). +The **default environment is core-only** (schema validation, the CLI, no +engine); each engine lives in its own environment: ```bash git clone https://github.com/NSLS2/PowderLine.git cd PowderLine -pixi install +pixi install # core only: validate recipes, no engine +pixi install -e gsasii # + GSAS-II (built as a conda package by pixi-build) +pixi install -e easydiffraction # + easydiffraction (Python >= 3.12) +pixi install -e all # every engine +# fresh checkout: add --frozen (e.g. `pixi install --frozen -e gsasii`) so the committed lock is used as is ``` -Platforms: `linux-64`, `win-64`, `osx-arm64`. Running a recipe through TOPAS -additionally requires a Windows machine with `tc.exe` installed; generating the -TOPAS input files needs no TOPAS and no GSAS-II. +Platforms: `linux-64`, `win-64`, `osx-arm64`. TOPAS has no Python package: +`topas.*` recipes validate everywhere and their input files are written +everywhere, but running them needs a Windows machine with TOPAS 6 (`tc.exe`). ## 2. Getting started -Run the bundled LaB6 calibrant example: +Run the bundled LaB6 calibrant example with GSAS-II: ```bash -pixi run kicker examples/example_LaB6/input.json +pixi run -e gsasii kicker examples/example_LaB6/input.json ``` Results are written next to the recipe in `examples/example_LaB6/output/`: @@ -57,28 +67,45 @@ Results are written next to the recipe in `examples/example_LaB6/output/`: | `LaB6_unit_cell_report.csv` | Per-phase unit-cell parameters + ESDs | | `LaB6_peak_list_report.csv` | Reflection list (hkl, d-spacing, 2θ, intensity) | | `fit_profile.txt` | Observed / calculated / background / difference | +| `output_recipe.json`, `parameter_dispositions.csv` | The recipe with the refined values written back, and how each value came about | | `dummy.lst` | Human-readable GSAS-II refinement log (Rwp, parameter tables) | | `dummy.gpx` | GSAS-II project — reopenable in the GSAS-II GUI | -> `examples/example_template/` is a fill-in-the-blanks skeleton, not a runnable -> recipe — copy it to start your own. +PowderLine removes its own fixed-name files from the output directory before +each run, so a reused directory holds one run's results. A failed run raises, +and its directory holds the engine's own files plus `failure.json` (the reason, +the message and the engine's last console lines) — never a result table. -**Bringing your own CIF, instrument, and data files?** PowderLine has no -built-in recipe builder; see [Building Recipes](docs/building-recipes.md) for -starting points, validation, and helper code you can adapt. +The same case as a TOPAS and an easydiffraction recipe sits in +`examples/example_LaB6/topas/` and `examples/example_LaB6/easydiffraction/`. + +> `examples/example_template/` holds fill-in-the-blanks skeletons for the +> three engines, not runnable recipes — copy one to start your own. + +**Bringing your own CIF, calibrant and data files?** PowderLine has no +built-in recipe builder; [Building a recipe](docs/input-guidance.md#building-a-recipe) +walks through writing one and validating it. ## 3. Ways to use PowderLine -**Command line** — run or validate a recipe: +**Command line** — one command for every engine; the recipe's `schema_name` +decides where it runs: ```bash -pixi run kicker # run a refinement -pixi run kicker --validate-only # check a recipe without running it -pixi run topas-kicker # generate a TOPAS v7 .inp + .xye +pixi run kicker --validate-only # check a recipe; needs no engine +pixi run -e gsasii kicker # run a gsasii.* recipe +pixi run -e easydiffraction kicker # run an easydiffraction.* recipe +pixi run kicker --topas-dir C:/TOPAS6 --topas-version 6 # run a topas.* recipe (tc.exe on Windows) +pixi run -e gsasii doctor # what this environment can do (gateways, engines, server) ``` -Other flags: `--output DIR` (default: `output/` next to the recipe) and -`--verbose`. +After `pixi reinstall powderline` the same program is the installed command +`powderline …`. Flags: `--output DIR` (default: `output/` next +to the recipe), `--verbose`, `--validate-only`; gsasii `--use-server` / +`--no-server` / `--server-timeout SECONDS` (default: no limit); topas +`--topas-dir DIR` / `--topas-version V` / +`--topas-timeout SECONDS` (default 3600; 0 = no limit). A flag given +for a recipe of another engine is an error. **Python API** — load a recipe, run it, get pandas DataFrames back: @@ -88,36 +115,42 @@ from pathlib import Path recipe = powderline.load_recipe_asset(Path("examples/example_LaB6/input.json")) -# run() writes its file reports into the directory you give it; if you only -# want the in-memory results, a throwaway temp dir works fine: -result = powderline.run(recipe, Path(tempfile.mkdtemp())) +# Engine-free check: every problem at its field path; warnings for defaults applied +checked = powderline.validate(recipe) +print(checked.recipe.schema_name, checked.warnings) -print(result["rwp"]) # weighted profile R-factor -print(result["refined_parameters"]) # DataFrame of refined values + ESDs +# run() writes its file reports into the directory you give it; the engine is +# the one the recipe names, so this needs the gsasii environment: +result = powderline.run(recipe, Path(tempfile.mkdtemp())) -# Same recipe, TOPAS engine: -result = powderline.run(recipe, Path(tempfile.mkdtemp()), engine="topas") +print(result["rwp"]) # PowderLine's uniform Rwp (%) +print(result["engine_details"]) # GSAS-II's own statistics, parameters requested vs varied +print(result["refined_parameters"]) # DataFrame of refined values + ESDs ``` -The returned dict holds more than the two keys shown: the fit metadata -(`success`, `rwp`, elapsed time, which execution path ran, and the error + -traceback on failure) plus every tabular report in memory — the full -refined-parameter table with ESDs, the fit profile, per-phase unit-cell and -peak-list tables (dicts keyed by phase name), and the SPF peak/convergence -tables when single-peak fitting. Everything the CSV/TXT files contain, without -touching disk yourself. - -The public API is `run`, `validate`, `load_recipe_asset`, -`validate_simulation_mode_parameters`, `RecipeModel`, and `GSASClient`. - -**The GSAS-II server (used by default)** — refinements go through a persistent -server that keeps GSAS-II resident in memory (auto-started in the background as -needed), which is a large speedup across many refinements. Manage it directly, -or opt out per run with `--no-server`: +The returned dict holds the fit metadata (`status`, `converged`, `rwp`, `r_exp`, +`gof`, `chi2_red`, `simulation_mode`, `engine_details`, `warnings`, elapsed time, +which execution path ran, the output recipe with its parameter dispositions; a +failed run raises instead of returning) plus every +tabular report in memory — the refined-parameter table with ESDs, the fit +profile, per-phase unit-cell and peak-list tables (dicts keyed by phase +name), and the SPF peak tables when single-peak fitting. Everything the +CSV/TXT files contain, without touching disk yourself. + +The public API (`powderline.__all__`) is `run`, `validate`, +`ValidationResult`, `load_recipe_asset`, `support_matrix` and the exceptions +`PowderLineError`, `GatewayNotInstalledError`, `EngineNotAvailableError`, +`EngineVersionError`, `EngineExecutionError`. `import powderline` imports no +engine. + +**The GSAS-II server (used by default for gsasii recipes)** — refinements go +through a persistent server that keeps GSAS-II resident in memory +(auto-started as needed), a large speedup across many refinements. Manage it +directly, or opt out per run with `--no-server`: ```bash -pixi run gsas-server status # start | status | stop | restart | logs -pixi run kicker --no-server # force an isolated one-shot subprocess +pixi run -e gsasii gsas-server status # start | status | stop | restart | logs +pixi run -e gsasii kicker --no-server # force an isolated in-process run ``` The server is per-user: it listens on loopback only and accepts only requests @@ -128,86 +161,52 @@ same machine can neither use your server nor impersonate it. To switch it off (`auto`) runs then go in-process, explicit server mode (`--use-server` / `execution_mode='server'`) fails, and nothing is auto-started. -**Simulate a pattern from Materials Project** (requires an MP API key in -`.powderline_config.yaml` — see `.powderline_config.yaml.example` — or in the -`MP_API_KEY` environment variable): - -```bash -pixi run mp-simulate --material-id mp-2680 --output patterns/ -``` - -## 4. Refinement Engines - -PowderLine supports three refinement engines that all consume the same recipe format: - -### GSAS-II (default) - -The primary engine, installed automatically with `pixi install`. All workflow types -and refinement flags are supported. +## 4. Refinement engines -### TOPAS v7 (optional) - -Bruker's commercial refinement package. PowderLine generates a TOPAS `.inp` + `.xye` -from unmodified `GSASII_Rietveld` and `GSASII_SPF` recipes; running the `.inp` requires -a Windows machine with `tc.exe` installed. The TOPAS path imports zero GSAS-II. - -```python -result = powderline.run(recipe, Path("output/"), engine="topas") -``` - -### easydiffraction (optional) - -Open-source Rietveld engine. Requires the optional `easydiff` pixi environment -(easydiffraction needs Python ≥3.12; the default environment stays at ≥3.10): - -```bash -pixi install -e easydiff -``` - -```python -import powderline -result = powderline.run(recipe, "output", engine="easydiffraction") -``` +| Engine | Schemas | Environment | Notes | +|---|---|---|---| +| **GSAS-II 5.7.9** | `gsasii.rietveld`, `gsasii.spf` | `gsasii` | The reference engine; the committed examples carry its outputs as regression references. | +| **TOPAS 6** (Bruker) | `topas.rietveld`, `topas.spf` | any (writing the INP); Windows + `tc.exe` (running) | The recipe states `engine_version: "6"`; the run needs the installed version and location declared (`--topas-version 6 --topas-dir DIR`, or `topas.version` / `topas.dir` in `.powderline_config.yaml`); PowderLine never guesses where `tc.exe` is. | +| **easydiffraction 0.21.1** | `easydiffraction.rietveld` | `easydiffraction` | The recipe states the calculator (`cryspy` or `crysfml`); no single-peak fitting. | -**v1 capabilities:** translates unmodified `GSASII_Rietveld` recipes; supports unit-cell, -scale, wavelength, Chebyshev background, Caglioti U/V/W + Lorentzian X/Y broadening, -and zero-shift refinement; multi-phase; simulation mode (no refinement flags set). -Rejects loudly (translation error) atom-level refinement flags, Kα₁/Kα₂ two-wavelength -recipes, refined Z / polarization / axial divergence / background peaks, and SPF -recipes. Fixed anisotropic ADP values are not modeled and are dropped with a warning. - -**Profile model:** a nonzero `SH/L` automatically selects the Thompson–Cox–Hastings -profile with fixed FCJ axial-divergence asymmetry (CrysFML calculator; hkl peak lists -are recovered with a post-fit CrysPy calculation). On the identical LaB6 recipe, -GSAS-II reaches Rwp 6.01% vs easydiffraction 9.63% (both χ² < 1), and the refined -lattice parameters agree to well under 0.001 Å. The remaining Rwp gap comes from -background peaks (not modeled) and residual profile-model differences, so **compare -lattice parameters, not Rwp, across engines** — Rwp is not an apples-to-apples metric. +The structural part of a recipe (space group, cell, atoms) is identical in +every engine; the instrument, background and controls are each engine's +own, with its own units. The +[cross-engine comparison](docs/cross-engine-comparison.md) refines the same +two data sets with every engine and explains why the numbers differ: +**compare lattice parameters, and read Rwp as a property of the model, not +of the engine.** What each engine does with your recipe, and what PowderLine +refuses on its behalf, is on the +[engine behaviour page](docs/engine-behavior.md). For the engine architecture and how to add a backend, see -[Adding a Refinement Engine](docs/DEVELOPMENT.md#adding-a-refinement-engine). -The full design dossier and backend survey live in the private -[PowderLine-devkit](https://github.com/NSLS2/PowderLine-devkit) (maintainers can -request access). +[Adding a refinement engine](docs/DEVELOPMENT.md#adding-a-refinement-engine). +Maintainers keep design records in a separate private repository. ## Documentation - **[Quickstart](docs/quickstart.md)** — clone → install → run → read the output. -- **[Getting Started](docs/getting-started.rst)** — full recipe structure, output +- **[Getting Started](docs/getting-started.rst)** — recipe structure, output files, and the Python API. -- **[Building Recipes](docs/building-recipes.md)** — writing and validating your - own recipes, with helper code and an LLM prompt template. -- **[Supported Features](docs/capabilities.md)** — what a recipe can describe, - per engine, and what is not yet supported. +- **[Recipe schemas](docs/schemas.md)**, **[Fields and features](docs/fields.md)**, + **[Input guidance](docs/input-guidance.md)** — the five schemas, every field + with its unit, how to supply data / structures / instruments. +- **[Engine behaviour notes](docs/engine-behavior.md)** — what each engine + does, and PowderLine's policy toward it. - **[Troubleshooting](docs/TROUBLESHOOTING.md)** — common errors and fixes. -- **[Schema History](docs/SCHEMA_HISTORY.md)** — recipe-schema changelog (current: - **0.26.0**) and migration guidance. +- **[Citing PowderLine](docs/citing.md)** — PowderLine, the engines and the + libraries behind them. +- **[Migration guide](docs/migration-0.1-to-0.2.md)** — from PowderLine 0.1.1 + (unified schema 0.26.0) to 0.2.0 (core + engine schemas 0.1.0). +- **[Schema History](docs/SCHEMA_HISTORY.md)** and the + **[support matrix](docs/support-matrix.md)** — schema versions and declared + compatibility. - **[Using PowderLine as a library](docs/integration-guide.md)** — install it into another project. -- **[Developer Guide](docs/DEVELOPMENT.md)** — architecture and how PowderLine - works internally, for contributors. See also the - [known-issues register](docs/known_issues.md) (`KI-NN` ids referenced from - code and docs). +- **[Developer Guide](docs/DEVELOPMENT.md)** and **[Policies](docs/policies.md)** + — architecture, how to add an engine, versioning, frozen code, review + gates. See also the [known-issues register](docs/known_issues.md) + (`KI-NN` ids referenced from code and docs). ## Citation @@ -222,10 +221,11 @@ Machine-readable metadata is in [`CITATION.cff`](CITATION.cff). ### Cite the refinement engine too -PowderLine drives an underlying refinement engine. If you use PowderLine in -your work, please cite the engine you used in addition to PowderLine: +PowderLine drives an underlying refinement engine: the one your recipe's +`schema_name` names. Please cite the engine you used in addition to +PowderLine. -- **GSAS-II** (default engine): +- **GSAS-II** (`gsasii.*` recipes; GSAS-II 5.7.9 in the `gsasii` environment): > B. H. Toby and R. B. Von Dreele. *GSAS-II: the genesis of a modern > open-source all purpose crystallography software package.* J. Appl. Cryst. > **46**, 544–549 (2013). @@ -235,22 +235,23 @@ your work, please cite the engine you used in addition to PowderLine: > J. H. O'Donnell, R. B. Von Dreele, M. K. Y. Chan, and B. H. Toby. *A > scripting interface for GSAS-II.* J. Appl. Cryst. **51**, 1244–1250 (2018). > [doi:10.1107/S1600576718008075](https://doi.org/10.1107/S1600576718008075) -- **TOPAS** (`engine="topas"`): +- **TOPAS** (`topas.*` recipes; TOPAS 6): > A. A. Coelho. *TOPAS and TOPAS-Academic: an optimization program > integrating computer algebra and crystallographic objects written in C++.* > J. Appl. Cryst. **51**, 210–218 (2018). > [doi:10.1107/S1600576718000183](https://doi.org/10.1107/S1600576718000183) -- **easydiffraction** (`engine="easydiffraction"`): the easydiffraction +- **easydiffraction** (`easydiffraction.*` recipes): the easydiffraction project asks you to cite the specific version you used, through its [Zenodo archive](https://doi.org/10.5281/zenodo.16806521) (all versions). - PowderLine's `easydiff` environment currently installs version 0.20.1: + PowderLine's `easydiffraction` environment installs version 0.21.1: > A. Sazonov, E. Lindgren, P. Rozyczko, and M. Seth. *easydiffraction - > 0.20.1.* Zenodo (2026). - > [doi:10.5281/zenodo.21999827](https://doi.org/10.5281/zenodo.21999827) + > 0.21.1.* Zenodo (2026). + > [doi:10.5281/zenodo.22905049](https://doi.org/10.5281/zenodo.22905049) -If you simulate patterns from Materials Project data (`pixi run mp-simulate`), -please also cite Materials Project — see -[Simulating Patterns from Materials Project](docs/mp-simulation.md#citation). + Please also cite the calculator your recipe names in + `refinement_controls.calculator`: CrysPy (`cryspy`) or CrysFML (`crysfml`). + The references are on the [citing page](docs/citing.md), which also covers + gemmi, the library behind PowderLine's space-group checks. ## License diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 5556e37..9015396 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -1,843 +1,534 @@ # PowderLine Developer Guide -This guide provides comprehensive context for developers working on PowderLine (and for AI coding assistants used alongside them). Read this first to understand the project architecture, design decisions, and development workflows. +This guide provides context for developers working on PowderLine (and for AI +coding assistants used alongside them). Read this first to understand the +architecture, the design decisions, and the development workflows. The rules +that bind every change (versioning, deliberate changes, the frozen GSAS-II +code, the engine pins, review gates, "ask, don't assume") are on the +[policies page](policies.md); this guide shows where things are and how to +work on them. ## Project Overview **What is PowderLine?** -PowderLine automates crystallographic refinement from a declarative JSON "recipe" and drives interchangeable refinement engines — GSAS-II by default, with Bruker TOPAS v7 and open-source easydiffraction as optional alternatives. It takes a recipe describing refinement parameters and produces standardized output reports. The goal is to make powder diffraction refinements reproducible, automatable, and accessible. +PowderLine automates crystallographic refinement from a declarative JSON +"recipe" and drives interchangeable refinement engines — GSAS-II, Bruker +TOPAS 6 and the open-source easydiffraction — through one API and one CLI. +A recipe names its engine and workflow in `schema_name` and is written in +that engine's own conventions; PowderLine validates it strictly, hands it to +the engine's **gateway**, and returns standardized result tables with uniform +fit statistics. The goal is to make powder diffraction refinements +reproducible, automatable, and accessible. **Scope:** -- Command-line tool that runs refinements from JSON recipes, dispatching to interchangeable engines (GSAS-II by default; TOPAS v7 and easydiffraction optional) -- Schema 0.26.0: Simplified two-workflow system (Rietveld refinement or single peak fitting) -- Schema validation using Pydantic -- Single-phase and multi-phase Rietveld refinements; phase-less single peak fitting -- Standard output reports (fit profiles, unit cell parameters with ESDs, peak lists, `refined_parameters.csv`) -- Programmatic Python API: `powderline.run()` with DataFrame returns -- Example-driven design: schema evolves based on real refinement cases +- One CLI (`powderline `) and one Python API (`powderline.run`, + `powderline.validate`) for every engine; the recipe decides where it runs +- A **core schema** (the shared frame and structural models) plus one + **engine schema** per gateway, all pydantic, `extra='forbid'`, engine-free +- Three gateways under `src/powderline/gateways/`, discovered through entry + points, each split into an engine-free schema layer and a lazily imported + runtime layer +- Single-phase and multi-phase Rietveld refinement; single peak fitting + (GSAS-II, TOPAS) +- Standard output reports plus each engine's native artifacts; uniform + Rwp / Rexp / GoF computed once in core, the engine's own values alongside +- Example-driven design: real refinement cases drive the schemas and are the + regression references **Design Philosophy:** -- **Example-driven**: Don't build features speculatively - add them when real examples need them -- **Schema-first**: Validate inputs before any GSAS-II operations -- **Fail fast**: Detect errors early with helpful messages -- **Reproducible**: Same JSON should produce identical refinement results - -## Schema Structure - -**Current schema**: 0.26.0 (payload-based structure with fixed output filenames) - -### Top-Level Structure - -All recipes use a three-key structure: - -```json -{ - "schema_name": "GSASII_Rietveld", // or "GSASII_SPF" - "schema_version": "0.26.0", - "payload": { - // All refinement parameters here - } -} -``` - -**Key field: `schema_name`** - Selects the workflow executor: -- `"GSASII_Rietveld"`: Full Rietveld structural refinement -- `"GSASII_SPF"`: Single peak fitting (peak-based analysis without crystal structure) - -### Payload Structure - -The `payload` contains all refinement parameters organized by concern: - -```javascript -"payload": { - "xrd_data": {...}, // Required: Diffraction pattern - "instrument": {...}, // Required: Beamline/instrument config - "phases": {...}, // Required for Rietveld, null for SPF - "background": {...}, // Optional: Background model (defaults to empty if omitted) - "refinement_controls": {...}, // Optional: Cycles, convergence - "fit_range": [min, max], // Optional: 2θ range limits - "single_peaks": {...}, // Required for SPF, optional otherwise - "single_peak_fitting_mode": {...} // For SPF workflows -} -``` - -**Required fields vary by `schema_name`**: -- **Rietveld** (`GSASII_Rietveld`): Must have `phases` defined -- **SPF** (`GSASII_SPF`): Must have `single_peaks` and `single_peak_fitting_mode` - -### Output Files (Fixed Names) - -PowderLine uses **fixed output filenames** independent of sample identity: - -- `dummy.gpx`: GSAS-II project file (reopenable in GUI) -- `dummy.lst`: Human-readable refinement log (Rwp, parameter tables) -- `_unit_cell_report.csv`: Refined unit cell (one per phase) -- `_peak_list_report.csv`: Reflection list (one per phase) -- `fit_profile.txt`: Observed/calculated/difference intensities - -**Rationale**: Fixed filenames eliminate variability in automation/testing. Sample identity should be managed externally (directory names, databases, metadata systems). - -### Refined Parameters Export with ESDs - -**File:** `refined_parameters.csv` (9 columns) - -PowderLine exports all refined parameters with estimated standard deviations (ESDs) after each refinement. This provides a structured, machine-readable record of refinement results with uncertainty quantification. - -**Column structure:** -1. `parameter_name`: GSAS-II internal parameter identifier (e.g., `::0:Scale`, `::A0`, `0::A0`) -2. `descriptive_name`: Human-readable description (e.g., "Scale factor for phase LaB6", "Background coefficient A0") -3. `phase_name`, `phase_idx`: Phase associations for phase-specific parameters (null otherwise) -4. `atom_name`, `atom_idx`: Atom associations for atom-specific parameters (null otherwise) -5. `value`: Refined parameter value -6. `esd`: Estimated standard deviation from covariance matrix -7. `category`: Parameter classification (instrument, background, cell, atom_position, atom_displacement, HAP, peak_broadening) - -**Implementation:** `export_refined_parameters_csv()` in [kicker.py](../src/powderline/kicker.py) - -**ESD calculation:** -- **Primary source**: GSAS-II covariance matrix (`proj.data['Covariance']`) -- **Fallback**: A `.lst`-parsing fallback exists in `kicker.py` (`extract_refined_params_from_lst`) but is **currently disabled at its call site**. It is preserved pending a test that confirms covariance matrix ESDs match what `.lst` parsing previously produced. Until that test exists, the covariance matrix is the **sole** ESD source. - - **Note**: The `.lst` fallback was incomplete — it only covered instrument, background, and unit cell parameters, not atom or HAP parameters. -- **Unit cell ESDs**: Uses `G2lat.getCellEsd()` to convert reciprocal metric tensor ESDs to direct lattice parameters - - Function: `calculate_cell_esds_from_A_matrix()` in [kicker.py](../src/powderline/kicker.py) - - GSAS-II stores cell as reciprocal metric tensor (A-matrix); ESDs require conversion - -**Parameter name parsing:** -- `parse_parameter_associations()` in [kicker.py](../src/powderline/kicker.py): Extracts phase/atom indices from GSAS-II parameter names -- `get_descriptive_param_name()` in [kicker.py](../src/powderline/kicker.py): Generates human-readable descriptions -- `build_phase_name_mapping()` in [kicker.py](../src/powderline/kicker.py): Maps phase indices to names -- `build_atom_name_mapping()` in [kicker.py](../src/powderline/kicker.py): Maps atom indices to labels - -**Phase-specific unit cell reports:** -In addition to the comprehensive `refined_parameters.csv`, each phase generates `_unit_cell_report.csv` with 3 columns: -- `parameter`: a, b, c, alpha, beta, gamma, volume -- `value`: Refined unit cell parameter -- `esd`: Estimated standard deviation - -**Note on simulations**: Simulation mode (all `refine_flag=false`) does not generate `refined_parameters.csv` since no parameters are refined. Unit cell reports are still generated, with an empty `esd` column (read as `NaN`). - -### Schema Evolution - -See [SCHEMA_HISTORY.md](SCHEMA_HISTORY.md) for historical context. - -**IMPORTANT — Schema Version Discipline:** -The GSAS-II server caches `kicker.py` at startup. If `kicker.py` changes (even without recipe format changes), a running server will use stale code. The `schema_version` in recipes is validated against `EXPECTED_SCHEMA_VERSION` in `schema.py`, so bumping the version forces a server restart. **You MUST bump `EXPECTED_SCHEMA_VERSION` whenever `kicker.py` output behavior changes** (new output files, format changes, column additions, etc.), even if the recipe input format is unchanged. Update all `input.json` files to match. - -## Domain Essentials - -### Rietveld Refinement Basics - -**What is Rietveld refinement?** -A method for refining crystal structures against powder diffraction data by fitting a calculated pattern to the observed pattern. The refinement adjusts parameters (unit cell, atom positions, peak shapes, background) to minimize the difference between calculated and observed intensities. - -**Key Quality Metric: Rwp (weighted residual)** -$$R_{wp} = \sqrt{\frac{\sum w_i (y_{obs,i} - y_{calc,i})^2}{\sum w_i y_{obs,i}^2}} \times 100\%$$ - -Lower Rwp indicates better fit. Typical values: 5-15% for good refinements. - -**Peak Profiles:** -GSAS-II uses Thompson-Cox-Hastings pseudo-Voigt profiles - a convolution of Gaussian and Lorentzian functions. Profile shape controlled by: -- **Instrument broadening** (U, V, W parameters) - due to instrumental effects -- **Sample broadening** (size, strain) - due to crystallite size and microstrain - -### Parameter Types - -PowderLine organizes refinement parameters into logical groups: - -1. **Structural Parameters (Phase-specific):** - - **Unit cell**: a, b, c, α, β, γ define crystal lattice dimensions - - **Atom parameters**: positions (x, y, z), occupancy, thermal parameters - - **Space group**: symmetry operations (defined in CIF, not refined) - -2. **Intensity Parameters (Phase-specific):** - - **Scale factor**: Converts calculated intensities to absolute scale - - **Preferred orientation**: Non-random crystallite orientations (not implemented yet) - -3. **Peak Shape Parameters (Phase-specific):** - - **Sample broadening**: Crystallite size, microstrain - -4. **Background Parameters:** - - **Chebyshev polynomials**: Smooth curved background - - **Single peaks**: Individual pseudo-Voigt peaks for known impurities - -### Background Default Behavior - -The `background` field is optional in the payload. If omitted (`background: null`): -- No Chebyshev coefficients are initialized -- No background single peaks are added -- GSAS-II uses an empty background (effectively zero) - -This is useful when background has been pre-subtracted from XRD data. - -5. **Instrument Parameters:** - - **Instrument broadening**: U, V, W (Gaussian), X, Y, Z (Lorentzian) - - **Profile asymmetry**: Axial divergence, sample transparency - - **Wavelength**: X-ray or neutron wavelength - - **Zero shift**: 2θ offset correction - - **Polarization**: For synchrotron data - -### The `[value, refine_flag, min, max]` Pattern - -Throughout the JSON schema and code, you'll see parameters represented as 4-element lists: -```python -"wavelength": [0.45236, false, null, null] -``` - -- **value**: Current parameter value -- **refine_flag**: `true` = refine this parameter, `false` = hold fixed -- **min/max**: Parameter bounds (placeholders for future - GSAS-II may not support bounds) - -This mirrors GSAS-II's internal parameter representation. - -### Phase vs Histogram Parameters - -**Critical distinction** (confusing in GSAS-II): -- **Phase parameters**: Belong to the crystal structure (scale, unit cell, atoms, space group, sample broadening) -- **Histogram parameters**: Belong to the measurement (instrument broadening, background) - -In multi-phase refinements, each phase has its own structural parameters, but histogram parameters are shared across phases (except scale factors, which are phase-histogram pairs). - -### Atom Parameter Refinement - -**Refine Flags String Format:** -GSAS-II uses a single string at atom record index 2 to encode which parameters are refined: -- **'F'**: Refine occupancy (fraction) -- **'X'**: Refine fractional coordinates (x, y, z) - a single lumped flag for all three -- **'U'**: Refine displacement parameters (isotropic or anisotropic) -- **Combinations**: 'FXU' (all), 'XU' (coordinates + displacement), 'F' (occupancy only), etc. - -**Per-Parameter Semantics (Schema 0.26):** Although GSAS-II exposes only the lumped 'X' flag (and one 'U' flag for all six anisotropic components), PowderLine honors the recipe's per-parameter flags: a coordinate or `Uij` component refines iff it is present with `refine_flag=true`; absent or false means fixed. This uses the same lumped-flag + "Hold"-constraint mechanism as unit-cell parameters — see [Unit Cell Refinement Semantics (Schema 0.26)](#unit-cell-refinement-semantics-schema-026) and `src/powderline/constraints.py`. For atoms, only site-symmetry-linked parameters remain coupled: e.g. `x` and `y` on an `(x,x,z)` site form one degree-of-freedom group that refines if either is requested; flags on symmetry-fixed parameters have no effect. - -**Displacement Parameter Types (ADP field):** -Each atom has an atom-specific `ADP` field indicating which displacement type to use: -- **Structure**: `phases[phase]['structure']['atoms'][label]['ADP']` indicates which type is used -- **Parameterization**: `phases[phase]['parameterization']['atoms'][label]['ADP']` indicates which type to refine - -Values: -- **'Uiso'**: Isotropic displacement (single scalar U value) -- **'Uaniso'**: Anisotropic displacement (6 values: U11, U22, U33, U12, U13, U23) - -The parameterization ADP controls atom_record[9] ('I' or 'A') in GSAS-II. - -**Dictionary Structure Examples:** - -Structure (embedded in payload): -```json -"phases": { - "LaB6": { - "structure": { - "atoms": { - "La": { - "element": "La", - "x": 0.0, "y": 0.0, "z": 0.0, - "occupancy": 1.0, - "ADP": "Uiso", - "Uiso": 0.00858, - "Uaniso": null - } - } - } - } -} -``` - -Parameterization (refinement settings): -```json -"phases": { - "LaB6": { - "parameterization": { - "atoms": { - "La": { - "x": [null, true, null, null], - "y": [null, false, null, null], - "z": [null, false, null, null], - "occupancy": [null, true, null, null], - "ADP": "Uiso", - "Uiso": [null, true, null, null], - "Uaniso": null - } - } - } - } -} -``` - -**Anisotropic Displacement Parameters:** -If using `ADP="Uaniso"`, all 6 anisotropic U values (U11, U22, U33, U12, U13, U23) must be provided in both structure and parameterization: - -```javascript -"atoms": { - "Li": { - "ADP": "Uaniso", - "Uiso": 0.01, // Can provide both - ADP dictates which is used - "Uaniso": { - "U11": 0.012, "U22": 0.011, "U33": 0.010, - "U12": 0.001, "U13": 0.001, "U23": 0.001 - } - } -} -``` - -**Mixed ADP Types:** It is common (and allowed) for one atom to have `ADP="Uaniso"` while another has `ADP="Uiso"` in the same phase. - -### Glossary - -- **CIF**: Crystallographic Information File - standard format for crystal structures (In PowderLine, structural information is provided as embedded dictionaries, not CIF files) -- **GPX**: GSAS-II project file (binary format) -- **LST**: GSAS-II refinement log file with Rwp and parameter tables -- **CHI**: Two-column ASCII file (2θ, intensity) for powder diffraction data (Note: PowderLine uses embedded data arrays, not files. This format is for reference only) -- **INSTPRM**: GSAS-II instrument parameter file (Note: PowderLine uses embedded instrument parameters, not files. This format is for reference only) -- **Recipe**: PowderLine's JSON input describing a refinement workflow -- **Multiplicity**: Number of symmetry-equivalent reflections -- **d-spacing**: Interplanar spacing for an hkl reflection -- **2θ (two-theta)**: Diffraction angle in degrees -- **hkl**: Miller indices describing a crystallographic plane - -## GSAS-II Integration - -### Why Direct Dictionary Manipulation? - -PowderLine manipulates the `proj.data` dictionary directly rather than using GSAS-II's phase/histogram objects. This decision was made because: -- **Phase object ambiguity**: Unclear how G2Phase initialization maps to parameter setting -- **Explicit control**: Direct dictionary access makes parameter locations clear -- **Less abstraction**: Easier to debug when you can see exact data structure -- **Trade-off**: More brittle if GSAS-II internal structure changes (acceptable risk for Phase 1) - -### The `proj.data` Dictionary Structure - -GSAS-II stores all project data in a nested dictionary. Key access patterns: +- **Example-driven**: don't build features speculatively; add them when real examples need them +- **Schema-first**: every rule a recipe must obey lives in the schema models, so validation + reports every problem at its field before any engine runs +- **Honest**: an engine's silent default, floor or conversion is either refused at + validation (with the value to write) or reported as a structured warning; never papered over +- **Engine-native**: no translation between engines; each recipe states the numbers its engine computes with +- **Reproducible**: the same recipe produces the same refinement; the references are tracked + +## Architecture (`src/powderline/`) + +### Core (engine-free) + +| Module | Role | +|---|---| +| `__init__.py` | the public API, `__all__`: `run`, `validate`, `ValidationResult`, `load_recipe_asset`, `support_matrix`, the exceptions. `import powderline` imports no engine | +| `api.py` | `validate()` and `run()`: resolve the gateway from `schema_name` (`.`) through the registry and hand the recipe over; `ValidationResult` | +| `kicker.py` | the one CLI (`powderline `; `pixi run kicker` runs the same `main`): loads the recipe, refuses templates, maps the engine flags onto the gateway's run options, prints the summary and the structured warnings | +| `registry.py` | gateway discovery from the `powderline.gateways` entry-point group, lazy loading, `Gateway` dataclass (`name`, `capabilities`, `validate`, `run`), `register_gateway` escape hatch, the engine-version check | +| `schema_core.py` | core schema 0.1.0: `CoreRecipe` (frame), `RefinableParameter` / `BoundedRefinableParameter`, `XRDData`, `FitRange`, `ChebyshevBackground`, `UnitCell`, `Atom`, `UanisoTensor`, `Phase[P]` (the phase block with every symmetry rule), `CoreFloat`/`CoreInt`/`CoreName`, `collect_warnings`, `parameters_requested`, `fit_limits_on_data`; the engine schema building blocks: `EngineRecipe`, `recipe_validator`, `refined_flags`, `custom_error` / `raise_problems`, `omit_absent`, `absent_not_null`, `unique_phase_names`, `fit_window`, `fit_range_problems`, `outside_window_problems`, `refined_flag_problems`, `unit_schema` | +| `symmetry.py` | gemmi-backed symmetry: canonical space-group names, cell tie groups and the cell check, special-position analysis, coupling groups for coordinates and Uij | +| `compat.py` | declared schema-version compatibility: `check_engine_schema_version`, `support_matrix()`, `schema_declarations()` (a gateway's `DECLARATIONS`) | +| `fitstats.py` | the uniform Rwp / Rexp / GoF / χ²_red over the fit window with positive weights | +| `reports.py` | the standardized report writers (`refined_parameters.csv`, unit-cell and peak-list reports, `fit_profile.txt`): one column order, UTF-8, LF; the fixed-name list PowderLine owns (`FIXED_OUTPUT_NAMES` / `FIXED_OUTPUT_PATTERNS`, `FAILURE_FILE`) and `clear_fixed_outputs()` | +| `recipes.py` | `load_recipe_asset` (JSON / YAML) | +| `exceptions.py` | `PowderLineError`, `SymmetryError`, `GatewayNotInstalledError`, `EngineNotAvailableError`, `EngineVersionError`, `EngineExecutionError`, `ExecutionBackendError` (both with `.reason` / `.result`), the `StructuredWarning` shape; `WARNING_CODES`, the registry of every structured-warning code with its owner and level (asserted against `src/` and the engine-behaviour table) | +| `results.py` | the run-result envelope: `ENVELOPE_VERSION`, the reason-code sets, `failure_envelope`, `generated_envelope`, `with_status_fields`, `raise_if_failed` | +| `config_loader.py` | `.powderline_config.yaml` (the `simulation_defaults` block; engine-free) | +| `_status.py` | console status glyphs | + +### Gateways (`src/powderline/gateways//`) + +Each gateway is a package with the same two layers: + +- **Schema layer** — `schema.py`: the engine schema models built on + `schema_core` (the engine's `Phase` subclass, instrument, background, + controls, payload and recipe models), the version declarations + (`ENGINE_SCHEMA_VERSION`, `SUPPORTED_ENGINE_SCHEMAS`, `REQUIRES_CORE_SCHEMA`, + exposed as `DECLARATIONS`), `SCHEMA_NAMES`, and `validate_recipe()`. Imports + no engine; this is what `powderline.validate()` runs. +- **Runtime layer** — `gateway.py` (the entry-point factory: `capabilities()`, + `validate()`, `run()`, `ENGINE_VERSION_SPEC`, and for pixi-installed engines + `ENV` / `INSTALL_COMMAND`) plus the modules that import the engine, imported + lazily from `run()`. + +| Gateway | Runtime modules | +|---|---| +| `gsasii/` (GSAS-II 5.7.9) | the **frozen** setup/execution code moved verbatim from `kicker.py` at the baseline `daace24`: `helpers.py`, `project.py`, `setters.py`, `executors.py`, `extractors.py`, `constraints.py` (code-hashed; see [policies](policies.md#frozen-gsas-ii-code)); non-frozen additions `routing.py` (one entry for in-process, server and client), `fit_report.py` (uniform statistics, `engine_details`, convergence, divergence), `sites.py` (GSAS-II's reading of each site vs core's), `report_rows.py`, `paths.py` (GSAS-II parameter names → recipe paths for the output recipe), `console.py` (the engine's console tail into a failed envelope), `scattering.py` (GSAS-II's ion table and spelling); `server.py` / `client.py` (the persistent FastAPI server and `GSASClient`: per-user, loopback, ephemeral port, signed requests and responses, `POWDERLINE_NO_SERVER=1` disables it — v0.1.2); `simulation_builder.py` (structure dict → simulation recipe; see [the builder](#the-simulation-recipe-builder)) | +| `topas/` (TOPAS 6) | `native_writer.py` (model → INP + `.xye`), `native_run.py` (run `tc.exe`, read TOPAS's files strictly, build the result; the background-only second run), `peak_list.py`, `runner.py` (find `tc.exe`, read `.powderline_config.yaml`) | +| `easydiffraction/` (0.21.1) | `native_builder.py` (model → easydiffraction `Project`; the CrysPy template rule; anisotropic atoms first), `native_run.py` (calculate or lmfit fit, the result), `space_group_table.py` / `space_group_support.py` (the 531 settings and the per-calculator verified sets), `scattering.py` (CrysPy's ion table) | + +The entry points are declared in `pyproject.toml` +(`[project.entry-points."powderline.gateways"]`); the metadata is written at +install time, so after editing that table run `pixi reinstall powderline` +(every environment has its own install: `--all`). There is deliberately no +in-code fallback (KI-13): the in-repo gateways use exactly the mechanism a +third-party engine would. + +### The execution stack + +``` +powderline / powderline.run(recipe, output_dir, **engine_options) + │ schema_name -> registry.get("") ; gateway.run(...) + ▼ +gateway.run() validates (schema layer), checks the engine version, + │ then the runtime layer: + ├─ gsasii: routing.run_refinement() in this process, or GSASClient + │ -> the FastAPI server (GSAS-II resident) -> routing.run_refinement() + │ -> executors.run_refinement() -> GSASIIscriptable + │ -> fit_report (uniform statistics) ; reports (files) + ├─ topas: native_writer -> tc.exe (twice: fit, background) -> native_run reads the files + └─ easydiffraction: native_builder -> lmfit / calculate() -> native_run + ▼ +the standardized result dict (tables as DataFrames) + the report files + native artifacts +``` + +`execution_mode` (gsasii only: `'auto'` | `'server'` | `'subprocess'`) is the +public option; `method` is the result key saying which path ran. The server +keeps GSAS-II imported in one process (~2.6 s import amortized); it caches +code, so **restart it after editing anything it runs** +(`pixi run -e gsasii gsas-server restart`). + +## The schema layer + +### Shape of a recipe + +``` +schema_name "." +core_schema_version "0.1.0" +engine_schema_version "0.1.0" +metadata free-form, echoed, never read (<= 1 MiB) +payload the engine schema's payload model +``` + +Core owns the frame, `xrd_data`, `fit_range`, `ChebyshevBackground` and the +**phase block** (`space_group`, `unit_cell`, `atoms`), generic over the +parameter type `P` (`RefinableParameter` for gsasii, `BoundedRefinableParameter` +for topas and easydiffraction). The engine schema owns everything else +(instrument, background placement, controls, engine phase fields such as +`scale` and `peak_broadening`) and may add checks, but can never redefine, +skip or rewrite core's (guarded when the class is defined: no reuse of a +core field, validator or private-attribute name, no `'before'`/`'wrap'` +validator on a core field, `extra='forbid'` kept; `tests/test_phase_canary.py` +runs core's must-fail recipes through every engine phase model). + +User-facing rules: [schemas](schemas.md), [fields](fields.md) (generated +tables), [input guidance](input-guidance.md), [SCHEMA_HISTORY](SCHEMA_HISTORY.md). + +### Validation model + +- Every recipe check is a pydantic validator raising `ValueError` (or + `SymmetryError`), so an invalid recipe raises **one** `pydantic.ValidationError` + listing every problem at its field path. There is no PowderLine wrapper + exception for invalid recipes. +- **Validation never changes a recipe.** The validated model holds exactly the + recipe's values plus documented defaults and the symmetry-derived values; a + value an engine would silently replace (a floor, a snapped coordinate, a + limit) is an **error naming the value to write**, never an adjustment. +- **Structured warnings** (`{code, message, field_path[, level]}`; `level` absent = `"warning"`, or `"info"`) are collected once + from the validated model (`collect_warnings`) and travel with it: a default + applied, a symmetry remark, a unit conversion the gateway will make. They + never change what the recipe means, so re-validating reproduces them. +- Engine quirks that reach a user are recorded in the maintainers' + engine-behaviour register and rendered on the + [engine behaviour page](engine-behavior.md); a schema rule that exists + because of a quirk cites its `EB-nn` in the error message. + +## Adding a refinement engine + +The gateway seam is the contract the refactor exists to provide. A new engine +is a package `src/powderline/gateways//` (in-repo) or a separate +distribution (out of tree) that provides: + +1. **A schema module** (`schema.py`), engine-free: + - the engine's `Phase` subclass (`class MyPhase(Phase[BoundedRefinableParameter])` + or `Phase[RefinableParameter]` if the engine has no usable bounds), adding + the engine's phase fields with their own validator names and `'after'` + validators only; + - instrument, background and controls models in the **engine's native + terms and units**, every quantity carrying `json_schema_extra={"unit": ...}` + (the [fields page](fields.md) is generated from it), `extra='forbid'`, + no `null` for a block that may be left out, and **no default that + replaces an engine behaviour silently** (either the value is required, or + the default is documented and reported by a warning); + - the recipe model(s) subclassing `powderline.schema_core.EngineRecipe` + with `schema_name` narrowed to a `Literal` and two class variables, + `gateway_name` and `schema_declarations = DECLARATIONS`, where + `DECLARATIONS = compat.schema_declarations(engine_schema_version="0.1.0", + supported_engine_schemas="==0.1.0", requires_core_schema="==0.1.0")` + (widened explicitly later, never by range); `EngineRecipe` runs the + version check; + - `validate_recipe = schema_core.recipe_validator({: , ...}, + engine="", title="Recipe")`: accepts a dict or an + already-validated model (idempotent) and reports an unknown + `schema_name` at `schema_name`; + - every engine rule as a validator: refuse what the engine cannot express + (settings, features) and what it would silently alter (floors, limits), + naming the value to write; apply the three shared value rules + (wavelength > 0, scale per engine, peak positions inside the window) and + the fit window on data points (`fit_limits_on_data`). The shared pieces + are core building blocks, not copies: `absent_not_null` for a + block that may be left out but never be `null`, `omit_absent` in the + wrap serializer that drops it from dumps, `unique_phase_names`, + `fit_range_problems` / `fit_window` / `outside_window_problems` / + `refined_flag_problems` for the payload rules, `refined_flags`, + `custom_error` + `raise_problems` to report every problem at once; + - every warning code the engine emits registered in + `powderline.exceptions.WARNING_CODES` (owner, level) and listed in the + engine-behaviour table; a core test holds the three in agreement. +2. **A gateway module** (`gateway.py`) exporting `get_gateway()` → + `registry.Gateway(name, capabilities, validate, run)`: + - `capabilities()` returns at least `name`, `workflows` (the schema names), + `engine_version_spec` (PEP 440) and the schema `DECLARATIONS`; + - `validate(recipe, *, verbose=False)` (exactly these keywords) returns the + validated model; + - `run(recipe, output_dir, *, verbose=False, validate_only=False, + allow_unsupported_engine_version=False, **own_options)`: validates, checks + the installed engine version against `engine_version_spec` + (`registry.check_engine_version`; raise `EngineNotAvailableError` with + `env` and `install_command` when the engine is missing — only on a real + run, never for `validate_only`), imports the engine **lazily**, runs, and + hands `powderline.roundtrip` its refined values by recipe path (`{path: (value, esd)}` + in recipe units, plus the flagged paths it did not vary and those that ended at a + limit; `roundtrip.build_output` / `attach` do the rest: tie propagation, the + multiplicity invariant, `output_recipe`, `output_recipe_valid`, `parameter_dispositions`, + the two files) and + returns the standardized result dict with the same keys and types as the + other gateways (`status`, `converged`, `envelope_version`, `run_id`, `rwp`, `r_exp`, `gof`, `chi2_red`, + `simulation_mode`, `engine_details` with `parameters_requested` / + `parameters_varied` / `n_points`, `warnings`, `elapsed_time`, `method`, + `output_files`, `fit_profile`, `unit_cell_data`, `peak_list_data`, + `refined_parameters`, `spf_peaks`, `spf_convergence_diagnostics`; gsasii adds + `peak_fit` for a peak fit). A gateway **never returns a failed + result**: it raises `EngineExecutionError` (the engine ran and failed) or + `ExecutionBackendError` (it did not run) with a `reason` from + `powderline.results.REASONS`, or returns + `results.raise_if_failed(envelope)` on an envelope it received; the + GSAS-II server/client show the wire form (`results.failure_envelope`, + `results.with_status_fields`). Statistics come from `powderline.fitstats` over + the window's weighted points with P read from the engine after the run; + the engine's own values go under `engine_details`; divergence (a + non-finite calculated pattern) raises `EngineExecutionError`. + - report files through `powderline.reports`; native artifacts kept. +3. **An entry point** in `pyproject.toml` + (`[project.entry-points."powderline.gateways"] = "...gateway:get_gateway"`), + then `pixi reinstall powderline`. A pixi feature/environment for the + engine's dependencies if the default environment must not carry them + (every in-repo engine has one); `ENV` / `INSTALL_COMMAND` on the gateway. +4. **Tests**, in the pattern of the existing gateways: schema tests + (`test__schema.py`: every rule, every refusal, with the error + path), the engine phase model registered in `tests/test_phase_canary.py` + `ENGINE_PHASES`, an import-block test proving the schema layer and + `import powderline` load no engine module, a space-group translation test + over every setting the engine accepts (orbit / operator comparison against + gemmi), fixtures + goldens for the runtime (hand-derived native recipes + with a README of the derivations; goldens recording the engine's version), + and the result-contract test (same keys and types as the other engines). + Tests that need the engine are marked / skipped so the core-only suite + stays green. +5. **Freeze-equivalent expectations**: the engine's goldens are the + references; a change in what the engine is asked to do (the INP, the + project, the input dictionary) is proved against them, and anything the + engine does silently is written up in the engine-behaviour register with + its policy before the gateway ships. +6. **Docs**: the schemas, fields (regenerate with + `scripts/gen_schema_field_tables.py`), input-guidance and engine-behaviour + pages; a SCHEMA_HISTORY section; the support matrix regenerates itself. + +### Adding a capability to an existing engine + +The same discipline, smaller: a new field or block goes into the engine +schema with its unit, its validators and its refusals; the gateway consumes it +from the validated model (for gsasii, an **input-side read in a frozen module +is a signed-off frozen-code edit**, otherwise the read happens in the non-frozen modules); a +fixture and a golden prove it reaches the engine and does what the recipe +says; the engine-behaviour register records anything the engine does with it +silently; SCHEMA_HISTORY and the generated field tables record the field. If +the field changes what an existing recipe means, that is a deliberate change +(recorded, CHANGELOG, migration note) — and if the engine's own behaviour +is unknown, that is a question for the maintainer, not an inference. + +Worked example — March–Dollase preferred orientation: + +1. **Ground truth first.** Read and run each engine: GSAS-II's HAP + `Pref.Ori.` entry and `GetPrefOri`; easydiffraction's + `preferred_orientation` rows, which only CrysPy reads, and only under the + lowercase structure key (EB-97); CrysPy's un-normalised correction (EB-98). +2. **One core building block, engine fields.** `schema_core.MarchDollase[P]` + carries the shape and the engine-independent rules (`hkl` not all zero, + `ratio > 0`); each engine's phase model adds `preferred_orientation` in + its own parameter shape (gsasii `[value, flag]`, easydiffraction bounded + plus the required `march_random_fract`, topas bounded); topas declared the + field and refused it until its half was verified on a TOPAS 6 machine + (the `PO` macro against the Dollase formula, then the writer and the + read-back of r). +3. **The gateway reads the model.** gsasii: an additive frozen setter and its + call, two signed-off frozen-code edits with proofs (the project-dict diff shows only + `Pref.Ori.`), and the refined name `p:h:MD` in `paths.py`; + easydiffraction: the builder's row plus the `_free` bookkeeping that maps + the refined value back to the recipe path. +4. **A gate, then a demonstration.** The pass/fail gate is a formula check on a + simulated pattern (each engine's textured/untextured intensity ratio equals + Dollase's correction over the reflection's equivalents); the example + (`example_LaB6_textured`) is the demonstration that refinement recovers the + programmed value, with its caveats written down (the start at exactly 1.0 + aborts, EB-99). +5. **Record.** Fields tables regenerated, SCHEMA_HISTORY per engine, + engine-behaviour register rows, CHANGELOG, the T-list row for the TOPAS + half, the P-row. + +## GSAS-II integration notes + +### The frozen modules and the project dictionary + +The GSAS-II setup/execution code manipulates the `proj.data` dictionary of a +GSAS-II project directly (explicit control, debuggable, brittle to GSAS-II +internals). It moved verbatim out of `kicker.py` at the baseline +`daace24` (not on `main`) and is +frozen behind a code hash; input-side edits go through the maintainers' +signed-off record of frozen-code edits ([policies](policies.md#frozen-gsas-ii-code)). +The module headers still read "moved verbatim"; that record, not the headers, +is the record of the additive edits made since (ionic types in `project.py`, +the preferred-orientation setter in `setters.py`, the simulation ESDs in +`extractors.py`). +Key access patterns, for reading the code: ```python -# Instrument parameters (list format: [current_value, value, refine_flag]). See kicker.py for setting functions -curr_wavelength = proj.data[hist.name]['Instrument Parameters'][0]['Lam'][1] # before setting, can get value from initialization (e.g., when xrd_data is added) +# Instrument parameters (list format: [current_value, value, refine_flag]); the native +# gateway builds Iparm1 from the recipe's instrument block (schema.gsasii_iparm1) proj.data[hist.name]['Instrument Parameters'][0]['Lam'][1] = wavelength proj.data[hist.name]['Instrument Parameters'][0]['Lam'][2] = refine_flag -# Background parameters +# Background proj.data[hist.name]['Background'] = [ [chebyshev, no_peaks, background_type], # Background metadata {'nDebye': 0, 'debyeTerms': [], ...}, # Debye-Scherrer params {'nPeaks': n, 'peaksList': [...]}, # Single peaks ] -# Histogram-atom parameters (HAP) -# Change phase intensity scale given a value and refine_flag from payload for a phase's parameterization: +# Histogram-atom parameters (HAP): phase scale, size, microstrain proj.data['Phases'][phase_name]['Histograms'][hist.name]['Scale'][0] = value -proj.data['Phases'][phase_name]['Histograms'][hist.name]['Scale'][1] = refine_flag - -# Change isotropic size broadening for a given phase from the payload for a phase's parameterization: -proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][0] = model # assume model is "isotropic" in this example -proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][1][0] = value # set isotropic crystallite size value -proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][2][0] = refine_flag # set isotropic size value refinement flag (if not None) - -# Change isotropic mustrain broadening for a given phase from the payload for a phase's parameterization: -proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][0] = model # assume model is "isotropic" in this example -proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][1][0] = value # set isotropic mustrain value -proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][2][0] = refine_flag # set isotropic mustrain value refinement flag (if not None) +proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][1][0] = value # isotropic size +proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][1][0] = value # isotropic microstrain # Phase parameters proj.data['Phases'][phase_name]['General']['Cell'] = [refine_cell, a, b, c, alpha, beta, gamma, volume] ``` +GSAS-II exposes lumped refine flags (one for the cell, `'X'` for all three +coordinates of an atom, `'U'` for all six Uij); `constraints.py` sets the +lumped flag and emits GSAS-II "Hold" constraints for the degrees of freedom +the recipe does not refine, so per-parameter flags are honoured. The native +schema has already refused any flag pattern GSAS-II could not honour (a strict +subset of a tie group or of a GSAS-II cell group), so no flag is ever silently +overridden. + +### What the native gsasii path adds around the frozen code + +- `sites.py` compares GSAS-II's `(site symmetry, multiplicity)` of every atom + with core's after phase setup and stops with an error naming an equivalent + position when GSAS-II misreads the site (some 2-fold sites of R32/R-3m/R-3c) + or cannot name it while a coordinate / `Uaniso` is refined. +- `fit_report.py` computes the uniform statistics over the stated window, + reads GSAS-II's stored messages into `gsasii_refinement_message` warnings, + its convergence flag into `engine_details.converged`, counts + `parameters_varied` from GSAS-II (`Nvars`; the Peak List count after + singular drops), and raises on a non-finite calculated pattern. +- The documented defaults (size/strain 10 µm / 0 with a warning; background + none) are pydantic defaults in `schema.py`, so the frozen setters receive + explicit values and GSAS-II's own 1 µm / 1000 / constant-1.0 defaults are + never used. + +### Known GSAS-II quirks + +All on the [engine behaviour page](engine-behavior.md); the ones a developer +meets first: the background-peak width `BkPksig` is a **variance** (the +schema names it `pv_gaussian_sigma_sq`); SH/L is floored at 0.002 in the +profile calculation; `Refine` returns nothing and stores its messages in the +project; `Nvars` counts parameters dropped as singular; `GOF` means two +different things in Rietveld and Peak List fits; limits are applied after the +cycles (why gsasii 0.1.0 exposes no bounds). + +### Output files + +Fixed filenames in every engine (`refined_parameters.csv`, +`_unit_cell_report.csv`, `_peak_list_report.csv`, +`fit_profile.txt`; single peak fitting adds a peak report), written by +`powderline.reports` with one column order and LF line endings so the files +are byte-stable across platforms. gsasii keeps `dummy.gpx`, `dummy.bak0.gpx` +and `dummy.lst`; topas keeps the INP, `.xye` and every file TOPAS wrote; +easydiffraction writes the reports only. Refinement runs add +`output_recipe.json` and `parameter_dispositions.csv`. `powderline.run()` +removes every PowderLine-owned fixed name (`reports.FIXED_OUTPUT_NAMES` / +`FIXED_OUTPUT_PATTERNS`) from the directory before dispatch and never the +engine's files; a failed run leaves the engine's files plus `failure.json` +(the envelope with a `powderline_provenance` block) and no result table — +in gsasii the checks run before the tables are written. + + The `refined_parameters.csv` +columns: `parameter_name` (the engine's identifier), `descriptive_name`, +`phase_name`, `phase_idx`, `atom_name`, `atom_idx`, `value`, `esd`, +`category`. gsasii's ESDs come from GSAS-II's covariance matrix +(`proj.data['Covariance']`); unit-cell ESDs are converted from the +reciprocal-metric tensor with `extractors.calculate_cell_esds_from_A_matrix`. + +## Domain essentials + +**Rietveld refinement** fits a calculated powder pattern to the observed one +by adjusting structural, profile and background parameters. The headline +quality metric, in PowderLine's uniform form (percent, over the fit window's +points with positive weight): + +$$R_{wp} = 100 \sqrt{\frac{\sum_i w_i (y_{obs,i} - y_{calc,i})^2}{\sum_i w_i y_{obs,i}^2}}, \quad +R_{exp} = 100 \sqrt{\frac{N - P}{\sum_i w_i y_{obs,i}^2}}, \quad +\mathrm{GoF} = R_{wp}/R_{exp}$$ + +with N the included points and P the engine's count of varied parameters. +Lower Rwp is a better fit of *that model* to *those points*; across engines +compare lattice parameters, not Rwp (the models differ: background peaks, +asymmetry treatment, sample broadening). + +**Parameter types** (every one a `[value, flag]` or `[value, flag, min, max]` +list): structural (cell, coordinates, occupancies, ADPs: the core phase block, +identical across engines), intensity (phase `scale`), peak shape (sample +size/strain in gsasii and topas; the instrument profile in every engine), +background (Chebyshev; gsasii/topas peaks), instrument (profile terms, +wavelength, zero shift, polarization, asymmetry: the engine's own names and +units). + +**Phase vs histogram parameters**: phase parameters belong to a crystal +structure (cell, atoms, scale, sample broadening); histogram parameters belong +to the measurement (instrument profile, background) and are shared across +phases in a multi-phase refinement. + +**Glossary**: *Recipe* — PowderLine's JSON input. *Gateway* — the per-engine +package behind the registry. *Schema layer / runtime layer* — the engine-free +and engine-importing halves of a gateway. *Tie group* — parameters the +symmetry makes one parameter (cubic a, b, c). *Golden* — a committed engine +output a test compares against. *GPX / LST* — the GSAS-II project and log. +*INP / `.xye`* — TOPAS's input and data files. + +## Development workflow + +### Environments and tasks -### Known GSAS-II Quirks - -These inconsistencies exist in GSAS-II (as of 2025) and are documented in kicker.py comments: - -1. **Size/Strain Documentation Conflict**: - - GSAS-II API does not document structure of dicts / lists well - - PowderLine uses correct extended format - -2. **Unit Cell Refinement**: - - GSAS-II natively exposes a single refine flag for all 6 unit cell parameters; since schema 0.26 PowderLine honors per-parameter flags instead. - - See [Unit Cell Refinement Semantics (Schema 0.26)](#unit-cell-refinement-semantics-schema-026) for the full mechanism and symmetry-coupling rules. - -3. **Reflection List Headers**: - - GSAS-II provides 15-column reflection arrays without headers - - PowderLine adds headers manually: h, k, l, multiplicity, d_spacing, 2theta, etc. - -### Peak Broadening Models - -**Schema Enhancement**: Size and strain broadening support model branching with schema-level validation. - -#### Size Broadening Models - -PowderLine supports three size broadening models matching GSAS-II's capabilities: - -| Model | Parameters | GSAS-II Structure | Status | -|-------|-----------|-------------------|--------| -| **isotropic** | `isotropic_size`, `LG_eta` | `Size[0] = 'isotropic'`
`Size[1][0]` = size
`Size[1][2]` = LG_eta | ✅ **Implemented** | -| **uniaxial** | `uniaxial_equatorial`, `uniaxial_axial`, `hkl_direction`, `LG_eta` | `Size[0] = 'uniaxial'`
`Size[1][0:2]` = eq/ax sizes
`Size[3]` = [h,k,l] | ⚠️ **NotImplementedError** | -| **ellipsoidal** | `S11`, `S22`, `S33`, `S12`, `S13`, `S23`, `LG_eta` | `Size[0] = 'ellipsoidal'`
`Size[4][0:6]` = tensor params | ⚠️ **NotImplementedError** | - -**Usage** (isotropic only): -```json -"size_broadening": { - "model": "isotropic", - "isotropic_size": [100.0, true, null, null], - "LG_eta": [0.5, false, null, null] -} -``` - -**Future models** raise `NotImplementedError` at schema validation: -```python -# This will fail during recipe validation: -"size_broadening": { - "model": "uniaxial", # Error: Not yet implemented - ... -} -``` - -#### Strain Broadening Models - -Strain broadening supports three models with increasing complexity: - -| Model | Parameters | GSAS-II Structure | Status | -|-------|-----------|-------------------|--------| -| **isotropic** | `isotropic_strain`, `LG_eta` | `Mustrain[0] = 'isotropic'`
`Mustrain[1][0]` = strain
`Mustrain[1][2]` = LG_eta | ✅ **Implemented** | -| **uniaxial** | `uniaxial_equatorial`, `uniaxial_axial`, `hkl_direction`, `LG_eta` | `Mustrain[0] = 'uniaxial'`
`Mustrain[1][0:2]` = eq/ax strains
`Mustrain[3]` = [h,k,l] | ⚠️ **NotImplementedError** | -| **generalized** (Stephens) | Symmetry-dependent parameters | Complex Laue class-specific | ⚠️ **NotImplementedError**
(Phase 2) | - -**Usage** (isotropic only): -```json -"strain_broadening": { - "model": "isotropic", - "isotropic_strain": [0.001, true, null, null], - "LG_eta": [0.8, false, null, null] -} -``` - -**Note on Stephens Model**: The `generalized` strain model uses Stephens formalism where the number and meaning of parameters depend on the crystal's Laue class (cubic, hexagonal, etc.). Implementation deferred to Phase 2 due to complexity. - -#### Implementation Details - -**Model Branching** (kicker.py): -```python -def set_phase_size_broadening(proj, hist, phase_name, size_dict, print_info=False): - """Set size broadening with model-specific branching.""" - model = size_dict.get('model', 'isotropic') # Default for backward compat - - # Set model type in GSAS-II - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][0] = model - - # Branch on model - if model == 'isotropic': - _set_isotropic_size_broadening(...) # Current implementation - elif model in ['uniaxial', 'ellipsoidal']: - raise NotImplementedError(f"{model} size broadening not yet supported") -``` - -**Schema Validation** (schema.py): -```python -class SizeBroadening(BaseModel): - model: Literal["isotropic", "uniaxial", "ellipsoidal"] = "isotropic" - # ... parameters for all models ... - - @model_validator(mode='after') - def validate_model_implementation(self) -> Self: - if self.model != 'isotropic': - raise NotImplementedError( - f"{self.model} size broadening not yet implemented. " - "Use 'isotropic' model instead." - ) - return self -``` - -**Design Rationale**: -- Schema documents complete API (all models) even if not implemented -- Clear error messages guide users to supported features -- Foundation for Phase 2 implementation without breaking changes -- Validation happens early (recipe parsing), not during refinement - -## Architecture & Design Decisions - -### Module Responsibilities - -**src/powderline/kicker.py** (the refinement engine): -- CLI entry point via argparse -- Recipe loading, template detection, validation -- GSAS-II project initialization -- All parameter setting functions (background, phases, instrument, unit cell, etc.) -- Refinement execution -- Output generation (CSV reports, fit profiles) -- **Role**: Complete workflow orchestration + implementation - -**src/powderline/schema.py**: -- Pydantic models matching JSON recipe structure -- Nested validation: RecipeModel → InstrumentModel, PhaseModel, BackgroundModel -- Custom validators for coefficient counts, list lengths, fit range -- **Role**: Input validation and type safety - -**src/powderline/gsas_server.py / gsas_client.py**: -- Persistent FastAPI server keeping GSAS-II loaded in memory, and the HTTP client that talks to it (with in-process subprocess fallback) -- Per-user and authenticated by signed requests/responses (private state dir, loopback, ephemeral port, single instance via a kernel lock); `POWDERLINE_NO_SERVER=1` disables it -- **Role**: Execution backends for `run()`'s `server`/`auto` modes - -**src/powderline/topas/ + src/powderline/easydiff/ + src/powderline/engine.py**: -- Alternate translation engines — TOPAS v7 (recipe → `.inp`/`.xye`, `tc.exe` runner, results round-trip; standalone `topas-kicker` CLI) and easydiffraction (recipe → easydiffraction `Project`, lmfit fit) — plus the engine dispatcher behind `powderline.run(recipe, output_dir, engine="gsasii"|"topas"|"easydiffraction")`. Both alternate paths import **zero** GSAS-II; the `gsasii` branch is a transparent pass-through to `kicker.run`. -- **Role**: Alternate refinement engines + engine dispatch - -**tests/**: -- `test_example_LaB6_regression.py`: End-to-end regression test with exact output matching -- `conftest.py`: Pytest fixtures for paths and test data -- **Role**: Quality assurance - detect refinement result changes - -**Monolithic Design Rationale:** -Phase 1 keeps all implementation in `kicker.py` intentionally: -- Simplifies development during schema evolution -- Easy to understand complete workflow in one file -- Refactoring to modules planned for Phase 2 when API stabilizes -- Comments saying "upstream" or "will be handled elsewhere" refer to future refactoring - -### Adding a Refinement Engine - -PowderLine's engine seam makes new backends cheap to add. The dispatcher -(`src/powderline/engine.py`) is a small `_ENGINES` tuple plus one lazy-import -branch per engine; every engine returns the **same result-dict shape**, locked -by `tests/test_api.py`. The TOPAS (`src/powderline/topas/`) and easydiffraction -(`src/powderline/easydiff/`) subpackages are the two reference implementations. - -The established pattern: - -1. **New subpackage** `src/powderline//` holding all engine logic: - translation (`builder`/`writer`), execution (`runner`), result parsing, unit - conversions, and a `run__recipe(recipe, output_dir, ...)` adapter that - returns the locked result dict. -2. **One lazy-import branch** in `powderline/engine.py` (add the name to - `_ENGINES`). Import the engine module only inside that branch so machines - without the engine's dependencies can still use the others. -3. **No schema changes** — engines translate the existing `GSASII_*` recipes; - they do not define their own recipe format. -4. **Reject unsupported features loudly** — a recipe feature the engine cannot - represent raises a translation error (or, if it's a *fixed* unmappable value, - is dropped with a recorded warning). Never silently ignore a refine flag. -5. **Optional pixi feature/environment** if the engine needs dependencies the - default environment shouldn't carry (e.g. easydiffraction needs Python ≥3.12, - so it lives in the optional `easydiff` environment). -6. **Keep it GSAS-II-free** if it can be — the alternate engines import zero - GSAS-II, a property enforced by subprocess import-block tests. - -**Simulation-mode semantics across engines.** The GSAS-II engine treats -`refinement_cycles == 1` as simulation and *rejects* any refine flag set in that -mode (`validate_simulation_mode_parameters` in `kicker.py`). The alternate -engines (TOPAS, easydiffraction) instead treat "no parameters flagged for -refinement" as simulation and do not enforce the `cycles == 1` lock. For -well-formed recipes the behavior matches; the two definitions only diverge on -inconsistent input (`cycles == 1` *with* a stray refine flag), which GSAS-II -refuses and the alternate engines would run. Uniform input-contract enforcement -across all engines is a tracked follow-up (see the PowderLine-devkit -easydiffraction dossier — a private maintainers' repo, access on request). - -### Schema Design: Why `extra='allow'`? - -Nearly all Pydantic models use `ConfigDict(extra='allow')` to permit fields not explicitly defined (the one exception is `RefinementParameterModel`, which uses `extra='forbid'`): - -```python -class RecipeModel(BaseModel): - model_config = ConfigDict(extra='allow') -``` - -**Rationale:** -- **Schema evolution**: Example-driven design means new fields emerge as examples are added -- **Backwards compatibility**: Old recipes continue working when new fields are added -- **Flexibility**: Users can add custom metadata without validation errors -- **Trade-off**: Typos in field names won't be caught (acceptable for Phase 1 iteration speed) - -Future phases may tighten validation to `extra='forbid'` once schema stabilizes. - -### The "Upstream" Pattern - -You'll see several TODO markers like `# TODO: validation will be handled upstream` throughout kicker.py. This means: - -- **Currently**: Validation happens in helper functions (e.g., check coefficient count in `set_chebyshev_background`) -- **Future**: Validation moves to Pydantic schema (separation of concerns) -- **Not implemented yet**: Still evolving what validation logic belongs where - -The pattern reflects Phase 1's iterative approach - implement in helper functions first, refactor to schema later. - -### File-less Schema Architecture - -PowderLine uses file-less JSON payloads. All data (XRD patterns, structures, instrument parameters) is embedded directly in JSON. File handling (loading XRD data from .chi files, parsing CIF structures, reading instrument parameters) occurs upstream of PowderLine. - -**Embedded Data Format:** -- **XRD data**: "xrd_data" contains "tth", "Itth", "Itth_weights" arrays -- **Structure**: "structure" contains "space_group", "unit_cell", "atoms" dictionaries -- **Instrument**: "instrument" contains "initialization" and optional "parameterization" dictionaries - -This design enables PowderLine to focus on refinement logic while delegating file I/O to upstream tools. - -### Phase Name Resolution - -In PowderLine, phase names come from the `phase_name` field in the embedded structure dictionary: - -```python -# Phase name is explicitly specified in structure -"phases": { - "LaB6": { # This becomes the phase identifier - "structure": { - "phase_name": "LaB6", # Must match the key above - "space_group": "P m -3 m", - ... - } - } -} -``` - -The phase name is used consistently throughout: -- Phase dictionary keys -- Structure `phase_name` field (must match key) -- Parameterization references -- Output file naming - -This ensures consistent phase identification throughout refinement and output generation. - -### Server Architecture (Three-Layer Execution Stack) - -`powderline.run()` dispatches through three layers: - -``` -powderline.run() / CLI - │ validates recipe, normalises DataFrames - ▼ -GSASClient.submit_simulation() - │ routes: HTTP server ──or── in-process fallback - ▼ -run_refinement() - │ single execution engine, returns JSON-serializable primitives - ▼ -GSAS-II (GSASIIscriptable) -``` - -**`_submit_via_subprocess` is in-process, not an OS subprocess.** Despite its name, -this method calls `run_refinement()` directly in the current interpreter. The name -has been retained for API stability; if crash-isolation is needed in a future phase -it can be upgraded to `multiprocessing` without changing callers. - -**`execution_mode` vs `method` — two distinct concepts:** -- `powderline.run()` accepts `execution_mode=` (`'auto'` | `'server'` | `'subprocess'`) as its public input parameter. -- `run_refinement()` accepts `method=` as its internal parameter (values: `'server'` | `'subprocess'` | `'test'`). -- Both `run_refinement()` and `GSASClient` include `method` as a **result dict output key** (`result['method']`) recording which execution path was used. -- These are not a renamed pair — they serve different roles at different layers of the stack. - -The FastAPI server (`gsas_server.py`) keeps GSAS-II imported in one persistent -process, amortising the ~2.6 s import cost across all requests. Requests are handled -synchronously (one-at-a-time) by design — concurrency is not needed for the current -single-user CLI and programmatic-API use cases. - -**After modifying any Python source file** (`kicker.py`, `schema.py`, or any other -module under `src/`), restart the server so the running process loads the new code: - -```bash -pixi run gsas-server restart -``` - -The server loads kicker.py at startup and caches it. Changes are invisible to the -running server until it is restarted. - ---- - -### MP Pipeline Status - -The Materials Project integration (`mp_interface.py` / `mp_simulate.py` / -`simulation_builder.py`) targets the current `mp-api` client (pinned -`>=0.46,<1` in `pixi.toml`) and recipe schema 0.26.0. - -**Updated for mp-api 0.46.x (previously written against older client behavior):** - -1. **Single summary fetch** — `get_structure()` uses - `client.materials.summary.search(material_ids=[...], fields=[...])` (one - request for structure + symmetry + energetics) instead of the legacy - `get_structure_by_material_id()` convenience method. -2. **Conventional-cell standardization** — MP's computed structure is often a - primitive cell; it is now standardized via - `SpacegroupAnalyzer(...).get_conventional_standard_structure()` so the - emitted space-group symbol matches the emitted cell. (Previously a - centered-lattice primitive cell was paired with the conventional H-M - symbol — wrong phase for anything non-primitive; LaB6 only worked because - its primitive and conventional cells coincide.) The symbol is derived from - the standardized structure itself (spglib condensed style with screw-axis - underscores stripped, e.g. `Pm-3m`, `I41/amd`), - which `kicker.py` normalizes via `G2spc.StandardizeSpcName`. -3. **`MPID` stringification** — search results now return `material_id` as - `str`; previously raw `MPID` objects crashed `material_id.startswith('mp-')` - on the `--formula` path. -4. **Polymorph selection** — `search_by_formula()` returns results sorted by - `energy_above_hull` (None last); the CLI lists all candidates and - auto-selects the most stable one, printing the choice. -5. **Partial occupancy support** — sites are extracted per species - (`site.species.items()`), carrying real occupancies into the recipe - (`AtomStructure.occupancy`); disordered structures no longer crash on - `site.specie`. `get_structure()` reports `is_ordered`. -6. **Error taxonomy** — `MPInterfaceError` base with `MPAuthError`, - `MPNotFoundError`, `MPConnectionError`; the CLI prints targeted hints - instead of a generic wrapped exception. -7. **Metadata fixes** — `crystal_system` now holds the actual crystal system - (previously the space-group number, now under `space_group_number`); - `nelements` now holds the element count (previously atom count, now under - `num_atoms`); `energy_above_hull` and `theoretical` added. -8. **Key handling** — API key resolution is config file first, then the - `MP_API_KEY` environment variable (`ConfigLoader.get_mp_api_key()`); - `MPInterface` is a context manager that closes the HTTP session. -9. **Server output-visibility guard** — a GSAS-II server can be reachable - over localhost yet have a divergent filesystem view (another node; a - sandbox with a private `/tmp`), reporting success while its output files - are invisible to the client. `GSASClient` verifies `fit_profile.txt` was - freshly written client-side after a "successful" server run (stat-compare - before/after — a stale file from a previous run into the same output dir - does not count) and falls back to in-process execution (or returns a - structured error when fallback is disabled). `mp-simulate --no-server` - skips the server entirely, and its `.chi` export is built from the - in-band `fit_profile` result data rather than re-reading the file. - Tests: `tests/test_gsas_client_visibility.py`, `tests/test_mp_simulate_cli.py`. - KI-12 tracks the follow-up that removes the shared-filesystem assumption - altogether (server returns output artifacts in-band). -10. **Strict config validation** — `SimulationRecipeBuilder` validates the - `simulation_defaults` block against its allowed shape: unknown keys at any - level (typos, the retired flat layout) and invalid values (null from an - empty YAML key, strings where numbers belong) raise a `ValueError` naming - the offending key path; the CLI exits with that message. These previously - passed `RecipeModel` validation (the instrument block is `Any`-typed - passthrough) and failed opaquely inside GSAS-II. - -**Historical (schema 0.21 → 0.26 fixes, retained by the regression suite):** -payload wrapper, `schema_name`, `isotropic_size`/`isotropic_strain` renames, -`recipe=` keyword for `GSASClient.submit_simulation()`. - -**Regression guard:** `tests/test_mp_interface.py` (mocked MPRester — real -pymatgen Structures, no live API) and `tests/test_mp_pipeline.py` run as part -of the standard test suite (`pixi run test`): - -```bash -pixi run pytest tests/test_mp_interface.py tests/test_mp_pipeline.py -v -``` - -**Limitation:** `mp_simulate.py` requires a live Materials Project API key to -fetch structures. The test suite uses mocks and a synthetic LaB6 fixture -(`mp_lab6_structure_data` in `conftest.py`) so no API key is needed for testing. - ---- - -### Future: File-less Output Design - -Currently `run_refinement()` always writes output files to `output_dir`. Two -options are under consideration for making file output optional: - -**Option A — `save_files` flag (default `False`)** -```python -result = powderline.run(recipe, output_dir=None, save_files=False) -# Returns DataFrames; no files written -``` -- Simplest API change; easy to add without breaking existing calls -- Requires `output_dir` to be optional throughout the stack - -**Option B — optional `output_dir` (default `None`)** -```python -result = powderline.run(recipe) # no files -result = powderline.run(recipe, output_dir=Path("/tmp/out")) # files + DataFrames -``` -- Slightly more discoverable ("no `output_dir` = no files") -- Requires `output_dir=None` guard at every write site in `run_refinement()` - -Both options are backwards-compatible additions. This will be evaluated alongside -the Phase 2 module refactoring work. - ---- - -## Development Workflow - -### Environment Setup - -PowderLine uses [pixi](https://pixi.sh) for reproducible conda environments: - -```bash -# Install dependencies (first time) -pixi install - -# Activate environment -pixi shell - -# Run refinement -pixi run kicker examples/example_LaB6/input.json - -# Run tests -pixi run test - -# Validate recipe only (no refinement) -pixi run kicker --validate-only examples/example_LaB6/input.json -``` - -**PYTHONPATH Configuration:** -The `kicker` task in `pixi.toml` sets `PYTHONPATH=$PWD/src:$PYTHONPATH` to enable `from powderline.schema import RecipeModel` imports. - -### Execution Modes - -PowderLine supports three execution modes for running refinements: - -#### 1. Auto-Detect Mode (Default) -```bash -pixi run kicker input.json -``` -- **Behavior**: Tries server → auto-starts if needed → falls back to subprocess -- **Performance**: 0.1-0.3s per simulation (if server available), 1-2s (if fallback) -- **Use case**: Normal development workflow - "just works" -- **Output**: Shows "🚀 server mode" or "🐢 subprocess mode" at end - -#### 2. Force Server Mode -```bash -pixi run kicker input.json --use-server -``` -- **Behavior**: Uses server only, **fails if unavailable**, no fallback -- **Performance**: 0.1s per simulation (10x+ faster than subprocess) -- **Use case**: Batch processing, CI/CD where performance matters -- **Auto-start**: Attempts to start server automatically if not running -- **Error handling**: Exits with clear error if server can't be started - -#### 3. Force Subprocess Mode -```bash -pixi run kicker input.json --no-server -``` -- **Behavior**: Direct in-process execution using loaded GSAS-II libraries, skip server entirely -- **Performance**: 1-2s per simulation (slower; GSAS-II imported on first use) -- **Use case**: Debugging, HPC/Slurm batch jobs, environments where the server is not suitable -- **Output**: Returns the same full structured result (DataFrames) as server mode - -#### Managing the Server - -**Start server manually:** ```bash -pixi run gsas-server start # Starts in background -pixi run gsas-server status # Check if running -pixi run gsas-server stop # Shutdown server -``` - -**Server state and security (per user):** the server binds `127.0.0.1` on a -free ephemeral port and writes its lock, PID, log, and an endpoint file (port + -random secret token) — all mode 0600 — to a private per-user state directory: -`$XDG_RUNTIME_DIR/powderline` (if it is a real directory owned by you), else -`/powderline-` on POSIX (mode 0700; refused if it is a symlink, -owned by someone else, or group/other-accessible, or if the temp directory -would let others replace it), and `%LOCALAPPDATA%\powderline` on Windows. On -POSIX the files are opened relative to a re-verified, no-follow directory -handle. +pixi install -e dev # every engine + docs/test tooling (contributors) +pixi install -e gsasii # GSAS-II only +pixi run kicker --validate-only # default env: engine-free +pixi run -e gsasii kicker # run a gsasii.* recipe +pixi run -e easydiffraction kicker # run an easydiffraction.* recipe +pixi run test # engine-free suites (core + topas_gen), any env +pixi run -e dev test-all # every suite, the pre-merge gauntlet +pixi run -e gsasii pytest tests/test_example_LaB6_regression.py -q # one engine's suite +pixi run docs # Sphinx with -W (zero warnings is the standard) +pixi run -e gsasii gsas-server start|status|stop|restart|logs +pixi run update-code-hash # after a signed edit to a frozen gsasii module +pixi reinstall powderline --all # after editing entry points / [project.scripts] +``` + +The default feature carries only PowderLine's runtime dependencies plus +pytest; `gsasii`, `easydiffraction`, `all` and `dev` are features/environments +in `pixi.toml`. `test` and `update-code-hash` live in the default feature and run anywhere; +tasks only `dev` has (`test-all`, `docs`, `docs-clean`) resolve without `-e`; engine-bound tasks live in their engine's feature, so pixi +reports them as ambiguous without `-e` and prints the form to use. Tasks that +import PowderLine set `PYTHONPATH` through the task-level `env` dict (cross-platform; +[cross-platform guide](cross-platform-guide.md)). + +### Execution modes (gsasii) + +| Mode | Command | Behaviour | +|---|---|---| +| auto (default) | `pixi run -e gsasii kicker input.json` | tries the server, auto-starts it, falls back to in-process | +| server | `... --use-server` | server only; fails if it cannot be started | +| in-process | `... --no-server` | skips the server; GSAS-II imported in this process | + +The server amortizes GSAS-II's import (~2.6 s) over many runs (batch jobs: +0.1–0.3 s per run against 1–2 s in-process). It **caches code**, so restart it +after editing anything under `src/` it executes; since 0.2.0 a forgotten +restart is caught: `/health` reports the PowderLine version and an MD5 of the +source tree the server loaded (`server.source_tree_hash()`), the client +compares both with its own and treats a mismatch as a **stale** server — +`auto` mode says so and runs in-process, `--use-server` fails with +`server_unavailable` naming `gsas-server restart`, and `gsas-server status` +prints `Code: STALE`. + +**No shared filesystem (KI-12):** the client sends the recipe inline and +the server runs each job in a private scratch directory under its state dir; +every output file comes back base64-encoded inside the signed response +(`files`, GSAS-II's `*.bak*.gpx` backups excepted) and the client writes it +into its own `output_dir` (atomic replace, retried on Windows). A server on +another node or in a container therefore behaves like a local one; a client +that cannot write its directory fails with `backend_error`, a malformed or +oversized transfer with `communication_failed` (auto mode then runs +in-process). + +**Server state and security (per user, v0.1.2):** the server binds `127.0.0.1` +on a free ephemeral port and writes its lock, PID, log, and an endpoint file +(port + random secret token) — all mode 0600 — to a private per-user state +directory: `$XDG_RUNTIME_DIR/powderline` (if it is a real directory owned by +you), else `/powderline-` on POSIX (mode 0700; refused if it is a +symlink, owned by someone else, or group/other-accessible, or if the temp +directory would let others replace it), and `%LOCALAPPDATA%\powderline` on +Windows. On POSIX the files are opened relative to a re-verified, no-follow +directory handle. The token never travels over the wire: every request carries a fresh nonce, a timestamp and an HMAC-SHA256 over method, path, nonce, timestamp and body, and -the server rejects anything unsigned, wrongly signed, stale, or replayed — -on every route, including 404/405/422 — before reading the body. Every -response is signed back over the nonce, status and body, and the client -discards unsigned responses. Other users on a shared host therefore can -neither submit jobs to your server nor impersonate it (e.g. by taking over the -port of a crashed server). `gsas-server start` takes a kernel-held lock -(`flock` / `msvcrt.locking` on `server.lock`) for the server's lifetime; the -OS releases it when the process exits, so concurrent auto-starts never spawn -duplicates and leftover PID files can never make a dead server look alive. +the server rejects anything unsigned, wrongly signed, stale, or replayed — on +every route, including 404/405/422 — before reading the body. Every response +is signed back over the nonce, status and body, and the client discards +unsigned responses. Other users on a shared host therefore can neither submit +jobs to your server nor impersonate it (e.g. by taking over the port of a +crashed server). `gsas-server start` takes a kernel-held lock (`flock` / +`msvcrt.locking` on `server.lock`) for the server's lifetime; the OS releases +it when the process exits, so concurrent auto-starts never spawn duplicates +and leftover PID files can never make a dead server look alive. + +**One refinement at a time:** the server runs `/simulate` requests strictly in +sequence (GSAS-II's module-level state is not thread-safe); concurrent clients +queue (up to the ASGI thread pool's size, 40 by default; `/health` is not +behind the lock). **Port problems are reported, not crashed:** a malformed +`POWDERLINE_SERVER_PORT` is refused up front by `gsas-server start` and by a +client about to auto-start (`ExecutionBackendError`, `server_unavailable`, +naming the variable); a busy port fails the start before GSAS-II is imported, +with the port named, and a client whose auto-started server exits at start +reports the exit and points at the server log. **Pin the server port** (only if needed — the default ephemeral port avoids collisions between users): ```bash export POWDERLINE_SERVER_PORT=19472 -pixi run gsas-server start -pixi run kicker input.json # client reads the port from your state directory +pixi run -e gsasii gsas-server start +pixi run -e gsasii kicker input.json # the client reads the port from your state directory ``` **Disable the server entirely** (shared workstations, locked-down deployments): @@ -846,323 +537,183 @@ export POWDERLINE_NO_SERVER=1 # also: true / yes / on ``` With it set, `execution_mode='auto'` (and the CLI default) runs in-process and never starts a server, `execution_mode='server'` / `--use-server` fail with a -clear error, and `pixi run gsas-server start|restart` refuse. +clear error, and `pixi run -e gsasii gsas-server start|restart` refuse. **View server logs** (`server.log` in the state directory; `status` prints the path): ```bash -pixi run gsas-server logs +pixi run -e gsasii gsas-server logs ``` -**Server benefits:** -- GSAS-II libraries loaded once (2.6s startup amortized across requests) -- Direct function calls using pre-loaded libraries (no subprocess overhead) -- Persistent process (no repeated Python interpreter startup) -- Ideal for batch simulations (10+ recipes) -- Connection retry logic (3 attempts with exponential backoff) handles transient issues - -**Server caching behavior:** - -The server keeps Python modules loaded in memory for performance. This means: -- ✅ **Production benefit**: 4-6x speedup (first run ~12s, subsequent ~2-3s) -- ⚠️ **Development caveat**: Code changes require server restart to take effect - -**During active development:** -```bash -# After making code changes to kicker.py or other modules: -pixi run gsas-server restart # gracefully restart with updated code - -# Next run will use the freshly started server with current code -pixi run kicker input.json -``` - -**For deterministic integration tests:** -```bash -# Restart the server first so tests run against current code -pixi run gsas-server restart -pixi run pytest tests/test_schema.py -q -``` - -See [TROUBLESHOOTING.md](TROUBLESHOOTING.md) ("Stale Server (Old Code Running)") for details on stale server issues. - -**When to use each mode:** -- **Auto-detect**: Default for interactive use -- **--use-server**: Batch processing, automation, performance-critical -- **--no-server**: Debugging kicker.py, isolated testing, server issues - -#### Performance Comparison (Post-Fix ✅) - -| Mode | LaB6 Simulation | DRX_33 Multi-phase | Typical Use | -|------|----------------|-------------------|-------------| -| Server (--use-server) | 0.1s | 0.3s | Batch jobs | -| Auto-detect (default) | 0.1-2s | 0.3-3s | Interactive | -| Subprocess (--no-server) | 1.1s | 3s | Debugging | - -**Speedup**: Server mode is **10.67x faster** than subprocess for LaB6 simulations. - -*Times measured on NSLS-II workstation post-fix* - -### Adding a New Refinement Parameter +### Adding a new recipe field (any engine) -Follow this pattern (using size broadening as example): +1. **Schema**: add the field to the engine's `schema.py` (unit metadata, + validators, refusals; for a structural quantity, to `schema_core`). +2. **Gateway**: consume it from the validated model in the runtime layer + (gsasii: a non-frozen module, or a signed-off edit for a frozen read). +3. **Fixture + golden**: a native recipe stating it and the engine's output. +4. **Example** if it is a real case: `examples//` with `DESCRIPTION.md` + and, for gsasii, the committed output (regression reference). +5. **Docs**: `scripts/gen_schema_field_tables.py`, SCHEMA_HISTORY, the + input-guidance / engine-behaviour pages as needed, CHANGELOG. -1. **Add to schema** (`schema.py`): - ```python - class PeakBroadening(BaseModel): - size_broadening: dict[str, RefinementParameter | None] | None = None - ``` +### Adding a new example -2. **Create setter function** (`kicker.py`): - ```python - def set_phase_size_broadening(proj, hist, phase_name, size_dict, print_info=False): - """Set crystallite size broadening for phase-histogram pair.""" - # Extract from size_dict - size_val = size_dict['size'] - # Access proj.data dictionary - hap = proj.data[hist.name]['Histograms'][phase_name] - hap['Size'] = [size_val[0], size_val[1], 'isotropic', [0, 0], 1.0, size_val[1]] - ``` +Examples drive schema evolution; see `examples/CONTRIBUTING_EXAMPLES.md`. +Directory `examples//` with `input.json` (the `gsasii.*` recipe), +`DESCRIPTION.md`, `output/` (committed GSAS-II results as regression +references), and optionally `topas/input.json`, `easydiffraction/input.json` +with a README each. An `easydiffraction/output/` folder holds that engine's +committed reference results (checked against the easydiffraction goldens); +TOPAS references live as goldens under `tests/data/topas/native/golden//` +(they come from a TOPAS machine; the directory is the fixture's `engine_version`). -3. **Integrate into parameterization** (in main execution): - ```python - if phase_param.peak_broadening and phase_param.peak_broadening.size_broadening: - set_phase_size_broadening(proj, hist, phase_name, - phase_param.peak_broadening.size_broadening) - ``` +### Running tests -4. **Add example** (create directory under `examples/`): - - `input.json` with new parameter - - `DESCRIPTION.md` explaining use case - - Run refinement and commit output files - -5. **Add test** (if example becomes reference): - ```python - def test_example_with_size_broadening(tmp_output_dir): - # Run refinement, compare outputs - ``` - -### Adding a New Example - -Examples drive schema evolution. To contribute: - -1. **Create directory**: `examples/example_N/` -2. **Add required files**: - - `input.json` - complete recipe - - `DESCRIPTION.md` - what refinement demonstrates, data source, expected results -3. **Run refinement**: `pixi run kicker examples/example_N/input.json` -4. **Commit outputs**: `output/` directory with .gpx, .lst, .csv files -5. **Update schema** if new fields needed -6. **Add regression test** if example becomes quality reference - -See `examples/CONTRIBUTING_EXAMPLES.md` for detailed guidelines. - -### Running Tests +Every test carries exactly one suite marker (`pyproject.toml` +`[tool.pytest.ini_options] markers`; `tests/conftest.py` refuses a collection +where one is missing or doubled), and the pixi tasks select on them: ```bash -# All tests +# Engine-free suites (core + topas_gen): any env, the default one included. +# Installs the core guard: an engine import or a tc.exe run fails loudly. pixi run test -# Specific test file -pixi run pytest tests/test_example_LaB6_regression.py - -# With verbose output -pixi run pytest -v - -# See stdout/stderr -pixi run pytest -s -``` - -**Regression test strategy:** -- Exact matching of Rwp, unit cell parameters, peak counts -- Detects any changes in GSAS-II refinement algorithm -- Reference outputs committed to git for comparison -- If test fails: inspect .lst file to determine if change is expected or bug - -**Note on test speed:** All tests currently run as a single suite (`pixi run test`). Introducing `@pytest.mark.slow` / `@pytest.mark.integration` markers to allow skipping GSAS-II-dependent tests in CI is planned. - -### Template File Detection - -PowderLine prevents users from accidentally running template files with three-level detection: - -1. **Path check**: Filename/directory contains "template" -2. **Required fields check**: Missing `payload.xrd_data`, `payload.instrument`, or `payload.phases` -3. **Placeholder text check**: Fields contain `"XXXX"` or `"TODO"` or `"REPLACE"` +# Engine suites, each in its env (the slow regressions are part of test-gsasii) +pixi run -e gsasii test-gsasii +pixi run -e easydiffraction test-easydiffraction -If detected, shows error with helpful message directing to real examples. +# TOPAS: generation everywhere; the topas_exec tests run tc.exe on the TOPAS +# machine when POWDERLINE_TOPAS_DIR and POWDERLINE_TOPAS_VERSION are set +# (PowerShell: $env:POWDERLINE_TOPAS_DIR='C:\TOPAS6'; $env:POWDERLINE_TOPAS_VERSION='6') +pixi run test-topas -## Key Gotchas & Implementation Notes +# Everything, in the dev env -- the pre-merge gauntlet +pixi run test-all -### Output File Formats - -After refinement, PowderLine generates (fixed filenames): -- **`dummy.gpx`**: GSAS-II project file (can reopen in GUI) -- **`dummy.bak0.gpx`**: Backup before refinement started -- **`dummy.lst`**: Human-readable refinement log with Rwp, parameter tables, correlations -- **`fit_profile.txt`**: 2θ, observed, calculated, background, difference intensities -- **`_unit_cell_report.csv`**: Refined unit cell parameters per phase -- **`_peak_list_report.csv`**: Reflection list (hkl, d-spacing, 2θ, intensities) per phase - -For single peak fitting (SPF) mode: -- **`single_peaks_report.txt`**: Peak fit results (position, width, intensity per peak) -- **`peak_convergence_diagnostics.txt`**: Convergence warnings for aphysical parameters - -**Note**: Output filenames are now fixed (`dummy.*`) regardless of sample name. This simplifies automation and testing by eliminating filename variability. - -### Parameter Correlation Warnings - -GSAS-II may print warnings about highly correlated parameters (e.g., background coefficients): -``` -** Warning: parameters 0 and 1 are 99.8% correlated ** +# Extra pytest arguments pass through +pixi run test -x -k schema +pixi run -e gsasii test-gsasii -m "gsasii and not slow" ``` -This is **normal** for over-parameterized models. Common causes: -- Too many Chebyshev background terms -- Refining both instrument and sample broadening simultaneously -- Limited 2θ range - -Not necessarily a problem if Rwp is good and parameters are physically reasonable. - -### Unit Cell Refinement Semantics (Schema 0.26) -GSAS-II natively refines all unit cell parameters together with a single lumped flag, but since schema 0.26 PowderLine honors per-parameter flags: a cell parameter refines iff it is present with `refine_flag=true`; absent or false means fixed. Internally, PowderLine sets the lumped GSAS-II flag when any parameter is requested and emits "Hold" constraints for the unrefined degrees of freedom (`src/powderline/constraints.py`): - -```json -"unit_cell": { - "a": [11.777, true, null, null], // refines - "c": [3.986, false, null, null] // held fixed (e.g. a tetragonal phase) -} -``` - -Only symmetry-linked parameters refine together: parameters coupled by the phase's Laue class form one degree-of-freedom group with logical OR within the group. For example, cubic `a=b=c` is a single group (any true flag refines all three), and the oblique monoclinic parameters `a`/`c`/`beta` form one coupled group (see KI-02 in `docs/known_issues.md`). Flags on symmetry-fixed parameters (e.g. cubic angles) have no effect. PowderLine does not validate flag/symmetry consistency — producing symmetry-consistent flags is the recipe author's responsibility. - -### Chebyshev Background Coefficients - -Indexing starts from 0th order (constant term): -```json -"coefficients": [ - [100.0, true, null, null], // 0th order (constant) - [-50.0, true, null, null], // 1st order (linear) - [10.0, true, null, null] // 2nd order (quadratic) -] -``` +Markers: `core` (imports no engine, runs no engine subprocess -- the schema +layer of every gateway included), `gsasii`, `topas_gen` (engine-free TOPAS +input generation), `topas_exec` (tc.exe), `easydiffraction`, plus the optional +`slow` (a full refinement runs). `POWDERLINE_CORE_GUARD=1` forces the guard on +for a path or `-k` selection; `=0` turns it off. -Number of coefficients must match `num_coefficients` field (validated in schema). - -### Single Peak Background Format - -Each single peak is a pseudo-Voigt with 4 parameters: -```json -"background": { - "single_peaks": { - "positions": [[35.5, false, null, null]], // 2θ position - "intensities": [[50.0, true, null, null]], // Peak height - "pv_gaussian_sigma": [[0.1, false, null, null]], // Gaussian width (σ) - "pv_lorentzian_gamma": [[0.05, false, null, null]] // Lorentzian width (γ, HWHM) - } -} -``` - -All lists must have same length (validated in schema). Useful for known impurity peaks that are part of the background. - -**Note**: `pv_mixing_eta` parameter not currently implemented in schema. - -### Single Peak Fitting (Peak List Mode) - -Earlier schemas introduced dedicated single peak fitting capabilities via the top-level `single_peaks` field (distinct from `background.single_peaks`), maintained in the current schema. - -This enables refining individual peaks with direct control over position, intensity, and pseudo-Voigt width parameters—useful for: -- Materials without crystal structure (amorphous, liquids, polymers) -- Unknown phases requiring peak characterization before structure solution -- Detailed peak shape analysis independent of structure -- Le Bail fitting (fit peak intensities without structural model) - -**Key Features:** -- **Independent width refinement**: With `use_instrument_profile: false`, peak widths (σ, γ) refine directly rather than being derived from instrument parameters (U, V, W, X, Y, Z) -- **Coexistence**: Both `background.single_peaks` and `single_peaks` can be used in same recipe—they populate different GSAS-II structures -- **Extended output**: Generates `single_peaks_report.txt` with refined parameters plus calculated FWHM and integral breadths - -**JSON Structure:** -```javascript -// use_instrument_profile lives in refinement_controls.single_peak_fitting_mode -// (false = direct width refinement), not inside single_peaks: -"single_peaks": { - "positions": [[21.3, true, null, null], [...]], // 2θ positions - "intensities": [[100.0, true, null, null], [...]], // Peak intensities - "pv_gaussian_sigma_sq": [[0.15, true, null, null], [...]], // Gaussian width variances (σ²) - "pv_lorentzian_gamma": [[0.08, true, null, null], [...]] // Lorentzian widths (γ, HWHM) -} -``` - -**Implementation Details:** -- **GSAS-II Location**: Peaks stored in `proj.data[hist.name]['Peak List']['peaks']` (not Background) -- **Format**: Each peak is `[pos, pos_flag, intensity, int_flag, σ², σ²_flag, γ, γ_flag]` - - Note: GSAS-II uses **variance** (σ²) internally, not σ -- **Instrument mode**: Set via `G2pwd.setPeakInstPrmMode(use_instrument_profile)` - - `False` (default): Peak widths refined independently - - `True`: Widths constrained by instrument parameters (U, V, W, X, Y, Z) - -**Output File: `single_peaks_report.txt`** - -Tab-separated file with 10 columns per peak: -``` -position_2theta intensity sigma gamma fwhm_gaussian fwhm_lorentzian fwhm_pseudovoigt integral_breadth_gaussian integral_breadth_lorentzian integral_breadth_pseudovoigt -``` - -**Calculated Values:** -- **FWHM values**: - - Gaussian: FWHM_G = 2√(2ln2) × σ ≈ 2.355σ - - Lorentzian: FWHM_L = 2γ - - Pseudo-Voigt: Thompson et al. (1987) approximation -- **Integral Breadths**: Area under peak / peak height - - Gaussian: IB_G = FWHM_G × √(π/(4ln2)) ≈ 1.065 × FWHM_G - - Lorentzian: IB_L = π × γ = (π/2) × FWHM_L - - Pseudo-Voigt: Weighted combination using mixing parameter η - -**Verification**: FWHM values are cross-checked against GSAS-II's `G2pwd.getgamFW(γ, σ)` with warning if >1% difference. - -**Example**: See `examples/example_LaB6_singlepeakfit/` for complete demonstration. - -**Schema Classes:** -- `SinglePeaksBackground`: For background-associated peaks (`background.single_peaks`) -- `SinglePeaks`: For Peak List fitting (`single_peaks` at top level) - includes `use_instrument_profile` - -### Error Handling Strategy - -PowderLine fails fast with actionable error messages: -- **File loading errors**: Check paths relative to JSON, file permissions -- **Template detection**: Redirect to real examples -- **Validation errors**: Show which field failed Pydantic validation -- **Histogram creation errors**: Check XRD data format, instrument file compatibility -- **Refinement errors**: Check parameter ranges, correlation warnings in .lst -- **Output errors**: Check directory permissions, disk space - -All errors exit with code 1 for automation compatibility. - -## Future Roadmap - -**Phase 2 (Next)**: Recipe generation API -- Python functions to build JSON programmatically -- Template system for common refinement types -- Possible FastAPI wrapper for web service - -**Phase 3**: Output parsing -- Structured extraction of all refined parameters to JSON/CSV/HDF5 -- Quality metrics beyond Rwp (χ², GOF, R-Bragg) - -**Phase 4**: Dash GUI for recipe building -- Visual parameter selection -- Live preview of refinement setup - -**Phase 5**: Dash GUI for results visualization -- Interactive plots of fit profiles -- Parameter evolution across refinement cycles -- Comparison between refinements +**Regression test strategy:** +- Rwp, unit cell parameters and refined values compared within the tolerances + of `regression-tolerance.md`; peak lists by row count +- Detects any change in the engine's refinement result +- Reference outputs committed to git for comparison +- If a test fails: inspect the `.lst` file to determine whether the change is + expected or a bug; a new engine version goes through `engine-versions.md` + + +Suite map: `test_schema_core`, `test_symmetry_core`, +`test_symmetry_characterization` (core rules; all 230 groups against +GSAS-II's site tables), `test_phase_canary` (engine phase models cannot +weaken core), `test_api`, `test_cli`, `test_registry`, `test_compat`, +`test_exceptions`, `test_fitstats`, `test_reports` (core), `test_gsasii_schema`, +`test_gsasii_schema_engine` (GSAS-II's reading of every setting), +`test_gsasii_native_run`, `test_example_LaB6_regression`, `test_esd_extraction`, +`test_per_parameter_flags`, `test_run_refinement_missing_keys`, +`test_constraints_mapping`, `test_code_hash`, the server/client tests +(gsasii), `test_topas_schema`, `test_topas_native`, `test_topas_native_golden` +(12 INPs byte-identical to the TOPAS 6 goldens), +`test_topas_runner` (topas), +`test_easydiffraction_schema`, `test_easydiffraction_native`, +`test_easydiffraction_space_groups` (easydiffraction), +`test_convert_recipe_026` (the migration tool), `test_cross_engine_comparison`, +`test_simulation_builder` (the structure → simulation-recipe builder). + +**Regression strategy:** the gsasii examples' outputs are compared within +the tolerances of [regression-tolerance.md](regression-tolerance.md) +(`tests/subprocess_utils.py`: `refined_params_match`, `unit_cell_match`), +peak lists by row count, GSAS-II's own `.lst` wR as a freeze tripwire and the +uniform `rwp` against a recorded value; TOPAS and easydiffraction against +their goldens (easydiffraction cell rtol 1e-4, values 1e-3). If a regression +test fails, inspect the engine's log and the deliberate-changes policy before +touching a reference. Some gsasii cases need a working GSAS-II refinement +and can fail for environment reasons: compare against the baseline run. + +### Documentation + +`pixi run docs` builds with `-W --keep-going` and `nitpicky`; zero warnings +is the standard. Pages under `docs/_generated/` are written by scripts +(`gen_schema_field_tables.py`: field tables and support matrix; +`cross_engine_comparison.py`: the comparison tables) and pulled in with MyST +`{include}`; regenerate them with the change that affects them. `api.rst` +documents the public API; the schema contract is the generated field tables. + +### Template file detection + +The CLI refuses a recipe whose path contains `template` or whose payload lacks +the blocks its workflow needs (`xrd_data`, `instrument`, `refinement_controls` +and `phases` or `single_peaks`), pointing at the examples. It is a CLI-only +guard: `powderline.run()` trusts its caller. + +## Key gotchas + +- **Restart the GSAS-II server** after code changes; a stale server is the + usual cause of "my fix has no effect". +- **`pixi reinstall powderline --all`** after touching entry points or + `[project.scripts]`, or when the registry reports no gateways (KI-13). +- **Frozen modules** change only through signed-off, recorded edits; `test_code_hash` guards + them; `pixi run update-code-hash` after a signed edit. +- **Generated docs** go stale silently unless regenerated + (`gen_schema_field_tables.py --check`). +- **Parameter correlation warnings** from GSAS-II (`gsasii_refinement_message`: + "parameters 0 and 1 are 99.8% correlated") are normal for + over-parameterized models (background terms, U/V/W, size vs strain); + they matter when a fit does not converge or values are unphysical. +- **Chebyshev coefficients** are indexed from the constant term; their basis + spans the fit window's first and last data points in every engine. +- **Single peak fitting**: `gsasii.spf` widths are σ² (centidegree²) and γ + (centidegree), each ≥ 0.001; with `use_instrument_profile: true` the + widths come from U..Z and the peaks' own width flags must be `false` + (GSAS-II would ignore them silently); `topas.spf` peaks are `xo_Is` with + the instrument peak type convolved with their own `gauss_fwhm` / `lor_fwhm`. + gsasii writes `single_peaks_report.txt` (position, intensity, σ, γ, FWHMs, + integral breadths, convergence) and `peak_convergence_diagnostics.txt` only + when a peak did not converge. +- **Error handling**: validation errors are pydantic's, listed together; + PowderLine's own errors derive from `PowderLineError`; the CLI exits 1 on + any failure. + +## The simulation recipe builder + +`powderline.gateways.gsasii.simulation_builder.SimulationRecipeBuilder` turns a +crystal-structure dict (`space_group`, `unit_cell`, `atoms`, `formula`) into a +`gsasii.rietveld` 0.1.0 simulation recipe: the conventional cell reduced to +symmetry-unique sites with an orbit self-check, two-origin groups moved to +origin choice 2, the canonical space-group name, every default stated, SH/L +0.002, instrument defaults from `.powderline_config.yaml`'s +`simulation_defaults`. The Materials Project fetch and `.chi` export that +drove it (`mp-simulate`) left PowderLine in 0.2.0; RandomXRD carries +its own copy. The recipe's `metadata.materials_project` block (material id, +formula, the space group as stated) keeps its name: it is what the tests and +RandomXRD's copy read, and a source-neutral key is a shape decision for the +maintainer. + +## Future roadmap + +- A later minor gsasii + schema version with bounds (clamp-freeze-refit); TOPAS 7 after a + compatibility run on a TOPAS 7 machine; `unsafe_mode` for deliberately + relaxed checks; a recipe builder / CIF importer upstream of the schemas; + a structure-source plugin (Materials Project, CIF) upstream of the builder. ## Contributing Key principles for future work: - Add features when real examples need them (not speculatively) -- Schema evolves based on examples -- Maintain backwards compatibility when possible -- Document GSAS-II quirks as you discover them -- Add regression tests for new examples +- Every rule in the schema; every engine quirk refused or warned about, and + recorded in the engine-behaviour register +- Behaviour changes are deliberate, recorded and reviewed; references move + only with an equivalence record +- Frozen modules only through signed-off, recorded edits; "ask, don't assume" on any open + decision ([policies](policies.md)) +- Add regression tests, fixtures and goldens for new capabilities Questions? Open an issue or discussion on GitHub. diff --git a/docs/SCHEMA_HISTORY.md b/docs/SCHEMA_HISTORY.md index c7c65b2..83d9b55 100644 --- a/docs/SCHEMA_HISTORY.md +++ b/docs/SCHEMA_HISTORY.md @@ -1,10 +1,523 @@ # Schema Evolution History +PowderLine recipes are validated against a **core schema** (the shared top level +and structural models, owned by PowderLine) plus one **engine schema** per +gateway (`gsasii`, `topas`, `easydiffraction`), each in its engine's native +conventions. Every schema has its own version. A recipe states both +(`core_schema_version`, `engine_schema_version`), and each PowderLine release +**declares** which versions it accepts. Compatibility is never inferred from the +version numbers (`powderline.support_matrix()` lists the declarations). + +> **PowderLine 0.2.0** reads these schemas only. The unified 0.26.0 schema of +> PowderLine 0.1.1 is documented in the archive at the bottom of this page and +> is no longer accepted; `scripts/convert_recipe_026.py` converts a 0.26.0 +> GSAS-II recipe (see the [migration guide](migration-0.1-to-0.2.md)). The +> field tables generated from these schemas are on the [fields page](fields.md). + +## Version numbering: a new line starting at 0.1.0 + +PowderLine 0.2.0 replaces the single recipe schema of PowderLine 0.1.x — +versions 0.1 to **0.26.0**, `schema_name` `GSASII_Rietveld` / `GSASII_SPF` — +with a **core schema** and **one schema per engine** (`gsasii`, `topas`, +`easydiffraction`). Each is versioned separately, and each starts at +**0.1.0** in PowderLine 0.2.0 (`"core_schema_version": "0.1.0"`, +`"engine_schema_version": "0.1.0"`). + +- The old line **ends at 0.26.0**. It is told apart from the new schemas by + `schema_name` (`GSASII_Rietveld` versus `gsasii.rietveld`) and by the split + into `core_schema_version` + `engine_schema_version` (instead of one + `schema_version`), **not by the number**: a new schema at 0.1.0 is not + older than 0.26.0, it is a different schema. +- The new schemas are 0.x because PowderLine is pre-production and they will + still evolve; the bump rule for 0.x versions is in + [policies](policies.md#versioning-and-compatibility). +- `scripts/convert_recipe_026.py` migrates a 0.26.0 GSAS-II recipe to + `gsasii.*` 0.1.0; there is no converter to `topas.*` or `easydiffraction.*` + (see the [migration guide](migration-0.1-to-0.2.md)). + +--- + +## Core schema + +### 0.1.0 — introduced in PowderLine 0.2.0 + +Defined in `src/powderline/schema_core.py`; every engine schema builds on it. + +> **Pre-release revision (not a new version).** Before its first +> release, core 0.1.0 replaced its structure-only phase model (`PhaseStructure` +> with plain values, plus `null`-valued "structure" parameters) with the +> **phase block** described below: one block per phase, every structural +> quantity a refinable parameter, flags and bounds checked against the symmetry, +> and `space_group` in gemmi's canonical spelling. No recipe was ever written +> against the earlier draft. + +- **Recipe frame** (`CoreRecipe`): `schema_name` (`"."`), + `core_schema_version`, `engine_schema_version`, `metadata`, `payload` (typed + by the engine schema). Unknown keys are errors at every level. +- **`metadata`**: free-form and never interpreted; must be JSON-serializable and + at most **1 MiB** as UTF-8 JSON. The cap is the constant + `schema_core.METADATA_MAX_BYTES`; change it there and record the change here. +- **Parameters**: `[value, refine_flag]` (no bounds) or + `[value, refine_flag, min, max]` (bounds the engine honors; `min`/`max` may + be `null` = open). A bounded list where bounds aren't supported is an error. + `value` is always a number and `refine_flag` a JSON boolean; neither is ever + `null`. +- **Data and ranges**: `xrd_data` (2θ in degrees, weights 1/σ², validated as in + 0.26.0); `fit_range` `[min, max]`, with `max > min`, inside the data's 2θ range, holding at least two points with a positive weight. +- **Background**: Chebyshev (`num_coefficients`, `coefficients`, `refine_flag`). + Coefficient semantics are documented per engine. +- **Units** are fixed per field in the schema, never written in a recipe. +- **Numbers** are JSON numbers: a quoted number (`"0.25"`) or a boolean is an + error, never converted. Integer fields (`Multiplicity`, `num_coefficients`) + take a whole number (`4` or `4.0`), not `4.5`. +- **Accepted core versions** (this release): `==0.1.0`. Compatibility is + declared, never inferred ([support matrix](support-matrix.md)). + +- **Phase block** (`Phase`): one block per phase, keyed by the phase name in + the engine payload's `phases` (no `phase_name` field). Core owns + `space_group`, `unit_cell` and `atoms`; each engine schema adds its own phase + fields next to them (e.g. gsasii `scale`, `peak_broadening`) and may add + its own checks, but never redefine, skip or rewrite core's fields and + validation (checked when the engine schema is defined, and by a test). Every structural quantity is a parameter (`[value, flag]`, + or `[value, flag, min, max]` in engines with bounds): cell `a`–`gamma`; atom + `x`, `y`, `z`, `occupancy`, `Uiso` or `U11`…`U23`. `element`, `ADP`, + `Multiplicity` and `space_group` are plain values. Nothing is `null` and + nothing has a default: `occupancy` must be stated; `Multiplicity` (derived, + so optional) is left out when not stated, never `null`. + **Names:** atom labels (the `atoms` keys) and phase names (the engine + payload's `phases` keys) start with a letter and contain only ASCII letters, + digits and `_` (`O1`, `LaB6_a`); phase names, and the atom labels of a + phase, must also differ by more than case. This is the form every engine can use as-is: GSAS-II renames a phase + with surrounding spaces or non-ASCII characters (and its settings were then + skipped), easydiffraction accepts no other atom label, TOPAS writes the names + into its input file, phase names become report file names (which ignore case + on Windows and macOS), and problems are reported at `.`-joined paths + (`atoms.O1.Uiso`). So `"2H-MoS2"` is written e.g. `MoS2_2H`. + Structural interpretation is checked once, in core, so every engine gets the + same structure. **The recipe is the record of the refinement intent**, and + validation never changes what it means. Values fixed or tied by symmetry + follow one rule (see *Symmetry-determined values* below): the first member + of each tie group is stated freely and kept as written; every other value is + derived from the symmetry and must be stated, either exactly (a constant + with a decimal form, such as `0.5` or `0`) or to the precision that states it + beyond doubt (a third, `0.333333`; a value derived from another stated + value). The validated model, which every engine receives, holds the derived + values. PowderLine never rewrites a recipe file; only a Python dump of a + validated model shows a derived value's full spelling + (`0.3333333333333333`), which means the same and validates the same. All problems + are reported together, each at its own field + (`unit_cell`, `atoms.