From d7c066e18d10073c033c0d69971bdd710d489dff Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 28 Sep 2026 15:09:43 -0400 Subject: [PATCH 001/259] docs(claude): add multi-engine refactor-in-progress banner Flag that the architecture described in CLAUDE.md is the pre-refactor v0.1.1 baseline being replaced on branch refactor/multi-engine, and point at the devkit dossiers (05-master-plan.md decision log + the active subplan + 00-pre-planning-findings.md) as the authoritative sources during the refactor. State the A25 "ask, don't assume" escalation rule, the kicker.py freeze + signed-off edit ledger, and the specific known-stale items (schema 0.26.0 exact-match, the engine= arg, GSASII_Rietveld/SPF names, the topas/easydiff layout, the easydiff env, the 6-name API / 4-element parameter list). The banner is removed by re/10, which rewrites this file for the new architecture. Co-Authored-By: Claude Opus 4.8 --- CLAUDE.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/CLAUDE.md b/CLAUDE.md index 3874fe4..582b4bf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1,19 @@ # CLAUDE.md — PowderLine +> ### ⚠️ Multi-engine refactor in progress (v0.2.0) +> **The architecture described below is the pre-refactor v0.1.1 baseline and is being replaced — do not treat it as the target.** Active on branch `refactor/multi-engine`. During the refactor the authoritative sources are, in order: +> 1. `_dev/dossiers/multi-engine/05-master-plan.md` — decision log (§3) + invariants (§4) + orchestration guidance (§6) +> 2. the active `_dev/dossiers/multi-engine/subplans/re-NN-*.md` +> 3. `_dev/dossiers/multi-engine/00-pre-planning-findings.md` — codebase map (file:line anchors) +> +> **Ask, don't assume (master plan A25):** if a decision isn't in the decision log or the active subplan, **stop and ask the maintainer — do not infer** — and record the answer in the dossier before proceeding. +> +> **Frozen:** GSAS-II setup/execution in `kicker.py` is move-only; additive edits go only through the signed-off ledger `_dev/dossiers/multi-engine/tasks/re04-frozen-edits.md`. +> +> **Known-stale below** (being changed — see the decision log): `0.26.0` / `EXPECTED_SCHEMA_VERSION` exact-match → core + per-engine schemas `1.0.0` with *declared* compatibility; the `engine=` arg → removed (engine named by `schema_name`, e.g. `gsasii.rietveld`); `GSASII_Rietveld`/`GSASII_SPF` → `gsasii.rietveld`/`gsasii.spf`; `src/powderline/{topas,easydiff}/` → `src/powderline/gateways/{gsasii,topas,easydiffraction}/`; env `easydiff` → `easydiffraction`; default env → core-only (no engines); the 6-name public API + flat "4-element list" → `RefinableParameter`/`BoundedRefinableParameter` (re/07). +> +> _This banner is removed in `re/10` (docs migration), which rewrites this file for the new architecture._ + 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 — From 3f35c26c1346657c73fb971bcd3a6988af7ad7fc Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Thu, 24 Sep 2026 10:48:00 -0400 Subject: [PATCH 002/259] refactor: de-duplicate phase-existence checks via require_phase decorator Validation exercise per devkit dossiers/multi-engine A22: byte-identical error messages (probe diff empty) and full suite green (492 passed, 3 skipped), matching the v0.1.1 baseline. See devkit dossiers/multi-engine/tasks/require-phase-validation.md. Co-Authored-By: Claude Sonnet 4.5 --- src/powderline/_code_hash.json | 2 +- src/powderline/kicker.py | 62 ++++++++++++++++++++++++---------- 2 files changed, 46 insertions(+), 18 deletions(-) diff --git a/src/powderline/_code_hash.json b/src/powderline/_code_hash.json index 5e3820a..e6f01c5 100644 --- a/src/powderline/_code_hash.json +++ b/src/powderline/_code_hash.json @@ -1,4 +1,4 @@ { "schema_version": "0.26.0", - "kicker_hash": "67826378ba97ed89c55cfb1df7e32ee4" + "kicker_hash": "7cf753703f6b93a0ccdc8c6c4c00f80a" } diff --git a/src/powderline/kicker.py b/src/powderline/kicker.py index 3a38b77..e275e51 100644 --- a/src/powderline/kicker.py +++ b/src/powderline/kicker.py @@ -93,6 +93,46 @@ def unpack_refinement_parameter(param: list | None, param_name: str = "parameter ) +def require_phase(error_suffix: str): + """ + Decorator to check phase existence in project before calling setter functions. + + Args: + error_suffix: The error message suffix (e.g., "Cannot set scale.") + + The decorated function must accept 'proj' as first positional arg and 'phase_name' + as a keyword or positional arg (position determined by inspection). + + Raises: + ValueError: If phase_name is not found in proj.phases() + """ + from functools import wraps + import inspect + + def decorator(func): + @wraps(func) + def wrapper(*args, **kwargs): + # Find proj and phase_name from args/kwargs + sig = inspect.signature(func) + bound = sig.bind(*args, **kwargs) + bound.apply_defaults() + + proj = bound.arguments.get('proj') + phase_name = bound.arguments.get('phase_name') + + if proj is None or phase_name is None: + # Shouldn't happen if decorator is used correctly + return func(*args, **kwargs) + + # Perform the phase existence check + if phase_name not in [p.name for p in proj.phases()]: + raise ValueError(f"Phase '{phase_name}' not found in project. {error_suffix}") + + return func(*args, **kwargs) + return wrapper + return decorator + + def load_recipe_asset(recipe_path: Path) -> dict: """Load a recipe asset from .json, .yaml/.yml, or .txt (YAML).""" ext = recipe_path.suffix.lower() @@ -1313,6 +1353,7 @@ def add_phases_from_dict(proj: Any, hist: Any, phases_dict: dict, print_info: bo ################################################################## # Functions for phase parameterization +@require_phase("Cannot set scale.") def set_phase_scale(proj: Any, hist: Any, phase_name: str, scale_param: list, print_info: bool = False) -> None: """ Set the phase scale factor in the GSAS-II project. @@ -1330,9 +1371,6 @@ def set_phase_scale(proj: Any, hist: Any, phase_name: str, scale_param: list, pr Returns: None """ - if phase_name not in [p.name for p in proj.phases()]: - raise ValueError(f"Phase '{phase_name}' not found in project. Cannot set scale.") - value, refine_flag, min_val, max_val = unpack_refinement_parameter(scale_param, "scale_param") # Set the scale factor value - defaults will be handled upstream in future in validation @@ -1351,6 +1389,7 @@ def set_phase_scale(proj: Any, hist: Any, phase_name: str, scale_param: list, pr if print_info: print(f"Set scale for phase '{phase_name}' to {value} with refine_flag={refine_flag}") +@require_phase("Cannot set unit cell parameters.") def set_phase_unit_cell(proj: Any, phase_name: str, unit_cell_dict: dict, print_info: bool = False) -> list[str]: """ Set the unit cell parameters in the GSAS-II project for a given phase. @@ -1389,9 +1428,6 @@ def set_phase_unit_cell(proj: Any, phase_name: str, unit_cell_dict: dict, print_ # This makes sticking with a project based approach more straightforward. phase_names = [p.name for p in proj.phases()] - if phase_name not in phase_names: - raise ValueError(f"Phase '{phase_name}' not found in project. Cannot set unit cell parameters.") - cell_changed = False cell_params = ['a', 'b', 'c', 'alpha', 'beta', 'gamma'] # must match schema, and match order in GSAS-II @@ -1438,6 +1474,7 @@ def set_phase_unit_cell(proj: Any, phase_name: str, unit_cell_dict: dict, print_ return cell_plan.holds +@require_phase("Cannot set size broadening parameters.") def set_phase_size_broadening(proj: Any, hist: Any, phase_name: str, size_broadening_dict: dict, print_info: bool = False) -> None: """ Set size broadening parameters in the GSAS-II project for a given phase. @@ -1462,10 +1499,6 @@ def set_phase_size_broadening(proj: Any, hist: Any, phase_name: str, size_broade Returns: None """ - - if phase_name not in [p.name for p in proj.phases()]: - raise ValueError(f"Phase '{phase_name}' not found in project. Cannot set size broadening parameters.") - # Extract model type (default to isotropic for backward compatibility) model = size_broadening_dict.get('model', 'isotropic') @@ -1557,6 +1590,7 @@ def _set_isotropic_size_broadening(proj: Any, hist: Any, phase_name: str, size_b # Setting strain broadening should be done in the same way as size broadening # The dictionary structure is very similar. We just need to map to the correct keys in the proj.data structure. +@require_phase("Cannot set strain broadening parameters.") def set_phase_strain_broadening(proj: Any, hist: Any, phase_name: str, strain_broadening_dict: dict, print_info: bool = False) -> None: """ Set strain broadening parameters in the GSAS-II project for a given phase. @@ -1581,10 +1615,6 @@ def set_phase_strain_broadening(proj: Any, hist: Any, phase_name: str, strain_br Returns: None """ - - if phase_name not in [p.name for p in proj.phases()]: - raise ValueError(f"Phase '{phase_name}' not found in project. Cannot set strain broadening parameters.") - # Extract model type (default to isotropic for backward compatibility) model = strain_broadening_dict.get('model', 'isotropic') @@ -1701,6 +1731,7 @@ def has_active_refinement_parameter(atom_param: dict) -> bool: # Function to set atom parameters for a phase +@require_phase("Cannot set atom parameters.") def set_phase_atom_parameters(proj: Any, phase_name: str, atom_parameters_dict: dict, print_info: bool = False) -> list[str]: """ Set atom parameters for a phase in the GSAS-II project. @@ -1787,9 +1818,6 @@ def set_phase_atom_parameters(proj: Any, phase_name: str, atom_parameters_dict: } phase_names = [p.name for p in proj.phases()] - if phase_name not in phase_names: - raise ValueError(f"Phase '{phase_name}' not found in project. Cannot set atom parameters.") - phase_idx = phase_names.index(phase_name) SGData = proj.data['Phases'][phase_name]['General']['SGData'] atom_labels_present = [x[0] for x in proj.data['Phases'][phase_name]['Atoms']] From daace240c7712fc14c60eb6c83d7efdcd32d1f81 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Thu, 24 Sep 2026 17:29:54 -0400 Subject: [PATCH 003/259] fix: require_phase decorator must not bypass the check for None phase/proj Devkit PR review finding (confirmed): the None special-case skipped the existence check, but the original inline checks raise ValueError for phase_name=None and AttributeError for proj=None. Also let sig.bind TypeErrors fall through so native missing-argument messages are preserved. Edge-case probe (phase=None x5 setters, proj=None, missing-args) diff empty vs main; original probe diff empty; full suite 492 passed, 3 skipped. Co-Authored-By: Claude Fable 5 --- src/powderline/_code_hash.json | 2 +- src/powderline/kicker.py | 26 +++++++++++++++++--------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/powderline/_code_hash.json b/src/powderline/_code_hash.json index e6f01c5..489cd31 100644 --- a/src/powderline/_code_hash.json +++ b/src/powderline/_code_hash.json @@ -1,4 +1,4 @@ { "schema_version": "0.26.0", - "kicker_hash": "7cf753703f6b93a0ccdc8c6c4c00f80a" + "kicker_hash": "e2156ec7355642a3557f75f687d124f1" } diff --git a/src/powderline/kicker.py b/src/powderline/kicker.py index e275e51..88a31d4 100644 --- a/src/powderline/kicker.py +++ b/src/powderline/kicker.py @@ -110,21 +110,29 @@ def require_phase(error_suffix: str): import inspect def decorator(func): + sig = inspect.signature(func) + # Decoration-time misuse check: decorated functions must take these args. + assert 'proj' in sig.parameters and 'phase_name' in sig.parameters + @wraps(func) def wrapper(*args, **kwargs): # Find proj and phase_name from args/kwargs - sig = inspect.signature(func) - bound = sig.bind(*args, **kwargs) + try: + bound = sig.bind(*args, **kwargs) + except TypeError: + # Missing/extra arguments: call through so Python raises the + # function's native signature error, as the undecorated + # function would. + return func(*args, **kwargs) bound.apply_defaults() - proj = bound.arguments.get('proj') - phase_name = bound.arguments.get('phase_name') - - if proj is None or phase_name is None: - # Shouldn't happen if decorator is used correctly - return func(*args, **kwargs) + proj = bound.arguments['proj'] + phase_name = bound.arguments['phase_name'] - # Perform the phase existence check + # Perform the phase existence check unconditionally — the original + # inline checks treated phase_name=None as a missing phase + # (ValueError) and proj=None as an AttributeError; both semantics + # are preserved by not special-casing None. if phase_name not in [p.name for p in proj.phases()]: raise ValueError(f"Phase '{phase_name}' not found in project. {error_suffix}") From ab87cc35a8051cca06624af390032765903568d7 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:51:43 -0400 Subject: [PATCH 004/259] refactor(gsasii): move kicker's GSAS-II code into gateways/gsasii (verbatim) Pure cut-paste split of the kicker.py monolith (multi-engine refactor, re/01). Every moved function/class/assignment body is byte-identical; only module docstrings and import lines are new. - gateways/gsasii/{helpers,project,setters,executors,extractors}.py: moved per the re/01 move map. Each module carries kicker.py's import block verbatim (constraints import pointed at its new home) plus explicit sibling imports. DEFAULT_* constants -> helpers.py, InstParm aliases -> project.py (A49). - constraints.py, gsas_server.py, gsas_client.py relocated unchanged to gateways/gsasii/{constraints,server,client}.py; explicit re-export shims at the old paths (gsas_server shim keeps its __main__). - kicker.py keeps run/validate/load_recipe_asset/is_template_file/ validate_simulation_mode_parameters + CLI and its original import block, and re-exports every moved name, so existing imports resolve. - gateways/gsasii/__init__.py imports nothing (GSAS-II stays lazy). Move fidelity: all 56 top-level nodes + __main__ byte-identical, banner comments preserved, relocated files identical (devkit probe re01_move_fidelity.py, source-rev daace24). Co-Authored-By: Claude Opus 5.5 --- src/powderline/constraints.py | 282 +- src/powderline/gateways/__init__.py | 0 src/powderline/gateways/gsasii/__init__.py | 6 + src/powderline/gateways/gsasii/client.py | 454 ++ src/powderline/gateways/gsasii/constraints.py | 266 ++ src/powderline/gateways/gsasii/executors.py | 515 +++ src/powderline/gateways/gsasii/extractors.py | 1010 +++++ src/powderline/gateways/gsasii/helpers.py | 232 + src/powderline/gateways/gsasii/project.py | 561 +++ src/powderline/gateways/gsasii/server.py | 518 +++ src/powderline/gateways/gsasii/setters.py | 1213 ++++++ src/powderline/gsas_client.py | 463 +- src/powderline/gsas_server.py | 537 +-- src/powderline/kicker.py | 3787 ++--------------- 14 files changed, 5076 insertions(+), 4768 deletions(-) create mode 100644 src/powderline/gateways/__init__.py create mode 100644 src/powderline/gateways/gsasii/__init__.py create mode 100644 src/powderline/gateways/gsasii/client.py create mode 100644 src/powderline/gateways/gsasii/constraints.py create mode 100644 src/powderline/gateways/gsasii/executors.py create mode 100644 src/powderline/gateways/gsasii/extractors.py create mode 100644 src/powderline/gateways/gsasii/helpers.py create mode 100644 src/powderline/gateways/gsasii/project.py create mode 100644 src/powderline/gateways/gsasii/server.py create mode 100644 src/powderline/gateways/gsasii/setters.py diff --git a/src/powderline/constraints.py b/src/powderline/constraints.py index 925a4d8..ecfc730 100644 --- a/src/powderline/constraints.py +++ b/src/powderline/constraints.py @@ -1,266 +1,20 @@ -"""Per-parameter refine-flag translation for GSAS-II (schema 0.26.0). +"""Deprecated import path — use ``powderline.gateways.gsasii.constraints``. -GSAS-II exposes only lumped refine flags for three parameter classes: one flag -for the whole unit cell (``General['Cell'][0]``), one ``'X'`` flag per atom for -all three coordinates, and one ``'U'`` flag per atom for all six anisotropic -displacement components. PowderLine recipes carry *per-parameter* flags. This -module computes, for each class, (a) whether the lumped GSAS-II flag must be -set and (b) which GSAS-II "Hold" constraints must be emitted so that only the -requested parameters actually refine. - -Normative semantics (schema 0.26): - -- A parameter is *requested* iff it is present with ``refine_flag=true``. -- Absent, ``None``, or ``refine_flag=false`` means fixed (held). -- Parameters partition into degree-of-freedom (DOF) groups; a group refines iff - ANY member is requested (group-OR). Flags on symmetry-fixed parameters have - no effect (there is no degree of freedom to control). -- PowderLine performs no flag/symmetry consistency validation - producing - symmetry-consistent flags is the upstream recipe builder's job. For a - well-formed recipe the translation is exact; for mixed flags within a group - the group-OR interpretation is deterministic and documented - (docs/known_issues.md, KI-02). - -The DOF-group structure mirrors GSAS-II's own machinery at the pinned commit: - -- Unit cell: ``GSASIIstrIO.cellVary``'s per-Laue-class A-term dispatch, plus - direct<->reciprocal coupling analysis - oblique cells couple direct - parameters, so monoclinic {a, c, oblique angle} and the whole triclinic / - rhombohedral-axes cell each form a single group (verified empirically - against the pinned GSAS-II). -- Coordinates / anisotropic Uij: the site-symmetry tables - ``GSASIIspc.GetCSxinel`` / ``GetCSuinel``, used exactly as - ``GSASIIstrIO.GetPhaseData`` uses them, including the KeyError -> - ``SytSym``-recompute patch for stale/blank site-symmetry strings. - -Hold variable names follow GSAS-II conventions: ``{p}::A{n}`` for cell terms, -``{p}::dAx:{i}`` / ``dAy`` / ``dAz`` for coordinate shifts, and -``{p}::AU11:{i}`` ... ``AU23:{i}`` for anisotropic components (verified by -probes 2, 3, and 5). +Kept for backward compatibility during the multi-engine refactor (re/01); +removed in a later branch. Re-exports every top-level name of the moved module. """ -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any, Sequence - -from GSASII import GSASIIspc as G2spc - - -@dataclass -class CellPlan: - """Result of translating unit-cell per-parameter flags.""" - refine_cell: bool - holds: list[str] = field(default_factory=list) - - -@dataclass -class AtomPlan: - """Result of translating one atom's per-parameter flags. - - ``refine_flags`` is the GSAS-II atom flag string ('F', 'X', 'U' pieces in - that order); ``holds`` are GSAS-II variable names to Hold. - """ - refine_flags: str - holds: list[str] = field(default_factory=list) - - -_CELL_PARAMS = ("a", "b", "c", "alpha", "beta", "gamma") -_COORD_PARAMS = ("x", "y", "z") -_DA_NAMES = ("dAx", "dAy", "dAz") -_UIJ_PARAMS = ("U11", "U22", "U33", "U12", "U13", "U23") -_AU_NAMES = ("AU11", "AU22", "AU33", "AU12", "AU13", "AU23") - - -def _is_requested(param: Any) -> bool: - """True iff a [value, refine_flag, min, max] entry requests refinement.""" - return ( - param is not None - and isinstance(param, (list, tuple)) - and len(param) >= 2 - and bool(param[1]) - ) - - -def cell_dof_groups(SGData: dict) -> list[tuple[tuple[str, ...], tuple[int, ...]]]: - """DOF-groups for the unit cell of a phase with symmetry ``SGData``. - - Returns a list of ``(direct_parameters, independent_A_term_indices)`` - pairs. Holding all listed A-terms of a group fixes exactly that group's - direct parameters (slaved A-terms - e.g. A1 for tetragonal - are covered - by GSAS-II's symmetry-equivalence cascade and need no explicit hold). - - The dispatch mirrors ``GSASIIstrIO.cellVary`` (pinned commit, lines - 997-1024); the grouping of oblique parameters follows findings.md - section C.6. - """ - laue = SGData["SGLaue"] - if laue in ("m3m", "m3"): - return [(("a", "b", "c"), (0,))] - if laue in ("4/m", "4/mmm"): - return [(("a", "b"), (0,)), (("c",), (2,))] - if laue in ("6/m", "6/mmm", "3", "3m1", "31m"): - return [(("a", "b"), (0,)), (("c",), (2,))] - if laue in ("3R", "3mR"): - # Rhombohedral axes: a(=b=c) and alpha(=beta=gamma) are coupled through - # both independent A-terms (A0 and A3) -> one all-or-nothing group. - return [(_CELL_PARAMS, (0, 3))] - if laue == "mmm": - return [(("a",), (0,)), (("b",), (1,)), (("c",), (2,))] - if laue == "2/m": - uniq = SGData.get("SGUniq") - if uniq == "a": - return [(("a",), (0,)), (("b", "c", "alpha"), (1, 2, 5))] - if uniq == "b": - return [(("b",), (1,)), (("a", "c", "beta"), (0, 2, 4))] - # cellVary's else-branch: anything other than 'a'/'b' (SpcGroup always - # emits a/b/c for 2/m) dispatches as unique axis c (oblique gamma, A3) - return [(("c",), (2,)), (("a", "b", "gamma"), (0, 1, 3))] - if laue == "-1": - return [(_CELL_PARAMS, (0, 1, 2, 3, 4, 5))] - raise ValueError(f"Unrecognized Laue class {laue!r} in SGData") - - -def cell_refinement_plan( - SGData: dict, unit_cell_params: dict | None, phase_idx: int -) -> CellPlan: - """Translate per-parameter unit-cell flags into (Cell flag, holds). - - Args: - SGData: the phase's GSAS-II space-group data dict - (``proj.data['Phases'][name]['General']['SGData']``). - unit_cell_params: the recipe's ``parameterization.unit_cell`` dict - mapping parameter names to ``[value, refine_flag, min, max]`` - lists (entries and the dict itself may be None/absent). - phase_idx: the phase's index in the project (for variable naming). - - Returns: - CellPlan. ``refine_cell`` is True iff at least one DOF-group has a - requested member; ``holds`` lists the independent A-term variables of - the *unrefined* groups (empty when ``refine_cell`` is False - a fixed - cell needs no holds). - """ - unit_cell_params = unit_cell_params or {} - requested = { - p for p in _CELL_PARAMS if _is_requested(unit_cell_params.get(p)) - } - groups = cell_dof_groups(SGData) - refining = [any(p in requested for p in params) for params, _ in groups] - if not any(refining): - return CellPlan(refine_cell=False) - holds = [ - f"{phase_idx}::A{n}" - for (params, a_terms), on in zip(groups, refining) - if not on - for n in a_terms - ] - return CellPlan(refine_cell=True, holds=holds) - - -def _site_ids( - table_lookup, - site_sym: str, - xyz: Sequence[float] | None, - SGData: dict | None, -): - """Site-symmetry table lookup with GSAS-II's own KeyError patch. - - Mirrors GSASIIstrIO.GetPhaseData (pinned commit, lines 1742-1747): valid - keys are the *oriented* strings SytSym emits (e.g. '4mm(z)'); on a stale - or blank key, recompute the site symmetry from the coordinates. - """ - try: - return table_lookup(site_sym)[0] - except KeyError: - if xyz is None or SGData is None: - raise - recomputed = G2spc.SytSym(list(xyz), SGData)[0] - return table_lookup(recomputed)[0] - - -def _free_groups(ids: Sequence[int]) -> list[list[int]]: - """Group parameter indices by shared nonzero site-symmetry id. - - Id 0 means fixed-by-symmetry (no DOF); equal nonzero ids are one coupled - DOF-group (e.g. x=y on an (x,x,z) site). - """ - groups: dict[int, list[int]] = {} - for i, gid in enumerate(ids): - if gid > 0: - groups.setdefault(gid, []).append(i) - return list(groups.values()) - - -def atom_refinement_plan( - atom_params: dict, - site_sym: str, - phase_idx: int, - atom_idx: int, - xyz: Sequence[float] | None = None, - SGData: dict | None = None, -) -> AtomPlan: - """Translate one atom's per-parameter flags into (flag string, holds). - - Args: - atom_params: the recipe's per-atom parameterization dict (keys 'x', - 'y', 'z', 'occupancy', 'ADP', 'Uiso', 'Uaniso'). - site_sym: the atom's oriented site-symmetry string - (``atom_record[7]``). - phase_idx / atom_idx: for GSAS-II variable naming. - xyz / SGData: coordinates and space-group data, used only to recompute - a stale/blank ``site_sym`` (GSAS-II's own patch behavior). - - Returns: - AtomPlan. Flag characters appear in GSAS-II's 'F','X','U' order. Holds - are emitted only for *free* (symmetry-allowed) DOF-groups with no - requested member, and only when the corresponding lumped flag is set. - """ - flags = "" - holds: list[str] = [] - - # Occupancy ('F') is a single parameter - already faithful, no holds. - if _is_requested(atom_params.get("occupancy")): - flags += "F" - - # Coordinates ('X'): group by site symmetry, group-OR, hold the rest. - requested_coords = { - i for i, p in enumerate(_COORD_PARAMS) - if _is_requested(atom_params.get(p)) - } - if requested_coords: - ids = _site_ids(G2spc.GetCSxinel, site_sym, xyz, SGData) - groups = _free_groups(ids) - refining = [any(i in requested_coords for i in g) for g in groups] - if any(refining): - flags += "X" - holds += [ - f"{phase_idx}::{_DA_NAMES[i]}:{atom_idx}" - for g, on in zip(groups, refining) - if not on - for i in g - ] - - # Displacement ('U'): Uiso is a single parameter; Uaniso groups like coords. - adp_type = atom_params.get("ADP") - if adp_type == "Uiso": - if _is_requested(atom_params.get("Uiso")): - flags += "U" - elif adp_type == "Uaniso": - uaniso = atom_params.get("Uaniso") or {} - requested_uij = { - i for i, p in enumerate(_UIJ_PARAMS) - if isinstance(uaniso, dict) and _is_requested(uaniso.get(p)) - } - if requested_uij: - ids = _site_ids(G2spc.GetCSuinel, site_sym, xyz, SGData) - groups = _free_groups(ids) - refining = [any(i in requested_uij for i in g) for g in groups] - if any(refining): - flags += "U" - holds += [ - f"{phase_idx}::{_AU_NAMES[i]}:{atom_idx}" - for g, on in zip(groups, refining) - if not on - for i in g - ] - - return AtomPlan(refine_flags=flags, holds=holds) +from powderline.gateways.gsasii.constraints import ( # noqa: F401 + CellPlan, + AtomPlan, + _CELL_PARAMS, + _COORD_PARAMS, + _DA_NAMES, + _UIJ_PARAMS, + _AU_NAMES, + _is_requested, + cell_dof_groups, + cell_refinement_plan, + _site_ids, + _free_groups, + atom_refinement_plan, +) diff --git a/src/powderline/gateways/__init__.py b/src/powderline/gateways/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/powderline/gateways/gsasii/__init__.py b/src/powderline/gateways/gsasii/__init__.py new file mode 100644 index 0000000..d1444ad --- /dev/null +++ b/src/powderline/gateways/gsasii/__init__.py @@ -0,0 +1,6 @@ +"""GSAS-II gateway package. + +Do not import runtime modules (setters, project, executors, extractors, ...) +here: they import GSAS-II at module top. The engine-free gateway factory +arrives in a later branch (re/02) as ``gateways/gsasii/gateway.py``. +""" diff --git a/src/powderline/gateways/gsasii/client.py b/src/powderline/gateways/gsasii/client.py new file mode 100644 index 0000000..a28401b --- /dev/null +++ b/src/powderline/gateways/gsasii/client.py @@ -0,0 +1,454 @@ +"""Client library for GSAS-II server communication. + +Provides a simple API for submitting simulations to the GSAS-II server. +Automatically falls back to in-process execution when the server is not +running, or when a "successful" server run produced output files that are +not visible to this process (server with a divergent filesystem view, e.g. +on another node or inside a sandbox with a private /tmp). +""" + +import subprocess +import sys +import os +from pathlib import Path +from typing import Dict, Any +import tempfile + +HOST = "127.0.0.1" +DEFAULT_PORT = 19471 +PORT = int(os.environ.get('POWDERLINE_SERVER_PORT', DEFAULT_PORT)) +PORT_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.port' + + +class GSASClient: + """Client for communicating with GSAS-II server.""" + + def __init__(self, fallback_to_subprocess: bool = True): + """Initialize client. + + Args: + fallback_to_subprocess: If True, use subprocess when server unavailable + """ + self.fallback_to_subprocess = fallback_to_subprocess + + def _get_port(self) -> int: + """Read the server port from the port file.""" + if PORT_FILE.exists(): + try: + return int(PORT_FILE.read_text().strip()) + except (ValueError, OSError): + pass + return PORT + + def is_server_available(self) -> bool: + """Check if server is running and accepting connections.""" + import httpx + + port = self._get_port() + try: + resp = httpx.get(f"http://{HOST}:{port}/health", timeout=2.0) + return resp.status_code == 200 + except (httpx.ConnectError, httpx.TimeoutException, OSError): + return False + + @staticmethod + def _stat_fit_profile(output_dir: Path) -> tuple | None: + """(mtime_ns, size) of output_dir/fit_profile.txt, or None if absent.""" + try: + st = (Path(output_dir) / 'fit_profile.txt').stat() + except OSError: + return None + return (st.st_mtime_ns, st.st_size) + + def _server_output_visible(self, result: Dict[str, Any], output_dir: Path, + stat_before: tuple | None) -> bool: + """Check that a 'successful' server run materialized its output files + where THIS process can see them. + + A GSAS-II server can be reachable over localhost yet have a different + filesystem view — e.g. started on another node of a cluster, or inside + a sandbox/container with a private /tmp. Such a server reports success + while its output files are unreachable. run_refinement always + (re)writes fit_profile.txt on success, so the file must exist AND its + (mtime, size) must differ from before the run — a stale file left by a + previous run into the same output_dir does not count. Costs two stat + calls per server run; nothing is read, written, or deleted. + """ + if not result.get('success'): + return True # error paths need no file check + stat_after = self._stat_fit_profile(output_dir) + return stat_after is not None and stat_after != stat_before + + _INVISIBLE_OUTPUT_ERROR = ( + "GSAS-II server reported success but did not write output files " + "visible to this process — the server has a different filesystem view " + "(started on another node, or inside a sandbox/container with a " + "private /tmp). Restart it with: pixi run gsas-server restart" + ) + + def _handle_invisible_server_output(self) -> Dict[str, Any] | None: + """Warn about a server with a divergent filesystem view. + + Returns None when in-process fallback is enabled (caller falls + through to it), or a structured error result when fallback is + disabled (execution_mode='server'). + """ + print(" WARNING: GSAS-II server reported success but did not write " + "output files visible to this process.") + print(" The server appears to have a different filesystem view " + "(started on another node, or inside a sandbox/container with a " + "private /tmp).") + if self.fallback_to_subprocess: + print(" Falling back to in-process execution. To fix the server: " + "pixi run gsas-server restart") + return None + print(" In-process fallback is disabled. To fix the server: " + "pixi run gsas-server restart") + return { + 'success': False, + 'error': self._INVISIBLE_OUTPUT_ERROR, + 'method': 'server', + } + + def _submit_to_server_guarded(self, recipe_dict: dict, + output_dir: Path) -> Dict[str, Any] | None: + """Submit to the server with the output-visibility guard applied. + + Returns the result to hand to the caller, or None when the caller + should fall through to the in-process fallback (invisible output + with fallback enabled). Exceptions from the server round-trip + propagate unchanged. + """ + stat_before = self._stat_fit_profile(output_dir) + result = self._submit_to_server(recipe_dict, output_dir) + result['method'] = 'server' + if self._server_output_visible(result, output_dir, stat_before): + return result + return self._handle_invisible_server_output() + + def submit_simulation(self, recipe, output_dir: Path, + verbose: bool = False, auto_start_server: bool = True, + use_server: bool = True) -> Dict[str, Any]: + """Submit a simulation request. + + Args: + recipe: Recipe to run. Accepts: + - Path: path to a JSON/YAML recipe file (loaded automatically) + - dict: pre-loaded recipe dictionary + - RecipeModel: validated Pydantic model instance + output_dir: Directory for output files + verbose: If True, print detailed output + auto_start_server: If True, start server automatically if not running + use_server: If False, skip the server entirely and run in-process + + Returns: + Dictionary with 'success', 'output_files', 'elapsed_time', + and optional 'error', 'method' fields + + Note: + A server response only counts if its output files were freshly + written where this process can see them (see + _server_output_visible — a stale fit_profile.txt from a previous + run does not count); otherwise the run falls back to in-process + execution with a warning — or, when fallback_to_subprocess is + False, returns a structured error explaining the filesystem-view + mismatch. + """ + recipe_dict = self._normalize_recipe(recipe) + + if not use_server: + if not verbose: + print(" Using in-process mode (use_server=False)") + # Try server first + elif self.is_server_available(): + if not verbose: + print(f" Using GSAS-II server mode") + try: + result = self._submit_to_server_guarded(recipe_dict, output_dir) + if result is not None: + return result + # fall through to in-process fallback below + except Exception as e: + if not self.fallback_to_subprocess: + return { + 'success': False, + 'error': f"Server communication failed: {e}", + 'method': 'server' + } + + if verbose: + print(f"Server communication failed: {e}") + print(" Falling back to subprocess mode...") + + # Try to start server if not available and auto_start_server enabled + elif auto_start_server: + if verbose: + print(" Attempting to start server automatically...") + if self._start_server_background(verbose): + import time + time.sleep(1) + + # Try again + if self.is_server_available(): + if not verbose: + print(f" Using GSAS-II server mode") + try: + result = self._submit_to_server_guarded(recipe_dict, output_dir) + if result is not None: + return result + # fall through to in-process fallback below + except Exception as e: + if verbose: + print(f"Failed to connect to auto-started server: {e}") + if not verbose: + print(f" Using subprocess mode (start server with: pixi run gsas-server start)") + else: + if verbose: + print(f" Server started but not responding") + if not verbose: + print(f" Using subprocess mode (start server with: pixi run gsas-server start)") + else: + if not verbose: + print(f" Using subprocess mode (start server with: pixi run gsas-server start)") + else: + if not verbose: + print(f" Using subprocess mode (start server with: pixi run gsas-server start)") + + # Fallback to subprocess + if self.fallback_to_subprocess: + result = self._submit_via_subprocess(recipe_dict, output_dir, verbose) + result['method'] = 'subprocess' + return result + elif not use_server: + # Explicitly requested state, kept honest: both execution paths + # were disabled by the caller, so nothing ran. + return { + 'success': False, + 'error': 'No execution path enabled: use_server=False and ' + 'fallback_to_subprocess=False — enable one of them.', + 'method': 'none' + } + else: + return { + 'success': False, + 'error': 'Server not available and fallback disabled', + 'method': 'none' + } + + def _normalize_recipe(self, recipe) -> dict: + """Normalize recipe input to a plain JSON-serializable dict. + + Accepts Path (loaded from disk), dict (used as-is), or RecipeModel + (serialized via .model_dump). Raises TypeError for unsupported inputs. + """ + if isinstance(recipe, Path): + import json + import yaml + ext = recipe.suffix.lower() + text = recipe.read_text() + if ext == '.json': + return json.loads(text) + if ext in {'.yaml', '.yml', '.txt'}: + return yaml.safe_load(text) or {} + raise ValueError(f"Unsupported recipe format: {recipe}") + if isinstance(recipe, dict): + return recipe + if hasattr(recipe, 'model_dump'): + return recipe.model_dump(mode='json') + raise TypeError( + f"recipe must be a Path, dict, or RecipeModel instance, got {type(recipe).__name__}" + ) + + def _start_server_background(self, verbose: bool = False) -> bool: + """Start server in background process. + + Returns: + True if server was started, False if already running or failed + """ + import subprocess + import os + import time + + # Check if already running + if self.is_server_available(): + return True + + try: + # Build command to start server + src_dir = Path(__file__).parent.parent + server_script = Path(__file__).parent / 'gsas_server.py' + + # Prepare environment + env = os.environ.copy() + env['PYTHONPATH'] = str(src_dir) + os.pathsep + env.get('PYTHONPATH', '') + + # Use subprocess to start server in background + try: + # Try with preexec_fn (Unix only) + proc = subprocess.Popen( + [sys.executable, str(server_script), 'start'], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, + env=env, + preexec_fn=os.setpgrp, # Detach from parent process group + start_new_session=False + ) + except (TypeError, AttributeError): + # Fallback for Windows or if preexec_fn not available + proc = subprocess.Popen( + [sys.executable, str(server_script), 'start'], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, + env=env, + creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == 'win32' else 0 + ) + + # Give server time to start + for attempt in range(30): # Wait up to 3 seconds + time.sleep(0.1) + if self.is_server_available(): + if verbose: + print(" Server started in background") + return True + + if verbose: + print(f" Server started (PID {proc.pid}) but not responding yet") + return True # Started even if not responding immediately + + except Exception as e: + if verbose: + print(f" Could not auto-start server: {e}") + return False + + def _submit_to_server(self, recipe_dict: dict, output_dir: Path) -> Dict[str, Any]: + """Submit simulation to server via HTTP with retry logic. + + Retries up to 3 times on connection errors to handle transient network issues. + """ + import httpx + import time + + port = self._get_port() + payload = { + 'recipe_data': recipe_dict, + 'output_dir': str(output_dir.absolute()), + } + + # Retry logic for connection errors + max_retries = 3 + retry_delay = 0.5 # seconds + + last_error = None + for attempt in range(max_retries): + try: + resp = httpx.post( + f"http://{HOST}:{port}/simulate", + json=payload, + timeout=300.0, + ) + resp.raise_for_status() + return resp.json() + except httpx.ConnectError as e: + last_error = e + if attempt < max_retries - 1: + time.sleep(retry_delay) + retry_delay *= 2 # Exponential backoff + continue + except httpx.HTTPStatusError as e: + # Don't retry on HTTP errors (4xx, 5xx) + raise + except httpx.TimeoutException as e: + # Don't retry on timeout (simulation is running) + raise + + # If we exhausted all retries, raise the last error + raise last_error + + def _submit_via_subprocess(self, recipe_dict: dict, output_dir: Path, + verbose: bool) -> Dict[str, Any]: + """Run simulation in-process (fallback mode when server is unavailable). + + **Important**: Despite the method name, this does NOT spawn an OS subprocess. + It calls ``run_refinement()`` directly in the current process. The name is + retained for API stability. If hard crash-isolation is needed in a future + phase, this method can be upgraded to use ``multiprocessing`` internally + without changing any callers. + + Contrast with ``_start_server_background()``, which *does* spawn an OS + subprocess to launch the FastAPI server. + + Calls run_refinement() directly in the current process, returning the + same structured result dict as server mode (fit_profile, unit_cell_data, + peak_list_data, refined_parameters, rwp, etc.). + """ + import time + from powderline.kicker import run_refinement + from powderline.schema import RecipeModel + from pydantic import ValidationError + + output_dir.mkdir(parents=True, exist_ok=True) + + try: + recipe = RecipeModel.model_validate(recipe_dict) + except ValidationError as e: + error_lines = [ + f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" + for err in e.errors() + ] + return { + 'success': False, + 'error': f"Recipe validation failed:\n" + "\n".join(error_lines), + 'method': 'subprocess' + } + except Exception as e: + return { + 'success': False, + 'error': f"Failed to parse recipe: {str(e)}", + 'method': 'subprocess' + } + + start_time = time.time() + try: + result = run_refinement(recipe, output_dir, verbose=verbose, method='subprocess') + except Exception as e: + elapsed = time.time() - start_time + return { + 'success': False, + 'error': str(e), + 'elapsed_time': elapsed, + 'method': 'subprocess' + } + + return result + + +# Convenience function for simple use cases +def run_simulation(recipe, output_dir: Path, + verbose: bool = False, auto_start_server: bool = True) -> Dict[str, Any]: + """Run a simulation using the server if available and usable, else in-process. + + This is a convenience wrapper around GSASClient.submit_simulation(), + including its output-visibility guard (a server whose files are not + visible to this process triggers an in-process rerun). + With auto_start_server=True (default), the server is automatically started + if not running, providing fast performance for first and subsequent uses. + + Args: + recipe: Recipe to run. Accepts Path, dict, or RecipeModel instance. + output_dir: Directory for output files + verbose: If True, print detailed output + auto_start_server: If True, automatically start server in background + + Returns: + Dictionary with 'success', 'output_files', 'elapsed_time', 'method' + + Example: + >>> result = run_simulation(Path('recipe.json'), Path('output/')) + >>> result = run_simulation(recipe_dict, Path('output/')) + >>> if result['success']: + ... print(f"Completed in {result['elapsed_time']:.1f}s via {result['method']}") + """ + client = GSASClient() + return client.submit_simulation(recipe, output_dir, verbose, auto_start_server) diff --git a/src/powderline/gateways/gsasii/constraints.py b/src/powderline/gateways/gsasii/constraints.py new file mode 100644 index 0000000..925a4d8 --- /dev/null +++ b/src/powderline/gateways/gsasii/constraints.py @@ -0,0 +1,266 @@ +"""Per-parameter refine-flag translation for GSAS-II (schema 0.26.0). + +GSAS-II exposes only lumped refine flags for three parameter classes: one flag +for the whole unit cell (``General['Cell'][0]``), one ``'X'`` flag per atom for +all three coordinates, and one ``'U'`` flag per atom for all six anisotropic +displacement components. PowderLine recipes carry *per-parameter* flags. This +module computes, for each class, (a) whether the lumped GSAS-II flag must be +set and (b) which GSAS-II "Hold" constraints must be emitted so that only the +requested parameters actually refine. + +Normative semantics (schema 0.26): + +- A parameter is *requested* iff it is present with ``refine_flag=true``. +- Absent, ``None``, or ``refine_flag=false`` means fixed (held). +- Parameters partition into degree-of-freedom (DOF) groups; a group refines iff + ANY member is requested (group-OR). Flags on symmetry-fixed parameters have + no effect (there is no degree of freedom to control). +- PowderLine performs no flag/symmetry consistency validation - producing + symmetry-consistent flags is the upstream recipe builder's job. For a + well-formed recipe the translation is exact; for mixed flags within a group + the group-OR interpretation is deterministic and documented + (docs/known_issues.md, KI-02). + +The DOF-group structure mirrors GSAS-II's own machinery at the pinned commit: + +- Unit cell: ``GSASIIstrIO.cellVary``'s per-Laue-class A-term dispatch, plus + direct<->reciprocal coupling analysis - oblique cells couple direct + parameters, so monoclinic {a, c, oblique angle} and the whole triclinic / + rhombohedral-axes cell each form a single group (verified empirically + against the pinned GSAS-II). +- Coordinates / anisotropic Uij: the site-symmetry tables + ``GSASIIspc.GetCSxinel`` / ``GetCSuinel``, used exactly as + ``GSASIIstrIO.GetPhaseData`` uses them, including the KeyError -> + ``SytSym``-recompute patch for stale/blank site-symmetry strings. + +Hold variable names follow GSAS-II conventions: ``{p}::A{n}`` for cell terms, +``{p}::dAx:{i}`` / ``dAy`` / ``dAz`` for coordinate shifts, and +``{p}::AU11:{i}`` ... ``AU23:{i}`` for anisotropic components (verified by +probes 2, 3, and 5). +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Sequence + +from GSASII import GSASIIspc as G2spc + + +@dataclass +class CellPlan: + """Result of translating unit-cell per-parameter flags.""" + refine_cell: bool + holds: list[str] = field(default_factory=list) + + +@dataclass +class AtomPlan: + """Result of translating one atom's per-parameter flags. + + ``refine_flags`` is the GSAS-II atom flag string ('F', 'X', 'U' pieces in + that order); ``holds`` are GSAS-II variable names to Hold. + """ + refine_flags: str + holds: list[str] = field(default_factory=list) + + +_CELL_PARAMS = ("a", "b", "c", "alpha", "beta", "gamma") +_COORD_PARAMS = ("x", "y", "z") +_DA_NAMES = ("dAx", "dAy", "dAz") +_UIJ_PARAMS = ("U11", "U22", "U33", "U12", "U13", "U23") +_AU_NAMES = ("AU11", "AU22", "AU33", "AU12", "AU13", "AU23") + + +def _is_requested(param: Any) -> bool: + """True iff a [value, refine_flag, min, max] entry requests refinement.""" + return ( + param is not None + and isinstance(param, (list, tuple)) + and len(param) >= 2 + and bool(param[1]) + ) + + +def cell_dof_groups(SGData: dict) -> list[tuple[tuple[str, ...], tuple[int, ...]]]: + """DOF-groups for the unit cell of a phase with symmetry ``SGData``. + + Returns a list of ``(direct_parameters, independent_A_term_indices)`` + pairs. Holding all listed A-terms of a group fixes exactly that group's + direct parameters (slaved A-terms - e.g. A1 for tetragonal - are covered + by GSAS-II's symmetry-equivalence cascade and need no explicit hold). + + The dispatch mirrors ``GSASIIstrIO.cellVary`` (pinned commit, lines + 997-1024); the grouping of oblique parameters follows findings.md + section C.6. + """ + laue = SGData["SGLaue"] + if laue in ("m3m", "m3"): + return [(("a", "b", "c"), (0,))] + if laue in ("4/m", "4/mmm"): + return [(("a", "b"), (0,)), (("c",), (2,))] + if laue in ("6/m", "6/mmm", "3", "3m1", "31m"): + return [(("a", "b"), (0,)), (("c",), (2,))] + if laue in ("3R", "3mR"): + # Rhombohedral axes: a(=b=c) and alpha(=beta=gamma) are coupled through + # both independent A-terms (A0 and A3) -> one all-or-nothing group. + return [(_CELL_PARAMS, (0, 3))] + if laue == "mmm": + return [(("a",), (0,)), (("b",), (1,)), (("c",), (2,))] + if laue == "2/m": + uniq = SGData.get("SGUniq") + if uniq == "a": + return [(("a",), (0,)), (("b", "c", "alpha"), (1, 2, 5))] + if uniq == "b": + return [(("b",), (1,)), (("a", "c", "beta"), (0, 2, 4))] + # cellVary's else-branch: anything other than 'a'/'b' (SpcGroup always + # emits a/b/c for 2/m) dispatches as unique axis c (oblique gamma, A3) + return [(("c",), (2,)), (("a", "b", "gamma"), (0, 1, 3))] + if laue == "-1": + return [(_CELL_PARAMS, (0, 1, 2, 3, 4, 5))] + raise ValueError(f"Unrecognized Laue class {laue!r} in SGData") + + +def cell_refinement_plan( + SGData: dict, unit_cell_params: dict | None, phase_idx: int +) -> CellPlan: + """Translate per-parameter unit-cell flags into (Cell flag, holds). + + Args: + SGData: the phase's GSAS-II space-group data dict + (``proj.data['Phases'][name]['General']['SGData']``). + unit_cell_params: the recipe's ``parameterization.unit_cell`` dict + mapping parameter names to ``[value, refine_flag, min, max]`` + lists (entries and the dict itself may be None/absent). + phase_idx: the phase's index in the project (for variable naming). + + Returns: + CellPlan. ``refine_cell`` is True iff at least one DOF-group has a + requested member; ``holds`` lists the independent A-term variables of + the *unrefined* groups (empty when ``refine_cell`` is False - a fixed + cell needs no holds). + """ + unit_cell_params = unit_cell_params or {} + requested = { + p for p in _CELL_PARAMS if _is_requested(unit_cell_params.get(p)) + } + groups = cell_dof_groups(SGData) + refining = [any(p in requested for p in params) for params, _ in groups] + if not any(refining): + return CellPlan(refine_cell=False) + holds = [ + f"{phase_idx}::A{n}" + for (params, a_terms), on in zip(groups, refining) + if not on + for n in a_terms + ] + return CellPlan(refine_cell=True, holds=holds) + + +def _site_ids( + table_lookup, + site_sym: str, + xyz: Sequence[float] | None, + SGData: dict | None, +): + """Site-symmetry table lookup with GSAS-II's own KeyError patch. + + Mirrors GSASIIstrIO.GetPhaseData (pinned commit, lines 1742-1747): valid + keys are the *oriented* strings SytSym emits (e.g. '4mm(z)'); on a stale + or blank key, recompute the site symmetry from the coordinates. + """ + try: + return table_lookup(site_sym)[0] + except KeyError: + if xyz is None or SGData is None: + raise + recomputed = G2spc.SytSym(list(xyz), SGData)[0] + return table_lookup(recomputed)[0] + + +def _free_groups(ids: Sequence[int]) -> list[list[int]]: + """Group parameter indices by shared nonzero site-symmetry id. + + Id 0 means fixed-by-symmetry (no DOF); equal nonzero ids are one coupled + DOF-group (e.g. x=y on an (x,x,z) site). + """ + groups: dict[int, list[int]] = {} + for i, gid in enumerate(ids): + if gid > 0: + groups.setdefault(gid, []).append(i) + return list(groups.values()) + + +def atom_refinement_plan( + atom_params: dict, + site_sym: str, + phase_idx: int, + atom_idx: int, + xyz: Sequence[float] | None = None, + SGData: dict | None = None, +) -> AtomPlan: + """Translate one atom's per-parameter flags into (flag string, holds). + + Args: + atom_params: the recipe's per-atom parameterization dict (keys 'x', + 'y', 'z', 'occupancy', 'ADP', 'Uiso', 'Uaniso'). + site_sym: the atom's oriented site-symmetry string + (``atom_record[7]``). + phase_idx / atom_idx: for GSAS-II variable naming. + xyz / SGData: coordinates and space-group data, used only to recompute + a stale/blank ``site_sym`` (GSAS-II's own patch behavior). + + Returns: + AtomPlan. Flag characters appear in GSAS-II's 'F','X','U' order. Holds + are emitted only for *free* (symmetry-allowed) DOF-groups with no + requested member, and only when the corresponding lumped flag is set. + """ + flags = "" + holds: list[str] = [] + + # Occupancy ('F') is a single parameter - already faithful, no holds. + if _is_requested(atom_params.get("occupancy")): + flags += "F" + + # Coordinates ('X'): group by site symmetry, group-OR, hold the rest. + requested_coords = { + i for i, p in enumerate(_COORD_PARAMS) + if _is_requested(atom_params.get(p)) + } + if requested_coords: + ids = _site_ids(G2spc.GetCSxinel, site_sym, xyz, SGData) + groups = _free_groups(ids) + refining = [any(i in requested_coords for i in g) for g in groups] + if any(refining): + flags += "X" + holds += [ + f"{phase_idx}::{_DA_NAMES[i]}:{atom_idx}" + for g, on in zip(groups, refining) + if not on + for i in g + ] + + # Displacement ('U'): Uiso is a single parameter; Uaniso groups like coords. + adp_type = atom_params.get("ADP") + if adp_type == "Uiso": + if _is_requested(atom_params.get("Uiso")): + flags += "U" + elif adp_type == "Uaniso": + uaniso = atom_params.get("Uaniso") or {} + requested_uij = { + i for i, p in enumerate(_UIJ_PARAMS) + if isinstance(uaniso, dict) and _is_requested(uaniso.get(p)) + } + if requested_uij: + ids = _site_ids(G2spc.GetCSuinel, site_sym, xyz, SGData) + groups = _free_groups(ids) + refining = [any(i in requested_uij for i in g) for g in groups] + if any(refining): + flags += "U" + holds += [ + f"{phase_idx}::{_AU_NAMES[i]}:{atom_idx}" + for g, on in zip(groups, refining) + if not on + for i in g + ] + + return AtomPlan(refine_flags=flags, holds=holds) diff --git a/src/powderline/gateways/gsasii/executors.py b/src/powderline/gateways/gsasii/executors.py new file mode 100644 index 0000000..60acfe2 --- /dev/null +++ b/src/powderline/gateways/gsasii/executors.py @@ -0,0 +1,515 @@ +"""GSAS-II gateway — refinement execution and orchestration (run_refinement). + +Moved verbatim from ``powderline/kicker.py`` (multi-engine refactor, re/01). +""" +from __future__ import annotations +import sys +import uuid +import yaml +import json +import argparse +import random as ran +import numpy as np +import pandas as pd +from typing import Any, Dict, List, Literal, Optional, Sequence, Union +from pathlib import Path +from pydantic import ValidationError +from GSASII import GSASIIscriptable as G2 # type: ignore +from GSASII import GSASIIlattice as G2lat +from GSASII import GSASIImapvars as G2mv +from GSASII import GSASIIobj as G2obj +from GSASII import GSASIIspc as G2spc +from GSASII import GSASIIElem as G2elem +from GSASII import GSASIIpwd as G2pwd +from powderline.schema import RecipeModel, RefinementControls +from powderline.gateways.gsasii.constraints import atom_refinement_plan, cell_refinement_plan +from powderline._status import CHECK, CROSS, INFO, WARN, emoji +from dataclasses import dataclass + +from powderline.gateways.gsasii.helpers import ( + DEFAULT_HIST_SCALE_REFINE_FLAG, + DEFAULT_HIST_SCALE_VAL, + OUTPUT_NAMING, +) +from powderline.gateways.gsasii.project import ( + add_phases_from_dict, + add_powder_histogram_from_arrays, +) +from powderline.gateways.gsasii.setters import ( + set_chebyshev_background, + set_fit_range_hist, + set_hist_scale, + set_instrument_parameterization, + set_phase_parameterization, + set_refinement_cycles, + set_single_peak_background, + set_single_peaks, +) +from powderline.gateways.gsasii.extractors import ( + _extract_fit_profile, + _extract_phase_reports, + _extract_refined_parameters, + _extract_spf_peak_report, + extract_refined_params_from_project, +) + + + +def _refine_with_message(proj) -> tuple[bool, str]: + """Run the project refinement, returning (ok, GSAS-II failure message). + + ``G2Project.refine()`` calls ``G2strMain.Refine`` and DISCARDS its + ``(OK, Rvals)`` return, so failure text like "Invalid metric tensor for + phase #0" reaches only the console — callers see a silent no-Rwp failure. + Mirror the non-sequential branch of ``refine()`` (index, constraint + check, Refine, reload) to keep ``Rvals['msg']``. Any surprise from + GSAS-II internals falls back to the plain ``proj.refine()`` so behavior + is never worse than before. + """ + try: + from GSASII import GSASIIstrIO as G2stIO + from GSASII import GSASIIstrMain as G2strMain + + seq_setting = proj.data['Controls']['data'].get('Seq Data', []) + if not seq_setting: + proj.index_ids() # saves the project, as refine() does + errmsg, _warnmsg = G2stIO.ReadCheckConstraints(proj.filename) + if errmsg: + return False, f"Constraint error: {errmsg}" + ret = G2strMain.Refine(proj.filename, makeBack=False) + proj.reload() + ok, rvals = (ret if isinstance(ret, tuple) and len(ret) == 2 + else (True, {})) + msg = rvals.get('msg', '') if isinstance(rvals, dict) else '' + msg = msg.replace('**** ERROR: Refinement failed ****', '').strip() + return bool(ok), msg + except (ImportError, AttributeError, KeyError, TypeError): + pass # GSAS-II internals changed: fall back to the plain call below + + proj.refine() + return True, '' + + +def execute_rietveld_refinement( + proj: Any, + hist: Any, + recipe: RecipeModel, + verbose: bool +) -> dict: + """ + Execute standard GSAS-II Rietveld refinement. + + This replaces the previous "structural_only" strategy. + + Args: + proj: GSAS-II project object + hist: Histogram object + recipe: Validated recipe model + verbose: Print detailed progress + + Returns: + Result dict with success, rwp, elapsed_time + """ + controls = recipe.payload.refinement_controls + + if verbose: + print(f"\n{'='*60}") + print(f"Executing Rietveld Refinement") + print(f" Cycles: {controls.refinement_cycles}") + print(f"{'='*60}\n") + + # Execute refinement (keeping GSAS-II's failure message, which + # G2Project.refine() would otherwise discard) + refine_ok, g2_msg = _refine_with_message(proj) + + # Extract Rwp + rwp_final = hist.residuals.get("wR") + + if not refine_ok or rwp_final is None: + if g2_msg: + error = f"Rietveld refinement failed: {' '.join(g2_msg.split())}" + else: + error = ("Rietveld refinement produced no Rwp — proj.refine() " + "may have failed silently") + return { + 'success': False, + 'rwp': None, + 'error': error, + } + + if verbose: + print(f"Rietveld refinement complete. Final Rwp: {rwp_final:.3f}%\n") + + return { + 'success': True, + 'rwp': rwp_final + } + + +def execute_spf_refinement( + proj: Any, + hist: Any, + recipe: RecipeModel, + verbose: bool +) -> dict: + """ + Execute single peak fitting refinement. + + This replaces the previous "peaks_only" strategy. + + Args: + proj: GSAS-II project object + hist: Histogram object + recipe: Validated recipe model + verbose: Print detailed progress + + Returns: + Result dict with success, rwp, elapsed_time + """ + controls = recipe.payload.refinement_controls + spf_mode = "useIP" if controls.single_peak_fitting_mode.use_instrument_profile else "hold" + + if verbose: + print(f"\n{'='*60}") + print(f"Executing Single Peak Fitting") + print(f" Mode: {spf_mode} ({'use instrument profile' if spf_mode == 'useIP' else 'refine peak widths'})") + print(f" Cycles: {controls.refinement_cycles}") + print(f"{'='*60}\n") + + # Execute single peak fitting (cycles already set in step 10) + peak_result = hist.refine_peaks(mode=spf_mode) + + # Extract Rwp from peak_result + rwp_final = peak_result[3].get("Rwp") if len(peak_result) > 3 else None + + if rwp_final is None: + return { + 'success': False, + 'rwp': None, + 'error': "Single peak fitting produced no Rwp — hist.refine_peaks() may have failed silently", + } + + if verbose: + print(f"Single peak fitting complete. Final Rwp: {rwp_final:.3f}%\n") + + return { + 'success': True, + 'rwp': rwp_final + } + + +# Schema executor registry +SCHEMA_EXECUTORS = { + 'GSASII_Rietveld': execute_rietveld_refinement, + 'GSASII_SPF': execute_spf_refinement +} + + +######################################## +# Kicker script for PowderLine +######################################## + +def run_refinement(recipe: RecipeModel, output_dir: Path, verbose: bool = False, method: str = 'server') -> dict: + """ + Internal execution engine: run a GSAS-II refinement using already-loaded libraries. + + This function is the single execution entry point used by all paths: + - ``gsas_server.py`` calls it directly after receiving an HTTP request + (``method='server'``). + - ``GSASClient._submit_via_subprocess()`` calls it in-process as the + subprocess fallback (``method='subprocess'``). Despite the method name, + no OS subprocess is spawned; see :meth:`GSASClient._submit_via_subprocess`. + + For programmatic use, prefer ``powderline.run()`` which validates the recipe, + dispatches to the appropriate backend, and normalises all structured data + fields to pandas DataFrames. + + Args: + recipe: Validated RecipeModel instance (call ``powderline.validate()`` + first if starting from a raw dict). + output_dir: Directory where output files are written (``dummy.gpx``, + ``dummy.lst``, CSV reports, ``fit_profile.txt``). Must exist or be + creatable. + verbose: If True, print detailed progress to stdout. + method: Execution method identifier string stored in the return dict. + Callers set this to ``'server'`` or ``'subprocess'`` so downstream + consumers know how the run was executed. Default ``'server'``. + + Returns: + dict with keys: + + - ``success`` (bool) + - ``run_id`` (str) — UUID4 string + - ``rwp`` (float | None) + - ``elapsed_time`` (float) — wall-clock seconds + - ``method`` (str) — value of the ``method`` argument + - ``output_files`` (list[str]) — paths of all files written to + ``output_dir`` (informational) + - ``fit_profile`` (dict) — column-oriented dict (JSON-serializable); + normalised to ``pd.DataFrame`` by ``run()`` + - ``unit_cell_data`` (dict) — ``{phase: list-of-records}`` + - ``peak_list_data`` (dict) — ``{phase: list-of-records}`` + - ``refined_parameters`` (list) — list-of-records (9-column schema) + - ``spf_peaks`` (dict) — column-oriented dict; populated for + ``GSASII_SPF`` runs, empty dict otherwise + - ``spf_convergence_diagnostics`` (dict) — column-oriented dict; + populated when SPF peaks have convergence issues, empty dict otherwise + - ``error`` (str) — present when ``success=False`` + - ``traceback`` (str) — present when an unhandled exception occurred + + Example:: + + from powderline.kicker import run_refinement + from powderline.schema import RecipeModel + recipe = RecipeModel.model_validate(recipe_dict) + result = run_refinement(recipe, Path('output'), verbose=True) + print(f"Rwp: {result['rwp']:.3f}% [run_id={result['run_id']}]") + """ + # Assign a unique ID for this refinement run immediately, before any work begins, + # so every exit path (success, GSAS-II failure, unexpected exception) can include + # it in the returned dict and server logs. + run_id = str(uuid.uuid4()) + import time + start_time = time.time() + + try: + # 1. Get xrd_data from validated model (file-less: no sample_name) + xrd_data = recipe.payload.xrd_data + + # 2. Construct name and initialize project using standard naming + gpx_path = output_dir / OUTPUT_NAMING.gpx_filename + proj = G2.G2Project(newgpx=str(gpx_path)) + + # 3. Instrument initialization - now a list of dicts [Iparm1, Iparm2] + instrument_init = recipe.payload.instrument.initialization + + # 4. Add histogram - phase1B update: xrd_data is now a dict with arrays, instrument_init is list of dicts + try: + hist = add_powder_histogram_from_arrays( + proj=proj, + tth_array=xrd_data.tth, + intensity_array=xrd_data.Itth, + intensity_weights_array=xrd_data.Itth_weights, + histogram_name=OUTPUT_NAMING.histogram_name, + instrument_prm_dict=instrument_init[0], # Use Iparm1 (first dict) + comments=None, + phases=None, # Optionally could link to phases if order of operations + ) + except Exception as e: + import traceback as _tb + tb = _tb.format_exc() + elapsed_time = time.time() - start_time + return { + 'success': False, + 'rwp': None, + 'run_id': run_id, + 'error': f"Failed to load XRD data or instrument parameters: {str(e)}", + 'traceback': tb, + 'elapsed_time': elapsed_time, + 'method': method + } + + # After adding histogram, set hist scale and refine flag to defaults + set_hist_scale(proj, hist, hist_scale_val=DEFAULT_HIST_SCALE_VAL, hist_scale_refine_flag=DEFAULT_HIST_SCALE_REFINE_FLAG, print_info=verbose) + + # 5. Set fit range + fit_range = recipe.payload.fit_range if recipe.payload.fit_range else (None, None) + if fit_range != (None, None): + set_fit_range_hist(hist, fit_range, print_info=verbose) + + # 6. Set background - Chebyshev and single peaks + if recipe.payload.background is not None: + background_dict = recipe.payload.background.model_dump(mode='json') + if recipe.payload.background.chebyshev is not None: + chebyshev_dict = background_dict.get('chebyshev') + set_chebyshev_background(proj, hist, chebyshev_dict, print_info=verbose) + if recipe.payload.background.single_peaks is not None: + bkg_single_peaks_dict = background_dict.get('single_peaks') + set_single_peak_background(proj, hist, bkg_single_peaks_dict, print_info=verbose) + + # 6b. Set single peaks (Peak List mode for non-background peaks) + if recipe.payload.single_peaks is not None: + single_peaks_dict = recipe.payload.single_peaks.model_dump(mode='json') + # Check if dict has any actual peak data before calling setter + has_peak_data = False + for key in ['positions', 'intensities', 'pv_gaussian_sigma_sq', 'pv_lorentzian_gamma']: + if key in single_peaks_dict and single_peaks_dict[key] and len(single_peaks_dict[key]) > 0: + has_peak_data = True + break + if has_peak_data: + set_single_peaks(proj, hist, single_peaks_dict, print_info=verbose) + + # 7. Add phases (if present) + if recipe.payload.phases is not None and len(recipe.payload.phases) > 0: + phases_dict = recipe.payload.model_dump(mode='json')['phases'] + add_phases_from_dict(proj, hist, phases_dict, print_info=verbose) + + # 8. Parameterize phases + holds = set_phase_parameterization(proj, hist, phases_dict, print_info=verbose) + + # 8b. Apply Hold constraints for per-parameter refine flags + # (schema 0.26: fixed members of partially-refined DOF groups). + # The isinstance guard keeps mocked-setter unit tests inert. + if isinstance(holds, list) and holds: + proj.add_HoldConstr(holds) + if verbose: + print(f"Applied {len(holds)} Hold constraint(s): {holds}") + + # 9. Set instrument parameterization + instrument_param_dict = recipe.payload.instrument.parameterization.model_dump(mode='json') if recipe.payload.instrument.parameterization else None + if instrument_param_dict is not None: + instrument_param_changes = False + for key, value in instrument_param_dict.items(): + if isinstance(value, dict): + if any(v is not None for v in value.values()): + instrument_param_changes = True + break + elif value is not None: + instrument_param_changes = True + break + if instrument_param_changes: + set_instrument_parameterization(proj, hist, instrument_param_dict, print_info=verbose) + + # 10. Get refinement controls and set refinement cycles + controls = recipe.payload.refinement_controls + + # 10a. Validate single_peak_fitting_mode requirements (only for GSASII_SPF) + if recipe.schema_name == 'GSASII_SPF': + if controls.single_peak_fitting_mode is None: + raise ValueError( + f"Schema '{recipe.schema_name}' requires " + f"'single_peak_fitting_mode' to be configured in refinement_controls." + ) + + num_cycles = controls.refinement_cycles + if num_cycles != proj.get_Controls('cycles'): + set_refinement_cycles(proj, num_cycles, print_info=verbose) + + # 11. Execute refinement using schema-based dispatch + executor = SCHEMA_EXECUTORS.get(recipe.schema_name) + if executor is None: + raise ValueError(f"Unknown schema_name: {recipe.schema_name}. Valid options: {list(SCHEMA_EXECUTORS.keys())}") + + try: + result = executor(proj, hist, recipe, verbose) + + # Check if executor succeeded + if not result.get('success', False): + elapsed_time = time.time() - start_time + return { + 'success': False, + 'rwp': None, + 'run_id': run_id, + 'error': result.get( + 'error', + f"Refinement executor '{recipe.schema_name}' returned success=False without an error message", + ), + 'traceback': result.get('traceback'), + 'elapsed_time': elapsed_time, + 'method': method + } + + except Exception as e: + import traceback as _tb + tb = _tb.format_exc() + elapsed_time = time.time() - start_time + return { + 'success': False, + 'rwp': None, + 'run_id': run_id, + 'error': f"Refinement failed: {str(e)}", + 'traceback': tb, + 'elapsed_time': elapsed_time, + 'method': method + } + + # Save GPX file after successful refinement + proj.save(str(gpx_path)) + + # 12. Extract final Rwp from result + rwp = result.get('rwp') + + # --- Post-refinement data extraction --- + # Each helper writes its own output files and returns JSON-serializable data. + # run() normalises all dicts/lists to DataFrames for programmatic callers. + + fit_profile_data = _extract_fit_profile(hist, output_dir) + + spf_peaks_data, spf_diagnostics_data = _extract_spf_peak_report( + proj, hist, recipe, output_dir, verbose + ) + + # Extract refined parameters (needed for unit cell ESDs in _extract_phase_reports) + if verbose: + print("\nExtracting refined parameters with ESDs...") + + # NOTE: .lst fallback (extract_refined_params_from_lst) is preserved for Phase 2 + # reference but its call site is intentionally disabled: .lst parsing is incomplete + # (no atom/HAP params; different naming scheme) and obscured covariance failures. + param_dict = extract_refined_params_from_project(proj, verbose=verbose) + + # Only raise if GSAS-II populated a varyList (i.e. parameters were actually varied) + # but we still got nothing back. An empty param_dict with an empty varyList is + # expected and correct for simulation mode (refinement_cycles=1, all params locked) + # and for GSASII_SPF (no standard covariance matrix produced). + cov_vary_list = ( + proj.data.get('Covariance', {}).get('data', {}).get('varyList', []) + ) + if len(param_dict) == 0 and len(cov_vary_list) > 0: + raise RuntimeError( + "GSAS-II populated a varyList but refined parameter extraction returned " + "empty results; covariance data may be corrupt. " + "Ensure refinement completed successfully. " + "Check the .lst file for GSAS-II error details." + ) + + # --- .lst fallback (disabled) --- + # NOTE: preserved for Phase 2 reference — .lst parsing is incomplete + # (no atom/HAP params; different naming scheme); covariance extraction is the + # only supported path. + # if len(param_dict) == 0: + # lst_file = output_dir / OUTPUT_NAMING.lst_filename + # if lst_file.exists(): + # if verbose: + # print(" Covariance data not available, parsing .lst file...") + # param_dict = extract_refined_params_from_lst(lst_file) + + unit_cell_data, peak_list_data = _extract_phase_reports( + proj, hist, recipe, param_dict, output_dir + ) + + refined_parameters_data = _extract_refined_parameters( + param_dict, output_dir, proj, verbose + ) + + elapsed_time = time.time() - start_time + return { + 'success': True, + 'run_id': run_id, + 'rwp': rwp, + 'elapsed_time': elapsed_time, + 'method': method, + 'output_files': [str(f) for f in output_dir.glob('*')], + 'fit_profile': fit_profile_data, + 'unit_cell_data': unit_cell_data, + 'peak_list_data': peak_list_data, + 'refined_parameters': refined_parameters_data, + 'spf_peaks': spf_peaks_data, + 'spf_convergence_diagnostics': spf_diagnostics_data, + } + + except Exception as e: + import traceback + tb = traceback.format_exc() + import logging + logging.getLogger(__name__).error("run_refinement failed:\n%s", tb) + elapsed_time = time.time() - start_time + return { + 'success': False, + 'rwp': None, + 'run_id': run_id, + 'error': str(e), + 'traceback': tb, + 'elapsed_time': elapsed_time, + 'method': method + } diff --git a/src/powderline/gateways/gsasii/extractors.py b/src/powderline/gateways/gsasii/extractors.py new file mode 100644 index 0000000..737e27b --- /dev/null +++ b/src/powderline/gateways/gsasii/extractors.py @@ -0,0 +1,1010 @@ +"""GSAS-II gateway — post-refinement extraction and reporting. + +Moved verbatim from ``powderline/kicker.py`` (multi-engine refactor, re/01). +""" +from __future__ import annotations +import sys +import uuid +import yaml +import json +import argparse +import random as ran +import numpy as np +import pandas as pd +from typing import Any, Dict, List, Literal, Optional, Sequence, Union +from pathlib import Path +from pydantic import ValidationError +from GSASII import GSASIIscriptable as G2 # type: ignore +from GSASII import GSASIIlattice as G2lat +from GSASII import GSASIImapvars as G2mv +from GSASII import GSASIIobj as G2obj +from GSASII import GSASIIspc as G2spc +from GSASII import GSASIIElem as G2elem +from GSASII import GSASIIpwd as G2pwd +from powderline.schema import RecipeModel, RefinementControls +from powderline.gateways.gsasii.constraints import atom_refinement_plan, cell_refinement_plan +from powderline._status import CHECK, CROSS, INFO, WARN, emoji +from dataclasses import dataclass + +from powderline.gateways.gsasii.helpers import ( + DEFAULT_SPF_GAMMA_MIN, + DEFAULT_SPF_SIGMA_MIN, + calculate_peak_widths, +) + + + +def calculate_cell_esds_from_A_matrix(phase_idx: int, proj: Any, phase_name: str) -> List[Optional[float]]: + """ + Calculate unit cell parameter ESDs using GSAS-II's reciprocal metric tensor conversion. + + GSAS-II refines reciprocal metric tensor components (A-matrix: A11, A22, A33, A12, A13, A23) + and this function converts those ESDs to direct lattice parameter ESDs (a, b, c, α, β, γ). + + Args: + phase_idx: Phase index (0-based) for parameter naming (e.g., "0::A0") + proj: GSAS-II project object after refinement + phase_name: Name of the phase + + Returns: + list[float | None]: The 7 ESDs, in order + ``[esd_a, esd_b, esd_c, esd_alpha, esd_beta, esd_gamma, esd_volume]``. + + Raises: + RuntimeError: If covariance data is unavailable or the ESD calculation fails. + + Note: + The A-matrix parameters (A0-A5) in GSAS-II correspond to: + A0=A11, A1=A22, A2=A33, A3=A12, A4=A13, A5=A23 (reciprocal metric tensor) + NOT direct cell parameters a, b, c, α, β, γ. + """ + try: + # Get covariance data + cov_data = proj.data.get('Covariance', {}).get('data', {}) + if not cov_data: + return [None] * 7 + + # Get space group data for this phase + SGData = proj.data['Phases'][phase_name]['General'].get('SGData') + if not SGData: + return [None] * 7 + + # Get current cell parameters and convert to A-matrix + cell = proj.data['Phases'][phase_name]['General']['Cell'][1:7] # a, b, c, alpha, beta, gamma + A = G2lat.cell2A(cell) # Convert to reciprocal metric tensor + + # Call GSAS-II's getCellEsd function + # pfx format: "phase_idx::" (e.g., "0::" for first phase) + pfx = f"{phase_idx}::" + cell_esds = G2lat.getCellEsd(pfx, SGData, A, cov_data) + + # getCellEsd returns [esd_a, esd_b, esd_c, esd_alpha, esd_beta, esd_gamma, esd_volume] + return cell_esds + + except Exception as e: + raise RuntimeError( + f"Cell ESD calculation from covariance matrix failed for phase '{phase_name}'. " + f"Ensure refinement completed successfully and covariance data is present. " + f"Original error: {e}" + ) from e + + +def extract_refined_params_from_project(proj: Any, verbose: bool = False) -> Dict[str, Dict[str, Any]]: + """ + Extract all refined parameters with their values and ESDs from proj.data. + + Uses the covariance data stored in proj.data['Covariance']['data'] after refinement. + This includes both independent and dependent parameters (via ComputeDepESD). + + Args: + proj: GSAS-II project object after refinement + verbose: If True, print progress messages. + + Returns: + dict: Mapping of parameter names to ``{"value": float, "esd": float}``. + Returns an empty dict if no covariance data is available. + + Raises: + RuntimeError: If ComputeDepESD fails (dependent parameter ESDs cannot be calculated). + + Example: + >>> params = extract_refined_params_from_project(proj) + >>> params[":0:U"] + {"value": 47.406, "esd": 8.314} + """ + cov_data = proj.data.get('Covariance', {}).get('data', {}) + + if not cov_data: + return {} + + vary_list = cov_data.get('varyList', []) + variables = cov_data.get('variables', []) + sig = cov_data.get('sig', []) + + # Check if any are empty (works for both lists and numpy arrays) + if len(vary_list) == 0 or len(variables) == 0 or len(sig) == 0: + return {} + + # Create parameter dictionary with values and ESDs for independent parameters + param_dict = {} + for param_name, value, esd in zip(vary_list, variables, sig): + param_dict[param_name] = { + "value": float(value), + "esd": float(esd) + } + + # Add dependent parameter ESDs using GSAS-II's ComputeDepESD + cov_matrix = cov_data.get('covMatrix') + # Check if cov_matrix exists and is not empty (works for None, empty array, etc.) + if cov_matrix is not None and hasattr(cov_matrix, '__len__') and len(cov_matrix) > 0: + try: + dep_sig_dict = G2mv.ComputeDepESD(cov_matrix, vary_list) + # dep_sig_dict only contains ESDs; values are already in param_dict from + # the independent-parameter loop above — just update the esd entries. + for param_name, esd in dep_sig_dict.items(): + if param_name in param_dict: + param_dict[param_name]["esd"] = float(esd) + # If param not in param_dict, it's a dependent param we haven't seen. + # For now, skip it as we don't have its value easily accessible. + except Exception as e: + raise RuntimeError( + f"ComputeDepESD failed; dependent parameter ESDs cannot be calculated. " + f"Original error: {e}" + ) from e + elif verbose: + print(" Note: covariance matrix is absent; dependent parameter ESDs skipped.") + + return param_dict + + +def extract_refined_params_from_lst(lst_file: Path) -> Dict[str, Dict[str, Any]]: + """ + PRESERVED (disabled at call site) — see commented block in run_refinement() for context. + + Extract all refined parameters with values and ESDs from .lst file. + + NOTE: This function is incomplete and its call site has been intentionally disabled. + The covariance matrix path (extract_refined_params_from_project) is the only supported + extraction method. This function does not cover atom parameters and uses a custom naming + scheme (e.g. "cell:a") that differs from the GSAS-II-native names in proj.data. + + # TODO: Remove this function once a test is written confirming that covariance matrix + # ESD output (extract_refined_params_from_project) matches what .lst parsing previously + # produced for the parameters it did cover (instrument, background, unit cell). + # Do not delete until that regression test exists and passes. + + Parses the GSAS-II .lst file to extract parameter names, values, and ESDs. + This is used as a fallback or complement to proj.data extraction. + + Args: + lst_file: Path to the .lst file + + Returns: + Dictionary mapping parameter names to {"value": float, "esd": float|None} + Parameters without ESDs (fixed parameters) have esd=None. + + Note: + Currently extracts instrument parameters, background, and unit cell. + Additional parameter types (atoms, etc.) can be added as needed. + """ + if not lst_file.exists(): + return {} + + param_dict = {} + content = lst_file.read_text() + lines = content.split('\n') + + i = 0 + while i < len(lines): + line = lines[i] + + # Instrument parameters section + if 'Instrument Parameters:' in line: + # Look for the "names :" line + i += 1 + while i < len(lines) and not lines[i].strip().startswith('names :'): + i += 1 + + if i < len(lines): + names_line = lines[i] + # Next line should be "value :" + i += 1 + if i < len(lines) and lines[i].strip().startswith('value :'): + values_line = lines[i] + # Next line should be "sig :" (ESDs) + i += 1 + sig_line = "" + if i < len(lines) and lines[i].strip().startswith('sig :'): + sig_line = lines[i] + + # Parse the three lines + names = names_line.split(':')[1].strip().split() + values = values_line.split(':')[1].strip().split() + sigs = sig_line.split(':')[1].strip().split() if sig_line else [] + + for j, name in enumerate(names): + if j < len(values): + try: + value = float(values[j]) + esd = float(sigs[j]) if j < len(sigs) and sigs[j] else None + # Use GSAS-II naming convention for instrument params + param_name = f":0:{name}" + param_dict[param_name] = {"value": value, "esd": esd} + except (ValueError, IndexError): + pass + + # Background coefficients section + elif 'Background function:' in line and 'chebyschev' in line: + # Next line should be "value :" + i += 1 + if i < len(lines) and lines[i].strip().startswith('value :'): + values_line = lines[i] + # Next line should be "sig :" + i += 1 + sig_line = "" + if i < len(lines) and lines[i].strip().startswith('sig :'): + sig_line = lines[i] + + values = values_line.split(':')[1].strip().split() + sigs = sig_line.split(':')[1].strip().split() if sig_line else [] + + for j, value_str in enumerate(values): + try: + value = float(value_str) + esd = float(sigs[j]) if j < len(sigs) and sigs[j] else None + param_name = f":0:Back;{j}" + param_dict[param_name] = {"value": value, "esd": esd} + except (ValueError, IndexError): + pass + + # Unit cell parameters section + elif 'New unit cell:' in line: + # Look for values line + i += 1 + while i < len(lines) and not lines[i].strip().startswith('values:'): + i += 1 + + if i < len(lines): + values_line = lines[i] + # Next line should be "esds :" + i += 1 + esds_line = "" + if i < len(lines) and lines[i].strip().startswith('esds :'): + esds_line = lines[i] + + # Parse - note that unit cell params are phase-specific + # For now, store with generic name (can be enhanced later to include phase name) + values = values_line.split(':')[1].strip().split() + esds = esds_line.split(':')[1].strip().split() if esds_line else [] + + cell_param_names = ['a', 'b', 'c', 'alpha', 'beta', 'gamma', 'volume'] + for j, name in enumerate(cell_param_names): + if j < len(values): + try: + value = float(values[j]) + esd = float(esds[j]) if j < len(esds) and esds[j] else None + # Store with generic cell param naming + param_name = f"cell:{name}" + param_dict[param_name] = {"value": value, "esd": esd} + except (ValueError, IndexError): + pass + + i += 1 + + return param_dict + + +def get_descriptive_param_name(param_name: str) -> str: + """ + Convert GSAS-II internal parameter names to human-readable descriptions. + + Args: + param_name: GSAS-II parameter name (e.g., ":0:U", "0::A0", ":0:Back;3") + + Returns: + Human-readable description of the parameter + + Examples: + >>> get_descriptive_param_name(":0:U") + "instrument_broadening_U" + >>> get_descriptive_param_name("0::A0") + "phase_0_A11_reciprocal_metric_tensor" + >>> get_descriptive_param_name(":0:Scale") + "phase_scale_factor" + >>> get_descriptive_param_name(":0:Back;3") + "background_coefficient_3" + """ + # Handle phase-specific reciprocal metric tensor (A-matrix) + # Check for A0-A5 specifically (not AUiso, Afrac, etc.) + if '::A' in param_name: + parts = param_name.split('::') + if len(parts) == 2: + phase_idx = parts[0] + a_param = parts[1] # e.g., "A0", "A1", etc. + + # Only handle A0-A5 (reciprocal metric tensor) + if a_param in ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']: + # A0-A5 map to A11, A22, A33, A12, A13, A23 + a_mapping = { + 'A0': 'A11', 'A1': 'A22', 'A2': 'A33', + 'A3': 'A12', 'A4': 'A13', 'A5': 'A23' + } + tensor_component = a_mapping[a_param] + return f"phase_{phase_idx}_reciprocal_metric_tensor_{tensor_component}" + + # Handle other phase parameters (e.g., "0::Afrac:0", "0::Ax:0") + if '::' in param_name: + parts = param_name.split('::') + phase_idx = parts[0] + param_type = parts[1] + + if ':' in param_type: + # Format: "0::Afrac:0" or "0::Ax:0" + sub_parts = param_type.split(':') + param_base = sub_parts[0] + atom_idx = sub_parts[1] + + if param_base == 'Afrac': + return f"phase_{phase_idx}_atom_{atom_idx}_occupancy" + elif param_base == 'AUiso': + return f"phase_{phase_idx}_atom_{atom_idx}_isotropic_displacement" + elif param_base == 'Ax': + return f"phase_{phase_idx}_atom_{atom_idx}_x_coordinate" + elif param_base == 'Ay': + return f"phase_{phase_idx}_atom_{atom_idx}_y_coordinate" + elif param_base == 'Az': + return f"phase_{phase_idx}_atom_{atom_idx}_z_coordinate" + elif param_base.startswith('AU'): + # Anisotropic displacement parameters (AU11, AU22, etc.) + return f"phase_{phase_idx}_atom_{atom_idx}_anisotropic_displacement_{param_base}" + else: + return f"phase_{phase_idx}_atom_{atom_idx}_{param_base}" + else: + return f"phase_{phase_idx}_{param_type}" + + # Handle histogram parameters (format: ":hist_idx:param") + if param_name.startswith(':') and param_name.count(':') >= 2: + parts = param_name.split(':') + # parts[0] is empty, parts[1] is hist_idx, parts[2] is param + hist_idx = parts[1] + param = parts[2] if len(parts) > 2 else "" + + # Instrument broadening parameters + if param == 'U': + return "instrument_broadening_U" + elif param == 'V': + return "instrument_broadening_V" + elif param == 'W': + return "instrument_broadening_W" + elif param == 'X': + return "instrument_broadening_X" + elif param == 'Y': + return "instrument_broadening_Y" + elif param == 'Z': + return "instrument_broadening_Z" + + # Instrument parameters + elif param == 'Lam': + return "wavelength" + elif param == 'Zero': + return "zero_point_correction" + elif param == 'SH/L': + return "axial_divergence" + elif param == 'Polariz': + return "polarization_correction" + + # Scale factor + elif param == 'Scale': + return "phase_scale_factor" + + # Background coefficients + elif param.startswith('Back;'): + coeff_idx = param.split(';')[1] + return f"background_coefficient_{coeff_idx}" + + # Background peaks + elif param.startswith('BkPk'): + # Format: "BkPkpos;0", "BkPkint;0", "BkPksig;0", "BkPkgam;0" + # Extract type (pos/int/sig/gam) and index + if ';' in param: + # Remove 'BkPk' prefix and split + without_prefix = param[4:] # Remove "BkPk" + parts = without_prefix.split(';') + pk_type = parts[0] # pos, int, sig, gam + pk_idx = parts[1] if len(parts) > 1 else "0" + + type_mapping = { + 'pos': 'position', + 'int': 'intensity', + 'sig': 'sigma', + 'gam': 'gamma' + } + return f"background_peak_{pk_idx}_{type_mapping.get(pk_type, pk_type)}" + else: + return f"background_peak_{param}" + + else: + return f"histogram_{hist_idx}_{param}" + + # Handle phase-histogram parameters (format: "phase_idx:hist_idx:param") + # This includes Scale and other HAP (Histogram-Atom-Phase) parameters + if ':' in param_name and not param_name.startswith(':'): + parts = param_name.split(':') + if len(parts) >= 3: + phase_idx = parts[0] + hist_idx = parts[1] + param = parts[2] + + if param == 'Scale': + return f"phase_{phase_idx}_scale_factor" + elif param.startswith('Mustrain'): + return f"phase_{phase_idx}_mustrain_{param.split(';')[1]}" + elif param.startswith('Size'): + return f"phase_{phase_idx}_crystallite_size_{param.split(';')[1]}" + else: + return f"phase_{phase_idx}_histogram_{hist_idx}_{param}" + + # Handle cell parameters from .lst parsing + if param_name.startswith('cell:'): + cell_param = param_name.split(':')[1] + param_mapping = { + 'a': 'lattice_parameter_a', + 'b': 'lattice_parameter_b', + 'c': 'lattice_parameter_c', + 'alpha': 'lattice_angle_alpha', + 'beta': 'lattice_angle_beta', + 'gamma': 'lattice_angle_gamma', + 'volume': 'unit_cell_volume' + } + return param_mapping.get(cell_param, f"cell_{cell_param}") + + # Fallback + return param_name + + +def parse_parameter_associations(param_name: str) -> dict: + """ + Parse GSAS-II parameter name to extract phase and atom associations. + + Args: + param_name: GSAS-II parameter name (e.g., "0::Afrac:2", ":0:U", "1:0:Scale") + + Returns: + Dictionary with keys 'phase_idx' and 'atom_idx' (both int or None) + + Examples: + >>> parse_parameter_associations("0::Afrac:2") + {"phase_idx": 0, "atom_idx": 2} + >>> parse_parameter_associations("1::A0") + {"phase_idx": 1, "atom_idx": None} + >>> parse_parameter_associations("0:0:Scale") + {"phase_idx": 0, "atom_idx": None} + >>> parse_parameter_associations(":0:U") + {"phase_idx": None, "atom_idx": None} + """ + phase_idx = None + atom_idx = None + + # Pattern 1: Phase-atom parameters (format: "phase_idx::param:atom_idx") + # Examples: "0::Afrac:2", "1::AUiso:0", "0::Ax:3" + if '::' in param_name: + parts = param_name.split('::') + try: + phase_idx = int(parts[0]) + except (ValueError, IndexError): + pass + + # Check if there's an atom index + if len(parts) > 1 and ':' in parts[1]: + sub_parts = parts[1].split(':') + if len(sub_parts) > 1: + try: + atom_idx = int(sub_parts[1]) + except (ValueError, IndexError): + pass + + # Pattern 2: Phase-histogram parameters (format: "phase_idx:hist_idx:param") + # Examples: "0:0:Scale", "1:0:Mustrain;i", "0:0:Size;mx" + elif ':' in param_name and not param_name.startswith(':'): + parts = param_name.split(':') + if len(parts) >= 2: + try: + phase_idx = int(parts[0]) + except (ValueError, IndexError): + pass + + # Pattern 3: Histogram-only parameters (format: ":hist_idx:param") + # Examples: ":0:U", ":0:Back;3", ":0:BkPkpos;1" + # These have no phase or atom association (already None) + + return {"phase_idx": phase_idx, "atom_idx": atom_idx} + + +def build_phase_name_mapping(proj: Any) -> Dict[int, str]: + """ + Build mapping from phase index to phase name. + + Args: + proj: GSAS-II project object + + Returns: + Dictionary mapping phase index (int) to phase name (str) + + Example: + >>> mapping = build_phase_name_mapping(proj) + >>> mapping + {0: "LaB6", 1: "DRX_33"} + """ + phase_mapping = {} + try: + phase_names = [p.name for p in proj.phases() if p is not None] + for phase_idx, phase_name in enumerate(phase_names): + phase_mapping[phase_idx] = phase_name + except Exception as e: + print(f" Warning: Failed to build phase name mapping: {e}") + return phase_mapping + + +def build_atom_name_mapping(proj: Any) -> Dict[int, Dict[int, str]]: + """ + Build mapping from (phase_idx, atom_idx) to atom label. + + Args: + proj: GSAS-II project object + + Returns: + Nested dictionary: {phase_idx: {atom_idx: atom_label}} + + Example: + >>> mapping = build_atom_name_mapping(proj) + >>> mapping + {0: {0: "La", 1: "B"}, 1: {0: "Li", 1: "Mg", 2: "Mn1"}} + """ + atom_mapping = {} + try: + phase_names = [p.name for p in proj.phases() if p is not None] + for phase_idx, phase_name in enumerate(phase_names): + atom_mapping[phase_idx] = {} + try: + atoms_list = proj.data['Phases'][phase_name]['Atoms'] + for atom_idx, atom_record in enumerate(atoms_list): + # atom_record[0] is the atom label + atom_label = atom_record[0] + atom_mapping[phase_idx][atom_idx] = atom_label + except (KeyError, IndexError, TypeError) as e: + print(f" Warning: Failed to extract atoms for phase '{phase_name}': {e}") + except Exception as e: + print(f" Warning: Failed to build atom name mapping: {e}") + return atom_mapping + + +def export_refined_parameters_csv( + param_dict: Dict[str, Dict[str, Any]], + output_file: Path, + proj: Any = None, + include_category: bool = True +) -> Optional[pd.DataFrame]: + """ + Export refined parameters to CSV file and return the DataFrame. + + Args: + param_dict: Dictionary from extract_refined_params_* functions + output_file: Path to output CSV file + proj: GSAS-II project object (optional, needed for phase/atom names) + include_category: If True, add 'category' and 'descriptive_name' columns (default: True) + + Returns: + DataFrame with the exported parameters, or None if param_dict is empty. + + Output CSV / DataFrame columns: + - parameter_name: GSAS-II internal parameter name + - descriptive_name: Human-readable parameter description (if include_category=True) + - phase_name: Name of associated phase (None if not phase-specific) + - phase_idx: Index of associated phase (None if not phase-specific) + - atom_name: Label of associated atom (None if not atom-specific) + - atom_idx: Index of associated atom (None if not atom-specific) + - value: Refined value + - esd: Estimated standard deviation (None for fixed parameters) + - category: Parameter category (instrument, background, cell, etc.) if include_category=True + """ + if len(param_dict) == 0: + return None + + # Build phase and atom mappings if proj is available + phase_mapping = {} + atom_mapping = {} + if proj is not None: + phase_mapping = build_phase_name_mapping(proj) + atom_mapping = build_atom_name_mapping(proj) + + rows = [] + for param_name, param_data in param_dict.items(): + # Parse parameter associations + associations = parse_parameter_associations(param_name) + phase_idx = associations["phase_idx"] + atom_idx = associations["atom_idx"] + + # Lookup names from mappings + phase_name = phase_mapping.get(phase_idx) if phase_idx is not None else None + atom_name = atom_mapping.get(phase_idx, {}).get(atom_idx) if phase_idx is not None and atom_idx is not None else None + + row = { + "parameter_name": param_name, + "value": param_data["value"], + "esd": param_data.get("esd"), + "phase_name": phase_name, + "phase_idx": phase_idx, + "atom_name": atom_name, + "atom_idx": atom_idx + } + + if include_category: + # Add descriptive name + row["descriptive_name"] = get_descriptive_param_name(param_name) + + # Determine category from parameter name + if '::A' in param_name and len(param_name.split('::')[1]) <= 2: + # Reciprocal metric tensor (A0-A5) + category = 'reciprocal_metric_tensor' + elif '::' in param_name: + # Other phase parameters (atoms, etc.) + param_type = param_name.split('::')[1] + if 'frac' in param_type: + category = 'atom_occupancy' + elif 'Uiso' in param_type: + category = 'atom_displacement_isotropic' + elif param_type.startswith('AU') and len(param_type) > 2: + category = 'atom_displacement_anisotropic' + elif param_type.startswith('A') and param_type[1] in ['x', 'y', 'z']: + category = 'atom_position' + else: + category = 'phase_other' + elif param_name.startswith('cell:'): + category = 'unit_cell' + elif ':' in param_name: + parts = param_name.split(':') + if len(parts) >= 3: + param_part = parts[2] + if param_part.startswith('Back;'): + category = 'background' + elif param_part.startswith('BkPk'): + category = 'background_peak' + elif param_part == 'Scale': + category = 'scale' + elif param_part in ['U', 'V', 'W', 'X', 'Y', 'Z']: + category = 'instrument_broadening' + elif param_part in ['Lam', 'Zero', 'SH/L', 'Polariz']: + category = 'instrument' + else: + category = 'other' + else: + category = 'other' + else: + category = 'other' + + row["category"] = category + + rows.append(row) + + # Sort by category, then parameter name + if include_category: + rows.sort(key=lambda x: (x["category"], x["parameter_name"])) + else: + rows.sort(key=lambda x: x["parameter_name"]) + + # Reorder columns: parameter_name, descriptive_name, phase_name, phase_idx, atom_name, atom_idx, value, esd, category + if include_category: + df = pd.DataFrame(rows, columns=["parameter_name", "descriptive_name", "phase_name", "phase_idx", "atom_name", "atom_idx", "value", "esd", "category"]) + else: + df = pd.DataFrame(rows, columns=["parameter_name", "phase_name", "phase_idx", "atom_name", "atom_idx", "value", "esd"]) + + # Convert index columns to nullable integer type (Int64) to avoid scientific notation formatting + df['phase_idx'] = df['phase_idx'].astype('Int64') + df['atom_idx'] = df['atom_idx'].astype('Int64') + + # Format float columns independently: values need 6 decimal places, ESDs need 8 + df['value'] = df['value'].apply(lambda x: f"{x:.6e}" if pd.notna(x) else "") + df['esd'] = df['esd'].apply(lambda x: f"{x:.8e}" if pd.notna(x) else "") + + df.to_csv(output_file, index=False, lineterminator="\n") + return df + + +######################################## +# Post-refinement extraction helpers +######################################## + +def _extract_fit_profile(hist: Any, output_dir: Path) -> dict: + """Extract fit profile arrays from histogram and save fit_profile.txt. + + Args: + hist: GSAS-II histogram object after refinement. + output_dir: Directory to write ``fit_profile.txt``. + + Returns: + dict: Column-oriented data (JSON-serializable) with keys ``two_theta``, + ``y_obs``, ``y_weights``, ``y_calc``, ``y_diff``, ``y_bkg``, ``q_values``, + ``d_spacings``. + """ + two_theta = hist.getdata(datatype="X") + q_values = hist.getdata(datatype="Q") + d_spacings = hist.getdata(datatype="d") + y_obs = hist.getdata(datatype="Yobs") + y_weights = hist.getdata(datatype="Yweight") + y_calc = hist.getdata(datatype="Ycalc") + y_bkg = hist.getdata(datatype="Background") + y_diff = hist.getdata(datatype="Residual") + + fit_profile_df = pd.DataFrame({ + "two_theta": two_theta, + "y_obs": y_obs, + "y_weights": y_weights, + "y_calc": y_calc, + "y_diff": y_diff, + "y_bkg": y_bkg, + "q_values": q_values, + "d_spacings": d_spacings, + }) + fit_profile_df.to_csv( + output_dir / "fit_profile.txt", sep="\t", float_format="%.8f", + header=True, index=False, lineterminator="\n" + ) + return {col: fit_profile_df[col].tolist() for col in fit_profile_df.columns} + + +def _extract_spf_peak_report( + proj: Any, hist: Any, recipe: RecipeModel, output_dir: Path, verbose: bool +) -> tuple[dict, dict]: + """Extract single peak fitting results and save report files. + + Called only for ``GSASII_SPF`` runs where ``recipe.payload.single_peaks`` + is set. Returns two column-oriented dicts (JSON-serializable) that are + normalised to DataFrames by ``run()``. + + Also writes: + - ``single_peaks_report.txt`` — per-peak widths and convergence status + - ``peak_convergence_diagnostics.txt`` — only when peaks have issues + + Args: + proj: GSAS-II project object after refinement. + hist: GSAS-II histogram object. + recipe: Validated RecipeModel. + output_dir: Directory to write report files. + verbose: If True, print convergence warnings to stdout. + + Returns: + ``(spf_peaks_data, spf_diagnostics_data)`` where each is a + column-oriented dict, or ``({}, {})`` when single peaks are not used. + """ + if recipe.payload.single_peaks is None: + return {}, {} + + peak_list = proj.data.get(hist.name, {}).get('Peak List', {}).get('peaks', []) + if not peak_list: + return {}, {} + + peak_data = [] + convergence_diagnostics = [] + converged_count = 0 + aphysical_count = 0 + + for i, peak in enumerate(peak_list): + pos, pos_flag, intensity, int_flag, sig_sq, sig_sq_flag, gamma, gam_flag = peak + + # Determine convergence status + status = "converged" + if np.isnan(sig_sq) or np.isnan(gamma): + status = "NaN_failed" + elif sig_sq <= 0 and gamma < 0: + status = "negative_sigma_sq_and_gamma_warning" + aphysical_count += 1 + elif sig_sq <= 0: + status = "zero_or_negative_sigma_sq_warning" + aphysical_count += 1 + elif gamma < 0: + status = "negative_gamma_warning" + aphysical_count += 1 + else: + converged_count += 1 + + # Copy GSAS-II behavior for PV calc — use a small positive default for + # aphysical (zero/negative) sigma_sq or gamma values + sigma = np.sqrt(sig_sq) if sig_sq > 0 else DEFAULT_SPF_SIGMA_MIN + # NOTE: GSAS-II gamma = FWHM_L (not HWHM), so we use gamma directly + gamma_calc = gamma if gamma > 0 else DEFAULT_SPF_GAMMA_MIN + + # Calculate widths in degrees (GSAS-II stores in centidegrees) + fwhm_g, fwhm_l, fwhm_pv, ib_g, ib_l, ib_pv, valid, warning_msg = calculate_peak_widths( + sigma / 100, gamma_calc * 0.5 / 100 + ) + + # Get GSAS-II verification (may fail for aphysical values) + try: + # GSAS-II uses gamma directly as FWHM_L (differs from scipy, TOPAS, literature) + fwhm_gsas = G2pwd.getgamFW(gamma_calc / 100, sigma / 100) + except Exception: + fwhm_gsas = np.nan + + converged_bool = status == "converged" + peak_data.append([ + pos, intensity, sigma, sig_sq, gamma_calc, + fwhm_g, fwhm_l, fwhm_pv, ib_g, ib_l, ib_pv, + fwhm_gsas, converged_bool, status + ]) + + if status != "converged": + convergence_diagnostics.append({ + 'peak_index': i, + 'position_2theta': pos, + 'final_sigma_sq': sig_sq, + 'final_gamma': gamma, + 'status': status, + 'notes': warning_msg if warning_msg else "" + }) + + # Build DataFrames + spf_cols = [ + "position_2theta", "intensity", "sigma", "sigma_squared", "gamma", + "fwhm_gaussian", "fwhm_lorentzian", "fwhm_pseudovoigt", + "integral_breadth_gaussian", "integral_breadth_lorentzian", + "integral_breadth_pseudovoigt", "fwhm_gsas_verification", + "converged", "convergence_detail" + ] + spf_peaks_df = pd.DataFrame(peak_data, columns=spf_cols) + diag_df = pd.DataFrame(convergence_diagnostics) if convergence_diagnostics else pd.DataFrame( + columns=['peak_index', 'position_2theta', 'final_sigma_sq', 'final_gamma', 'status', 'notes'] + ) + + # Write single_peaks_report.txt (custom mixed-type formatting) + header_comment = ( + f"{converged_count} of {len(peak_list)} peaks converged; " + f"{aphysical_count} peaks have aphysical values (warnings)" + ) + header_cols = "\t".join(spf_cols) + peak_array = np.array(peak_data, dtype=object) + with open(output_dir / "single_peaks_report.txt", 'w', newline="\n") as f: + f.write(f"# {header_comment}\n") + f.write(f"{header_cols}\n") + for row in peak_array: + formatted_row = [] + for j, val in enumerate(row): + col_name = spf_cols[j] + if col_name == "converged": + formatted_row.append(str(val).lower()) + elif col_name == "convergence_detail": + formatted_row.append(str(val)) + else: + formatted_row.append("nan" if np.isnan(val) else f"{val:.8f}") + f.write("\t".join(formatted_row) + "\n") + + # Write diagnostics file if there are issues + if convergence_diagnostics: + diag_df.to_csv( + output_dir / "peak_convergence_diagnostics.txt", sep="\t", + float_format="%.8f", header=True, index=False, lineterminator="\n" + ) + if verbose: + print( + f"\nWarning: {len(convergence_diagnostics)} of {len(peak_list)} " + f"peaks have convergence issues" + ) + print(f" See {output_dir / 'peak_convergence_diagnostics.txt'} for details\n") + + return ( + {col: spf_peaks_df[col].tolist() for col in spf_peaks_df.columns}, + {col: diag_df[col].tolist() for col in diag_df.columns}, + ) + + +def _extract_phase_reports( + proj: Any, hist: Any, recipe: RecipeModel, param_dict: dict, output_dir: Path +) -> tuple[dict, dict]: + """Extract unit cell and peak list reports for all phases. + + Writes ``{phase}_unit_cell_report.csv`` and ``{phase}_peak_list_report.csv`` + for each phase. + + Args: + proj: GSAS-II project object after refinement. + hist: GSAS-II histogram object. + recipe: Validated RecipeModel (used to check if phases exist). + param_dict: Refined parameter dict from + ``extract_refined_params_from_project()`` (needed for cell ESDs). + output_dir: Directory to write CSV files. + + Returns: + ``(unit_cell_data, peak_list_data)`` — each is a + ``{phase_name: list-of-records}`` dict (JSON-serializable). + """ + unit_cell_data: dict = {} + peak_list_data: dict = {} + + if recipe.payload.phases is None or len(recipe.payload.phases) == 0: + return unit_cell_data, peak_list_data + + phase_names = [p.name for p in proj.phases() if p is not None] + + for phase_idx, phase_name in enumerate(phase_names): + try: + unit_cell = proj.data['Phases'][phase_name]['General']['Cell'][1:8] + except (KeyError, IndexError): + continue + + cell_params = ["cell_a", "cell_b", "cell_c", "cell_alpha", "cell_beta", "cell_gamma", "cell_volume"] + esds = calculate_cell_esds_from_A_matrix(phase_idx, proj, phase_name) + + # NOTE: .lst fallback for cell ESDs is disabled — preserved for Phase 2 reference. + # calculate_cell_esds_from_A_matrix raises RuntimeError on failure rather than + # returning [None]*7, so the fallback block below is unreachable. + # if all(esd is None for esd in esds): + # cell_param_keys = ['a', 'b', 'c', 'alpha', 'beta', 'gamma', 'volume'] + # esds = [param_dict.get(f"cell:{k}", {}).get("esd") for k in cell_param_keys] + + unit_cell_df = pd.DataFrame({ + "parameter": cell_params, + "value": unit_cell, + "esd": esds, + }) + unit_cell_df.to_csv( + output_dir / f"{phase_name}_unit_cell_report.csv", + float_format="%.8f", index=False, lineterminator="\n" + ) + unit_cell_data[phase_name] = json.loads(unit_cell_df.to_json(orient='records')) + + # Peak list for each phase + reflection_lists = proj.data.get(hist.name, {}).get('Reflection Lists', {}) + for phase_name in phase_names: + if phase_name not in reflection_lists: + continue + phase_ref = reflection_lists[phase_name] + if 'RefList' not in phase_ref: + continue + reflection_list = phase_ref['RefList'] + headers = [ + "h", "k", "l", "multiplicity", "d_spacing", "2theta", + "sigma_squared", "gamma", "F_obs_squared", "F_calc_squared", + "phase", "I_corr", "Prfo", "Trans", "ExtP" + ] + peak_list_df = pd.DataFrame(reflection_list, columns=headers) + peak_list_df.to_csv( + output_dir / f"{phase_name}_peak_list_report.csv", + float_format="%.8f", index=False, lineterminator="\n" + ) + peak_list_data[phase_name] = json.loads(peak_list_df.to_json(orient='records')) + + return unit_cell_data, peak_list_data + + +def _extract_refined_parameters( + param_dict: dict, output_dir: Path, proj: Any, verbose: bool +) -> list: + """Export refined parameters to CSV and return as list-of-records. + + Args: + param_dict: From ``extract_refined_params_from_project()``. + output_dir: Directory to write ``refined_parameters.csv``. + proj: GSAS-II project object (for phase/atom name mappings). + verbose: If True, print export status to stdout. + + Returns: + List of dicts (records) with the 9-column schema. Returns ``[]`` + when ``param_dict`` is empty (simulation mode, SPF, etc.). + """ + if not param_dict: + if verbose: + print(" No refined parameters found to export") + return [] + + try: + refined_params_csv = output_dir / "refined_parameters.csv" + refined_params_df = export_refined_parameters_csv( + param_dict, refined_params_csv, proj=proj + ) + if refined_params_df is not None: + if verbose: + print(f" Exported {len(param_dict)} refined parameters to {refined_params_csv.name}") + return refined_params_df.to_dict('records') + except Exception as e: + if verbose: + print(f" Warning: Failed to export refined parameters CSV: {e}") + return [] diff --git a/src/powderline/gateways/gsasii/helpers.py b/src/powderline/gateways/gsasii/helpers.py new file mode 100644 index 0000000..5eb37f6 --- /dev/null +++ b/src/powderline/gateways/gsasii/helpers.py @@ -0,0 +1,232 @@ +"""GSAS-II gateway — shared helpers, output naming and default constants. + +Moved verbatim from ``powderline/kicker.py`` (multi-engine refactor, re/01). +""" +from __future__ import annotations +import sys +import uuid +import yaml +import json +import argparse +import random as ran +import numpy as np +import pandas as pd +from typing import Any, Dict, List, Literal, Optional, Sequence, Union +from pathlib import Path +from pydantic import ValidationError +from GSASII import GSASIIscriptable as G2 # type: ignore +from GSASII import GSASIIlattice as G2lat +from GSASII import GSASIImapvars as G2mv +from GSASII import GSASIIobj as G2obj +from GSASII import GSASIIspc as G2spc +from GSASII import GSASIIElem as G2elem +from GSASII import GSASIIpwd as G2pwd +from powderline.schema import RecipeModel, RefinementControls +from powderline.gateways.gsasii.constraints import atom_refinement_plan, cell_refinement_plan +from powderline._status import CHECK, CROSS, INFO, WARN, emoji +from dataclasses import dataclass + + +# Standard naming (file-less, no sample_name) +@dataclass +class OutputNamingConfig: + """Standard naming for file-less refinements.""" + gpx_filename: str = "dummy.gpx" + histogram_name: str = "PWDR dummy" + lst_filename: str = "dummy.lst" # GSAS-II generates .lst with same basename as .gpx + +OUTPUT_NAMING = OutputNamingConfig() + +# TODO: In phase 2 move these defaults upstream for the recipe creation process. +# Further default parameters and values include refinement flags (False) +DEFAULT_HIST_SCALE_VAL = 1.0 +DEFAULT_HIST_SCALE_REFINE_FLAG = False +# TODO: Phase 2 upstream recipe builder — will be used when setting default peak broadening parameters +DEFAULT_PHASE_CRYSTALLITE_SIZE = 10 # isotropic crystallite size in microns +# TODO: Phase 2 upstream recipe builder — will be used when setting default peak broadening parameters +DEFAULT_PHASE_MICROSTRAIN = 0.0 # isotropic microstrain +DEFAULT_SPF_SIGMA_MIN = 0.0001 # Minimum sigma_sq value for single peak fitting (centidegrees) +DEFAULT_SPF_GAMMA_MIN = 0.0001 # Minimum gamma value for single peak fitting (centidegrees) + + +def unpack_refinement_parameter(param: list | None, param_name: str = "parameter") -> tuple[Any, Any, Any, Any]: + """ + Unpack refinement parameter from [value, refine_flag, min, max] format. + + This utility reduces boilerplate for the common pattern of unpacking refinement + parameters throughout the codebase. Use only in straightforward cases - complex + conditional logic should inline the unpacking for clarity. + + Args: + param: RefinementParameter list [value, refine_flag, min, max] or None + param_name: Name of parameter for error messages (optional) + + Returns: + Tuple of (value, refine_flag, min_val, max_val) + If param is None, returns (None, None, None, None) + + Raises: + ValueError: If param is neither list nor None + + Examples: + >>> value, refine_flag, min_val, max_val = unpack_refinement_parameter([1.0, True, None, None]) + >>> value, refine_flag, min_val, max_val = unpack_refinement_parameter(None) + """ + if param is None: + return (None, None, None, None) + elif isinstance(param, list): + if len(param) != 4: + raise ValueError( + f"{param_name} must be a list of exactly 4 elements " + f"[value, refine_flag, min, max], got {len(param)} elements" + ) + return tuple(param) + else: + raise ValueError( + f"{param_name} must be a list [value, refine_flag, min, max] or None, " + f"got {type(param).__name__}" + ) + + +def require_phase(error_suffix: str): + """ + Decorator to check phase existence in project before calling setter functions. + + Args: + error_suffix: The error message suffix (e.g., "Cannot set scale.") + + The decorated function must accept 'proj' as first positional arg and 'phase_name' + as a keyword or positional arg (position determined by inspection). + + Raises: + ValueError: If phase_name is not found in proj.phases() + """ + from functools import wraps + import inspect + + def decorator(func): + sig = inspect.signature(func) + # Decoration-time misuse check: decorated functions must take these args. + assert 'proj' in sig.parameters and 'phase_name' in sig.parameters + + @wraps(func) + def wrapper(*args, **kwargs): + # Find proj and phase_name from args/kwargs + try: + bound = sig.bind(*args, **kwargs) + except TypeError: + # Missing/extra arguments: call through so Python raises the + # function's native signature error, as the undecorated + # function would. + return func(*args, **kwargs) + bound.apply_defaults() + + proj = bound.arguments['proj'] + phase_name = bound.arguments['phase_name'] + + # Perform the phase existence check unconditionally — the original + # inline checks treated phase_name=None as a missing phase + # (ValueError) and proj=None as an AttributeError; both semantics + # are preserved by not special-casing None. + if phase_name not in [p.name for p in proj.phases()]: + raise ValueError(f"Phase '{phase_name}' not found in project. {error_suffix}") + + return func(*args, **kwargs) + return wrapper + return decorator + + +def calculate_peak_widths(sigma: float, gamma: float) -> tuple[float, float, float, float, float, float, bool, str | None]: + """ + Calculate FWHM and integral breadth values for Gaussian, Lorentzian, and pseudo-Voigt peak shapes. + + Parameters: + sigma: Squareroot of Gaussian width variance. No units assumed. + gamma: Lorentzian width parameter (HWHM). No units assumed. + + Returns: + Tuple of (fwhm_gaussian, fwhm_lorentzian, fwhm_pseudovoigt, + ib_gaussian, ib_lorentzian, ib_pseudovoigt, valid, warning_msg) + valid: True if calculation succeeded (even with aphysical values), False for NaN/inf + warning_msg: String describing any issues, or None if none + + NOTE: This functions differs from GSAS-II's internal getgamFW() which uses gamma as FWHM_L. + Conventionally, gamma is HWHM_L. This function uses gamma as HWHM_L for consistency with scipy, TOPAS, and literature. + """ + import warnings + warning_msg = None + + # FWHM for Gaussian component + fwhm_g = 2.0 * np.sqrt(2.0 * np.log(2.0)) * sigma # ≈ 2.35482 * sigma + + # FWHM for Lorentzian component - NOTE: GSAS-II uses gamma = FWHM_L, not gamma = HWHM_L. + fwhm_l = 2.0 * gamma + + # Pseudo-Voigt FWHM approximation (Thompson et al. 1987) + fwhm_pv = (fwhm_g**5 + 2.69269*fwhm_g**4*fwhm_l + 2.42843*fwhm_g**3*fwhm_l**2 + + 4.47163*fwhm_g**2*fwhm_l**3 + 0.07842*fwhm_g*fwhm_l**4 + fwhm_l**5)**(1/5) + + try: + gsas_fwhm = G2pwd.getgamFW(fwhm_l, sigma) # Call GSAS-II function - use FWHM_L (=gamma from SPF) and sigma + if abs(fwhm_pv - gsas_fwhm) > 0.01 * abs(gsas_fwhm): # >1% difference + msg = f"Calculated FWHM ({fwhm_pv:.6f}) differs from GSAS-II ({gsas_fwhm:.6f})" + warnings.warn(msg) + warning_msg = msg if warning_msg is None else f"{warning_msg}; {msg}" + except Exception as e: + # GSAS-II function may fail with negative values + msg = f"GSAS-II getgamFW() failed: {str(e)}" + warnings.warn(msg) + warning_msg = msg if warning_msg is None else f"{warning_msg}; {msg}" + + # Integral breadths + # For Gaussian: IB = FWHM * sqrt(π / (4 * ln(2))) ≈ FWHM * 1.0645 + ib_g = fwhm_g * np.sqrt(np.pi / (4.0 * np.log(2.0))) + + # For Lorentzian: IB = π * HWHM = π * gamma = (π/2) * FWHM + ib_l = np.pi * gamma # or equivalently: fwhm_l * np.pi / 2.0 + + # For pseudo-Voigt: approximate using convolution relationship + # IB_pV ≈ η * IB_L + (1-η) * IB_G, where η is mixing parameter + # Simplified approximation (may need refinement based on actual η calculation) + try: + eta = 1.36603 * (fwhm_l / fwhm_pv) - 0.47719 * (fwhm_l / fwhm_pv)**2 + 0.11116 * (fwhm_l / fwhm_pv)**3 + ib_pv = eta * ib_l + (1.0 - eta) * ib_g + except (ZeroDivisionError, RuntimeWarning): + ib_pv = np.nan + warning_msg = "Failed to calculate pseudo-Voigt integral breadth" if warning_msg is None else f"{warning_msg}; eta calculation failed" + + return fwhm_g, fwhm_l, fwhm_pv, ib_g, ib_l, ib_pv, True, warning_msg + + +def has_active_refinement_parameter(atom_param: dict) -> bool: + """ + Check if any refinement parameter has non-default values. + + Parameters: + atom_param : dict + Atom parameters dict with keys like 'x', 'y', 'z', 'occupancy', 'ADP', 'Uiso', 'Uaniso' + + Returns: + bool + True if any parameter should be set (not all [None, False, None, None]) + + Notes: + - Skips 'ADP' field (string, not refinement parameter) + - Handles 'Uaniso' nested dict separately + - Checks RefinementParameter lists for non-default values + """ + for key, value in atom_param.items(): + if key == 'ADP': + continue # Skip ADP type string (not a refinement parameter) + + if key == 'Uaniso' and isinstance(value, dict): + # Check nested Uaniso dict - any U value not [None, False, None, None]? + if any(v is not None and v != [None, False, None, None] for v in value.values()): + return True + + elif isinstance(value, list) and len(value) == 4: + # Check RefinementParameter list [value, refine_flag, min, max] + if value != [None, False, None, None]: + return True + + return False diff --git a/src/powderline/gateways/gsasii/project.py b/src/powderline/gateways/gsasii/project.py new file mode 100644 index 0000000..150b86b --- /dev/null +++ b/src/powderline/gateways/gsasii/project.py @@ -0,0 +1,561 @@ +"""GSAS-II gateway — GSAS-II project construction (histograms, phases). + +Moved verbatim from ``powderline/kicker.py`` (multi-engine refactor, re/01). +""" +from __future__ import annotations +import sys +import uuid +import yaml +import json +import argparse +import random as ran +import numpy as np +import pandas as pd +from typing import Any, Dict, List, Literal, Optional, Sequence, Union +from pathlib import Path +from pydantic import ValidationError +from GSASII import GSASIIscriptable as G2 # type: ignore +from GSASII import GSASIIlattice as G2lat +from GSASII import GSASIImapvars as G2mv +from GSASII import GSASIIobj as G2obj +from GSASII import GSASIIspc as G2spc +from GSASII import GSASIIElem as G2elem +from GSASII import GSASIIpwd as G2pwd +from powderline.schema import RecipeModel, RefinementControls +from powderline.gateways.gsasii.constraints import atom_refinement_plan, cell_refinement_plan +from powderline._status import CHECK, CROSS, INFO, WARN, emoji +from dataclasses import dataclass + + +# Functions to add histogram with instrument parameters from recipe.xrd_data (dict with arrays) and recipe.instrument.initialization (list of dicts) + +InstParmValue = Union[float, int, str, Sequence[Any]] +InstParmDict = Dict[str, InstParmValue] +G2InstParmDict = Dict[str, List[Any]] # values like [val, val, 0] + +def _to_gsasii_instparm_dict(flat: InstParmDict) -> G2InstParmDict: + """ + Convert a "flat" instrument parameter dictionary (values as scalars/strings) + into the GSAS-II scripting format where each value is a 3-item list: + + key: [value, value, refinement_flag] + + Examples (GSAS-II format): + "Type": ["PXC", "PXC", False] + "U": [2.0, 2.0, False] + + If the value already looks like a GSAS-II 3-item list/tuple, it is passed through. + + Notes + ----- + GSAS-II's scriptable examples show this 3-item-list structure for direct + instrument parameter specification. + """ + out: G2InstParmDict = {} + + for k, v in flat.items(): + # Already in GSAS-II form? + if isinstance(v, (list, tuple)) and len(v) == 3: + out[k] = list(v) + continue + + # Otherwise convert scalar/string -> [v, v, False] + out[k] = [v, v, False] + + # Ensure a few expected keys exist where possible + if "Bank" in out: + # normalize Bank to int-ish in the first two slots when possible + try: + b = int(float(out["Bank"][0])) + out["Bank"] = [b, b, out["Bank"][2]] + except Exception: + pass + + return out + + +def add_powder_histogram_from_arrays( + proj, + tth_array: Union[np.ndarray, Sequence[float]], + intensity_array: Union[np.ndarray, Sequence[float]], + intensity_weights_array: Union[np.ndarray, Sequence[float]], + histogram_name: str, + instrument_prm_dict: Dict[str, Any], + *, + comments: Optional[List[str]] = None, + phases: Union[None, str, Sequence[Any]] = None, +): + """ + Create a GSAS-II powder histogram inside an in-memory GSASIIscriptable project, + using arrays rather than reading a powder data file from disk. + + Parameters + ---------- + proj + A `GSASIIscriptable.G2Project` instance (e.g. created with `G2Project(newgpx='dummy')`). + + tth_array, intensity_array, intensity_weights_array + 1D arrays (same length) for 2θ (degrees), Iobs, and weights. + Weights are used directly in the histogram. + Default weighting (set in phase 2, the recipe creator) is 1 / sigma**2 where sigma is the uncertainty in the intensity (default is SQRT(Iobs)). + + histogram_name + Name to use for the histogram. If it does not start with "PWDR ", + the prefix is added. If the name collides with an existing histogram, + it is made unique using `G2obj.MakeUniqueLabel`. + TODO: catch non-unique names in phase2 (recipe creator) + + instrument_prm_dict + Instrument parameters. This can be either: + * a "flat" dict with scalars/strings (your current format), or + * a GSAS-II scripting-format dict where each value is a 3-item list + like `[val, val, False]`. + + This function will convert flat dicts into the GSAS-II scripting format. + + The histogram will store instrument parameters as `[Iparm1, Iparm2]`, + where Iparm2 is an empty dict (typical for CW lab/synchrotron usage). + + comments + Optional list of strings for the histogram "Comments" entry. Default is []. + + phases + Optional linking behavior, mirroring `add_powder_histogram`: + * None: do not link phases + * 'all': link all phases in the project + * sequence: link the listed phases (objects/names/rIds/etc) + + (Linking is not needed for your current test requirement, but it’s here + so the histogram is inserted in the same place in the project tree and + can be linked the same way.) + + Returns + ------- + hist + A `G2PwdrData` histogram wrapper object from `proj.histogram(histname)`. + + Implementation notes + -------------------- + This function intentionally mirrors the internal GSAS-II construction performed + in `GSASIIscriptable.load_pwd_from_reader` for the output histogram dictionary: + keys, `data` packing, defaults for background and peaks, and ID handling. + + Because this builds the same dict structure GSAS-II uses, the project is GUI-compatible + if later saved, and downstream GSAS-II operations (background fitting/refinement/etc.) + see the histogram in the expected format. + """ + # ---- Validate/normalize arrays + x = np.asarray(tth_array, dtype=float).ravel() + y = np.asarray(intensity_array, dtype=float).ravel() + w = np.asarray(intensity_weights_array, dtype=float).ravel() + + # GSAS-II powderdata commonly holds 6 arrays (obs, weights, calc, bkg, diff) + ycalc = np.zeros_like(y) + ybkg = np.zeros_like(y) + ydiff = np.zeros_like(y) + + powderdata = [x, y, w, ycalc, ybkg, ydiff] + + # ---- Instrument parameters: convert flat dict -> GSAS-II list-of-3 form if needed + Iparm1 = _to_gsasii_instparm_dict(instrument_prm_dict) + Iparm2: Dict[str, Any] = {} + + # Sanity: Type must be present and be list-like for GSAS-II-style indexing + if "Type" not in Iparm1 or not isinstance(Iparm1["Type"], list) or len(Iparm1["Type"]) < 1: + raise ValueError( + "instrument_prm_dict must define 'Type' (e.g. 'PXC'), " + "and after conversion it must be list-like (e.g. ['PXC','PXC', False])." + ) + + # TODO: in phase 2 (recipe creator), the full histname including 'PWDR' will be validated upstream. + # ---- Histogram naming: match GSAS-II convention + HistName = histogram_name.strip() + if not HistName.startswith("PWDR "): + HistName = "PWDR " + HistName + + # TODO: in phase 2 (recipe creator), a check for existing histogram names will be done. + # Make unique vs existing histogram names + existing = [h.name for h in proj.histograms()] # GSASIIscriptable method + HistName = G2obj.MakeUniqueLabel(HistName, existing) + + # ---- Mirror load_pwd_from_reader value packing and defaults + Ymin = float(np.min(y)) + Ymax = float(np.max(y)) + + # TODO: in phase 2 (recipe creator), the random ID generation will be done upstream using a schema check. + + valuesdict = { + "wtFactor": 1.0, + "Dummy": False, + "ranId": ran.randint(0, sys.maxsize), + "Offset": [0.0, 0.0], + "delOffset": 0.02 * Ymax, + "refOffset": -0.1 * Ymax, + "refDelt": 0.1 * Ymax, + "Yminmax": [Ymin, Ymax], + } + + Tmin = float(np.min(x)) + Tmax = float(np.max(x)) + Tmin1 = Tmin + + # Keep the small special-case from load_pwd_from_reader for NT data + try: + if "NT" in Iparm1["Type"][0] and G2lat.Pos2dsp(Iparm1, Tmin) < 0.4: + Tmin1 = float(G2lat.Dsp2pos(Iparm1, 0.4)) + except Exception: + # If Pos2dsp fails (unlikely for PXC), ignore + pass + + # TODO: in phase 2 (recipe creator), the default background will be set upstream using a schema check. + default_background = [ + ["chebyschev-1", False, 3, 1.0, 0.0, 0.0], + {"nDebye": 0, "debyeTerms": [], "nPeaks": 0, "peaksList": [], "background PWDR": ["", 1.0, False]}, + ] + + sample = G2obj.SetDefaultSample() + sample["ranId"] = valuesdict["ranId"] # matches load_pwd_from_reader behavior + # If Azimuth supplied in inst parms, copy into sample (nice-to-have consistency) + try: + if "Azimuth" in Iparm1 and isinstance(Iparm1["Azimuth"], list): + sample["Azimuth"] = float(Iparm1["Azimuth"][0]) + except Exception: + pass + + output_dict = { + "Reflection Lists": {}, + "Limits": [(Tmin, Tmax), [Tmin1, Tmax]], + "data": [valuesdict, powderdata, HistName], + "Index Peak List": [[], []], + "Comments": comments if comments is not None else [], + "Unit Cells List": [], + "Sample Parameters": sample, + "Peak List": {"peaks": [], "sigDict": {}}, + "Background": default_background, + "Instrument Parameters": [Iparm1, Iparm2], + } + + # Tree ordering list matches load_pwd_from_reader + section_names = [ + "Comments", + "Limits", + "Background", + "Instrument Parameters", + "Sample Parameters", + "Peak List", + "Index Peak List", + "Unit Cells List", + "Reflection Lists", + ] + new_names = [HistName] + section_names + + # ---- Insert into project in the same way add_powder_histogram does + if HistName in proj.data: + # keep behavior: redefine with a warning-like action + try: + import GSASIIfiles as G2fil + G2fil.G2Print("Warning - redefining histogram", HistName) + except Exception: + pass + + # proj.names is a list of "tree entries"; match add_powder_histogram insertion point + if proj.names and proj.names[-1][0] == "Phases": + proj.names.insert(-1, new_names) + else: + proj.names.append(new_names) + + proj.data[HistName] = output_dict + proj.update_ids() + + # Optional phase linking (mirrors add_powder_histogram flow) + if phases == "all": + phases = proj.phases() + if phases: + for ph in phases: + ph_obj = proj.phase(ph) + proj.link_histogram_phase(HistName, ph_obj) + + return proj.histogram(HistName) + +def add_phase_from_cif_dict(proj: Any, cif_data: Dict[str, Any], phase_name: str, histograms: Union[Sequence, str] = 'all') -> Any: + """ + Add a phase to a GSAS-II project from an embedded structure dictionary. + + This function creates a phase from an in-memory structure data dictionary + (file-less payload format) without reading from files. It creates a new phase entry + in the project, sets up the phase's general data (space group, unit_cell) and + atoms, and links the phase to specified histograms. + + Parameters + ---------- + proj : GSASIIscriptable.G2Project + The GSAS-II project object to which the phase will be added. + cif_data : dict + The structure dictionary containing phase structural information. + From the payload this dict is stowed in payload['phases'][phase]['structure'] + (e.g., payload['phases']['LaB6']['structure']). + phase_name : str + Name for the new phase. Top level key for a phase in payload['phases'], + or within payload['phases'][phase]['structure']['phase_name'] from payload. + histograms : list or 'all', optional + Which histograms to associate with this phase. Can be: + - 'all' (default): link to all powder histograms in the project. + - a list of histogram identifiers (names, objects, or indices). + - None or empty list for no links. + + Returns + ------- + phase_obj : GSASIIscriptable.G2Phase + The newly created phase object (GSAS-II scriptable phase wrapper). + + Raises + ------ + ValueError + If the space group in cif_data is invalid or cannot be interpreted. + + Notes + ----- + The function generates a new phase dictionary using GSASIIobj.SetNewPhase with + the provided space group and unit_cell parameters. Atomic coordinates and + occupancies from cif_data are inserted into the phase's atom list. Anisotropic + displacement parameters, if present, are fully supported. + + By default, the phase will be linked to all existing powder histograms in the + project. You can specify a subset of histograms by name, index, or object, or + pass an empty list/None to link none. + """ + pname = phase_name if phase_name else cif_data.get("name", "New Phase") + # Ensure phase name is unique in project + # TODO: handle phase name collisions more gracefully upstream in validation + existing_names = [p.name for p in proj.phases()] + pname = G2obj.MakeUniqueLabel(pname, existing_names) + + # Interpret space group symbol into SGData + sg = cif_data.get("space_group", "P 1") + err, SGData = G2spc.SpcGroup(sg) + + # Attempt normalization if initial interpretation failed + normalized_sg = sg + if err and sg: + normalized_sg = G2spc.StandardizeSpcName(sg) + if normalized_sg and normalized_sg != sg: + err, SGData = G2spc.SpcGroup(normalized_sg) + + # Handle space group interpretation errors + if err: + error_msg = G2spc.SGErrors(err) + raise ValueError( + f"Space group '{sg}' could not be interpreted.\n" + f"Error: {error_msg}\n" + f"Attempted normalization: '{normalized_sg}'\n" + f"\nCommon issues:\n" + f" • Missing spaces in Hermann-Mauguin notation (e.g., use 'R 3 m' not 'R3m')\n" + f" • Ambiguous rhombohedral symbols (R-3m normalizes to R-3c rhombohedral)\n" + f" • Check structure dict space_group entry matches the crystal structure\n" + ) + + # Create a new phase data structure (similar to reading from file): + phase_data = G2obj.SetNewPhase(Name=pname, SGData=SGData) + phase_data['General']['Name'] = pname + + # Document any space group normalization that occurred (silently - verbose mode not available here) + # if normalized_sg != sg: + # print(f"ℹ️ Space group normalization: '{sg}' → '{normalized_sg}'") + + # Set unit cell parameters if available + unit_cell = cif_data.get("unit_cell", {}) + if unit_cell: + unit_cell_constants = [unit_cell.get("a"), unit_cell.get("b"), unit_cell.get("c"), unit_cell.get("alpha"), unit_cell.get("beta"), unit_cell.get("gamma")] + if len(unit_cell_constants) == 6 and None not in unit_cell_constants: + phase_data['General']['Cell'][1:7] = unit_cell_constants # insert a,b,c,alpha,beta,gamma + try: + # Recalculate volume for consistency + phase_data['General']['Cell'][7] = G2lat.calc_V(G2lat.cell2A(tuple(unit_cell_constants))) + except Exception as e: + raise RuntimeError( + f"Unit cell volume calculation failed for phase '{pname}'. " + f"Cell parameters: {unit_cell_constants}. " + f"Original error: {e}" + ) from e + + # Add atoms from cif_data into phase_data['Atoms'] + # TODO: review handling of site_sym, multiplicity, and ADPS. + # The current approach expects minimal info in cif_data, but we are now populating this with the complete info needed. + # For example, cif_data['atoms'] stows info as shown below, where label is the key for each atom entry.: + # atoms[label] = { + # "element": element, + # "Multiplicity": mult, + # "x": x, "y": y, "z": z, + # "occupancy": occ, + # "ADP": ADP, + # "Uiso": Uiso_val + # } + # # Add Uij if anisotropic and data available + # if ADP == "Uani" and label in aniso_data: + # atoms[label]["Uij"] = aniso_data[label] + # TODO: in phase 2, assembly of atom_record using GSAS-II helpers will done upstream using "parse_cif_to_dict" function. + # This code will need to be update accordingly and use "get" with defaults for missing values. E.g., don't interpret site sym or mult. + + for label, atom in cif_data.get("atoms", {}).items(): + x = float(atom.get("x", 0.0)) + y = float(atom.get("y", 0.0)) + z = float(atom.get("z", 0.0)) + occ = float(atom.get("occupancy", 1.0)) + + # Get ADP type for this atom (required in schema 0.22) + adp_type = atom.get("ADP", None) + if adp_type is None: + raise ValueError( + f"Atom '{label}' in phase '{pname}' is missing required 'ADP' field. " + f"Schema 0.22 requires explicit ADP specification ('Uiso' or 'Uaniso') for all atoms." + ) + + # Prepare atom record list (based on GSAS-II internal format): + atom_record = ["", "", "", 0.0, 0.0, 0.0, 1.0, "", 0.0, "I", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + atom_record[0] = label + atom_record[1] = atom.get("element", label.rstrip('0123456789') or "X") + atom_record[2] = "" # refinement flags placeholder (left blank) + atom_record[3] = x + atom_record[4] = y + atom_record[5] = z + atom_record[6] = occ + # Determine site symmetry and multiplicity for this atom in the given SG + site_sym, mult = "", 1 + try: + site_sym, mult = G2spc.SytSym([x, y, z], SGData)[0:2] + except Exception: + pass + atom_record[7] = site_sym if site_sym is not None else "" + atom_record[8] = mult if mult is not None else 1 + + # Set displacement parameters (isotropic or anisotropic) + if adp_type == "Uaniso": + # Anisotropic displacement parameters + atom_record[9] = "A" + + # Get Uaniso dict (supports both "Uij" old name and "Uaniso" new name) + uaniso_dict = atom.get("Uaniso") or atom.get("Uij") + + if uaniso_dict: + # Validate all 6 anisotropic values are present + required_keys = ["U11", "U22", "U33", "U12", "U13", "U23"] + missing_keys = [k for k in required_keys if k not in uaniso_dict or uaniso_dict[k] is None] + if missing_keys: + raise ValueError( + f"Atom '{label}' marked as anisotropic (ADP='Uaniso') but missing required U values: {missing_keys}. " + f"All 6 anisotropic parameters (U11, U22, U33, U12, U13, U23) must be provided." + ) + + # Populate U11, U22, U33, U12, U13, U23 (indices 11-16) + atom_record[11] = float(uaniso_dict["U11"]) + atom_record[12] = float(uaniso_dict["U22"]) + atom_record[13] = float(uaniso_dict["U33"]) + atom_record[14] = float(uaniso_dict["U12"]) + atom_record[15] = float(uaniso_dict["U13"]) + atom_record[16] = float(uaniso_dict["U23"]) + + # Set atom_record[10] to Uiso if provided, else calculate from diagonal elements + if atom.get("Uiso") is not None: + atom_record[10] = float(atom["Uiso"]) + else: + # Calculate equivalent isotropic value from diagonal elements + atom_record[10] = (atom_record[11] + atom_record[12] + atom_record[13]) / 3.0 + else: + raise ValueError( + f"Atom '{label}' marked as anisotropic (ADP='Uaniso') but no Uaniso dict found. " + f"Provide 'Uaniso' dict with U11, U22, U33, U12, U13, U23 values." + ) + else: + # Isotropic displacement parameters + atom_record[9] = "I" + uiso = atom.get("Uiso") + if uiso is not None: + atom_record[10] = float(uiso) + else: + atom_record[10] = 0.0 + atom_record[11:17] = [0.0]*6 # six anisotropic Uij (zeros since not used here) + + # Append a random unique ID for the atom + atom_record.append(ran.randint(0, sys.maxsize)) + phase_data['Atoms'].append(atom_record) + + # Insert the new phase into project data structure + if 'Phases' not in proj.data: + proj.data['Phases'] = {'data': None} + assert pname not in proj.data['Phases'], "Phase name collision despite uniqueness check" + proj.data['Phases'][pname] = phase_data + # Update the project tree name list for phases + for entry in proj.names: + if entry[0] == 'Phases': + entry.append(pname); break + else: + proj.names.append(['Phases', pname]) + + # Initialize phase general data (e.g. set default atom form factors): + try: + G2elem.SetupGeneral(phase_data, None) + except ValueError as err: + raise ValueError(f"Error in phase initialization: {err}") + + # Link phase to specified histograms + hist_list = [] + if histograms == 'all': + hist_list = [h.name for h in proj.histograms()] + elif histograms: + for h in histograms: + if hasattr(h, 'name'): + hist_list.append(h.name) + elif isinstance(h, str): + hist_list.append(h) + elif isinstance(h, int): + try: + hist_list.append(proj.histogram(h).name) + except Exception: + continue + for hist_name in hist_list: + try: + proj.link_histogram_phase(hist_name, pname) + except Exception as e: + print(f"Warning: could not link phase to histogram '{hist_name}': {e}") + + # Refresh internal IDs and return the new phase object + proj.index_ids() + proj.update_ids() + return proj.phase(pname) + +# Add all phases from phases dict (file-less approach) +def add_phases_from_dict(proj: Any, hist: Any, phases_dict: dict, print_info: bool = False) -> None: + """ + Add phases to the GSAS-II project from a phases dictionary. + + Parameters: + proj : GSAS-II project object + The GSAS-II project to add phases to. + hist : GSAS-II histogram object + The histogram to associate with the phases. + phases_dict : dict + Dictionary containing phase information. (e.g., payload['phases']) + print_info : bool + Whether to print information about the added phases. + + Returns: + None + """ + + for phase_name, phase_info in phases_dict.items(): + structure_info = phase_info.get('structure', {}) + + # Validation check (TODO: move this upstream in phase2) + if phase_name != structure_info.get('phase_name'): + raise NameError(f"Phase name mismatch for '{phase_name}'. Structure info name is '{structure_info.get('phase_name')}'.") + + # Prevent duplicate phase names - TODO: handle upstream in schema validation / recipe maker + if phase_name in [p.name for p in proj.phases()]: + raise ValueError(f"Phase '{phase_name}' already exists in project.") + + try: + add_phase_from_cif_dict(proj=proj, cif_data=structure_info, phase_name=phase_name, histograms=[hist]) + except Exception as e: + raise RuntimeError(f"Failed to add phase '{phase_name}': {e}") from e + if print_info: + print("\nPhases in proj: ", *[ph.name for ph in proj.phases()], sep='\n\t') diff --git a/src/powderline/gateways/gsasii/server.py b/src/powderline/gateways/gsasii/server.py new file mode 100644 index 0000000..72cd717 --- /dev/null +++ b/src/powderline/gateways/gsasii/server.py @@ -0,0 +1,518 @@ +"""GSAS-II persistent server for fast simulations. + +This server keeps GSAS-II loaded in memory to eliminate startup overhead. +Listens on an HTTP port via FastAPI and processes simulation requests sequentially. + +Security notes: + - The server binds exclusively to ``127.0.0.1`` (loopback). It is not + accessible from remote hosts and requires no authentication by design. + - No rate limiting is applied. For a shared or multi-user environment, + add rate limiting via a reverse proxy or a middleware library such as + ``slowapi`` before exposing this server to untrusted callers. + - ``output_dir`` paths are sent by the client and used as-is; path + traversal is only exploitable by a local user who already has file-system + access equivalent to the server process. + - The server resolves ``output_dir`` in ITS OWN filesystem view. A client + on another node — or a server started inside a sandbox/container with a + private /tmp — will never see the output files even though the run + succeeds. ``GSASClient._server_output_visible`` guards clients against + this and falls back to in-process execution. + +Performance: +- First simulation: ~12s (server startup + GSAS-II import) +- Subsequent simulations: ~2-3s each (no startup overhead) +- 4-6x speedup for batch operations + +Usage: + # Start server (daemon mode) + pixi run gsas-server start + + # Stop server + pixi run gsas-server stop + + # Check status + pixi run gsas-server status + + # View logs + tail -f /tmp/powderline_gsas_server.log + + # Restart server + pixi run gsas-server restart +""" + +import json +import sys +import os +import signal +import time +import subprocess +import logging +from pathlib import Path +from typing import Dict, Any, Optional, List +import tempfile +import atexit +from datetime import datetime + +from pydantic import BaseModel + +# Server configuration +HOST = "127.0.0.1" +DEFAULT_PORT = 19471 +PORT = int(os.environ.get('POWDERLINE_SERVER_PORT', DEFAULT_PORT)) +PORT_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.port' +PID_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.pid' +LOG_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.log' + + +# --- Pydantic request/response models --- + +class SimulationRequest(BaseModel): + recipe_data: dict + output_dir: str + verbose: bool = False + + +class SimulationResponse(BaseModel): + success: bool + run_id: Optional[str] = None + rwp: Optional[float] = None + elapsed_time: Optional[float] = None + method: Optional[str] = None + error: Optional[str] = None + traceback: Optional[str] = None + output_files: Optional[List[str]] = None + fit_profile: Optional[dict] = None + unit_cell_data: Optional[dict] = None + peak_list_data: Optional[dict] = None + refined_parameters: Optional[list] = None + spf_peaks: Optional[dict] = None + spf_convergence_diagnostics: Optional[dict] = None + + +# --- Logging --- + +def setup_logging(log_file: Path) -> logging.Logger: + """Set up logging to both console and file.""" + logger = logging.getLogger('powderline.server') + logger.setLevel(logging.DEBUG) + + # File handler (always log everything) + file_handler = logging.FileHandler(log_file, mode='a') + file_handler.setLevel(logging.DEBUG) + + # Console handler (info level for cleaner output) + console_handler = logging.StreamHandler() + console_handler.setLevel(logging.INFO) + + # Formatter with timestamps + formatter = logging.Formatter( + '%(asctime)s - %(levelname)s - %(message)s', + datefmt='%Y-%m-%d %H:%M:%S' + ) + file_handler.setFormatter(formatter) + console_handler.setFormatter(formatter) + + logger.addHandler(file_handler) + logger.addHandler(console_handler) + + return logger + + +# --- Server class --- + +class GSASServer: + """Persistent GSAS-II server for fast simulations.""" + + def __init__(self, logger: logging.Logger = None): + """Initialize server (GSAS-II import happens here). + + Args: + logger: Optional logger instance. If not provided, one will be created. + """ + self.running = False + self.request_count = 0 + self.start_time = None + + # Set up logging + self.logger = logger or setup_logging(LOG_FILE) + + # Import GSAS-II (this is the slow part we want to do once) + self.logger.info("Loading GSAS-II libraries...") + import_start = time.time() + + # Set PYTHONPATH to include src directory + src_dir = Path(__file__).parent.parent + if str(src_dir) not in sys.path: + sys.path.insert(0, str(src_dir)) + + try: + # Import kicker module which has all the GSAS-II integration + from powderline import kicker + self.kicker = kicker + import_time = time.time() - import_start + self.logger.info(f"GSAS-II loaded in {import_time:.1f}s") + except ImportError as e: + self.logger.error(f"Failed to import GSAS-II: {e}") + sys.exit(1) + + def create_app(self): + """Build and return the FastAPI application.""" + from fastapi import FastAPI + + app = FastAPI(title="PowderLine GSAS-II Server") + server = self # capture for closures + + @app.post("/simulate", response_model=SimulationResponse) + def simulate(req: SimulationRequest): + server.request_count += 1 + schema_name = req.recipe_data.get('schema_name', 'unknown') if isinstance(req.recipe_data, dict) else 'unknown' + server.logger.info(f"Request #{server.request_count}: schema={schema_name}") + + result = server._run_simulation(req.model_dump()) + + elapsed = result.get('elapsed_time', 0) + run_id = result.get('run_id', 'n/a') + if result.get('success'): + server.logger.info(f"Request #{server.request_count} (run_id={run_id}) completed in {elapsed:.1f}s") + else: + server.logger.warning( + f"Request #{server.request_count} (run_id={run_id}) failed: {result.get('error', 'Unknown error')}" + ) + if result.get('traceback'): + server.logger.debug( + f"Request #{server.request_count} traceback:\n{result['traceback']}" + ) + return SimulationResponse(**result) + + @app.get("/health") + def health(): + uptime = (datetime.now() - server.start_time).total_seconds() if server.start_time else 0 + return { + "status": "ok", + "pid": os.getpid(), + "uptime_seconds": uptime, + "request_count": server.request_count, + } + + return app + + def start(self): + """Start the server with uvicorn.""" + import uvicorn + + self.start_time = datetime.now() + self.logger.info("=" * 60) + self.logger.info("GSAS-II Server Starting") + self.logger.info("=" * 60) + + # Write PID and port files + PID_FILE.write_text(str(os.getpid())) + PORT_FILE.write_text(str(PORT)) + + # Register cleanup + atexit.register(self.cleanup) + signal.signal(signal.SIGTERM, self._signal_handler) + signal.signal(signal.SIGINT, self._signal_handler) + + self.running = True + self.logger.info(f"GSAS-II server started") + self.logger.info(f" URL: http://{HOST}:{PORT}") + self.logger.info(f" Log file: {LOG_FILE}") + self.logger.info(f" PID: {os.getpid()}") + self.logger.info(f" Started: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}") + self.logger.info(f" Listening for simulation requests...") + self.logger.info("-" * 60) + + app = self.create_app() + uvicorn.run(app, host=HOST, port=PORT, log_level="warning") + + def _run_simulation(self, request: Dict[str, Any]) -> Dict[str, Any]: + """Run a GSAS-II simulation using the loaded kicker module. + + Args: + request: Dictionary with 'recipe_data' (inline recipe dict), 'output_dir', + and optional 'verbose' + + Returns: + Dictionary with keys: 'success', 'run_id', 'rwp', 'elapsed_time', + 'method', 'output_files', 'fit_profile' (dict), 'unit_cell_data' (dict), + 'peak_list_data' (dict), 'refined_parameters' (list), 'spf_peaks' (dict), + 'spf_convergence_diagnostics' (dict), and optional 'error', 'traceback'. + """ + from powderline.kicker import run_refinement + from powderline.schema import RecipeModel + from pydantic import ValidationError + + recipe_dict = request.get('recipe_data') + output_dir = Path(request['output_dir']) + verbose = request.get('verbose', False) + + if recipe_dict is None: + return { + 'success': False, + 'error': 'Missing recipe_data in request', + 'method': 'server' + } + + output_dir.mkdir(parents=True, exist_ok=True) + + # Validate recipe + try: + recipe = RecipeModel.model_validate(recipe_dict) + except ValidationError as e: + error_lines = [f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" + for err in e.errors()] + return { + 'success': False, + 'error': f"Recipe validation failed:\n" + "\n".join(error_lines), + 'method': 'server' + } + except Exception as e: + return { + 'success': False, + 'error': f"Failed to parse recipe: {str(e)}", + 'method': 'server' + } + + # Run refinement directly using loaded GSAS-II libraries + result = run_refinement(recipe, output_dir, verbose=verbose, method='server') + + return result + + def _signal_handler(self, signum, frame): + """Handle shutdown signals.""" + self.logger.info(f"Received signal {signum}, shutting down...") + self.running = False + self.cleanup() + sys.exit(0) + + def cleanup(self): + """Clean up port file and PID file.""" + if PORT_FILE.exists(): + PORT_FILE.unlink() + if PID_FILE.exists(): + PID_FILE.unlink() + + if self.start_time: + uptime = datetime.now() - self.start_time + self.logger.info(f"Server stopped") + self.logger.info(f" Total requests: {self.request_count}") + self.logger.info(f" Uptime: {uptime}") + self.logger.info("=" * 60) + + +def _pid_alive(pid: int) -> bool: + """Return True if a process with ``pid`` exists (cross-platform). + + ``os.kill(pid, 0)`` is a valid liveness probe on POSIX but not on Windows, + where ``os.kill`` terminates the target (or raises) rather than checking it; + use the Win32 API there instead. + """ + if os.name == "nt": + import ctypes + from ctypes import wintypes + + PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 + STILL_ACTIVE = 259 + kernel32 = ctypes.windll.kernel32 + handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid) + if not handle: + return False + try: + code = wintypes.DWORD() + if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)): + return False + return code.value == STILL_ACTIVE + finally: + kernel32.CloseHandle(handle) + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +def is_server_running() -> bool: + """Check if server is currently running.""" + if not PID_FILE.exists(): + return False + + try: + pid = int(PID_FILE.read_text()) + except ValueError: + PID_FILE.unlink() + return False + + if _pid_alive(pid): + return True + # PID file exists but the process does not + PID_FILE.unlink() + return False + + +def stop_server() -> bool: + """Stop the running server.""" + if not is_server_running(): + print("Server is not running") + return False + + pid = int(PID_FILE.read_text()) + print(f"Stopping server (PID {pid})...") + + try: + os.kill(pid, signal.SIGTERM) + + # Wait for graceful shutdown + for _ in range(50): # 5 seconds timeout + time.sleep(0.1) + if not is_server_running(): + print("Server stopped") + return True + + # Force kill if still running. SIGKILL does not exist on Windows; + # there os.kill(pid, SIGTERM) maps to TerminateProcess (a hard kill), + # which is the correct escalation. + print("Forcing shutdown...") + force_signal = getattr(signal, "SIGKILL", signal.SIGTERM) + os.kill(pid, force_signal) + time.sleep(0.5) + + if not is_server_running(): + print("Server stopped (forced)") + return True + else: + print("Failed to stop server") + return False + + except ProcessLookupError: + print("Server process not found") + PID_FILE.unlink() + return False + + +def get_server_info() -> Optional[Dict[str, Any]]: + """Get information about the running server. + + Returns: + Dictionary with server info (pid, url, log_file, uptime) or None if not running + """ + if not is_server_running(): + return None + + try: + pid = int(PID_FILE.read_text()) + port = int(PORT_FILE.read_text()) if PORT_FILE.exists() else PORT + + # Try to get process info + import psutil + proc = psutil.Process(pid) + uptime = datetime.now() - datetime.fromtimestamp(proc.create_time()) + + return { + 'pid': pid, + 'url': f"http://{HOST}:{port}", + 'log_file': str(LOG_FILE), + 'uptime': str(uptime).split('.')[0], # Remove microseconds + 'cpu_percent': proc.cpu_percent(interval=0.1), + 'memory_mb': proc.memory_info().rss / 1024 / 1024, + } + except Exception: + # psutil not available, return basic info + port = int(PORT_FILE.read_text()) if PORT_FILE.exists() else PORT + return { + 'pid': pid, + 'url': f"http://{HOST}:{port}", + 'log_file': str(LOG_FILE), + } + + +def main(): + """Main entry point for server management.""" + import argparse + + parser = argparse.ArgumentParser(description="GSAS-II persistent server") + subparsers = parser.add_subparsers(dest='action', help='Server action') + + subparsers.add_parser('start', help='Start the server') + subparsers.add_parser('stop', help='Stop the server') + subparsers.add_parser('status', help='Show server status') + subparsers.add_parser('restart', help='Restart the server') + subparsers.add_parser('logs', help='Show recent server logs') + + args = parser.parse_args() + action = args.action or 'status' # Default to status if no action + + if action == 'start': + if is_server_running(): + print("Server is already running") + print(f" PID: {PID_FILE.read_text()}") + port = int(PORT_FILE.read_text()) if PORT_FILE.exists() else PORT + print(f" URL: http://{HOST}:{port}") + print(f"\n To view logs: tail -f {LOG_FILE}") + sys.exit(1) + + print("Starting GSAS-II server...") + logger = setup_logging(LOG_FILE) + server = GSASServer(logger) + server.start() + + elif action == 'stop': + stop_server() + + elif action == 'status': + info = get_server_info() + if info: + print(f"Server is running") + print(f" PID: {info['pid']}") + print(f" URL: {info['url']}") + print(f" Log file: {info['log_file']}") + if 'uptime' in info: + print(f" Uptime: {info['uptime']}") + if 'cpu_percent' in info: + print(f" CPU: {info['cpu_percent']:.1f}%") + if 'memory_mb' in info: + print(f" Memory: {info['memory_mb']:.1f} MB") + print(f"\n To view logs: tail -f {info['log_file']}") + else: + print("Server is not running") + print(f"\n To start: pixi run gsas-server start") + print(f" Log file: {LOG_FILE}") + sys.exit(1) + + elif action == 'restart': + if is_server_running(): + stop_server() + time.sleep(1) + + print("Starting GSAS-II server...") + logger = setup_logging(LOG_FILE) + server = GSASServer(logger) + server.start() + + elif action == 'logs': + if not LOG_FILE.exists(): + print(f"Log file not created yet: {LOG_FILE}") + sys.exit(0) + + print(f"Recent logs from {LOG_FILE}:") + print(" (showing last 50 lines)") + print("-" * 60) + + try: + # Show last 50 lines + with open(LOG_FILE, 'r') as f: + lines = f.readlines() + for line in lines[-50:]: + print(line.rstrip()) + except Exception as e: + print(f"Failed to read log file: {e}") + sys.exit(1) + + print("-" * 60) + print(f" To follow logs in real-time: tail -f {LOG_FILE}") + + +if __name__ == '__main__': + main() diff --git a/src/powderline/gateways/gsasii/setters.py b/src/powderline/gateways/gsasii/setters.py new file mode 100644 index 0000000..d88f33e --- /dev/null +++ b/src/powderline/gateways/gsasii/setters.py @@ -0,0 +1,1213 @@ +"""GSAS-II gateway — refinement-parameter setters. + +Moved verbatim from ``powderline/kicker.py`` (multi-engine refactor, re/01). +""" +from __future__ import annotations +import sys +import uuid +import yaml +import json +import argparse +import random as ran +import numpy as np +import pandas as pd +from typing import Any, Dict, List, Literal, Optional, Sequence, Union +from pathlib import Path +from pydantic import ValidationError +from GSASII import GSASIIscriptable as G2 # type: ignore +from GSASII import GSASIIlattice as G2lat +from GSASII import GSASIImapvars as G2mv +from GSASII import GSASIIobj as G2obj +from GSASII import GSASIIspc as G2spc +from GSASII import GSASIIElem as G2elem +from GSASII import GSASIIpwd as G2pwd +from powderline.schema import RecipeModel, RefinementControls +from powderline.gateways.gsasii.constraints import atom_refinement_plan, cell_refinement_plan +from powderline._status import CHECK, CROSS, INFO, WARN, emoji +from dataclasses import dataclass + +from powderline.gateways.gsasii.helpers import ( + has_active_refinement_parameter, + require_phase, + unpack_refinement_parameter, +) + + + +# By default (G2obj.SetSampleDefault() called when adding histogram) histogram scale set to refine +def set_hist_scale(proj: Any, hist: Any, hist_scale_val: float = 1.0, hist_scale_refine_flag: bool = False, print_info: bool = False) -> None: + """Set histogram scale and refine flag.""" + proj.data[hist.name]['Sample Parameters']['Scale'] = [hist_scale_val, hist_scale_refine_flag] + if print_info: + print(f"Set histogram scale to {hist_scale_val} with refine flag {hist_scale_refine_flag} for histogram {hist.name}") + + +def set_fit_range_hist(hist: Any, fit_range: tuple[float | None, float | None], print_info: bool = False) -> None: + """Set fit range for histogram in GSAS-II project.""" + min_val, max_val = fit_range + old_limits = hist.data['Limits'][1].copy() # this is a view on the object, need to save old limits before changing + if min_val is not None: + hist.data['Limits'][1][0] = min_val + if max_val is not None: + hist.data['Limits'][1][1] = max_val + if print_info: + print('Updated fit limits in hist from ', old_limits, 'to', hist.data['Limits'][1]) + + +def set_chebyshev_background(proj: Any, hist: Any, chebyshev_dict: dict, print_info: bool = False) -> None: + """ + Set the Chebyshev background for a given histogram. + + Chebyshev polynomials provide smooth curved backgrounds. Coefficients start + at 0th order (constant term) and increase: [c0, c1, c2, ...] represents + c0 + c1*T1(x) + c2*T2(x) + ... where Tn are Chebyshev polynomials. + + The function manipulates proj.data[hist.name]['Background'][0] which has structure: + [background_type, refine_flag, num_coefficients, c0, c1, c2, ...] + + Parameters: + proj: GSAS-II project object containing the histogram + hist: Histogram object to set the background for + chebyshev_dict: Dictionary containing Chebyshev background parameters: + - num_coefficients (int): Number of Chebyshev coefficients + - coefficients (list[float]): Coefficient values [c0, c1, c2, ...] + - refine_flag (bool): Whether to refine background during fitting + print_info: If True, print background configuration to stdout + + Returns: + None + + Raises: + ValueError: If number of coefficients doesn't match list length or + required background entries are missing + + Examples: + >>> chebyshev_dict = { + ... 'num_coefficients': 3, + ... 'coefficients': [100.0, -50.0, 10.0], + ... 'refine_flag': True + ... } + >>> set_chebyshev_background(proj, hist, chebyshev_dict) + """ + # First parse the chebyshev_dict + num_coefficients = chebyshev_dict.get('num_coefficients') + coefficients = chebyshev_dict.get('coefficients') + refine_flag = chebyshev_dict.get('refine_flag') + + # Defaults are not provided because those will be provided upstream + # None will be caught in validation and trigger a default assignment. + # The code below is an example of how to handle defaults here if needed. + + # This should be enforced with the pydantic schema when loading the recipe + if coefficients is None: + coefficients = [0.0] * num_coefficients + + if num_coefficients != len(coefficients): + raise ValueError( + "Number of coefficients does not match the length of the coefficients list." + ) + + chebyshev_bkg = proj.data[hist.name]['Background'][0] + + # Check for default entries (type, refine flag, num coefficients) + if len(chebyshev_bkg) < 3: + raise ValueError("Chebyshev background list missing required entries. type, refine flag, num coefficients should be present by default.") + + # Set number of coefficients + chebyshev_bkg[2] = num_coefficients + + # Pad or truncate the coefficients list in chebyshev_bkg to match num_coefficients + # This would be done in an earlier validation step! + needed_len = num_coefficients + 3 + if len(chebyshev_bkg) < needed_len: + chebyshev_bkg.extend([0.0] * (needed_len - len(chebyshev_bkg))) + elif len(chebyshev_bkg) > needed_len: + del chebyshev_bkg[needed_len:] # in-place truncate + + # Set coefficients + for i, coeff in enumerate(coefficients): + chebyshev_bkg[i + 3] = coeff + + # Set refine flag + chebyshev_bkg[1] = refine_flag + + if print_info: + print(f"Chebyshev background set with {chebyshev_bkg[2]} coeffiencients, refine_flag={chebyshev_bkg[1]}") + print(f"Coefficients: {chebyshev_bkg[3:3+chebyshev_bkg[2]]}") + + +# function to set single peak background +# this should be a rather exposed function +# e.g., take lists of positions, intensities, sigmas, gammas, refine flags, etc. +# This function should expect inputs from the background_dict['single_peaks'] structure + +def set_single_peak_background(proj: Any, hist: Any, bkg_single_peaks_dict: dict, print_info: bool = False) -> None: + """ + Set single peak background for histogram using pseudo-Voigt profiles. + + Single peaks are useful for modeling known impurity peaks or other non-background + features that shouldn't be included in the main phase refinement. Each peak is + described by a pseudo-Voigt profile (weighted sum of Gaussian and Lorentzian). + + Peak profile: I(2θ) = intensity * [η*L(2θ) + (1-η)*G(2θ)] + where: + - G(2θ) is Gaussian with width sigma + - L(2θ) is Lorentzian with width gamma + - η (eta) is mixing parameter (0=pure Gaussian, 1=pure Lorentzian) + + Args: + proj: GSAS-II project object + hist: Histogram object to set single peaks for + bkg_single_peaks_dict: Dictionary with keys: + - positions: List of [[2θ, refine, min, max], ...] for peak positions + - intensities: List of [[I, refine, min, max], ...] for peak heights + - pv_gaussian_sigma: List of [[σ, refine, min, max], ...] for Gaussian widths + - pv_lorentzian_gamma: List of [[γ, refine, min, max], ...] for Lorentzian widths + All lists must have same length (number of peaks) + print_info: If True, print peak configuration to stdout + + Returns: + None + + Raises: + ValueError: If parameter lists have inconsistent lengths + + Examples: + >>> # Two single peaks at 2θ=35.5° and 42.0° + >>> single_peaks = { + ... 'positions': [[35.5, False, None, None], [42.0, False, None, None]], + ... 'intensities': [[50.0, True, None, None], [30.0, True, None, None]], + ... 'pv_gaussian_sigma': [[0.1, False, None, None], [0.1, False, None, None]], + ... 'pv_lorentzian_gamma': [[0.05, False, None, None], [0.05, False, None, None]] + ... } + >>> set_single_peak_background(proj, hist, single_peaks) + """ + """ + Set the single peak background for a given histogram. + + Parameters: + proj: object + The GSAS-II project containing the histogram. + hist : object + The histogram to set the background for. + bkg_single_peaks_dict : dict + Dictionary containing single peak background parameters: + - positions : list of [float, bool, float, float]. Indices 2 and 3 can be None. + List of [position value, refine flag, min, max] for each peak. + These are two-theta values. Q / d can be passed upstream and converted in validation. + - intensities: list of [float, bool, float, float]. Indices 2 and 3 can be None. + List of [intensity value, refine flag, min, max] for each peak. + - pv_gaussian_sigma: list of [float, bool, float, float]. Indices 2 and 3 can be None. + List of [gaussian sigma value, refine flag, min, max] for each peak. + - pv_lorentzian_gamma: list of [float, bool, float, float]. Indices 2 and 3 can be None. + List of [lorentzian gamma value, refine flag, min, max] for each peak. + print_info : bool + Whether to print information about the set background. + Returns: + None + """ + # Parse the bkg_single_peaks_dict + positions = bkg_single_peaks_dict.get('positions', []) + intensities = bkg_single_peaks_dict.get('intensities', []) + gaussian_sigmas = bkg_single_peaks_dict.get('pv_gaussian_sigma', []) + lorentzian_gammas = bkg_single_peaks_dict.get('pv_lorentzian_gamma', []) + + # Default intensity, sigma, gamma values to use if value input is None + # TODO: Phase 2 upstream recipe builder — these defaults will be set before calling this function + # default_intensity = 1.0 + # default_sigma = 0.1 + # default_gamma = 0.1 + # default_refine_flag = False + + # Validate that all input lists have the same length + if not (len(positions) == len(intensities) == len(gaussian_sigmas) == len(lorentzian_gammas)): + raise ValueError("All input lists must have the same length.") + + num_peaks = len(positions) # only used for looping + + # Construct the single peak background list + single_peak_bkg = [] + + for i in range(num_peaks): + pos, pos_refine, pos_min, pos_max = positions[i] + inten, inten_refine, inten_min, inten_max = intensities[i] + g_sigma, g_refine, g_sigma_min, g_sigma_max = gaussian_sigmas[i] + l_gamma, l_refine, l_gamma_min, l_gamma_max = lorentzian_gammas[i] + + # TODO: move default behavior upstream + # # Use default values if None provided + # if inten is None: + # inten = default_intensity + # if g_sigma is None: + # g_sigma = default_sigma + # if l_gamma is None: + # l_gamma = default_gamma + + # # Use default refine flags if None provided + # if pos_refine is None: + # pos_refine = default_refine_flag + # if inten_refine is None: + # inten_refine = default_refine_flag + # if g_refine is None: + # g_refine = default_refine_flag + # if l_refine is None: + # l_refine = default_refine_flag + + # Min / max not currently available in GSAS-II single peak background definition + # They can be stored upstream for reference, but not used downstream currently. + # [placeholder for code to handle min/max if needed in future] + + # Append peak parameters to the single peak background list + # Each peak is a list: + # [pos, pos_refine, inten, inten_refine, g_sigma, g_refine, l_gamma, l_refine] + if None in [pos, pos_refine, + inten, inten_refine, + g_sigma, g_refine, + l_gamma, l_refine]: + continue + + # We only append if there are no Nones - this is a temp fix before phase2 + # TODO: update this behavior in the future when this list will only be passed with valid contents + single_peak_bkg.append([pos, pos_refine, + inten, inten_refine, + g_sigma, g_refine, + l_gamma, l_refine]) + + # Append the single peak background to the histogram's background list + if proj.data[hist.name]['Background'][1]['peaksList'] is None: + proj.data[hist.name]['Background'][1]['peaksList'] = [] + + # Since single_peak_bkg is a list of peaks, we need to append each peak individually + for peak in single_peak_bkg: + proj.data[hist.name]['Background'][1]['peaksList'].append(peak) + + # Update the number of peaks + proj.data[hist.name]['Background'][1]['nPeaks'] = len(proj.data[hist.name]['Background'][1]['peaksList']) + + # if print_info, then print details about the set background using the proj data, not the inputs + if print_info: + print(f"Single peak background set with {proj.data[hist.name]['Background'][1]['nPeaks']} peaks:") + for peak in proj.data[hist.name]['Background'][1]['peaksList']: + print(f" Position: {peak[0]} (refine: {peak[1]}), Intensity: {peak[2]} (refine: {peak[3]}), " + f"Gaussian Sigma: {peak[4]} (refine: {peak[5]}), Lorentzian Gamma: {peak[6]} (refine: {peak[7]})") + + +def set_single_peaks(proj: Any, hist: Any, single_peaks_dict: dict, print_info: bool = False) -> None: + """ + Set single peaks in the Peak List (non-background peaks) with direct control over position, intensity, + and pseudo-Voigt width parameters (sigma_sq, gamma). + + **Schema 0.24:** Values should be sigma² (variance), not sigma - no conversion is performed. + Peak fitting mode is controlled by refinement strategy execution functions via + refinement_controls.single_peak_fitting_mode and passed to hist.refine_peaks(). + + sigma_sq and gamma must be positive non-zero values. + GSAS-II does not use negative values for FWHM calc and instead enforces a minimum (0.001 in centidegrees for sigma and gamma). + In our approach, we raise an error for negative or zero values to avoid confusion. + GSAS-II will output negative values if refined to such, but uses the near-zero value in PV calculation. + + Parameters: + proj: GSAS-II project object + hist: Histogram object + single_peaks_dict: Dictionary containing peak parameters (positions, intensities, pv_gaussian_sigma_sq, pv_lorentzian_gamma) + print_info: If True, print details about set peaks + """ + # Extract parameters from dict + positions = single_peaks_dict.get('positions') + intensities = single_peaks_dict.get('intensities') + pv_gaussian_sigma_sq = single_peaks_dict.get('pv_gaussian_sigma_sq') + pv_lorentzian_gamma = single_peaks_dict.get('pv_lorentzian_gamma') + + # Validate that all required lists are present + required_keys = ['positions', 'intensities', 'pv_gaussian_sigma_sq', 'pv_lorentzian_gamma'] + for key in required_keys: + if single_peaks_dict.get(key) is None: + raise ValueError(f"Missing required key '{key}' in single_peaks_dict") + + # Validate all lists are non-empty + if not positions or len(positions) == 0: + raise ValueError("positions list cannot be empty") + if not intensities or len(intensities) == 0: + raise ValueError("intensities list cannot be empty") + if not pv_gaussian_sigma_sq or len(pv_gaussian_sigma_sq) == 0: + raise ValueError("pv_gaussian_sigma_sq list cannot be empty") + if not pv_lorentzian_gamma or len(pv_lorentzian_gamma) == 0: + raise ValueError("pv_lorentzian_gamma list cannot be empty") + + # Validate all lists have the same length + list_lengths = [ + len(positions), + len(intensities), + len(pv_gaussian_sigma_sq), + len(pv_lorentzian_gamma) + ] + if len(set(list_lengths)) > 1: + raise ValueError( + f"All peak parameter lists must have the same length. " + f"Got: positions={len(positions)}, intensities={len(intensities)}, " + f"pv_gaussian_sigma_sq={len(pv_gaussian_sigma_sq)}, pv_lorentzian_gamma={len(pv_lorentzian_gamma)}" + ) + + num_peaks = len(positions) + + # Check if Peak List exists, initialize if not + if 'Peak List' not in proj.data[hist.name]: + import warnings + warnings.warn(f"Peak List not found for histogram {hist.name}. Initializing with default structure.") + proj.data[hist.name]['Peak List'] = { + 'peaks': [], + 'sigDict': {}, + 'xtraPeaks': [], + 'xtraMode': False + } + + # Build peak list + peaks_list = [] + for i in range(num_peaks): + # Extract values and refine flags from RefinementParameter format [value, refine_flag, min, max] + pos_val, pos_refine = positions[i][0], positions[i][1] + int_val, int_refine = intensities[i][0], intensities[i][1] + sigma_sq_val, sigma_sq_refine = pv_gaussian_sigma_sq[i][0], pv_gaussian_sigma_sq[i][1] + gamma_val, gamma_refine = pv_lorentzian_gamma[i][0], pv_lorentzian_gamma[i][1] + + # Input validation - check for invalid values + if np.isnan(sigma_sq_val) or np.isinf(sigma_sq_val): + raise ValueError(f"Peak {i}: sigma² value is NaN or inf ({sigma_sq_val}), which is always invalid") + if np.isnan(gamma_val) or np.isinf(gamma_val): + raise ValueError(f"Peak {i}: gamma value is NaN or inf ({gamma_val}), which is always invalid") + + # Check for negative or zero values, raise Error (while GSAS-II allows negative values, we will not in our approach) + if sigma_sq_val <= 0: + raise ValueError(f"Peak {i}: sigma² <= 0 ({sigma_sq_val}), which is invalid for peak fitting") + if gamma_val <= 0: + raise ValueError(f"Peak {i}: gamma <= 0 ({gamma_val}), which is invalid for peak fitting") + + # Convert boolean refine flags to integers (0 or 1) + pos_flag = 1 if pos_refine else 0 + int_flag = 1 if int_refine else 0 + # Refine flag for sig² (variance) - input is already sigma² from GUI/calculations + sig_sq_flag = 1 if sigma_sq_refine else 0 + gamma_flag = 1 if gamma_refine else 0 + + # Build peak as: [pos, pos_flag, intensity, int_flag, sig², sig²_flag, gamma, gam_flag] + peak = [pos_val, pos_flag, int_val, int_flag, sigma_sq_val, sig_sq_flag, gamma_val, gamma_flag] + peaks_list.append(peak) + + # Set peaks in Peak List + proj.data[hist.name]['Peak List']['peaks'] = peaks_list + + # Print info if requested + if print_info: + print(f"Single peaks (Peak List) set with {num_peaks} peaks:") + for i, peak in enumerate(peaks_list): + pos, pos_flag, intensity, int_flag, sig_sq, sig_sq_flag, gamma, gam_flag = peak + print(f" Peak {i+1}: Position={pos:.4f} (refine: {bool(pos_flag)}), " + f"Intensity={intensity:.4f} (refine: {bool(int_flag)}), " + f"Sigma²={sig_sq:.6f}, (refine: {bool(sig_sq_flag)}), " + f"Gamma={gamma:.6f} (refine: {bool(gam_flag)})") + + +################################################################## +# Functions for phase parameterization + +@require_phase("Cannot set scale.") +def set_phase_scale(proj: Any, hist: Any, phase_name: str, scale_param: list, print_info: bool = False) -> None: + """ + Set the phase scale factor in the GSAS-II project. + + Parameters: + proj : GSAS-II project object + The GSAS-II project containing the phase. + hist : GSAS-II histogram object + The histogram associated with the phase. + phase_name : str + The name of the phase to set the scale for. + scale_param : list + List containing [value, refine_flag, min, max] for the scale factor. + + Returns: + None + """ + value, refine_flag, min_val, max_val = unpack_refinement_parameter(scale_param, "scale_param") + + # Set the scale factor value - defaults will be handled upstream in future in validation + if value is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Scale'][0] = value + + # Set refinement flag + if refine_flag is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Scale'][1] = refine_flag + # Set min and max if provided - CURRENTLY NOT IMPLEMENETED. Unclear if allowed in GSAS-II. + # if min_val is not None: + # phase.set_parameter_min('Scale', min_val) + # if max_val is not None: + # phase.set_parameter_max('Scale', max_val) + + if print_info: + print(f"Set scale for phase '{phase_name}' to {value} with refine_flag={refine_flag}") + +@require_phase("Cannot set unit cell parameters.") +def set_phase_unit_cell(proj: Any, phase_name: str, unit_cell_dict: dict, print_info: bool = False) -> list[str]: + """ + Set the unit cell parameters in the GSAS-II project for a given phase. + + Schema 0.26 semantics: each cell parameter refines iff it is present with + refine_flag=true; absent or false means fixed. Because GSAS-II has a single + whole-cell refine flag, per-parameter control is achieved by setting that + flag when any symmetry degree-of-freedom (DOF) group is requested and + returning "Hold" constraint variable names (e.g. '0::A2') for the DOF + groups that were not requested. Symmetry-linked parameters (e.g. cubic + a=b=c, or the coupled monoclinic {a, c, beta}) refine together if any + member is requested — see powderline.constraints. + + Parameters: + proj : GSAS-II project object + The GSAS-II project containing the phase. + phase_name : str + The name of the phase to set the unit cell for. + unit_cell_dict : dict + Dictionary containing unit cell parameters and their parameterization. + print_info : bool + Whether to print information about the set unit cell. + + Returns: + list[str] + GSAS-II variable names to Hold (empty when the whole cell refines or + is entirely fixed). The caller applies them via proj.add_HoldConstr. + """ + + # Note: cell values are set verbatim; validating them against the phase's + # crystal system is intentionally NOT done here (PowderLine is the engine, + # not the arbiter of recipe correctness — see docs/known_issues.md, KI-01). + + # Note2: hist not required since unit cell is phase-specific, not histogram-specific. + # The delineation of phase and histogram parameters is confusing in GSAS-II documentation. + # This makes sticking with a project based approach more straightforward. + + phase_names = [p.name for p in proj.phases()] + cell_changed = False + cell_params = ['a', 'b', 'c', 'alpha', 'beta', 'gamma'] # must match schema, and match order in GSAS-II + + for i, param in enumerate(cell_params): + if unit_cell_dict.get(param) is not None: + value, refine_flag, min_val, max_val = unit_cell_dict[param] + + # Set the unit cell parameter value - a=1, b=2, c=3, alpha=4, beta=5, gamma=6 + if value is not None: + proj.data['Phases'][phase_name]['General']['Cell'][i+1] = value + cell_changed = True + + # Set min and max if provided - CURRENTLY NOT IMPLEMENTED (deferred; + # GSAS-II's own min/max semantics differ from simple bounds). + + # Calculate and set volume from unit cell parameters only if cell was changed + if cell_changed: + cell = proj.data['Phases'][phase_name]['General']['Cell'][1:7] # get list of a, b, c, alpha, beta, gamma + proj.data['Phases'][phase_name]['General']['Cell'][7] = G2lat.calc_V(G2lat.cell2A(cell)) # index 7 is volume + + # Translate per-parameter refine flags into the whole-cell flag + holds + SGData = proj.data['Phases'][phase_name]['General']['SGData'] + phase_idx = phase_names.index(phase_name) + cell_plan = cell_refinement_plan(SGData, unit_cell_dict, phase_idx) + proj.data['Phases'][phase_name]['General']['Cell'][0] = cell_plan.refine_cell + + if print_info: + curr_cell = proj.data['Phases'][phase_name]['General']['Cell'] + if cell_changed: + cell_prms_dict = {"a": curr_cell[1], + "b": curr_cell[2], + "c": curr_cell[3], + "alpha": curr_cell[4], + "beta": curr_cell[5], + "gamma": curr_cell[6], + "volume": curr_cell[7]} + + print(f"Set unit cell parameters for phase '{phase_name}' to {[(key, value) for key, value in cell_prms_dict.items()]} with refine_flag={curr_cell[0]}") + else: + print(f"No unit cell parameters were changed for phase '{phase_name}'. Refine_flag={curr_cell[0]}") + if cell_plan.holds: + print(f"Holding fixed unit cell DOFs for phase '{phase_name}': {cell_plan.holds}") + + return cell_plan.holds + + +@require_phase("Cannot set size broadening parameters.") +def set_phase_size_broadening(proj: Any, hist: Any, phase_name: str, size_broadening_dict: dict, print_info: bool = False) -> None: + """ + Set size broadening parameters in the GSAS-II project for a given phase. + + Supports model branching for isotropic, uniaxial, and ellipsoidal models. + Currently only isotropic model is implemented - others raise NotImplementedError. + + Parameters: + proj : GSAS-II project object + The GSAS-II project containing the phase. + hist : GSAS-II histogram object + The histogram associated with the phase. + phase_name : str + The name of the phase to set the size broadening for. + size_broadening_dict : dict + Dictionary containing size broadening parameters with 'model' key. + + Raises: + NotImplementedError: For uniaxial or ellipsoidal models + ValueError: For unknown model types or invalid parameters + + Returns: + None + """ + # Extract model type (default to isotropic for backward compatibility) + model = size_broadening_dict.get('model', 'isotropic') + + # Validate model type + valid_models = ['isotropic', 'uniaxial', 'ellipsoidal'] + if model not in valid_models: + raise ValueError( + f"Unknown size broadening model '{model}'. " + f"Valid options: {valid_models}" + ) + + # Set model type in GSAS-II data structure + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][0] = model + + # Branch on model type + if model == 'isotropic': + _set_isotropic_size_broadening(proj, hist, phase_name, size_broadening_dict, print_info) + elif model == 'uniaxial': + raise NotImplementedError( + "Uniaxial size broadening model is not yet implemented. " + "Support planned for future release. Use 'isotropic' model instead." + ) + elif model == 'ellipsoidal': + raise NotImplementedError( + "Ellipsoidal size broadening model is not yet implemented. " + "Support planned for future release. Use 'isotropic' model instead." + ) + + +def _set_isotropic_size_broadening(proj: Any, hist: Any, phase_name: str, size_broadening_dict: dict, print_info: bool = False) -> None: + """ + Set isotropic size broadening parameters (internal helper). + + Refactored from original set_phase_size_broadening function. + """ + + # Example structure of proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size']: + # ['isotropic', # [0]: str for broadening type. 'isotropic', 'uniaxial', or 'ellipsoidal' + # [1.0, 1.0, 1.0], # [1][0]: iso size or equatorial size, [1][1]: axial size (if uniaxial used, else ignored), [1][2]: LG_mix (eta parameter, 1 = Lorentzian, 0 = Gaussian) + # [False, False, False], # boolean refinement flags. [2][0]: isotropic or uniaxial equatorial refine, [2][1]: uniaxial axial refine, [2][2]: LG_mix refine + # [0, 0, 1], # hkl direction for uniaxial broadening. [3][0]: h, [3][1]: k, [3][2]: l + # [1.0, 1.0, 1.0, 0.0, 0.0, 0.0], # ellipsoidal sizes. S11, S22, S33, S12, S13, S23 for [4][0:6] + # [False, False, False, False, False, False]] # ellipsoidal size refine flags. S11, S22, S33, S12, S13, S23 for [5][0:6] + ############################ + # Set isotropic size parameters + ############################ + value, refine_flag, min_val, max_val = unpack_refinement_parameter( + size_broadening_dict.get('isotropic_size'), "isotropic_size" + ) + + # Set the size parameter value + if value is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][1][0] = value + + # Set refinement flag + if refine_flag is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][2][0] = refine_flag + + # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. + + if print_info: + print(f"Set size broadening size parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") + + ############################ + # Set size LG_eta parameter + ############################ + try: + value, refine_flag, min_val, max_val = unpack_refinement_parameter( + size_broadening_dict.get('LG_eta'), "LG_eta" + ) + except (ValueError, TypeError) as e: + # Preserve original error message format + raise ValueError(f"Size broadening 'LG_eta' parameter must be a list or None.\nType for phase {phase_name} is {type(size_broadening_dict['LG_eta'])}.") from e + + # Set the LG_eta parameter value + if value is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][1][2] = value + + # Set refinement flag + if refine_flag is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][2][2] = refine_flag + + # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. + + if print_info: + print(f"Set size broadening LG_eta parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") + + +# Setting strain broadening should be done in the same way as size broadening +# The dictionary structure is very similar. We just need to map to the correct keys in the proj.data structure. + +@require_phase("Cannot set strain broadening parameters.") +def set_phase_strain_broadening(proj: Any, hist: Any, phase_name: str, strain_broadening_dict: dict, print_info: bool = False) -> None: + """ + Set strain broadening parameters in the GSAS-II project for a given phase. + + Supports model branching for isotropic, uniaxial, and generalized (Stephens) models. + Currently only isotropic model is implemented - others raise NotImplementedError. + + Parameters: + proj : GSAS-II project object + The GSAS-II project containing the phase. + hist : GSAS-II histogram object + The histogram associated with the phase. + phase_name : str + The name of the phase to set the strain broadening for. + strain_broadening_dict : dict + Dictionary containing strain broadening parameters with 'model' key. + + Raises: + NotImplementedError: For uniaxial or generalized models + ValueError: For unknown model types or invalid parameters + + Returns: + None + """ + # Extract model type (default to isotropic for backward compatibility) + model = strain_broadening_dict.get('model', 'isotropic') + + # Validate model type + valid_models = ['isotropic', 'uniaxial', 'generalized'] + if model not in valid_models: + raise ValueError( + f"Unknown strain broadening model '{model}'. " + f"Valid options: {valid_models}" + ) + + # Set model type in GSAS-II data structure + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][0] = model + + # Branch on model type + if model == 'isotropic': + _set_isotropic_strain_broadening(proj, hist, phase_name, strain_broadening_dict, print_info) + elif model == 'uniaxial': + raise NotImplementedError( + "Uniaxial strain broadening model is not yet implemented. " + "Support planned for future release. Use 'isotropic' model instead." + ) + elif model == 'generalized': + raise NotImplementedError( + "Generalized (Stephens) strain broadening model is not yet implemented. " + "This model requires complex symmetry-dependent parameterization. " + "Support planned for Phase 2. Use 'isotropic' model instead." + ) + + +def _set_isotropic_strain_broadening(proj: Any, hist: Any, phase_name: str, strain_broadening_dict: dict, print_info: bool = False) -> None: + """ + Set isotropic strain broadening parameters (internal helper). + + Refactored from original set_phase_strain_broadening function. + """ + ############################ + # Set isotropic strain parameters + ############################ + value, refine_flag, min_val, max_val = unpack_refinement_parameter( + strain_broadening_dict.get('isotropic_strain'), "isotropic_strain" + ) + + # Set the strain parameter value + if value is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][1][0] = value + + # Set refinement flag + if refine_flag is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][2][0] = refine_flag + + # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. + + if print_info: + print(f"Set strain broadening strain parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") + + ############################ + # Set strain LG_eta parameter + ############################ + try: + value, refine_flag, min_val, max_val = unpack_refinement_parameter( + strain_broadening_dict.get('LG_eta'), "LG_eta" + ) + except (ValueError, TypeError) as e: + # Preserve original error message format + raise ValueError(f"Strain broadening dict key 'LG_eta' must hold a value that is a list or None.\nType for phase {phase_name} is {type(strain_broadening_dict['LG_eta'])}.") from e + + # Set the LG_eta parameter value + if value is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][1][2] = value + + # Set refinement flag + if refine_flag is not None: + proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][2][2] = refine_flag + + # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. + + if print_info: + print(f"Set strain broadening LG_eta parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") + + +# Function to set atom parameters for a phase +@require_phase("Cannot set atom parameters.") +def set_phase_atom_parameters(proj: Any, phase_name: str, atom_parameters_dict: dict, print_info: bool = False) -> list[str]: + """ + Set atom parameters for a phase in the GSAS-II project. + + This function parses atom-specific refinement parameters (coordinates, occupancy, displacement) + and constructs GSAS-II's refine_flags string ('F', 'X', 'U' combinations). + + Schema 0.26 semantics: each coordinate (x/y/z) and each anisotropic Uij + component refines iff present with refine_flag=true; absent or false means + fixed. GSAS-II's 'X'/'U' flags are per-atom, so per-component control is + achieved by returning "Hold" constraint variable names (e.g. '0::dAy:3', + '0::AU22:4') for the site-symmetry DOF groups that were not requested — + see powderline.constraints. + Symmetry-linked components (e.g. x=y on an (x,x,z) site) refine together + if any member is requested. + + Parameters: + proj : GSAS-II project object + The GSAS-II project containing the phase. + phase_name : str + The name of the phase to set the atom parameters for. + atom_parameters_dict : dict + Dictionary containing atom parameters and their parameterization. + E.g., payload['phases'][phase_name]['parameterization']['atoms'] + + Expected structure: + { + 'atom_label': { + 'x': [value, refine_flag, min, max], + 'y': [value, refine_flag, min, max], + 'z': [value, refine_flag, min, max], + 'occupancy': [value, refine_flag, min, max], + 'ADP': 'Uiso' or 'Uaniso', + 'Uiso': [value, refine_flag, min, max], # if ADP='Uiso' + 'Uaniso': { # if ADP='Uaniso' + 'U11': [value, refine_flag, min, max], + 'U22': [value, refine_flag, min, max], + ... + } + } + } + print_info : bool, optional + If True, print detailed information about the atom parameters being set. Default is False. + + Returns: + list[str] + GSAS-II variable names to Hold (empty when every requested DOF group + refines in full). The caller applies them via proj.add_HoldConstr. + + Notes: + proj.data['Phases'][phase_name]['Atoms'] is a list of lists, where each sublist represents an atom and its parameters. + Sublist structure in atom_param_index_mapping below. + + Example: proj.data['Phases'][phase_name]['Atoms'][0] from LaB6 example returns: + ['La', 'La', '', 0.0, 0.0, 0.0, 1.0, 'm3m', 1, 'I', 0.00858, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 844046454091148456] + + GSAS-II refine_flags string format (index 2): + - 'F': refine occupancy + - 'X': refine all coordinates (x, y, z together) + - 'U': refine displacement parameters (isotropic or anisotropic) + - Combinations: 'FXU', 'XU', 'F', etc. + """ + + # Dictionary of atom parameter names to their indices in the atom list + atom_param_index_mapping = { + 'label': 0, # atom label + 'element': 1, # element symbol + 'refine_flags': 2, # string of refine flags e.g., 'F', 'X', 'U' or any combination such as 'FXU'. F for occupancy, X for xyz coords, U for displacement parameters + 'x': 3, # fractional coordinate x value + 'y': 4, # fractional coordinate y value + 'z': 5, # fractional coordinate z value + 'occupancy': 6, # float, referred to as frac in GSAS-II syntax + 'site_symmetry': 7, # string representation of site symmetry + 'multiplicity': 8, # multiplicity of the site, integer + 'Utype': 9, # 'I' for isotropic, 'A' for anisotropic + 'Uiso': 10, # value if isotropic + 'U11': 11, # value if anisotropic + 'U22': 12, # value if anisotropic + 'U33': 13, # value if anisotropic + 'U12': 14, # value if anisotropic + 'U13': 15, # value if anisotropic + 'U23': 16 # value if anisotropic + # Note: index 17 is a random unique ID for the atom, not a parameter to set + } + + phase_names = [p.name for p in proj.phases()] + phase_idx = phase_names.index(phase_name) + SGData = proj.data['Phases'][phase_name]['General']['SGData'] + atom_labels_present = [x[0] for x in proj.data['Phases'][phase_name]['Atoms']] + holds: list[str] = [] + + for atom_label, atom_params in atom_parameters_dict.items(): + if atom_label not in atom_labels_present: + print(f"Atom '{atom_label}' not found in phase '{phase_name}'. Skipping.") + continue + + # Get the atom record + atom_index = atom_labels_present.index(atom_label) + atom_record = proj.data['Phases'][phase_name]['Atoms'][atom_index] + + # Get ADP type for this atom (required in schema 0.22) + adp_type = atom_params.get('ADP') + + # Process coordinate parameters (x, y, z) — values only; refine flags + # are translated by atom_refinement_plan below + for coord in ['x', 'y', 'z']: + if coord in atom_params and atom_params[coord] is not None: + param_value = atom_params[coord] + if param_value != [None, False, None, None]: + value, refine_flag, min_val, max_val = param_value + + # Update coordinate value if provided + if value is not None: + atom_record[atom_param_index_mapping[coord]] = value + + # Process occupancy + if 'occupancy' in atom_params and atom_params['occupancy'] is not None: + param_value = atom_params['occupancy'] + if param_value != [None, False, None, None]: + value, refine_flag, min_val, max_val = param_value + + # Update occupancy value if provided + if value is not None: + atom_record[6] = value + + # Process displacement parameters based on ADP type + if adp_type == 'Uiso': + # Isotropic displacement parameters + if 'Uiso' in atom_params and atom_params['Uiso'] is not None: + param_value = atom_params['Uiso'] + if param_value != [None, False, None, None]: + value, refine_flag, min_val, max_val = param_value + + # Update Uiso value if provided + if value is not None: + atom_record[9] = 'I' # Set to isotropic + atom_record[10] = value + + elif adp_type == 'Uaniso': + # Anisotropic displacement parameters + if 'Uaniso' in atom_params and atom_params['Uaniso'] is not None: + uaniso_dict = atom_params['Uaniso'] + + # Track if any anisotropic values are being updated + aniso_values_provided = [] + + # Process each anisotropic parameter + for u_key in ['U11', 'U22', 'U33', 'U12', 'U13', 'U23']: + if u_key in uaniso_dict and uaniso_dict[u_key] is not None: + param_value = uaniso_dict[u_key] + if param_value != [None, False, None, None]: + value, refine_flag, min_val, max_val = param_value + + # Update anisotropic value if provided + if value is not None: + atom_record[9] = 'A' # Set to anisotropic + atom_record[atom_param_index_mapping[u_key]] = value + aniso_values_provided.append(u_key) + + # Validate that if any anisotropic values are provided, all 6 must be provided + if aniso_values_provided: + required_keys = ['U11', 'U22', 'U33', 'U12', 'U13', 'U23'] + missing_keys = [k for k in required_keys if k not in aniso_values_provided] + if missing_keys: + raise ValueError( + f"Atom '{atom_label}' in phase '{phase_name}': " + f"When updating anisotropic displacement parameters, all 6 values (U11-U23) must be provided. " + f"Missing: {missing_keys}" + ) + + # Translate per-parameter refine flags into GSAS-II's per-atom flag + # string plus holds for the unrefined site-symmetry DOF groups. + # xyz/SGData let the plan recompute a stale/blank site symmetry the + # same way GSAS-II itself does (GetPhaseData's KeyError patch). + atom_plan = atom_refinement_plan( + atom_params, + atom_record[7], + phase_idx, + atom_index, + xyz=atom_record[3:6], + SGData=SGData, + ) + atom_record[2] = atom_plan.refine_flags + holds.extend(atom_plan.holds) + + # Verbose logging + if print_info and atom_plan.refine_flags: + adp_display = adp_type if adp_type else "inherited" + print(f" Set refine flags for atom '{atom_label}' ({adp_display}): '{atom_plan.refine_flags}'") + if atom_plan.holds: + print(f" Holding fixed DOFs for atom '{atom_label}': {atom_plan.holds}") + + return holds + + +# Main function to set phase parameterization from phases dictionary + +def set_phase_parameterization(proj: Any, hist: Any, phases_dict: dict, print_info: bool = False) -> list[str]: + """ + Set phase parameterization in the GSAS-II project from a phases dictionary. + + Parameters: + proj : GSAS-II project object + The GSAS-II project containing the phases. + hist : GSAS-II histogram object + The histogram associated with the phases. + phases_dict : dict + Dictionary containing phase parameterization information. E.g., payload['phases'] + print_info : bool, optional + If True, print information about the parameterization being set. Default is False. + + Returns: + list[str] + Accumulated GSAS-II "Hold" variable names from the unit-cell and atom + setters (schema 0.26 per-parameter refine flags). The caller applies + them once via proj.add_HoldConstr. + """ + holds: list[str] = [] + + for phase_name, phase_info in phases_dict.items(): + + # In schema 0.21, phase_name is the dict key itself + # (structure.phase_name should match, but we use the key for consistency) + + # Check that phase exists in project - this would indicate an error in phase addition earlier + if phase_name not in [p.name for p in proj.phases()]: + print(f"Phase '{phase_name}' not found in project. Skipping parameterization.") + continue + + # Now that we have the phase name, we can add phase-specific parameterization here + # This will call on a few helper functions to set scale, unit cell, peak broadening, atom parameters, etc. + # Each of these helper functions will take the proj, phase name (rather than phase object), and relevant parameterization dict + + # First, get parameterization dict from phase_info (already phase-specific) + param_dict = phase_info.get('parameterization', {}) + + # Keys in param dict are 'scale', 'unit_cell', 'peak_broadening', and 'atoms' for now + # It is not as simple as looping over keys since some have nested dicts and others hold values or lists + + # Set scale factor if provided + scale_param = param_dict.get('scale', None) + if scale_param is not None: + if any(value is not None for value in scale_param): + set_phase_scale(proj, hist, phase_name, scale_param, print_info=False) + + # Set unit cell parameters if provided. The key values can be None, + # so here we cannot just check for unit_cell_dict not being None. + # We need to check if any of hte keys in unit_cell_dict are not None. + unit_cell_dict = param_dict.get('unit_cell', None) + + if unit_cell_dict is not None: + if any(value is not None for value in unit_cell_dict.values()): + holds.extend(set_phase_unit_cell(proj, phase_name, unit_cell_dict, print_info=False)) + + # Set peak broadening if provided. Keys are "size_broadening" and "strain_broadening" + # and each holds a dict with relevant parameters (size or strain) and the LG_eta + # ("or {}" because model_dump emits an explicit None when the section is absent) + peak_broadening_dict = param_dict.get('peak_broadening') or {} + size_broadening_dict = peak_broadening_dict.get('size_broadening', None) + strain_broadening_dict = peak_broadening_dict.get('strain_broadening', None) + + if size_broadening_dict is not None: + if any(value is not None for value in size_broadening_dict.values()): + set_phase_size_broadening(proj, hist, phase_name, size_broadening_dict, print_info=False) + + if strain_broadening_dict is not None: + if any(value is not None for value in strain_broadening_dict.values()): + set_phase_strain_broadening(proj, hist, phase_name, strain_broadening_dict, print_info=False) + + atoms_parameters_dict = param_dict.get('atoms', {}) + if atoms_parameters_dict and any(has_active_refinement_parameter(ap) for ap in atoms_parameters_dict.values()): + holds.extend(set_phase_atom_parameters(proj, phase_name, atoms_parameters_dict, print_info=False)) + + if print_info: + print(f"Completed parameterization for phase '{phase_name}'.") + + if print_info: + print("All phase parameterization complete. Phases in proj: ", *[p.name for p in proj.phases()], sep='\n\t') + if holds: + print("Hold constraints to apply (per-parameter refine flags): ", *holds, sep='\n\t') + + return holds + +# Function for setting instrument parameterization +def set_instrument_parameterization(proj: Any, hist: Any, instrument_param_dict: dict, print_info: bool = False) -> None: + """ + Set instrument parameterization in the GSAS-II project from an instrument parameterization dictionary. + + Parameters: + proj : GSAS-II project object + The GSAS-II project containing the histogram. + hist : GSAS-II histogram object + The histogram associated with the instrument. + instrument_param_dict : dict + Dictionary containing instrument parameterization information. E.g., payload['instrument'] + print_info : bool, optional + If True, print information about the parameterization being set. Default is False. + + Returns: + None + """ + + # Note: GSAS-II's instrument parameters hold values in a list. + # The indices for each parameter (e.g., 'Lam' for wavelength) are as follows: + # [0] default/starting value from iprms, [1] = value, [2] = refinement flag + + # Wavelength + wavelength_param = instrument_param_dict.get('wavelength', None) + if wavelength_param is not None: + value, refine_flag, min_val, max_val = unpack_refinement_parameter(wavelength_param, "wavelength") + wavelength_changed = False # track if wavelength value changed + + # Set wavelength value + curr_wavelength = proj.data[hist.name]['Instrument Parameters'][0]['Lam'][1] + + if value is not None and value != curr_wavelength: + proj.data[hist.name]['Instrument Parameters'][0]['Lam'][1] = value + wavelength_changed = True + + # Set refinement flag + if refine_flag is not None: + proj.data[hist.name]['Instrument Parameters'][0]['Lam'][2] = refine_flag + + if print_info: + if wavelength_changed: + print(f"Set instrument wavelength to {value} with refine_flag={refine_flag}") + else: + print(f"No change to instrument wavelength. Refine_flag={refine_flag}") + + # Additional instrument parameters (polarization, broadening, corrections) would be set similarly + # Implementing those follows the same pattern as above + + # Polarization + polarization_param = instrument_param_dict.get('polarization', None) + if polarization_param is not None: + value, refine_flag, min_val, max_val = unpack_refinement_parameter(polarization_param, "polarization") + polarization_changed = False # track if polarization value changed + + curr_polarization = proj.data[hist.name]['Instrument Parameters'][0]['Polariz.'][1] + + # Set polarization value + if value is not None and value != curr_polarization: + proj.data[hist.name]['Instrument Parameters'][0]['Polariz.'][1] = value + polarization_changed = True + + # Set refinement flag + if refine_flag is not None: + proj.data[hist.name]['Instrument Parameters'][0]['Polariz.'][2] = refine_flag + + if print_info: + if polarization_changed: + print(f"Set instrument polarization to {value} with refine_flag={refine_flag}") + else: + print(f"No change to instrument polarization. Refine_flag={refine_flag}") + + # Broadening parameters (U, V, W, X, Y, Z) + broadening_dict = instrument_param_dict.get('broadening', {}) + for param_key in broadening_dict.keys(): + broadening_param = broadening_dict.get(param_key, None) + if broadening_param is not None: + value, refine_flag, min_val, max_val = unpack_refinement_parameter(broadening_param, f"broadening.{param_key}") + + broadening_changed = False + + # Set broadening parameter value + if value is not None: + proj.data[hist.name]['Instrument Parameters'][0][param_key][1] = value + broadening_changed = True + + # Set refinement flag + if refine_flag is not None: + proj.data[hist.name]['Instrument Parameters'][0][param_key][2] = refine_flag + + if print_info: + if broadening_changed: + # Print changed parameter + print(f"Set instrument broadening parameter '{param_key}' to {value} with refine_flag={refine_flag}") + + # Always print refinement flag even if value not changed + else: + print(f"No change to instrument broadening parameter '{param_key}'. Refine_flag={refine_flag}") + + + # Corrections parameters (zero_shift, axial_divergence, sample_height_displacement) + corrections_dict = instrument_param_dict.get('corrections', {}) + for param_key in corrections_dict.keys(): + correction_param = corrections_dict.get(param_key, None) + if correction_param is not None: # only loop over provided params + + if param_key == 'zero_shift': + gsas_key = 'Zero' + elif param_key == 'axial_divergence': + gsas_key = 'SH/L' + #elif param_key == 'sample_height_displacement': # irrelevant to area detector data, future work for Bragg-Brentano geometry + # gsas_key = 'SampHt' + else: + raise ValueError(f"Unknown instrument correction parameter key '{param_key}'.") + + value, refine_flag, min_val, max_val = correction_param + correction_changed = False + + # Set correction parameter value + if value is not None: + proj.data[hist.name]['Instrument Parameters'][0][gsas_key][1] = value + correction_changed = True + + # Set refinement flag + if refine_flag is not None: + proj.data[hist.name]['Instrument Parameters'][0][gsas_key][2] = refine_flag + + if print_info: + if correction_changed: + # Print changed parameter + print(f"Set instrument correction parameter '{param_key}' to {value} with refine_flag={refine_flag}") + + # Always print refinement flag even if value not changed + else: + print(f"No change to instrument correction parameter '{param_key}'. Refine_flag={refine_flag}") + + # Print instrument parameters set and flags if requested + if print_info: + # Check if 1st and 2nd indices are different for any instrument parameteters + # If they are all the same, then no parameters were changed + params_changed = False + for param in proj.data[hist.name]['Instrument Parameters'][0].values(): + if param[0] != param[1]: + params_changed = True + break + if not params_changed: + print("No instrument parameters were changed from their default values.") + + # print refine flags for all instrument parameters + print("Instrument parameter refinement flags:") + for param_key, param in proj.data[hist.name]['Instrument Parameters'][0].items(): + print(f" {param_key}: refine_flag={param[2]}") + + +def set_refinement_cycles(proj: Any, num_cycles: int, print_info: bool = False) -> None: + """ + Set the number of refinement cycles in the GSAS-II project. + + Parameters: + proj : GSAS-II project object + The GSAS-II project to set the refinement cycles for. + num_cycles : int + The number of refinement cycles to set. + print_info : bool, optional + If True, print information about the refinement cycles being set. Default is False. + + Returns: + None + """ + + proj.set_Controls('cycles', num_cycles) + if print_info: + print(f"Set number of refinement cycles to {num_cycles}") diff --git a/src/powderline/gsas_client.py b/src/powderline/gsas_client.py index a28401b..099afe7 100644 --- a/src/powderline/gsas_client.py +++ b/src/powderline/gsas_client.py @@ -1,454 +1,13 @@ -"""Client library for GSAS-II server communication. +"""Deprecated import path — use ``powderline.gateways.gsasii.client``. -Provides a simple API for submitting simulations to the GSAS-II server. -Automatically falls back to in-process execution when the server is not -running, or when a "successful" server run produced output files that are -not visible to this process (server with a divergent filesystem view, e.g. -on another node or inside a sandbox with a private /tmp). +Kept for backward compatibility during the multi-engine refactor (re/01); +removed in a later branch. Re-exports every top-level name of the moved module. """ - -import subprocess -import sys -import os -from pathlib import Path -from typing import Dict, Any -import tempfile - -HOST = "127.0.0.1" -DEFAULT_PORT = 19471 -PORT = int(os.environ.get('POWDERLINE_SERVER_PORT', DEFAULT_PORT)) -PORT_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.port' - - -class GSASClient: - """Client for communicating with GSAS-II server.""" - - def __init__(self, fallback_to_subprocess: bool = True): - """Initialize client. - - Args: - fallback_to_subprocess: If True, use subprocess when server unavailable - """ - self.fallback_to_subprocess = fallback_to_subprocess - - def _get_port(self) -> int: - """Read the server port from the port file.""" - if PORT_FILE.exists(): - try: - return int(PORT_FILE.read_text().strip()) - except (ValueError, OSError): - pass - return PORT - - def is_server_available(self) -> bool: - """Check if server is running and accepting connections.""" - import httpx - - port = self._get_port() - try: - resp = httpx.get(f"http://{HOST}:{port}/health", timeout=2.0) - return resp.status_code == 200 - except (httpx.ConnectError, httpx.TimeoutException, OSError): - return False - - @staticmethod - def _stat_fit_profile(output_dir: Path) -> tuple | None: - """(mtime_ns, size) of output_dir/fit_profile.txt, or None if absent.""" - try: - st = (Path(output_dir) / 'fit_profile.txt').stat() - except OSError: - return None - return (st.st_mtime_ns, st.st_size) - - def _server_output_visible(self, result: Dict[str, Any], output_dir: Path, - stat_before: tuple | None) -> bool: - """Check that a 'successful' server run materialized its output files - where THIS process can see them. - - A GSAS-II server can be reachable over localhost yet have a different - filesystem view — e.g. started on another node of a cluster, or inside - a sandbox/container with a private /tmp. Such a server reports success - while its output files are unreachable. run_refinement always - (re)writes fit_profile.txt on success, so the file must exist AND its - (mtime, size) must differ from before the run — a stale file left by a - previous run into the same output_dir does not count. Costs two stat - calls per server run; nothing is read, written, or deleted. - """ - if not result.get('success'): - return True # error paths need no file check - stat_after = self._stat_fit_profile(output_dir) - return stat_after is not None and stat_after != stat_before - - _INVISIBLE_OUTPUT_ERROR = ( - "GSAS-II server reported success but did not write output files " - "visible to this process — the server has a different filesystem view " - "(started on another node, or inside a sandbox/container with a " - "private /tmp). Restart it with: pixi run gsas-server restart" - ) - - def _handle_invisible_server_output(self) -> Dict[str, Any] | None: - """Warn about a server with a divergent filesystem view. - - Returns None when in-process fallback is enabled (caller falls - through to it), or a structured error result when fallback is - disabled (execution_mode='server'). - """ - print(" WARNING: GSAS-II server reported success but did not write " - "output files visible to this process.") - print(" The server appears to have a different filesystem view " - "(started on another node, or inside a sandbox/container with a " - "private /tmp).") - if self.fallback_to_subprocess: - print(" Falling back to in-process execution. To fix the server: " - "pixi run gsas-server restart") - return None - print(" In-process fallback is disabled. To fix the server: " - "pixi run gsas-server restart") - return { - 'success': False, - 'error': self._INVISIBLE_OUTPUT_ERROR, - 'method': 'server', - } - - def _submit_to_server_guarded(self, recipe_dict: dict, - output_dir: Path) -> Dict[str, Any] | None: - """Submit to the server with the output-visibility guard applied. - - Returns the result to hand to the caller, or None when the caller - should fall through to the in-process fallback (invisible output - with fallback enabled). Exceptions from the server round-trip - propagate unchanged. - """ - stat_before = self._stat_fit_profile(output_dir) - result = self._submit_to_server(recipe_dict, output_dir) - result['method'] = 'server' - if self._server_output_visible(result, output_dir, stat_before): - return result - return self._handle_invisible_server_output() - - def submit_simulation(self, recipe, output_dir: Path, - verbose: bool = False, auto_start_server: bool = True, - use_server: bool = True) -> Dict[str, Any]: - """Submit a simulation request. - - Args: - recipe: Recipe to run. Accepts: - - Path: path to a JSON/YAML recipe file (loaded automatically) - - dict: pre-loaded recipe dictionary - - RecipeModel: validated Pydantic model instance - output_dir: Directory for output files - verbose: If True, print detailed output - auto_start_server: If True, start server automatically if not running - use_server: If False, skip the server entirely and run in-process - - Returns: - Dictionary with 'success', 'output_files', 'elapsed_time', - and optional 'error', 'method' fields - - Note: - A server response only counts if its output files were freshly - written where this process can see them (see - _server_output_visible — a stale fit_profile.txt from a previous - run does not count); otherwise the run falls back to in-process - execution with a warning — or, when fallback_to_subprocess is - False, returns a structured error explaining the filesystem-view - mismatch. - """ - recipe_dict = self._normalize_recipe(recipe) - - if not use_server: - if not verbose: - print(" Using in-process mode (use_server=False)") - # Try server first - elif self.is_server_available(): - if not verbose: - print(f" Using GSAS-II server mode") - try: - result = self._submit_to_server_guarded(recipe_dict, output_dir) - if result is not None: - return result - # fall through to in-process fallback below - except Exception as e: - if not self.fallback_to_subprocess: - return { - 'success': False, - 'error': f"Server communication failed: {e}", - 'method': 'server' - } - - if verbose: - print(f"Server communication failed: {e}") - print(" Falling back to subprocess mode...") - - # Try to start server if not available and auto_start_server enabled - elif auto_start_server: - if verbose: - print(" Attempting to start server automatically...") - if self._start_server_background(verbose): - import time - time.sleep(1) - - # Try again - if self.is_server_available(): - if not verbose: - print(f" Using GSAS-II server mode") - try: - result = self._submit_to_server_guarded(recipe_dict, output_dir) - if result is not None: - return result - # fall through to in-process fallback below - except Exception as e: - if verbose: - print(f"Failed to connect to auto-started server: {e}") - if not verbose: - print(f" Using subprocess mode (start server with: pixi run gsas-server start)") - else: - if verbose: - print(f" Server started but not responding") - if not verbose: - print(f" Using subprocess mode (start server with: pixi run gsas-server start)") - else: - if not verbose: - print(f" Using subprocess mode (start server with: pixi run gsas-server start)") - else: - if not verbose: - print(f" Using subprocess mode (start server with: pixi run gsas-server start)") - - # Fallback to subprocess - if self.fallback_to_subprocess: - result = self._submit_via_subprocess(recipe_dict, output_dir, verbose) - result['method'] = 'subprocess' - return result - elif not use_server: - # Explicitly requested state, kept honest: both execution paths - # were disabled by the caller, so nothing ran. - return { - 'success': False, - 'error': 'No execution path enabled: use_server=False and ' - 'fallback_to_subprocess=False — enable one of them.', - 'method': 'none' - } - else: - return { - 'success': False, - 'error': 'Server not available and fallback disabled', - 'method': 'none' - } - - def _normalize_recipe(self, recipe) -> dict: - """Normalize recipe input to a plain JSON-serializable dict. - - Accepts Path (loaded from disk), dict (used as-is), or RecipeModel - (serialized via .model_dump). Raises TypeError for unsupported inputs. - """ - if isinstance(recipe, Path): - import json - import yaml - ext = recipe.suffix.lower() - text = recipe.read_text() - if ext == '.json': - return json.loads(text) - if ext in {'.yaml', '.yml', '.txt'}: - return yaml.safe_load(text) or {} - raise ValueError(f"Unsupported recipe format: {recipe}") - if isinstance(recipe, dict): - return recipe - if hasattr(recipe, 'model_dump'): - return recipe.model_dump(mode='json') - raise TypeError( - f"recipe must be a Path, dict, or RecipeModel instance, got {type(recipe).__name__}" - ) - - def _start_server_background(self, verbose: bool = False) -> bool: - """Start server in background process. - - Returns: - True if server was started, False if already running or failed - """ - import subprocess - import os - import time - - # Check if already running - if self.is_server_available(): - return True - - try: - # Build command to start server - src_dir = Path(__file__).parent.parent - server_script = Path(__file__).parent / 'gsas_server.py' - - # Prepare environment - env = os.environ.copy() - env['PYTHONPATH'] = str(src_dir) + os.pathsep + env.get('PYTHONPATH', '') - - # Use subprocess to start server in background - try: - # Try with preexec_fn (Unix only) - proc = subprocess.Popen( - [sys.executable, str(server_script), 'start'], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - stdin=subprocess.DEVNULL, - env=env, - preexec_fn=os.setpgrp, # Detach from parent process group - start_new_session=False - ) - except (TypeError, AttributeError): - # Fallback for Windows or if preexec_fn not available - proc = subprocess.Popen( - [sys.executable, str(server_script), 'start'], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - stdin=subprocess.DEVNULL, - env=env, - creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if sys.platform == 'win32' else 0 - ) - - # Give server time to start - for attempt in range(30): # Wait up to 3 seconds - time.sleep(0.1) - if self.is_server_available(): - if verbose: - print(" Server started in background") - return True - - if verbose: - print(f" Server started (PID {proc.pid}) but not responding yet") - return True # Started even if not responding immediately - - except Exception as e: - if verbose: - print(f" Could not auto-start server: {e}") - return False - - def _submit_to_server(self, recipe_dict: dict, output_dir: Path) -> Dict[str, Any]: - """Submit simulation to server via HTTP with retry logic. - - Retries up to 3 times on connection errors to handle transient network issues. - """ - import httpx - import time - - port = self._get_port() - payload = { - 'recipe_data': recipe_dict, - 'output_dir': str(output_dir.absolute()), - } - - # Retry logic for connection errors - max_retries = 3 - retry_delay = 0.5 # seconds - - last_error = None - for attempt in range(max_retries): - try: - resp = httpx.post( - f"http://{HOST}:{port}/simulate", - json=payload, - timeout=300.0, - ) - resp.raise_for_status() - return resp.json() - except httpx.ConnectError as e: - last_error = e - if attempt < max_retries - 1: - time.sleep(retry_delay) - retry_delay *= 2 # Exponential backoff - continue - except httpx.HTTPStatusError as e: - # Don't retry on HTTP errors (4xx, 5xx) - raise - except httpx.TimeoutException as e: - # Don't retry on timeout (simulation is running) - raise - - # If we exhausted all retries, raise the last error - raise last_error - - def _submit_via_subprocess(self, recipe_dict: dict, output_dir: Path, - verbose: bool) -> Dict[str, Any]: - """Run simulation in-process (fallback mode when server is unavailable). - - **Important**: Despite the method name, this does NOT spawn an OS subprocess. - It calls ``run_refinement()`` directly in the current process. The name is - retained for API stability. If hard crash-isolation is needed in a future - phase, this method can be upgraded to use ``multiprocessing`` internally - without changing any callers. - - Contrast with ``_start_server_background()``, which *does* spawn an OS - subprocess to launch the FastAPI server. - - Calls run_refinement() directly in the current process, returning the - same structured result dict as server mode (fit_profile, unit_cell_data, - peak_list_data, refined_parameters, rwp, etc.). - """ - import time - from powderline.kicker import run_refinement - from powderline.schema import RecipeModel - from pydantic import ValidationError - - output_dir.mkdir(parents=True, exist_ok=True) - - try: - recipe = RecipeModel.model_validate(recipe_dict) - except ValidationError as e: - error_lines = [ - f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" - for err in e.errors() - ] - return { - 'success': False, - 'error': f"Recipe validation failed:\n" + "\n".join(error_lines), - 'method': 'subprocess' - } - except Exception as e: - return { - 'success': False, - 'error': f"Failed to parse recipe: {str(e)}", - 'method': 'subprocess' - } - - start_time = time.time() - try: - result = run_refinement(recipe, output_dir, verbose=verbose, method='subprocess') - except Exception as e: - elapsed = time.time() - start_time - return { - 'success': False, - 'error': str(e), - 'elapsed_time': elapsed, - 'method': 'subprocess' - } - - return result - - -# Convenience function for simple use cases -def run_simulation(recipe, output_dir: Path, - verbose: bool = False, auto_start_server: bool = True) -> Dict[str, Any]: - """Run a simulation using the server if available and usable, else in-process. - - This is a convenience wrapper around GSASClient.submit_simulation(), - including its output-visibility guard (a server whose files are not - visible to this process triggers an in-process rerun). - With auto_start_server=True (default), the server is automatically started - if not running, providing fast performance for first and subsequent uses. - - Args: - recipe: Recipe to run. Accepts Path, dict, or RecipeModel instance. - output_dir: Directory for output files - verbose: If True, print detailed output - auto_start_server: If True, automatically start server in background - - Returns: - Dictionary with 'success', 'output_files', 'elapsed_time', 'method' - - Example: - >>> result = run_simulation(Path('recipe.json'), Path('output/')) - >>> result = run_simulation(recipe_dict, Path('output/')) - >>> if result['success']: - ... print(f"Completed in {result['elapsed_time']:.1f}s via {result['method']}") - """ - client = GSASClient() - return client.submit_simulation(recipe, output_dir, verbose, auto_start_server) +from powderline.gateways.gsasii.client import ( # noqa: F401 + HOST, + DEFAULT_PORT, + PORT, + PORT_FILE, + GSASClient, + run_simulation, +) diff --git a/src/powderline/gsas_server.py b/src/powderline/gsas_server.py index 72cd717..6885a5a 100644 --- a/src/powderline/gsas_server.py +++ b/src/powderline/gsas_server.py @@ -1,518 +1,25 @@ -"""GSAS-II persistent server for fast simulations. +"""Deprecated import path — use ``powderline.gateways.gsasii.server``. -This server keeps GSAS-II loaded in memory to eliminate startup overhead. -Listens on an HTTP port via FastAPI and processes simulation requests sequentially. - -Security notes: - - The server binds exclusively to ``127.0.0.1`` (loopback). It is not - accessible from remote hosts and requires no authentication by design. - - No rate limiting is applied. For a shared or multi-user environment, - add rate limiting via a reverse proxy or a middleware library such as - ``slowapi`` before exposing this server to untrusted callers. - - ``output_dir`` paths are sent by the client and used as-is; path - traversal is only exploitable by a local user who already has file-system - access equivalent to the server process. - - The server resolves ``output_dir`` in ITS OWN filesystem view. A client - on another node — or a server started inside a sandbox/container with a - private /tmp — will never see the output files even though the run - succeeds. ``GSASClient._server_output_visible`` guards clients against - this and falls back to in-process execution. - -Performance: -- First simulation: ~12s (server startup + GSAS-II import) -- Subsequent simulations: ~2-3s each (no startup overhead) -- 4-6x speedup for batch operations - -Usage: - # Start server (daemon mode) - pixi run gsas-server start - - # Stop server - pixi run gsas-server stop - - # Check status - pixi run gsas-server status - - # View logs - tail -f /tmp/powderline_gsas_server.log - - # Restart server - pixi run gsas-server restart +Kept for backward compatibility during the multi-engine refactor (re/01); +removed in a later branch. Re-exports every top-level name of the moved module. """ - -import json -import sys -import os -import signal -import time -import subprocess -import logging -from pathlib import Path -from typing import Dict, Any, Optional, List -import tempfile -import atexit -from datetime import datetime - -from pydantic import BaseModel - -# Server configuration -HOST = "127.0.0.1" -DEFAULT_PORT = 19471 -PORT = int(os.environ.get('POWDERLINE_SERVER_PORT', DEFAULT_PORT)) -PORT_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.port' -PID_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.pid' -LOG_FILE = Path(tempfile.gettempdir()) / 'powderline_gsas_server.log' - - -# --- Pydantic request/response models --- - -class SimulationRequest(BaseModel): - recipe_data: dict - output_dir: str - verbose: bool = False - - -class SimulationResponse(BaseModel): - success: bool - run_id: Optional[str] = None - rwp: Optional[float] = None - elapsed_time: Optional[float] = None - method: Optional[str] = None - error: Optional[str] = None - traceback: Optional[str] = None - output_files: Optional[List[str]] = None - fit_profile: Optional[dict] = None - unit_cell_data: Optional[dict] = None - peak_list_data: Optional[dict] = None - refined_parameters: Optional[list] = None - spf_peaks: Optional[dict] = None - spf_convergence_diagnostics: Optional[dict] = None - - -# --- Logging --- - -def setup_logging(log_file: Path) -> logging.Logger: - """Set up logging to both console and file.""" - logger = logging.getLogger('powderline.server') - logger.setLevel(logging.DEBUG) - - # File handler (always log everything) - file_handler = logging.FileHandler(log_file, mode='a') - file_handler.setLevel(logging.DEBUG) - - # Console handler (info level for cleaner output) - console_handler = logging.StreamHandler() - console_handler.setLevel(logging.INFO) - - # Formatter with timestamps - formatter = logging.Formatter( - '%(asctime)s - %(levelname)s - %(message)s', - datefmt='%Y-%m-%d %H:%M:%S' - ) - file_handler.setFormatter(formatter) - console_handler.setFormatter(formatter) - - logger.addHandler(file_handler) - logger.addHandler(console_handler) - - return logger - - -# --- Server class --- - -class GSASServer: - """Persistent GSAS-II server for fast simulations.""" - - def __init__(self, logger: logging.Logger = None): - """Initialize server (GSAS-II import happens here). - - Args: - logger: Optional logger instance. If not provided, one will be created. - """ - self.running = False - self.request_count = 0 - self.start_time = None - - # Set up logging - self.logger = logger or setup_logging(LOG_FILE) - - # Import GSAS-II (this is the slow part we want to do once) - self.logger.info("Loading GSAS-II libraries...") - import_start = time.time() - - # Set PYTHONPATH to include src directory - src_dir = Path(__file__).parent.parent - if str(src_dir) not in sys.path: - sys.path.insert(0, str(src_dir)) - - try: - # Import kicker module which has all the GSAS-II integration - from powderline import kicker - self.kicker = kicker - import_time = time.time() - import_start - self.logger.info(f"GSAS-II loaded in {import_time:.1f}s") - except ImportError as e: - self.logger.error(f"Failed to import GSAS-II: {e}") - sys.exit(1) - - def create_app(self): - """Build and return the FastAPI application.""" - from fastapi import FastAPI - - app = FastAPI(title="PowderLine GSAS-II Server") - server = self # capture for closures - - @app.post("/simulate", response_model=SimulationResponse) - def simulate(req: SimulationRequest): - server.request_count += 1 - schema_name = req.recipe_data.get('schema_name', 'unknown') if isinstance(req.recipe_data, dict) else 'unknown' - server.logger.info(f"Request #{server.request_count}: schema={schema_name}") - - result = server._run_simulation(req.model_dump()) - - elapsed = result.get('elapsed_time', 0) - run_id = result.get('run_id', 'n/a') - if result.get('success'): - server.logger.info(f"Request #{server.request_count} (run_id={run_id}) completed in {elapsed:.1f}s") - else: - server.logger.warning( - f"Request #{server.request_count} (run_id={run_id}) failed: {result.get('error', 'Unknown error')}" - ) - if result.get('traceback'): - server.logger.debug( - f"Request #{server.request_count} traceback:\n{result['traceback']}" - ) - return SimulationResponse(**result) - - @app.get("/health") - def health(): - uptime = (datetime.now() - server.start_time).total_seconds() if server.start_time else 0 - return { - "status": "ok", - "pid": os.getpid(), - "uptime_seconds": uptime, - "request_count": server.request_count, - } - - return app - - def start(self): - """Start the server with uvicorn.""" - import uvicorn - - self.start_time = datetime.now() - self.logger.info("=" * 60) - self.logger.info("GSAS-II Server Starting") - self.logger.info("=" * 60) - - # Write PID and port files - PID_FILE.write_text(str(os.getpid())) - PORT_FILE.write_text(str(PORT)) - - # Register cleanup - atexit.register(self.cleanup) - signal.signal(signal.SIGTERM, self._signal_handler) - signal.signal(signal.SIGINT, self._signal_handler) - - self.running = True - self.logger.info(f"GSAS-II server started") - self.logger.info(f" URL: http://{HOST}:{PORT}") - self.logger.info(f" Log file: {LOG_FILE}") - self.logger.info(f" PID: {os.getpid()}") - self.logger.info(f" Started: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}") - self.logger.info(f" Listening for simulation requests...") - self.logger.info("-" * 60) - - app = self.create_app() - uvicorn.run(app, host=HOST, port=PORT, log_level="warning") - - def _run_simulation(self, request: Dict[str, Any]) -> Dict[str, Any]: - """Run a GSAS-II simulation using the loaded kicker module. - - Args: - request: Dictionary with 'recipe_data' (inline recipe dict), 'output_dir', - and optional 'verbose' - - Returns: - Dictionary with keys: 'success', 'run_id', 'rwp', 'elapsed_time', - 'method', 'output_files', 'fit_profile' (dict), 'unit_cell_data' (dict), - 'peak_list_data' (dict), 'refined_parameters' (list), 'spf_peaks' (dict), - 'spf_convergence_diagnostics' (dict), and optional 'error', 'traceback'. - """ - from powderline.kicker import run_refinement - from powderline.schema import RecipeModel - from pydantic import ValidationError - - recipe_dict = request.get('recipe_data') - output_dir = Path(request['output_dir']) - verbose = request.get('verbose', False) - - if recipe_dict is None: - return { - 'success': False, - 'error': 'Missing recipe_data in request', - 'method': 'server' - } - - output_dir.mkdir(parents=True, exist_ok=True) - - # Validate recipe - try: - recipe = RecipeModel.model_validate(recipe_dict) - except ValidationError as e: - error_lines = [f"{' -> '.join(str(loc) for loc in err['loc'])}: {err['msg']}" - for err in e.errors()] - return { - 'success': False, - 'error': f"Recipe validation failed:\n" + "\n".join(error_lines), - 'method': 'server' - } - except Exception as e: - return { - 'success': False, - 'error': f"Failed to parse recipe: {str(e)}", - 'method': 'server' - } - - # Run refinement directly using loaded GSAS-II libraries - result = run_refinement(recipe, output_dir, verbose=verbose, method='server') - - return result - - def _signal_handler(self, signum, frame): - """Handle shutdown signals.""" - self.logger.info(f"Received signal {signum}, shutting down...") - self.running = False - self.cleanup() - sys.exit(0) - - def cleanup(self): - """Clean up port file and PID file.""" - if PORT_FILE.exists(): - PORT_FILE.unlink() - if PID_FILE.exists(): - PID_FILE.unlink() - - if self.start_time: - uptime = datetime.now() - self.start_time - self.logger.info(f"Server stopped") - self.logger.info(f" Total requests: {self.request_count}") - self.logger.info(f" Uptime: {uptime}") - self.logger.info("=" * 60) - - -def _pid_alive(pid: int) -> bool: - """Return True if a process with ``pid`` exists (cross-platform). - - ``os.kill(pid, 0)`` is a valid liveness probe on POSIX but not on Windows, - where ``os.kill`` terminates the target (or raises) rather than checking it; - use the Win32 API there instead. - """ - if os.name == "nt": - import ctypes - from ctypes import wintypes - - PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 - STILL_ACTIVE = 259 - kernel32 = ctypes.windll.kernel32 - handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid) - if not handle: - return False - try: - code = wintypes.DWORD() - if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)): - return False - return code.value == STILL_ACTIVE - finally: - kernel32.CloseHandle(handle) - try: - os.kill(pid, 0) - except ProcessLookupError: - return False - except PermissionError: - return True - return True - - -def is_server_running() -> bool: - """Check if server is currently running.""" - if not PID_FILE.exists(): - return False - - try: - pid = int(PID_FILE.read_text()) - except ValueError: - PID_FILE.unlink() - return False - - if _pid_alive(pid): - return True - # PID file exists but the process does not - PID_FILE.unlink() - return False - - -def stop_server() -> bool: - """Stop the running server.""" - if not is_server_running(): - print("Server is not running") - return False - - pid = int(PID_FILE.read_text()) - print(f"Stopping server (PID {pid})...") - - try: - os.kill(pid, signal.SIGTERM) - - # Wait for graceful shutdown - for _ in range(50): # 5 seconds timeout - time.sleep(0.1) - if not is_server_running(): - print("Server stopped") - return True - - # Force kill if still running. SIGKILL does not exist on Windows; - # there os.kill(pid, SIGTERM) maps to TerminateProcess (a hard kill), - # which is the correct escalation. - print("Forcing shutdown...") - force_signal = getattr(signal, "SIGKILL", signal.SIGTERM) - os.kill(pid, force_signal) - time.sleep(0.5) - - if not is_server_running(): - print("Server stopped (forced)") - return True - else: - print("Failed to stop server") - return False - - except ProcessLookupError: - print("Server process not found") - PID_FILE.unlink() - return False - - -def get_server_info() -> Optional[Dict[str, Any]]: - """Get information about the running server. - - Returns: - Dictionary with server info (pid, url, log_file, uptime) or None if not running - """ - if not is_server_running(): - return None - - try: - pid = int(PID_FILE.read_text()) - port = int(PORT_FILE.read_text()) if PORT_FILE.exists() else PORT - - # Try to get process info - import psutil - proc = psutil.Process(pid) - uptime = datetime.now() - datetime.fromtimestamp(proc.create_time()) - - return { - 'pid': pid, - 'url': f"http://{HOST}:{port}", - 'log_file': str(LOG_FILE), - 'uptime': str(uptime).split('.')[0], # Remove microseconds - 'cpu_percent': proc.cpu_percent(interval=0.1), - 'memory_mb': proc.memory_info().rss / 1024 / 1024, - } - except Exception: - # psutil not available, return basic info - port = int(PORT_FILE.read_text()) if PORT_FILE.exists() else PORT - return { - 'pid': pid, - 'url': f"http://{HOST}:{port}", - 'log_file': str(LOG_FILE), - } - - -def main(): - """Main entry point for server management.""" - import argparse - - parser = argparse.ArgumentParser(description="GSAS-II persistent server") - subparsers = parser.add_subparsers(dest='action', help='Server action') - - subparsers.add_parser('start', help='Start the server') - subparsers.add_parser('stop', help='Stop the server') - subparsers.add_parser('status', help='Show server status') - subparsers.add_parser('restart', help='Restart the server') - subparsers.add_parser('logs', help='Show recent server logs') - - args = parser.parse_args() - action = args.action or 'status' # Default to status if no action - - if action == 'start': - if is_server_running(): - print("Server is already running") - print(f" PID: {PID_FILE.read_text()}") - port = int(PORT_FILE.read_text()) if PORT_FILE.exists() else PORT - print(f" URL: http://{HOST}:{port}") - print(f"\n To view logs: tail -f {LOG_FILE}") - sys.exit(1) - - print("Starting GSAS-II server...") - logger = setup_logging(LOG_FILE) - server = GSASServer(logger) - server.start() - - elif action == 'stop': - stop_server() - - elif action == 'status': - info = get_server_info() - if info: - print(f"Server is running") - print(f" PID: {info['pid']}") - print(f" URL: {info['url']}") - print(f" Log file: {info['log_file']}") - if 'uptime' in info: - print(f" Uptime: {info['uptime']}") - if 'cpu_percent' in info: - print(f" CPU: {info['cpu_percent']:.1f}%") - if 'memory_mb' in info: - print(f" Memory: {info['memory_mb']:.1f} MB") - print(f"\n To view logs: tail -f {info['log_file']}") - else: - print("Server is not running") - print(f"\n To start: pixi run gsas-server start") - print(f" Log file: {LOG_FILE}") - sys.exit(1) - - elif action == 'restart': - if is_server_running(): - stop_server() - time.sleep(1) - - print("Starting GSAS-II server...") - logger = setup_logging(LOG_FILE) - server = GSASServer(logger) - server.start() - - elif action == 'logs': - if not LOG_FILE.exists(): - print(f"Log file not created yet: {LOG_FILE}") - sys.exit(0) - - print(f"Recent logs from {LOG_FILE}:") - print(" (showing last 50 lines)") - print("-" * 60) - - try: - # Show last 50 lines - with open(LOG_FILE, 'r') as f: - lines = f.readlines() - for line in lines[-50:]: - print(line.rstrip()) - except Exception as e: - print(f"Failed to read log file: {e}") - sys.exit(1) - - print("-" * 60) - print(f" To follow logs in real-time: tail -f {LOG_FILE}") - - -if __name__ == '__main__': +from powderline.gateways.gsasii.server import ( # noqa: F401 + HOST, + DEFAULT_PORT, + PORT, + PORT_FILE, + PID_FILE, + LOG_FILE, + SimulationRequest, + SimulationResponse, + setup_logging, + GSASServer, + _pid_alive, + is_server_running, + stop_server, + get_server_info, + main, +) + +if __name__ == "__main__": main() diff --git a/src/powderline/kicker.py b/src/powderline/kicker.py index 88a31d4..36f3ddc 100644 --- a/src/powderline/kicker.py +++ b/src/powderline/kicker.py @@ -32,113 +32,70 @@ from powderline._status import CHECK, CROSS, INFO, WARN, emoji from dataclasses import dataclass -# Standard naming (file-less, no sample_name) -@dataclass -class OutputNamingConfig: - """Standard naming for file-less refinements.""" - gpx_filename: str = "dummy.gpx" - histogram_name: str = "PWDR dummy" - lst_filename: str = "dummy.lst" # GSAS-II generates .lst with same basename as .gpx - -OUTPUT_NAMING = OutputNamingConfig() - -# TODO: In phase 2 move these defaults upstream for the recipe creation process. -# Further default parameters and values include refinement flags (False) -DEFAULT_HIST_SCALE_VAL = 1.0 -DEFAULT_HIST_SCALE_REFINE_FLAG = False -# TODO: Phase 2 upstream recipe builder — will be used when setting default peak broadening parameters -DEFAULT_PHASE_CRYSTALLITE_SIZE = 10 # isotropic crystallite size in microns -# TODO: Phase 2 upstream recipe builder — will be used when setting default peak broadening parameters -DEFAULT_PHASE_MICROSTRAIN = 0.0 # isotropic microstrain -DEFAULT_SPF_SIGMA_MIN = 0.0001 # Minimum sigma_sq value for single peak fitting (centidegrees) -DEFAULT_SPF_GAMMA_MIN = 0.0001 # Minimum gamma value for single peak fitting (centidegrees) - - -def unpack_refinement_parameter(param: list | None, param_name: str = "parameter") -> tuple[Any, Any, Any, Any]: - """ - Unpack refinement parameter from [value, refine_flag, min, max] format. - - This utility reduces boilerplate for the common pattern of unpacking refinement - parameters throughout the codebase. Use only in straightforward cases - complex - conditional logic should inline the unpacking for clarity. - - Args: - param: RefinementParameter list [value, refine_flag, min, max] or None - param_name: Name of parameter for error messages (optional) - - Returns: - Tuple of (value, refine_flag, min_val, max_val) - If param is None, returns (None, None, None, None) - - Raises: - ValueError: If param is neither list nor None - - Examples: - >>> value, refine_flag, min_val, max_val = unpack_refinement_parameter([1.0, True, None, None]) - >>> value, refine_flag, min_val, max_val = unpack_refinement_parameter(None) - """ - if param is None: - return (None, None, None, None) - elif isinstance(param, list): - if len(param) != 4: - raise ValueError( - f"{param_name} must be a list of exactly 4 elements " - f"[value, refine_flag, min, max], got {len(param)} elements" - ) - return tuple(param) - else: - raise ValueError( - f"{param_name} must be a list [value, refine_flag, min, max] or None, " - f"got {type(param).__name__}" - ) - - -def require_phase(error_suffix: str): - """ - Decorator to check phase existence in project before calling setter functions. - - Args: - error_suffix: The error message suffix (e.g., "Cannot set scale.") - - The decorated function must accept 'proj' as first positional arg and 'phase_name' - as a keyword or positional arg (position determined by inspection). - - Raises: - ValueError: If phase_name is not found in proj.phases() - """ - from functools import wraps - import inspect - - def decorator(func): - sig = inspect.signature(func) - # Decoration-time misuse check: decorated functions must take these args. - assert 'proj' in sig.parameters and 'phase_name' in sig.parameters - - @wraps(func) - def wrapper(*args, **kwargs): - # Find proj and phase_name from args/kwargs - try: - bound = sig.bind(*args, **kwargs) - except TypeError: - # Missing/extra arguments: call through so Python raises the - # function's native signature error, as the undecorated - # function would. - return func(*args, **kwargs) - bound.apply_defaults() - - proj = bound.arguments['proj'] - phase_name = bound.arguments['phase_name'] - - # Perform the phase existence check unconditionally — the original - # inline checks treated phase_name=None as a missing phase - # (ValueError) and proj=None as an AttributeError; both semantics - # are preserved by not special-casing None. - if phase_name not in [p.name for p in proj.phases()]: - raise ValueError(f"Phase '{phase_name}' not found in project. {error_suffix}") - - return func(*args, **kwargs) - return wrapper - return decorator +# Backward-compatible re-exports: the GSAS-II implementation moved to +# powderline.gateways.gsasii (multi-engine refactor, re/01). These keep every +# existing ``powderline.kicker.`` import working; removed in a later branch. +from powderline.gateways.gsasii.helpers import ( # noqa: F401 + OutputNamingConfig, + OUTPUT_NAMING, + DEFAULT_HIST_SCALE_VAL, + DEFAULT_HIST_SCALE_REFINE_FLAG, + DEFAULT_PHASE_CRYSTALLITE_SIZE, + DEFAULT_PHASE_MICROSTRAIN, + DEFAULT_SPF_SIGMA_MIN, + DEFAULT_SPF_GAMMA_MIN, + unpack_refinement_parameter, + require_phase, + calculate_peak_widths, + has_active_refinement_parameter, +) +from powderline.gateways.gsasii.project import ( # noqa: F401 + InstParmValue, + InstParmDict, + G2InstParmDict, + _to_gsasii_instparm_dict, + add_powder_histogram_from_arrays, + add_phase_from_cif_dict, + add_phases_from_dict, +) +from powderline.gateways.gsasii.setters import ( # noqa: F401 + set_hist_scale, + set_fit_range_hist, + set_chebyshev_background, + set_single_peak_background, + set_single_peaks, + set_phase_scale, + set_phase_unit_cell, + set_phase_size_broadening, + _set_isotropic_size_broadening, + set_phase_strain_broadening, + _set_isotropic_strain_broadening, + set_phase_atom_parameters, + set_phase_parameterization, + set_instrument_parameterization, + set_refinement_cycles, +) +from powderline.gateways.gsasii.executors import ( # noqa: F401 + _refine_with_message, + execute_rietveld_refinement, + execute_spf_refinement, + SCHEMA_EXECUTORS, + run_refinement, +) +from powderline.gateways.gsasii.extractors import ( # noqa: F401 + calculate_cell_esds_from_A_matrix, + extract_refined_params_from_project, + extract_refined_params_from_lst, + get_descriptive_param_name, + parse_parameter_associations, + build_phase_name_mapping, + build_atom_name_mapping, + export_refined_parameters_csv, + _extract_fit_profile, + _extract_spf_peak_report, + _extract_phase_reports, + _extract_refined_parameters, +) def load_recipe_asset(recipe_path: Path) -> dict: @@ -171,3157 +128,223 @@ def is_template_file(recipe_dict: dict, input_path: Path) -> tuple[bool, str | N Examples: >>> is_template_file({}, Path("example_template/input.json")) - (True, "filename or path contains 'template'") - - >>> is_template_file({"schema_name": "GSASII_Rietveld", "payload": {"xrd_data": {...}}}, Path("example_LaB6/input.json")) - (False, None) - """ - # Check 1: Path contains "template" - if "template" in str(input_path).lower(): - return True, "filename or path contains 'template'" - - # Check 2: Missing payload or schema-specific required fields - payload = recipe_dict.get('payload', {}) - if not payload: - return True, "missing payload" - - # Check for schema-specific required fields - schema_name = recipe_dict.get('schema_name') - if schema_name == 'GSASII_Rietveld': - required_fields = ['xrd_data', 'instrument', 'phases', 'refinement_controls'] - missing = [field for field in required_fields if field not in payload or payload[field] is None] - if missing: - return True, f"GSASII_Rietveld schema missing required fields: {missing}" - elif schema_name == 'GSASII_SPF': - required_fields = ['xrd_data', 'instrument', 'single_peaks', 'refinement_controls'] - missing = [field for field in required_fields if field not in payload or payload[field] is None] - if missing: - return True, f"GSASII_SPF schema missing required fields: {missing}" - else: - # Fallback: check for common core fields if schema unknown - core_fields = ['xrd_data', 'instrument', 'refinement_controls'] - missing_core = [field for field in core_fields if field not in payload] - if len(missing_core) == len(core_fields): - return True, "missing all required fields in payload (xrd_data, instrument, refinement_controls)" - - return False, None - - -def calculate_peak_widths(sigma: float, gamma: float) -> tuple[float, float, float, float, float, float, bool, str | None]: - """ - Calculate FWHM and integral breadth values for Gaussian, Lorentzian, and pseudo-Voigt peak shapes. - - Parameters: - sigma: Squareroot of Gaussian width variance. No units assumed. - gamma: Lorentzian width parameter (HWHM). No units assumed. - - Returns: - Tuple of (fwhm_gaussian, fwhm_lorentzian, fwhm_pseudovoigt, - ib_gaussian, ib_lorentzian, ib_pseudovoigt, valid, warning_msg) - valid: True if calculation succeeded (even with aphysical values), False for NaN/inf - warning_msg: String describing any issues, or None if none - - NOTE: This functions differs from GSAS-II's internal getgamFW() which uses gamma as FWHM_L. - Conventionally, gamma is HWHM_L. This function uses gamma as HWHM_L for consistency with scipy, TOPAS, and literature. - """ - import warnings - warning_msg = None - - # FWHM for Gaussian component - fwhm_g = 2.0 * np.sqrt(2.0 * np.log(2.0)) * sigma # ≈ 2.35482 * sigma - - # FWHM for Lorentzian component - NOTE: GSAS-II uses gamma = FWHM_L, not gamma = HWHM_L. - fwhm_l = 2.0 * gamma - - # Pseudo-Voigt FWHM approximation (Thompson et al. 1987) - fwhm_pv = (fwhm_g**5 + 2.69269*fwhm_g**4*fwhm_l + 2.42843*fwhm_g**3*fwhm_l**2 + - 4.47163*fwhm_g**2*fwhm_l**3 + 0.07842*fwhm_g*fwhm_l**4 + fwhm_l**5)**(1/5) - - try: - gsas_fwhm = G2pwd.getgamFW(fwhm_l, sigma) # Call GSAS-II function - use FWHM_L (=gamma from SPF) and sigma - if abs(fwhm_pv - gsas_fwhm) > 0.01 * abs(gsas_fwhm): # >1% difference - msg = f"Calculated FWHM ({fwhm_pv:.6f}) differs from GSAS-II ({gsas_fwhm:.6f})" - warnings.warn(msg) - warning_msg = msg if warning_msg is None else f"{warning_msg}; {msg}" - except Exception as e: - # GSAS-II function may fail with negative values - msg = f"GSAS-II getgamFW() failed: {str(e)}" - warnings.warn(msg) - warning_msg = msg if warning_msg is None else f"{warning_msg}; {msg}" - - # Integral breadths - # For Gaussian: IB = FWHM * sqrt(π / (4 * ln(2))) ≈ FWHM * 1.0645 - ib_g = fwhm_g * np.sqrt(np.pi / (4.0 * np.log(2.0))) - - # For Lorentzian: IB = π * HWHM = π * gamma = (π/2) * FWHM - ib_l = np.pi * gamma # or equivalently: fwhm_l * np.pi / 2.0 - - # For pseudo-Voigt: approximate using convolution relationship - # IB_pV ≈ η * IB_L + (1-η) * IB_G, where η is mixing parameter - # Simplified approximation (may need refinement based on actual η calculation) - try: - eta = 1.36603 * (fwhm_l / fwhm_pv) - 0.47719 * (fwhm_l / fwhm_pv)**2 + 0.11116 * (fwhm_l / fwhm_pv)**3 - ib_pv = eta * ib_l + (1.0 - eta) * ib_g - except (ZeroDivisionError, RuntimeWarning): - ib_pv = np.nan - warning_msg = "Failed to calculate pseudo-Voigt integral breadth" if warning_msg is None else f"{warning_msg}; eta calculation failed" - - return fwhm_g, fwhm_l, fwhm_pv, ib_g, ib_l, ib_pv, True, warning_msg - - -def validate_simulation_mode_parameters(recipe: RecipeModel, verbose: bool = False) -> tuple[bool, List[str]]: - """ - Validate that simulation mode examples have all refinement parameters locked. - - Simulation mode (refinement_cycles=1 with all parameters fixed) must have deterministic - output. This function checks for any `refine_flag: true` in structural or background - parameters that would violate determinism. - - Args: - recipe: Validated RecipeModel instance (uses payload structure) - verbose: If True, print detailed parameter checks - - Returns: - (is_valid, warnings): is_valid is True if all parameters are properly locked, - warnings is a list of issues found (empty if valid). - - Examples: - >>> is_valid, warnings = validate_simulation_mode_parameters(recipe) - >>> if not is_valid: - ... for warning in warnings: - ... print(f"WARNING: {warning}") - """ - is_valid = True - warnings: List[str] = [] - - # Get refinement controls (in payload) - controls = recipe.payload.refinement_controls - - # Only check simulation mode (refinement_cycles == 1) - if controls.refinement_cycles != 1: - return True, [] # Not simulation mode, skip validation - - if verbose: - print("Validating simulation mode constraints...") - - # Check background parameters - if recipe.payload.background is not None: - if recipe.payload.background.chebyshev is not None: - if recipe.payload.background.chebyshev.refine_flag: - msg = "CRITICAL: Chebyshev background has refine_flag=true in simulation mode (refinement_cycles=1). " \ - "This violates determinism - all parameters must be locked. Set refine_flag=false." - warnings.append(msg) - is_valid = False - if verbose: - print(f" {CROSS} {msg}") - - if recipe.payload.background.single_peaks is not None: - # Check single peak parameters - param_lists = [ - (recipe.payload.background.single_peaks.positions, "single_peaks.positions"), - (recipe.payload.background.single_peaks.intensities, "single_peaks.intensities"), - (recipe.payload.background.single_peaks.pv_gaussian_sigma, "single_peaks.pv_gaussian_sigma"), - (recipe.payload.background.single_peaks.pv_lorentzian_gamma, "single_peaks.pv_lorentzian_gamma"), - ] - for param_list, param_name in param_lists: - if param_list is not None: - for i, param in enumerate(param_list): - if param[1]: # refine_flag is second element - msg = f"WARNING: {param_name}[{i}] has refine_flag=true in simulation mode. " \ - "Set refine_flag=false for deterministic output." - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check instrument parameterization - if recipe.payload.instrument.parameterization is not None: - param_dict = recipe.payload.instrument.parameterization.model_dump(mode='json') - - # Check wavelength - if param_dict.get('wavelength') and param_dict['wavelength'][1]: - msg = "WARNING: instrument.parameterization.wavelength has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check broadening parameters - if param_dict.get('broadening'): - for param_key, param_value in param_dict['broadening'].items(): - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: instrument.parameterization.broadening.{param_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check corrections - if param_dict.get('corrections'): - for param_key, param_value in param_dict['corrections'].items(): - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: instrument.parameterization.corrections.{param_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check phase-level parameters (only if phases exist) - if recipe.payload.phases is not None: - phases_dict = recipe.payload.model_dump(mode='json')['phases'] - for phase_name, phase_info in phases_dict.items(): - param_dict = phase_info.get('parameterization', {}) - - # Check scale - if param_dict.get('scale') and param_dict['scale'][1]: - msg = f"WARNING: phases.{phase_name}.parameterization.scale has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check unit cell - unit_cell = param_dict.get('unit_cell', {}) - if unit_cell: - for cell_param, param_value in unit_cell.items(): - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: phases.{phase_name}.parameterization.unit_cell.{cell_param} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check peak broadening - peak_broadening = param_dict.get('peak_broadening', {}) - if peak_broadening: - # Check size broadening - if peak_broadening.get('size_broadening'): - for param_key, param_value in peak_broadening['size_broadening'].items(): - if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) - continue - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.size_broadening.{param_key} has refine_flag=true" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check strain broadening - if peak_broadening.get('strain_broadening'): - for param_key, param_value in peak_broadening['strain_broadening'].items(): - if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) - continue - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.strain_broadening.{param_key} has refine_flag=true" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check atom parameters (using same logic as has_active_refinement_parameter for consistency) - atoms = param_dict.get('atoms', {}) - if atoms: - for atom_label, atom_params in atoms.items(): - for param_key, param_value in atom_params.items(): - # Skip ADP field (it's a string, not a RefinementParameter) - if param_key == 'ADP': - continue - - # Handle Uaniso nested dict - if param_key == 'Uaniso' and isinstance(param_value, dict): - for uaniso_key, uaniso_value in param_value.items(): - if isinstance(uaniso_value, list) and len(uaniso_value) >= 2 and uaniso_value[1]: - msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.Uaniso.{uaniso_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check regular RefinementParameter lists (use elif to avoid checking lists after Uaniso) - elif isinstance(param_value, list) and len(param_value) >= 2 and param_value[1]: - msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.{param_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - if verbose: - if is_valid: - print(f"{CHECK} All parameters properly locked for simulation mode determinism") - - return is_valid, warnings - -# Functions to add histogram with instrument parameters from recipe.xrd_data (dict with arrays) and recipe.instrument.initialization (list of dicts) - -InstParmValue = Union[float, int, str, Sequence[Any]] -InstParmDict = Dict[str, InstParmValue] -G2InstParmDict = Dict[str, List[Any]] # values like [val, val, 0] - -def _to_gsasii_instparm_dict(flat: InstParmDict) -> G2InstParmDict: - """ - Convert a "flat" instrument parameter dictionary (values as scalars/strings) - into the GSAS-II scripting format where each value is a 3-item list: - - key: [value, value, refinement_flag] - - Examples (GSAS-II format): - "Type": ["PXC", "PXC", False] - "U": [2.0, 2.0, False] - - If the value already looks like a GSAS-II 3-item list/tuple, it is passed through. - - Notes - ----- - GSAS-II's scriptable examples show this 3-item-list structure for direct - instrument parameter specification. - """ - out: G2InstParmDict = {} - - for k, v in flat.items(): - # Already in GSAS-II form? - if isinstance(v, (list, tuple)) and len(v) == 3: - out[k] = list(v) - continue - - # Otherwise convert scalar/string -> [v, v, False] - out[k] = [v, v, False] - - # Ensure a few expected keys exist where possible - if "Bank" in out: - # normalize Bank to int-ish in the first two slots when possible - try: - b = int(float(out["Bank"][0])) - out["Bank"] = [b, b, out["Bank"][2]] - except Exception: - pass - - return out - - -def add_powder_histogram_from_arrays( - proj, - tth_array: Union[np.ndarray, Sequence[float]], - intensity_array: Union[np.ndarray, Sequence[float]], - intensity_weights_array: Union[np.ndarray, Sequence[float]], - histogram_name: str, - instrument_prm_dict: Dict[str, Any], - *, - comments: Optional[List[str]] = None, - phases: Union[None, str, Sequence[Any]] = None, -): - """ - Create a GSAS-II powder histogram inside an in-memory GSASIIscriptable project, - using arrays rather than reading a powder data file from disk. - - Parameters - ---------- - proj - A `GSASIIscriptable.G2Project` instance (e.g. created with `G2Project(newgpx='dummy')`). - - tth_array, intensity_array, intensity_weights_array - 1D arrays (same length) for 2θ (degrees), Iobs, and weights. - Weights are used directly in the histogram. - Default weighting (set in phase 2, the recipe creator) is 1 / sigma**2 where sigma is the uncertainty in the intensity (default is SQRT(Iobs)). - - histogram_name - Name to use for the histogram. If it does not start with "PWDR ", - the prefix is added. If the name collides with an existing histogram, - it is made unique using `G2obj.MakeUniqueLabel`. - TODO: catch non-unique names in phase2 (recipe creator) - - instrument_prm_dict - Instrument parameters. This can be either: - * a "flat" dict with scalars/strings (your current format), or - * a GSAS-II scripting-format dict where each value is a 3-item list - like `[val, val, False]`. - - This function will convert flat dicts into the GSAS-II scripting format. - - The histogram will store instrument parameters as `[Iparm1, Iparm2]`, - where Iparm2 is an empty dict (typical for CW lab/synchrotron usage). - - comments - Optional list of strings for the histogram "Comments" entry. Default is []. - - phases - Optional linking behavior, mirroring `add_powder_histogram`: - * None: do not link phases - * 'all': link all phases in the project - * sequence: link the listed phases (objects/names/rIds/etc) - - (Linking is not needed for your current test requirement, but it’s here - so the histogram is inserted in the same place in the project tree and - can be linked the same way.) - - Returns - ------- - hist - A `G2PwdrData` histogram wrapper object from `proj.histogram(histname)`. - - Implementation notes - -------------------- - This function intentionally mirrors the internal GSAS-II construction performed - in `GSASIIscriptable.load_pwd_from_reader` for the output histogram dictionary: - keys, `data` packing, defaults for background and peaks, and ID handling. - - Because this builds the same dict structure GSAS-II uses, the project is GUI-compatible - if later saved, and downstream GSAS-II operations (background fitting/refinement/etc.) - see the histogram in the expected format. - """ - # ---- Validate/normalize arrays - x = np.asarray(tth_array, dtype=float).ravel() - y = np.asarray(intensity_array, dtype=float).ravel() - w = np.asarray(intensity_weights_array, dtype=float).ravel() - - # GSAS-II powderdata commonly holds 6 arrays (obs, weights, calc, bkg, diff) - ycalc = np.zeros_like(y) - ybkg = np.zeros_like(y) - ydiff = np.zeros_like(y) - - powderdata = [x, y, w, ycalc, ybkg, ydiff] - - # ---- Instrument parameters: convert flat dict -> GSAS-II list-of-3 form if needed - Iparm1 = _to_gsasii_instparm_dict(instrument_prm_dict) - Iparm2: Dict[str, Any] = {} - - # Sanity: Type must be present and be list-like for GSAS-II-style indexing - if "Type" not in Iparm1 or not isinstance(Iparm1["Type"], list) or len(Iparm1["Type"]) < 1: - raise ValueError( - "instrument_prm_dict must define 'Type' (e.g. 'PXC'), " - "and after conversion it must be list-like (e.g. ['PXC','PXC', False])." - ) - - # TODO: in phase 2 (recipe creator), the full histname including 'PWDR' will be validated upstream. - # ---- Histogram naming: match GSAS-II convention - HistName = histogram_name.strip() - if not HistName.startswith("PWDR "): - HistName = "PWDR " + HistName - - # TODO: in phase 2 (recipe creator), a check for existing histogram names will be done. - # Make unique vs existing histogram names - existing = [h.name for h in proj.histograms()] # GSASIIscriptable method - HistName = G2obj.MakeUniqueLabel(HistName, existing) - - # ---- Mirror load_pwd_from_reader value packing and defaults - Ymin = float(np.min(y)) - Ymax = float(np.max(y)) - - # TODO: in phase 2 (recipe creator), the random ID generation will be done upstream using a schema check. - - valuesdict = { - "wtFactor": 1.0, - "Dummy": False, - "ranId": ran.randint(0, sys.maxsize), - "Offset": [0.0, 0.0], - "delOffset": 0.02 * Ymax, - "refOffset": -0.1 * Ymax, - "refDelt": 0.1 * Ymax, - "Yminmax": [Ymin, Ymax], - } - - Tmin = float(np.min(x)) - Tmax = float(np.max(x)) - Tmin1 = Tmin - - # Keep the small special-case from load_pwd_from_reader for NT data - try: - if "NT" in Iparm1["Type"][0] and G2lat.Pos2dsp(Iparm1, Tmin) < 0.4: - Tmin1 = float(G2lat.Dsp2pos(Iparm1, 0.4)) - except Exception: - # If Pos2dsp fails (unlikely for PXC), ignore - pass - - # TODO: in phase 2 (recipe creator), the default background will be set upstream using a schema check. - default_background = [ - ["chebyschev-1", False, 3, 1.0, 0.0, 0.0], - {"nDebye": 0, "debyeTerms": [], "nPeaks": 0, "peaksList": [], "background PWDR": ["", 1.0, False]}, - ] - - sample = G2obj.SetDefaultSample() - sample["ranId"] = valuesdict["ranId"] # matches load_pwd_from_reader behavior - # If Azimuth supplied in inst parms, copy into sample (nice-to-have consistency) - try: - if "Azimuth" in Iparm1 and isinstance(Iparm1["Azimuth"], list): - sample["Azimuth"] = float(Iparm1["Azimuth"][0]) - except Exception: - pass - - output_dict = { - "Reflection Lists": {}, - "Limits": [(Tmin, Tmax), [Tmin1, Tmax]], - "data": [valuesdict, powderdata, HistName], - "Index Peak List": [[], []], - "Comments": comments if comments is not None else [], - "Unit Cells List": [], - "Sample Parameters": sample, - "Peak List": {"peaks": [], "sigDict": {}}, - "Background": default_background, - "Instrument Parameters": [Iparm1, Iparm2], - } - - # Tree ordering list matches load_pwd_from_reader - section_names = [ - "Comments", - "Limits", - "Background", - "Instrument Parameters", - "Sample Parameters", - "Peak List", - "Index Peak List", - "Unit Cells List", - "Reflection Lists", - ] - new_names = [HistName] + section_names - - # ---- Insert into project in the same way add_powder_histogram does - if HistName in proj.data: - # keep behavior: redefine with a warning-like action - try: - import GSASIIfiles as G2fil - G2fil.G2Print("Warning - redefining histogram", HistName) - except Exception: - pass - - # proj.names is a list of "tree entries"; match add_powder_histogram insertion point - if proj.names and proj.names[-1][0] == "Phases": - proj.names.insert(-1, new_names) - else: - proj.names.append(new_names) - - proj.data[HistName] = output_dict - proj.update_ids() - - # Optional phase linking (mirrors add_powder_histogram flow) - if phases == "all": - phases = proj.phases() - if phases: - for ph in phases: - ph_obj = proj.phase(ph) - proj.link_histogram_phase(HistName, ph_obj) - - return proj.histogram(HistName) - - -# By default (G2obj.SetSampleDefault() called when adding histogram) histogram scale set to refine -def set_hist_scale(proj: Any, hist: Any, hist_scale_val: float = 1.0, hist_scale_refine_flag: bool = False, print_info: bool = False) -> None: - """Set histogram scale and refine flag.""" - proj.data[hist.name]['Sample Parameters']['Scale'] = [hist_scale_val, hist_scale_refine_flag] - if print_info: - print(f"Set histogram scale to {hist_scale_val} with refine flag {hist_scale_refine_flag} for histogram {hist.name}") - - -def set_fit_range_hist(hist: Any, fit_range: tuple[float | None, float | None], print_info: bool = False) -> None: - """Set fit range for histogram in GSAS-II project.""" - min_val, max_val = fit_range - old_limits = hist.data['Limits'][1].copy() # this is a view on the object, need to save old limits before changing - if min_val is not None: - hist.data['Limits'][1][0] = min_val - if max_val is not None: - hist.data['Limits'][1][1] = max_val - if print_info: - print('Updated fit limits in hist from ', old_limits, 'to', hist.data['Limits'][1]) - - -def set_chebyshev_background(proj: Any, hist: Any, chebyshev_dict: dict, print_info: bool = False) -> None: - """ - Set the Chebyshev background for a given histogram. - - Chebyshev polynomials provide smooth curved backgrounds. Coefficients start - at 0th order (constant term) and increase: [c0, c1, c2, ...] represents - c0 + c1*T1(x) + c2*T2(x) + ... where Tn are Chebyshev polynomials. - - The function manipulates proj.data[hist.name]['Background'][0] which has structure: - [background_type, refine_flag, num_coefficients, c0, c1, c2, ...] - - Parameters: - proj: GSAS-II project object containing the histogram - hist: Histogram object to set the background for - chebyshev_dict: Dictionary containing Chebyshev background parameters: - - num_coefficients (int): Number of Chebyshev coefficients - - coefficients (list[float]): Coefficient values [c0, c1, c2, ...] - - refine_flag (bool): Whether to refine background during fitting - print_info: If True, print background configuration to stdout - - Returns: - None - - Raises: - ValueError: If number of coefficients doesn't match list length or - required background entries are missing - - Examples: - >>> chebyshev_dict = { - ... 'num_coefficients': 3, - ... 'coefficients': [100.0, -50.0, 10.0], - ... 'refine_flag': True - ... } - >>> set_chebyshev_background(proj, hist, chebyshev_dict) - """ - # First parse the chebyshev_dict - num_coefficients = chebyshev_dict.get('num_coefficients') - coefficients = chebyshev_dict.get('coefficients') - refine_flag = chebyshev_dict.get('refine_flag') - - # Defaults are not provided because those will be provided upstream - # None will be caught in validation and trigger a default assignment. - # The code below is an example of how to handle defaults here if needed. - - # This should be enforced with the pydantic schema when loading the recipe - if coefficients is None: - coefficients = [0.0] * num_coefficients - - if num_coefficients != len(coefficients): - raise ValueError( - "Number of coefficients does not match the length of the coefficients list." - ) - - chebyshev_bkg = proj.data[hist.name]['Background'][0] - - # Check for default entries (type, refine flag, num coefficients) - if len(chebyshev_bkg) < 3: - raise ValueError("Chebyshev background list missing required entries. type, refine flag, num coefficients should be present by default.") - - # Set number of coefficients - chebyshev_bkg[2] = num_coefficients - - # Pad or truncate the coefficients list in chebyshev_bkg to match num_coefficients - # This would be done in an earlier validation step! - needed_len = num_coefficients + 3 - if len(chebyshev_bkg) < needed_len: - chebyshev_bkg.extend([0.0] * (needed_len - len(chebyshev_bkg))) - elif len(chebyshev_bkg) > needed_len: - del chebyshev_bkg[needed_len:] # in-place truncate - - # Set coefficients - for i, coeff in enumerate(coefficients): - chebyshev_bkg[i + 3] = coeff - - # Set refine flag - chebyshev_bkg[1] = refine_flag - - if print_info: - print(f"Chebyshev background set with {chebyshev_bkg[2]} coeffiencients, refine_flag={chebyshev_bkg[1]}") - print(f"Coefficients: {chebyshev_bkg[3:3+chebyshev_bkg[2]]}") - - -# function to set single peak background -# this should be a rather exposed function -# e.g., take lists of positions, intensities, sigmas, gammas, refine flags, etc. -# This function should expect inputs from the background_dict['single_peaks'] structure - -def set_single_peak_background(proj: Any, hist: Any, bkg_single_peaks_dict: dict, print_info: bool = False) -> None: - """ - Set single peak background for histogram using pseudo-Voigt profiles. - - Single peaks are useful for modeling known impurity peaks or other non-background - features that shouldn't be included in the main phase refinement. Each peak is - described by a pseudo-Voigt profile (weighted sum of Gaussian and Lorentzian). - - Peak profile: I(2θ) = intensity * [η*L(2θ) + (1-η)*G(2θ)] - where: - - G(2θ) is Gaussian with width sigma - - L(2θ) is Lorentzian with width gamma - - η (eta) is mixing parameter (0=pure Gaussian, 1=pure Lorentzian) - - Args: - proj: GSAS-II project object - hist: Histogram object to set single peaks for - bkg_single_peaks_dict: Dictionary with keys: - - positions: List of [[2θ, refine, min, max], ...] for peak positions - - intensities: List of [[I, refine, min, max], ...] for peak heights - - pv_gaussian_sigma: List of [[σ, refine, min, max], ...] for Gaussian widths - - pv_lorentzian_gamma: List of [[γ, refine, min, max], ...] for Lorentzian widths - All lists must have same length (number of peaks) - print_info: If True, print peak configuration to stdout - - Returns: - None - - Raises: - ValueError: If parameter lists have inconsistent lengths - - Examples: - >>> # Two single peaks at 2θ=35.5° and 42.0° - >>> single_peaks = { - ... 'positions': [[35.5, False, None, None], [42.0, False, None, None]], - ... 'intensities': [[50.0, True, None, None], [30.0, True, None, None]], - ... 'pv_gaussian_sigma': [[0.1, False, None, None], [0.1, False, None, None]], - ... 'pv_lorentzian_gamma': [[0.05, False, None, None], [0.05, False, None, None]] - ... } - >>> set_single_peak_background(proj, hist, single_peaks) - """ - """ - Set the single peak background for a given histogram. - - Parameters: - proj: object - The GSAS-II project containing the histogram. - hist : object - The histogram to set the background for. - bkg_single_peaks_dict : dict - Dictionary containing single peak background parameters: - - positions : list of [float, bool, float, float]. Indices 2 and 3 can be None. - List of [position value, refine flag, min, max] for each peak. - These are two-theta values. Q / d can be passed upstream and converted in validation. - - intensities: list of [float, bool, float, float]. Indices 2 and 3 can be None. - List of [intensity value, refine flag, min, max] for each peak. - - pv_gaussian_sigma: list of [float, bool, float, float]. Indices 2 and 3 can be None. - List of [gaussian sigma value, refine flag, min, max] for each peak. - - pv_lorentzian_gamma: list of [float, bool, float, float]. Indices 2 and 3 can be None. - List of [lorentzian gamma value, refine flag, min, max] for each peak. - print_info : bool - Whether to print information about the set background. - Returns: - None - """ - # Parse the bkg_single_peaks_dict - positions = bkg_single_peaks_dict.get('positions', []) - intensities = bkg_single_peaks_dict.get('intensities', []) - gaussian_sigmas = bkg_single_peaks_dict.get('pv_gaussian_sigma', []) - lorentzian_gammas = bkg_single_peaks_dict.get('pv_lorentzian_gamma', []) - - # Default intensity, sigma, gamma values to use if value input is None - # TODO: Phase 2 upstream recipe builder — these defaults will be set before calling this function - # default_intensity = 1.0 - # default_sigma = 0.1 - # default_gamma = 0.1 - # default_refine_flag = False - - # Validate that all input lists have the same length - if not (len(positions) == len(intensities) == len(gaussian_sigmas) == len(lorentzian_gammas)): - raise ValueError("All input lists must have the same length.") - - num_peaks = len(positions) # only used for looping - - # Construct the single peak background list - single_peak_bkg = [] - - for i in range(num_peaks): - pos, pos_refine, pos_min, pos_max = positions[i] - inten, inten_refine, inten_min, inten_max = intensities[i] - g_sigma, g_refine, g_sigma_min, g_sigma_max = gaussian_sigmas[i] - l_gamma, l_refine, l_gamma_min, l_gamma_max = lorentzian_gammas[i] - - # TODO: move default behavior upstream - # # Use default values if None provided - # if inten is None: - # inten = default_intensity - # if g_sigma is None: - # g_sigma = default_sigma - # if l_gamma is None: - # l_gamma = default_gamma - - # # Use default refine flags if None provided - # if pos_refine is None: - # pos_refine = default_refine_flag - # if inten_refine is None: - # inten_refine = default_refine_flag - # if g_refine is None: - # g_refine = default_refine_flag - # if l_refine is None: - # l_refine = default_refine_flag - - # Min / max not currently available in GSAS-II single peak background definition - # They can be stored upstream for reference, but not used downstream currently. - # [placeholder for code to handle min/max if needed in future] - - # Append peak parameters to the single peak background list - # Each peak is a list: - # [pos, pos_refine, inten, inten_refine, g_sigma, g_refine, l_gamma, l_refine] - if None in [pos, pos_refine, - inten, inten_refine, - g_sigma, g_refine, - l_gamma, l_refine]: - continue - - # We only append if there are no Nones - this is a temp fix before phase2 - # TODO: update this behavior in the future when this list will only be passed with valid contents - single_peak_bkg.append([pos, pos_refine, - inten, inten_refine, - g_sigma, g_refine, - l_gamma, l_refine]) - - # Append the single peak background to the histogram's background list - if proj.data[hist.name]['Background'][1]['peaksList'] is None: - proj.data[hist.name]['Background'][1]['peaksList'] = [] - - # Since single_peak_bkg is a list of peaks, we need to append each peak individually - for peak in single_peak_bkg: - proj.data[hist.name]['Background'][1]['peaksList'].append(peak) - - # Update the number of peaks - proj.data[hist.name]['Background'][1]['nPeaks'] = len(proj.data[hist.name]['Background'][1]['peaksList']) - - # if print_info, then print details about the set background using the proj data, not the inputs - if print_info: - print(f"Single peak background set with {proj.data[hist.name]['Background'][1]['nPeaks']} peaks:") - for peak in proj.data[hist.name]['Background'][1]['peaksList']: - print(f" Position: {peak[0]} (refine: {peak[1]}), Intensity: {peak[2]} (refine: {peak[3]}), " - f"Gaussian Sigma: {peak[4]} (refine: {peak[5]}), Lorentzian Gamma: {peak[6]} (refine: {peak[7]})") - - -def set_single_peaks(proj: Any, hist: Any, single_peaks_dict: dict, print_info: bool = False) -> None: - """ - Set single peaks in the Peak List (non-background peaks) with direct control over position, intensity, - and pseudo-Voigt width parameters (sigma_sq, gamma). - - **Schema 0.24:** Values should be sigma² (variance), not sigma - no conversion is performed. - Peak fitting mode is controlled by refinement strategy execution functions via - refinement_controls.single_peak_fitting_mode and passed to hist.refine_peaks(). - - sigma_sq and gamma must be positive non-zero values. - GSAS-II does not use negative values for FWHM calc and instead enforces a minimum (0.001 in centidegrees for sigma and gamma). - In our approach, we raise an error for negative or zero values to avoid confusion. - GSAS-II will output negative values if refined to such, but uses the near-zero value in PV calculation. - - Parameters: - proj: GSAS-II project object - hist: Histogram object - single_peaks_dict: Dictionary containing peak parameters (positions, intensities, pv_gaussian_sigma_sq, pv_lorentzian_gamma) - print_info: If True, print details about set peaks - """ - # Extract parameters from dict - positions = single_peaks_dict.get('positions') - intensities = single_peaks_dict.get('intensities') - pv_gaussian_sigma_sq = single_peaks_dict.get('pv_gaussian_sigma_sq') - pv_lorentzian_gamma = single_peaks_dict.get('pv_lorentzian_gamma') - - # Validate that all required lists are present - required_keys = ['positions', 'intensities', 'pv_gaussian_sigma_sq', 'pv_lorentzian_gamma'] - for key in required_keys: - if single_peaks_dict.get(key) is None: - raise ValueError(f"Missing required key '{key}' in single_peaks_dict") - - # Validate all lists are non-empty - if not positions or len(positions) == 0: - raise ValueError("positions list cannot be empty") - if not intensities or len(intensities) == 0: - raise ValueError("intensities list cannot be empty") - if not pv_gaussian_sigma_sq or len(pv_gaussian_sigma_sq) == 0: - raise ValueError("pv_gaussian_sigma_sq list cannot be empty") - if not pv_lorentzian_gamma or len(pv_lorentzian_gamma) == 0: - raise ValueError("pv_lorentzian_gamma list cannot be empty") - - # Validate all lists have the same length - list_lengths = [ - len(positions), - len(intensities), - len(pv_gaussian_sigma_sq), - len(pv_lorentzian_gamma) - ] - if len(set(list_lengths)) > 1: - raise ValueError( - f"All peak parameter lists must have the same length. " - f"Got: positions={len(positions)}, intensities={len(intensities)}, " - f"pv_gaussian_sigma_sq={len(pv_gaussian_sigma_sq)}, pv_lorentzian_gamma={len(pv_lorentzian_gamma)}" - ) - - num_peaks = len(positions) - - # Check if Peak List exists, initialize if not - if 'Peak List' not in proj.data[hist.name]: - import warnings - warnings.warn(f"Peak List not found for histogram {hist.name}. Initializing with default structure.") - proj.data[hist.name]['Peak List'] = { - 'peaks': [], - 'sigDict': {}, - 'xtraPeaks': [], - 'xtraMode': False - } - - # Build peak list - peaks_list = [] - for i in range(num_peaks): - # Extract values and refine flags from RefinementParameter format [value, refine_flag, min, max] - pos_val, pos_refine = positions[i][0], positions[i][1] - int_val, int_refine = intensities[i][0], intensities[i][1] - sigma_sq_val, sigma_sq_refine = pv_gaussian_sigma_sq[i][0], pv_gaussian_sigma_sq[i][1] - gamma_val, gamma_refine = pv_lorentzian_gamma[i][0], pv_lorentzian_gamma[i][1] - - # Input validation - check for invalid values - if np.isnan(sigma_sq_val) or np.isinf(sigma_sq_val): - raise ValueError(f"Peak {i}: sigma² value is NaN or inf ({sigma_sq_val}), which is always invalid") - if np.isnan(gamma_val) or np.isinf(gamma_val): - raise ValueError(f"Peak {i}: gamma value is NaN or inf ({gamma_val}), which is always invalid") - - # Check for negative or zero values, raise Error (while GSAS-II allows negative values, we will not in our approach) - if sigma_sq_val <= 0: - raise ValueError(f"Peak {i}: sigma² <= 0 ({sigma_sq_val}), which is invalid for peak fitting") - if gamma_val <= 0: - raise ValueError(f"Peak {i}: gamma <= 0 ({gamma_val}), which is invalid for peak fitting") - - # Convert boolean refine flags to integers (0 or 1) - pos_flag = 1 if pos_refine else 0 - int_flag = 1 if int_refine else 0 - # Refine flag for sig² (variance) - input is already sigma² from GUI/calculations - sig_sq_flag = 1 if sigma_sq_refine else 0 - gamma_flag = 1 if gamma_refine else 0 - - # Build peak as: [pos, pos_flag, intensity, int_flag, sig², sig²_flag, gamma, gam_flag] - peak = [pos_val, pos_flag, int_val, int_flag, sigma_sq_val, sig_sq_flag, gamma_val, gamma_flag] - peaks_list.append(peak) - - # Set peaks in Peak List - proj.data[hist.name]['Peak List']['peaks'] = peaks_list - - # Print info if requested - if print_info: - print(f"Single peaks (Peak List) set with {num_peaks} peaks:") - for i, peak in enumerate(peaks_list): - pos, pos_flag, intensity, int_flag, sig_sq, sig_sq_flag, gamma, gam_flag = peak - print(f" Peak {i+1}: Position={pos:.4f} (refine: {bool(pos_flag)}), " - f"Intensity={intensity:.4f} (refine: {bool(int_flag)}), " - f"Sigma²={sig_sq:.6f}, (refine: {bool(sig_sq_flag)}), " - f"Gamma={gamma:.6f} (refine: {bool(gam_flag)})") - -def add_phase_from_cif_dict(proj: Any, cif_data: Dict[str, Any], phase_name: str, histograms: Union[Sequence, str] = 'all') -> Any: - """ - Add a phase to a GSAS-II project from an embedded structure dictionary. - - This function creates a phase from an in-memory structure data dictionary - (file-less payload format) without reading from files. It creates a new phase entry - in the project, sets up the phase's general data (space group, unit_cell) and - atoms, and links the phase to specified histograms. - - Parameters - ---------- - proj : GSASIIscriptable.G2Project - The GSAS-II project object to which the phase will be added. - cif_data : dict - The structure dictionary containing phase structural information. - From the payload this dict is stowed in payload['phases'][phase]['structure'] - (e.g., payload['phases']['LaB6']['structure']). - phase_name : str - Name for the new phase. Top level key for a phase in payload['phases'], - or within payload['phases'][phase]['structure']['phase_name'] from payload. - histograms : list or 'all', optional - Which histograms to associate with this phase. Can be: - - 'all' (default): link to all powder histograms in the project. - - a list of histogram identifiers (names, objects, or indices). - - None or empty list for no links. - - Returns - ------- - phase_obj : GSASIIscriptable.G2Phase - The newly created phase object (GSAS-II scriptable phase wrapper). - - Raises - ------ - ValueError - If the space group in cif_data is invalid or cannot be interpreted. - - Notes - ----- - The function generates a new phase dictionary using GSASIIobj.SetNewPhase with - the provided space group and unit_cell parameters. Atomic coordinates and - occupancies from cif_data are inserted into the phase's atom list. Anisotropic - displacement parameters, if present, are fully supported. - - By default, the phase will be linked to all existing powder histograms in the - project. You can specify a subset of histograms by name, index, or object, or - pass an empty list/None to link none. - """ - pname = phase_name if phase_name else cif_data.get("name", "New Phase") - # Ensure phase name is unique in project - # TODO: handle phase name collisions more gracefully upstream in validation - existing_names = [p.name for p in proj.phases()] - pname = G2obj.MakeUniqueLabel(pname, existing_names) - - # Interpret space group symbol into SGData - sg = cif_data.get("space_group", "P 1") - err, SGData = G2spc.SpcGroup(sg) - - # Attempt normalization if initial interpretation failed - normalized_sg = sg - if err and sg: - normalized_sg = G2spc.StandardizeSpcName(sg) - if normalized_sg and normalized_sg != sg: - err, SGData = G2spc.SpcGroup(normalized_sg) - - # Handle space group interpretation errors - if err: - error_msg = G2spc.SGErrors(err) - raise ValueError( - f"Space group '{sg}' could not be interpreted.\n" - f"Error: {error_msg}\n" - f"Attempted normalization: '{normalized_sg}'\n" - f"\nCommon issues:\n" - f" • Missing spaces in Hermann-Mauguin notation (e.g., use 'R 3 m' not 'R3m')\n" - f" • Ambiguous rhombohedral symbols (R-3m normalizes to R-3c rhombohedral)\n" - f" • Check structure dict space_group entry matches the crystal structure\n" - ) - - # Create a new phase data structure (similar to reading from file): - phase_data = G2obj.SetNewPhase(Name=pname, SGData=SGData) - phase_data['General']['Name'] = pname - - # Document any space group normalization that occurred (silently - verbose mode not available here) - # if normalized_sg != sg: - # print(f"ℹ️ Space group normalization: '{sg}' → '{normalized_sg}'") - - # Set unit cell parameters if available - unit_cell = cif_data.get("unit_cell", {}) - if unit_cell: - unit_cell_constants = [unit_cell.get("a"), unit_cell.get("b"), unit_cell.get("c"), unit_cell.get("alpha"), unit_cell.get("beta"), unit_cell.get("gamma")] - if len(unit_cell_constants) == 6 and None not in unit_cell_constants: - phase_data['General']['Cell'][1:7] = unit_cell_constants # insert a,b,c,alpha,beta,gamma - try: - # Recalculate volume for consistency - phase_data['General']['Cell'][7] = G2lat.calc_V(G2lat.cell2A(tuple(unit_cell_constants))) - except Exception as e: - raise RuntimeError( - f"Unit cell volume calculation failed for phase '{pname}'. " - f"Cell parameters: {unit_cell_constants}. " - f"Original error: {e}" - ) from e - - # Add atoms from cif_data into phase_data['Atoms'] - # TODO: review handling of site_sym, multiplicity, and ADPS. - # The current approach expects minimal info in cif_data, but we are now populating this with the complete info needed. - # For example, cif_data['atoms'] stows info as shown below, where label is the key for each atom entry.: - # atoms[label] = { - # "element": element, - # "Multiplicity": mult, - # "x": x, "y": y, "z": z, - # "occupancy": occ, - # "ADP": ADP, - # "Uiso": Uiso_val - # } - # # Add Uij if anisotropic and data available - # if ADP == "Uani" and label in aniso_data: - # atoms[label]["Uij"] = aniso_data[label] - # TODO: in phase 2, assembly of atom_record using GSAS-II helpers will done upstream using "parse_cif_to_dict" function. - # This code will need to be update accordingly and use "get" with defaults for missing values. E.g., don't interpret site sym or mult. - - for label, atom in cif_data.get("atoms", {}).items(): - x = float(atom.get("x", 0.0)) - y = float(atom.get("y", 0.0)) - z = float(atom.get("z", 0.0)) - occ = float(atom.get("occupancy", 1.0)) - - # Get ADP type for this atom (required in schema 0.22) - adp_type = atom.get("ADP", None) - if adp_type is None: - raise ValueError( - f"Atom '{label}' in phase '{pname}' is missing required 'ADP' field. " - f"Schema 0.22 requires explicit ADP specification ('Uiso' or 'Uaniso') for all atoms." - ) - - # Prepare atom record list (based on GSAS-II internal format): - atom_record = ["", "", "", 0.0, 0.0, 0.0, 1.0, "", 0.0, "I", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] - atom_record[0] = label - atom_record[1] = atom.get("element", label.rstrip('0123456789') or "X") - atom_record[2] = "" # refinement flags placeholder (left blank) - atom_record[3] = x - atom_record[4] = y - atom_record[5] = z - atom_record[6] = occ - # Determine site symmetry and multiplicity for this atom in the given SG - site_sym, mult = "", 1 - try: - site_sym, mult = G2spc.SytSym([x, y, z], SGData)[0:2] - except Exception: - pass - atom_record[7] = site_sym if site_sym is not None else "" - atom_record[8] = mult if mult is not None else 1 - - # Set displacement parameters (isotropic or anisotropic) - if adp_type == "Uaniso": - # Anisotropic displacement parameters - atom_record[9] = "A" - - # Get Uaniso dict (supports both "Uij" old name and "Uaniso" new name) - uaniso_dict = atom.get("Uaniso") or atom.get("Uij") - - if uaniso_dict: - # Validate all 6 anisotropic values are present - required_keys = ["U11", "U22", "U33", "U12", "U13", "U23"] - missing_keys = [k for k in required_keys if k not in uaniso_dict or uaniso_dict[k] is None] - if missing_keys: - raise ValueError( - f"Atom '{label}' marked as anisotropic (ADP='Uaniso') but missing required U values: {missing_keys}. " - f"All 6 anisotropic parameters (U11, U22, U33, U12, U13, U23) must be provided." - ) - - # Populate U11, U22, U33, U12, U13, U23 (indices 11-16) - atom_record[11] = float(uaniso_dict["U11"]) - atom_record[12] = float(uaniso_dict["U22"]) - atom_record[13] = float(uaniso_dict["U33"]) - atom_record[14] = float(uaniso_dict["U12"]) - atom_record[15] = float(uaniso_dict["U13"]) - atom_record[16] = float(uaniso_dict["U23"]) - - # Set atom_record[10] to Uiso if provided, else calculate from diagonal elements - if atom.get("Uiso") is not None: - atom_record[10] = float(atom["Uiso"]) - else: - # Calculate equivalent isotropic value from diagonal elements - atom_record[10] = (atom_record[11] + atom_record[12] + atom_record[13]) / 3.0 - else: - raise ValueError( - f"Atom '{label}' marked as anisotropic (ADP='Uaniso') but no Uaniso dict found. " - f"Provide 'Uaniso' dict with U11, U22, U33, U12, U13, U23 values." - ) - else: - # Isotropic displacement parameters - atom_record[9] = "I" - uiso = atom.get("Uiso") - if uiso is not None: - atom_record[10] = float(uiso) - else: - atom_record[10] = 0.0 - atom_record[11:17] = [0.0]*6 # six anisotropic Uij (zeros since not used here) - - # Append a random unique ID for the atom - atom_record.append(ran.randint(0, sys.maxsize)) - phase_data['Atoms'].append(atom_record) - - # Insert the new phase into project data structure - if 'Phases' not in proj.data: - proj.data['Phases'] = {'data': None} - assert pname not in proj.data['Phases'], "Phase name collision despite uniqueness check" - proj.data['Phases'][pname] = phase_data - # Update the project tree name list for phases - for entry in proj.names: - if entry[0] == 'Phases': - entry.append(pname); break - else: - proj.names.append(['Phases', pname]) - - # Initialize phase general data (e.g. set default atom form factors): - try: - G2elem.SetupGeneral(phase_data, None) - except ValueError as err: - raise ValueError(f"Error in phase initialization: {err}") - - # Link phase to specified histograms - hist_list = [] - if histograms == 'all': - hist_list = [h.name for h in proj.histograms()] - elif histograms: - for h in histograms: - if hasattr(h, 'name'): - hist_list.append(h.name) - elif isinstance(h, str): - hist_list.append(h) - elif isinstance(h, int): - try: - hist_list.append(proj.histogram(h).name) - except Exception: - continue - for hist_name in hist_list: - try: - proj.link_histogram_phase(hist_name, pname) - except Exception as e: - print(f"Warning: could not link phase to histogram '{hist_name}': {e}") - - # Refresh internal IDs and return the new phase object - proj.index_ids() - proj.update_ids() - return proj.phase(pname) - -# Add all phases from phases dict (file-less approach) -def add_phases_from_dict(proj: Any, hist: Any, phases_dict: dict, print_info: bool = False) -> None: - """ - Add phases to the GSAS-II project from a phases dictionary. - - Parameters: - proj : GSAS-II project object - The GSAS-II project to add phases to. - hist : GSAS-II histogram object - The histogram to associate with the phases. - phases_dict : dict - Dictionary containing phase information. (e.g., payload['phases']) - print_info : bool - Whether to print information about the added phases. - - Returns: - None - """ - - for phase_name, phase_info in phases_dict.items(): - structure_info = phase_info.get('structure', {}) - - # Validation check (TODO: move this upstream in phase2) - if phase_name != structure_info.get('phase_name'): - raise NameError(f"Phase name mismatch for '{phase_name}'. Structure info name is '{structure_info.get('phase_name')}'.") - - # Prevent duplicate phase names - TODO: handle upstream in schema validation / recipe maker - if phase_name in [p.name for p in proj.phases()]: - raise ValueError(f"Phase '{phase_name}' already exists in project.") - - try: - add_phase_from_cif_dict(proj=proj, cif_data=structure_info, phase_name=phase_name, histograms=[hist]) - except Exception as e: - raise RuntimeError(f"Failed to add phase '{phase_name}': {e}") from e - if print_info: - print("\nPhases in proj: ", *[ph.name for ph in proj.phases()], sep='\n\t') - - -################################################################## -# Functions for phase parameterization - -@require_phase("Cannot set scale.") -def set_phase_scale(proj: Any, hist: Any, phase_name: str, scale_param: list, print_info: bool = False) -> None: - """ - Set the phase scale factor in the GSAS-II project. - - Parameters: - proj : GSAS-II project object - The GSAS-II project containing the phase. - hist : GSAS-II histogram object - The histogram associated with the phase. - phase_name : str - The name of the phase to set the scale for. - scale_param : list - List containing [value, refine_flag, min, max] for the scale factor. - - Returns: - None - """ - value, refine_flag, min_val, max_val = unpack_refinement_parameter(scale_param, "scale_param") - - # Set the scale factor value - defaults will be handled upstream in future in validation - if value is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Scale'][0] = value - - # Set refinement flag - if refine_flag is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Scale'][1] = refine_flag - # Set min and max if provided - CURRENTLY NOT IMPLEMENETED. Unclear if allowed in GSAS-II. - # if min_val is not None: - # phase.set_parameter_min('Scale', min_val) - # if max_val is not None: - # phase.set_parameter_max('Scale', max_val) - - if print_info: - print(f"Set scale for phase '{phase_name}' to {value} with refine_flag={refine_flag}") - -@require_phase("Cannot set unit cell parameters.") -def set_phase_unit_cell(proj: Any, phase_name: str, unit_cell_dict: dict, print_info: bool = False) -> list[str]: - """ - Set the unit cell parameters in the GSAS-II project for a given phase. - - Schema 0.26 semantics: each cell parameter refines iff it is present with - refine_flag=true; absent or false means fixed. Because GSAS-II has a single - whole-cell refine flag, per-parameter control is achieved by setting that - flag when any symmetry degree-of-freedom (DOF) group is requested and - returning "Hold" constraint variable names (e.g. '0::A2') for the DOF - groups that were not requested. Symmetry-linked parameters (e.g. cubic - a=b=c, or the coupled monoclinic {a, c, beta}) refine together if any - member is requested — see powderline.constraints. - - Parameters: - proj : GSAS-II project object - The GSAS-II project containing the phase. - phase_name : str - The name of the phase to set the unit cell for. - unit_cell_dict : dict - Dictionary containing unit cell parameters and their parameterization. - print_info : bool - Whether to print information about the set unit cell. - - Returns: - list[str] - GSAS-II variable names to Hold (empty when the whole cell refines or - is entirely fixed). The caller applies them via proj.add_HoldConstr. - """ - - # Note: cell values are set verbatim; validating them against the phase's - # crystal system is intentionally NOT done here (PowderLine is the engine, - # not the arbiter of recipe correctness — see docs/known_issues.md, KI-01). - - # Note2: hist not required since unit cell is phase-specific, not histogram-specific. - # The delineation of phase and histogram parameters is confusing in GSAS-II documentation. - # This makes sticking with a project based approach more straightforward. - - phase_names = [p.name for p in proj.phases()] - cell_changed = False - cell_params = ['a', 'b', 'c', 'alpha', 'beta', 'gamma'] # must match schema, and match order in GSAS-II - - for i, param in enumerate(cell_params): - if unit_cell_dict.get(param) is not None: - value, refine_flag, min_val, max_val = unit_cell_dict[param] - - # Set the unit cell parameter value - a=1, b=2, c=3, alpha=4, beta=5, gamma=6 - if value is not None: - proj.data['Phases'][phase_name]['General']['Cell'][i+1] = value - cell_changed = True - - # Set min and max if provided - CURRENTLY NOT IMPLEMENTED (deferred; - # GSAS-II's own min/max semantics differ from simple bounds). - - # Calculate and set volume from unit cell parameters only if cell was changed - if cell_changed: - cell = proj.data['Phases'][phase_name]['General']['Cell'][1:7] # get list of a, b, c, alpha, beta, gamma - proj.data['Phases'][phase_name]['General']['Cell'][7] = G2lat.calc_V(G2lat.cell2A(cell)) # index 7 is volume - - # Translate per-parameter refine flags into the whole-cell flag + holds - SGData = proj.data['Phases'][phase_name]['General']['SGData'] - phase_idx = phase_names.index(phase_name) - cell_plan = cell_refinement_plan(SGData, unit_cell_dict, phase_idx) - proj.data['Phases'][phase_name]['General']['Cell'][0] = cell_plan.refine_cell - - if print_info: - curr_cell = proj.data['Phases'][phase_name]['General']['Cell'] - if cell_changed: - cell_prms_dict = {"a": curr_cell[1], - "b": curr_cell[2], - "c": curr_cell[3], - "alpha": curr_cell[4], - "beta": curr_cell[5], - "gamma": curr_cell[6], - "volume": curr_cell[7]} - - print(f"Set unit cell parameters for phase '{phase_name}' to {[(key, value) for key, value in cell_prms_dict.items()]} with refine_flag={curr_cell[0]}") - else: - print(f"No unit cell parameters were changed for phase '{phase_name}'. Refine_flag={curr_cell[0]}") - if cell_plan.holds: - print(f"Holding fixed unit cell DOFs for phase '{phase_name}': {cell_plan.holds}") - - return cell_plan.holds - - -@require_phase("Cannot set size broadening parameters.") -def set_phase_size_broadening(proj: Any, hist: Any, phase_name: str, size_broadening_dict: dict, print_info: bool = False) -> None: - """ - Set size broadening parameters in the GSAS-II project for a given phase. - - Supports model branching for isotropic, uniaxial, and ellipsoidal models. - Currently only isotropic model is implemented - others raise NotImplementedError. - - Parameters: - proj : GSAS-II project object - The GSAS-II project containing the phase. - hist : GSAS-II histogram object - The histogram associated with the phase. - phase_name : str - The name of the phase to set the size broadening for. - size_broadening_dict : dict - Dictionary containing size broadening parameters with 'model' key. - - Raises: - NotImplementedError: For uniaxial or ellipsoidal models - ValueError: For unknown model types or invalid parameters - - Returns: - None - """ - # Extract model type (default to isotropic for backward compatibility) - model = size_broadening_dict.get('model', 'isotropic') - - # Validate model type - valid_models = ['isotropic', 'uniaxial', 'ellipsoidal'] - if model not in valid_models: - raise ValueError( - f"Unknown size broadening model '{model}'. " - f"Valid options: {valid_models}" - ) - - # Set model type in GSAS-II data structure - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][0] = model - - # Branch on model type - if model == 'isotropic': - _set_isotropic_size_broadening(proj, hist, phase_name, size_broadening_dict, print_info) - elif model == 'uniaxial': - raise NotImplementedError( - "Uniaxial size broadening model is not yet implemented. " - "Support planned for future release. Use 'isotropic' model instead." - ) - elif model == 'ellipsoidal': - raise NotImplementedError( - "Ellipsoidal size broadening model is not yet implemented. " - "Support planned for future release. Use 'isotropic' model instead." - ) - - -def _set_isotropic_size_broadening(proj: Any, hist: Any, phase_name: str, size_broadening_dict: dict, print_info: bool = False) -> None: - """ - Set isotropic size broadening parameters (internal helper). - - Refactored from original set_phase_size_broadening function. - """ - - # Example structure of proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size']: - # ['isotropic', # [0]: str for broadening type. 'isotropic', 'uniaxial', or 'ellipsoidal' - # [1.0, 1.0, 1.0], # [1][0]: iso size or equatorial size, [1][1]: axial size (if uniaxial used, else ignored), [1][2]: LG_mix (eta parameter, 1 = Lorentzian, 0 = Gaussian) - # [False, False, False], # boolean refinement flags. [2][0]: isotropic or uniaxial equatorial refine, [2][1]: uniaxial axial refine, [2][2]: LG_mix refine - # [0, 0, 1], # hkl direction for uniaxial broadening. [3][0]: h, [3][1]: k, [3][2]: l - # [1.0, 1.0, 1.0, 0.0, 0.0, 0.0], # ellipsoidal sizes. S11, S22, S33, S12, S13, S23 for [4][0:6] - # [False, False, False, False, False, False]] # ellipsoidal size refine flags. S11, S22, S33, S12, S13, S23 for [5][0:6] - ############################ - # Set isotropic size parameters - ############################ - value, refine_flag, min_val, max_val = unpack_refinement_parameter( - size_broadening_dict.get('isotropic_size'), "isotropic_size" - ) - - # Set the size parameter value - if value is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][1][0] = value - - # Set refinement flag - if refine_flag is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][2][0] = refine_flag - - # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. - - if print_info: - print(f"Set size broadening size parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") - - ############################ - # Set size LG_eta parameter - ############################ - try: - value, refine_flag, min_val, max_val = unpack_refinement_parameter( - size_broadening_dict.get('LG_eta'), "LG_eta" - ) - except (ValueError, TypeError) as e: - # Preserve original error message format - raise ValueError(f"Size broadening 'LG_eta' parameter must be a list or None.\nType for phase {phase_name} is {type(size_broadening_dict['LG_eta'])}.") from e - - # Set the LG_eta parameter value - if value is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][1][2] = value - - # Set refinement flag - if refine_flag is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Size'][2][2] = refine_flag - - # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. - - if print_info: - print(f"Set size broadening LG_eta parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") - - -# Setting strain broadening should be done in the same way as size broadening -# The dictionary structure is very similar. We just need to map to the correct keys in the proj.data structure. - -@require_phase("Cannot set strain broadening parameters.") -def set_phase_strain_broadening(proj: Any, hist: Any, phase_name: str, strain_broadening_dict: dict, print_info: bool = False) -> None: - """ - Set strain broadening parameters in the GSAS-II project for a given phase. - - Supports model branching for isotropic, uniaxial, and generalized (Stephens) models. - Currently only isotropic model is implemented - others raise NotImplementedError. - - Parameters: - proj : GSAS-II project object - The GSAS-II project containing the phase. - hist : GSAS-II histogram object - The histogram associated with the phase. - phase_name : str - The name of the phase to set the strain broadening for. - strain_broadening_dict : dict - Dictionary containing strain broadening parameters with 'model' key. - - Raises: - NotImplementedError: For uniaxial or generalized models - ValueError: For unknown model types or invalid parameters - - Returns: - None - """ - # Extract model type (default to isotropic for backward compatibility) - model = strain_broadening_dict.get('model', 'isotropic') - - # Validate model type - valid_models = ['isotropic', 'uniaxial', 'generalized'] - if model not in valid_models: - raise ValueError( - f"Unknown strain broadening model '{model}'. " - f"Valid options: {valid_models}" - ) - - # Set model type in GSAS-II data structure - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][0] = model - - # Branch on model type - if model == 'isotropic': - _set_isotropic_strain_broadening(proj, hist, phase_name, strain_broadening_dict, print_info) - elif model == 'uniaxial': - raise NotImplementedError( - "Uniaxial strain broadening model is not yet implemented. " - "Support planned for future release. Use 'isotropic' model instead." - ) - elif model == 'generalized': - raise NotImplementedError( - "Generalized (Stephens) strain broadening model is not yet implemented. " - "This model requires complex symmetry-dependent parameterization. " - "Support planned for Phase 2. Use 'isotropic' model instead." - ) - - -def _set_isotropic_strain_broadening(proj: Any, hist: Any, phase_name: str, strain_broadening_dict: dict, print_info: bool = False) -> None: - """ - Set isotropic strain broadening parameters (internal helper). - - Refactored from original set_phase_strain_broadening function. - """ - ############################ - # Set isotropic strain parameters - ############################ - value, refine_flag, min_val, max_val = unpack_refinement_parameter( - strain_broadening_dict.get('isotropic_strain'), "isotropic_strain" - ) - - # Set the strain parameter value - if value is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][1][0] = value - - # Set refinement flag - if refine_flag is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][2][0] = refine_flag - - # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. - - if print_info: - print(f"Set strain broadening strain parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") - - ############################ - # Set strain LG_eta parameter - ############################ - try: - value, refine_flag, min_val, max_val = unpack_refinement_parameter( - strain_broadening_dict.get('LG_eta'), "LG_eta" - ) - except (ValueError, TypeError) as e: - # Preserve original error message format - raise ValueError(f"Strain broadening dict key 'LG_eta' must hold a value that is a list or None.\nType for phase {phase_name} is {type(strain_broadening_dict['LG_eta'])}.") from e - - # Set the LG_eta parameter value - if value is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][1][2] = value - - # Set refinement flag - if refine_flag is not None: - proj.data['Phases'][phase_name]['Histograms'][hist.name]['Mustrain'][2][2] = refine_flag - - # Set min and max if provided - CURRENTLY NOT IMPLEMENTED. Unclear if allowed in GSAS-II. - - if print_info: - print(f"Set strain broadening LG_eta parameters for phase '{phase_name}' to {value} with refine_flag={refine_flag}") - - -def has_active_refinement_parameter(atom_param: dict) -> bool: - """ - Check if any refinement parameter has non-default values. - - Parameters: - atom_param : dict - Atom parameters dict with keys like 'x', 'y', 'z', 'occupancy', 'ADP', 'Uiso', 'Uaniso' - - Returns: - bool - True if any parameter should be set (not all [None, False, None, None]) - - Notes: - - Skips 'ADP' field (string, not refinement parameter) - - Handles 'Uaniso' nested dict separately - - Checks RefinementParameter lists for non-default values - """ - for key, value in atom_param.items(): - if key == 'ADP': - continue # Skip ADP type string (not a refinement parameter) - - if key == 'Uaniso' and isinstance(value, dict): - # Check nested Uaniso dict - any U value not [None, False, None, None]? - if any(v is not None and v != [None, False, None, None] for v in value.values()): - return True - - elif isinstance(value, list) and len(value) == 4: - # Check RefinementParameter list [value, refine_flag, min, max] - if value != [None, False, None, None]: - return True - - return False - - -# Function to set atom parameters for a phase -@require_phase("Cannot set atom parameters.") -def set_phase_atom_parameters(proj: Any, phase_name: str, atom_parameters_dict: dict, print_info: bool = False) -> list[str]: - """ - Set atom parameters for a phase in the GSAS-II project. - - This function parses atom-specific refinement parameters (coordinates, occupancy, displacement) - and constructs GSAS-II's refine_flags string ('F', 'X', 'U' combinations). - - Schema 0.26 semantics: each coordinate (x/y/z) and each anisotropic Uij - component refines iff present with refine_flag=true; absent or false means - fixed. GSAS-II's 'X'/'U' flags are per-atom, so per-component control is - achieved by returning "Hold" constraint variable names (e.g. '0::dAy:3', - '0::AU22:4') for the site-symmetry DOF groups that were not requested — - see powderline.constraints. - Symmetry-linked components (e.g. x=y on an (x,x,z) site) refine together - if any member is requested. - - Parameters: - proj : GSAS-II project object - The GSAS-II project containing the phase. - phase_name : str - The name of the phase to set the atom parameters for. - atom_parameters_dict : dict - Dictionary containing atom parameters and their parameterization. - E.g., payload['phases'][phase_name]['parameterization']['atoms'] - - Expected structure: - { - 'atom_label': { - 'x': [value, refine_flag, min, max], - 'y': [value, refine_flag, min, max], - 'z': [value, refine_flag, min, max], - 'occupancy': [value, refine_flag, min, max], - 'ADP': 'Uiso' or 'Uaniso', - 'Uiso': [value, refine_flag, min, max], # if ADP='Uiso' - 'Uaniso': { # if ADP='Uaniso' - 'U11': [value, refine_flag, min, max], - 'U22': [value, refine_flag, min, max], - ... - } - } - } - print_info : bool, optional - If True, print detailed information about the atom parameters being set. Default is False. - - Returns: - list[str] - GSAS-II variable names to Hold (empty when every requested DOF group - refines in full). The caller applies them via proj.add_HoldConstr. - - Notes: - proj.data['Phases'][phase_name]['Atoms'] is a list of lists, where each sublist represents an atom and its parameters. - Sublist structure in atom_param_index_mapping below. - - Example: proj.data['Phases'][phase_name]['Atoms'][0] from LaB6 example returns: - ['La', 'La', '', 0.0, 0.0, 0.0, 1.0, 'm3m', 1, 'I', 0.00858, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 844046454091148456] - - GSAS-II refine_flags string format (index 2): - - 'F': refine occupancy - - 'X': refine all coordinates (x, y, z together) - - 'U': refine displacement parameters (isotropic or anisotropic) - - Combinations: 'FXU', 'XU', 'F', etc. - """ - - # Dictionary of atom parameter names to their indices in the atom list - atom_param_index_mapping = { - 'label': 0, # atom label - 'element': 1, # element symbol - 'refine_flags': 2, # string of refine flags e.g., 'F', 'X', 'U' or any combination such as 'FXU'. F for occupancy, X for xyz coords, U for displacement parameters - 'x': 3, # fractional coordinate x value - 'y': 4, # fractional coordinate y value - 'z': 5, # fractional coordinate z value - 'occupancy': 6, # float, referred to as frac in GSAS-II syntax - 'site_symmetry': 7, # string representation of site symmetry - 'multiplicity': 8, # multiplicity of the site, integer - 'Utype': 9, # 'I' for isotropic, 'A' for anisotropic - 'Uiso': 10, # value if isotropic - 'U11': 11, # value if anisotropic - 'U22': 12, # value if anisotropic - 'U33': 13, # value if anisotropic - 'U12': 14, # value if anisotropic - 'U13': 15, # value if anisotropic - 'U23': 16 # value if anisotropic - # Note: index 17 is a random unique ID for the atom, not a parameter to set - } - - phase_names = [p.name for p in proj.phases()] - phase_idx = phase_names.index(phase_name) - SGData = proj.data['Phases'][phase_name]['General']['SGData'] - atom_labels_present = [x[0] for x in proj.data['Phases'][phase_name]['Atoms']] - holds: list[str] = [] - - for atom_label, atom_params in atom_parameters_dict.items(): - if atom_label not in atom_labels_present: - print(f"Atom '{atom_label}' not found in phase '{phase_name}'. Skipping.") - continue - - # Get the atom record - atom_index = atom_labels_present.index(atom_label) - atom_record = proj.data['Phases'][phase_name]['Atoms'][atom_index] - - # Get ADP type for this atom (required in schema 0.22) - adp_type = atom_params.get('ADP') - - # Process coordinate parameters (x, y, z) — values only; refine flags - # are translated by atom_refinement_plan below - for coord in ['x', 'y', 'z']: - if coord in atom_params and atom_params[coord] is not None: - param_value = atom_params[coord] - if param_value != [None, False, None, None]: - value, refine_flag, min_val, max_val = param_value - - # Update coordinate value if provided - if value is not None: - atom_record[atom_param_index_mapping[coord]] = value - - # Process occupancy - if 'occupancy' in atom_params and atom_params['occupancy'] is not None: - param_value = atom_params['occupancy'] - if param_value != [None, False, None, None]: - value, refine_flag, min_val, max_val = param_value - - # Update occupancy value if provided - if value is not None: - atom_record[6] = value - - # Process displacement parameters based on ADP type - if adp_type == 'Uiso': - # Isotropic displacement parameters - if 'Uiso' in atom_params and atom_params['Uiso'] is not None: - param_value = atom_params['Uiso'] - if param_value != [None, False, None, None]: - value, refine_flag, min_val, max_val = param_value - - # Update Uiso value if provided - if value is not None: - atom_record[9] = 'I' # Set to isotropic - atom_record[10] = value - - elif adp_type == 'Uaniso': - # Anisotropic displacement parameters - if 'Uaniso' in atom_params and atom_params['Uaniso'] is not None: - uaniso_dict = atom_params['Uaniso'] - - # Track if any anisotropic values are being updated - aniso_values_provided = [] - - # Process each anisotropic parameter - for u_key in ['U11', 'U22', 'U33', 'U12', 'U13', 'U23']: - if u_key in uaniso_dict and uaniso_dict[u_key] is not None: - param_value = uaniso_dict[u_key] - if param_value != [None, False, None, None]: - value, refine_flag, min_val, max_val = param_value - - # Update anisotropic value if provided - if value is not None: - atom_record[9] = 'A' # Set to anisotropic - atom_record[atom_param_index_mapping[u_key]] = value - aniso_values_provided.append(u_key) - - # Validate that if any anisotropic values are provided, all 6 must be provided - if aniso_values_provided: - required_keys = ['U11', 'U22', 'U33', 'U12', 'U13', 'U23'] - missing_keys = [k for k in required_keys if k not in aniso_values_provided] - if missing_keys: - raise ValueError( - f"Atom '{atom_label}' in phase '{phase_name}': " - f"When updating anisotropic displacement parameters, all 6 values (U11-U23) must be provided. " - f"Missing: {missing_keys}" - ) - - # Translate per-parameter refine flags into GSAS-II's per-atom flag - # string plus holds for the unrefined site-symmetry DOF groups. - # xyz/SGData let the plan recompute a stale/blank site symmetry the - # same way GSAS-II itself does (GetPhaseData's KeyError patch). - atom_plan = atom_refinement_plan( - atom_params, - atom_record[7], - phase_idx, - atom_index, - xyz=atom_record[3:6], - SGData=SGData, - ) - atom_record[2] = atom_plan.refine_flags - holds.extend(atom_plan.holds) - - # Verbose logging - if print_info and atom_plan.refine_flags: - adp_display = adp_type if adp_type else "inherited" - print(f" Set refine flags for atom '{atom_label}' ({adp_display}): '{atom_plan.refine_flags}'") - if atom_plan.holds: - print(f" Holding fixed DOFs for atom '{atom_label}': {atom_plan.holds}") - - return holds - - -# Main function to set phase parameterization from phases dictionary - -def set_phase_parameterization(proj: Any, hist: Any, phases_dict: dict, print_info: bool = False) -> list[str]: - """ - Set phase parameterization in the GSAS-II project from a phases dictionary. - - Parameters: - proj : GSAS-II project object - The GSAS-II project containing the phases. - hist : GSAS-II histogram object - The histogram associated with the phases. - phases_dict : dict - Dictionary containing phase parameterization information. E.g., payload['phases'] - print_info : bool, optional - If True, print information about the parameterization being set. Default is False. - - Returns: - list[str] - Accumulated GSAS-II "Hold" variable names from the unit-cell and atom - setters (schema 0.26 per-parameter refine flags). The caller applies - them once via proj.add_HoldConstr. - """ - holds: list[str] = [] - - for phase_name, phase_info in phases_dict.items(): - - # In schema 0.21, phase_name is the dict key itself - # (structure.phase_name should match, but we use the key for consistency) - - # Check that phase exists in project - this would indicate an error in phase addition earlier - if phase_name not in [p.name for p in proj.phases()]: - print(f"Phase '{phase_name}' not found in project. Skipping parameterization.") - continue - - # Now that we have the phase name, we can add phase-specific parameterization here - # This will call on a few helper functions to set scale, unit cell, peak broadening, atom parameters, etc. - # Each of these helper functions will take the proj, phase name (rather than phase object), and relevant parameterization dict - - # First, get parameterization dict from phase_info (already phase-specific) - param_dict = phase_info.get('parameterization', {}) - - # Keys in param dict are 'scale', 'unit_cell', 'peak_broadening', and 'atoms' for now - # It is not as simple as looping over keys since some have nested dicts and others hold values or lists - - # Set scale factor if provided - scale_param = param_dict.get('scale', None) - if scale_param is not None: - if any(value is not None for value in scale_param): - set_phase_scale(proj, hist, phase_name, scale_param, print_info=False) - - # Set unit cell parameters if provided. The key values can be None, - # so here we cannot just check for unit_cell_dict not being None. - # We need to check if any of hte keys in unit_cell_dict are not None. - unit_cell_dict = param_dict.get('unit_cell', None) - - if unit_cell_dict is not None: - if any(value is not None for value in unit_cell_dict.values()): - holds.extend(set_phase_unit_cell(proj, phase_name, unit_cell_dict, print_info=False)) - - # Set peak broadening if provided. Keys are "size_broadening" and "strain_broadening" - # and each holds a dict with relevant parameters (size or strain) and the LG_eta - # ("or {}" because model_dump emits an explicit None when the section is absent) - peak_broadening_dict = param_dict.get('peak_broadening') or {} - size_broadening_dict = peak_broadening_dict.get('size_broadening', None) - strain_broadening_dict = peak_broadening_dict.get('strain_broadening', None) - - if size_broadening_dict is not None: - if any(value is not None for value in size_broadening_dict.values()): - set_phase_size_broadening(proj, hist, phase_name, size_broadening_dict, print_info=False) - - if strain_broadening_dict is not None: - if any(value is not None for value in strain_broadening_dict.values()): - set_phase_strain_broadening(proj, hist, phase_name, strain_broadening_dict, print_info=False) - - atoms_parameters_dict = param_dict.get('atoms', {}) - if atoms_parameters_dict and any(has_active_refinement_parameter(ap) for ap in atoms_parameters_dict.values()): - holds.extend(set_phase_atom_parameters(proj, phase_name, atoms_parameters_dict, print_info=False)) - - if print_info: - print(f"Completed parameterization for phase '{phase_name}'.") - - if print_info: - print("All phase parameterization complete. Phases in proj: ", *[p.name for p in proj.phases()], sep='\n\t') - if holds: - print("Hold constraints to apply (per-parameter refine flags): ", *holds, sep='\n\t') - - return holds - -# Function for setting instrument parameterization -def set_instrument_parameterization(proj: Any, hist: Any, instrument_param_dict: dict, print_info: bool = False) -> None: - """ - Set instrument parameterization in the GSAS-II project from an instrument parameterization dictionary. - - Parameters: - proj : GSAS-II project object - The GSAS-II project containing the histogram. - hist : GSAS-II histogram object - The histogram associated with the instrument. - instrument_param_dict : dict - Dictionary containing instrument parameterization information. E.g., payload['instrument'] - print_info : bool, optional - If True, print information about the parameterization being set. Default is False. - - Returns: - None - """ - - # Note: GSAS-II's instrument parameters hold values in a list. - # The indices for each parameter (e.g., 'Lam' for wavelength) are as follows: - # [0] default/starting value from iprms, [1] = value, [2] = refinement flag - - # Wavelength - wavelength_param = instrument_param_dict.get('wavelength', None) - if wavelength_param is not None: - value, refine_flag, min_val, max_val = unpack_refinement_parameter(wavelength_param, "wavelength") - wavelength_changed = False # track if wavelength value changed - - # Set wavelength value - curr_wavelength = proj.data[hist.name]['Instrument Parameters'][0]['Lam'][1] - - if value is not None and value != curr_wavelength: - proj.data[hist.name]['Instrument Parameters'][0]['Lam'][1] = value - wavelength_changed = True - - # Set refinement flag - if refine_flag is not None: - proj.data[hist.name]['Instrument Parameters'][0]['Lam'][2] = refine_flag - - if print_info: - if wavelength_changed: - print(f"Set instrument wavelength to {value} with refine_flag={refine_flag}") - else: - print(f"No change to instrument wavelength. Refine_flag={refine_flag}") - - # Additional instrument parameters (polarization, broadening, corrections) would be set similarly - # Implementing those follows the same pattern as above - - # Polarization - polarization_param = instrument_param_dict.get('polarization', None) - if polarization_param is not None: - value, refine_flag, min_val, max_val = unpack_refinement_parameter(polarization_param, "polarization") - polarization_changed = False # track if polarization value changed - - curr_polarization = proj.data[hist.name]['Instrument Parameters'][0]['Polariz.'][1] - - # Set polarization value - if value is not None and value != curr_polarization: - proj.data[hist.name]['Instrument Parameters'][0]['Polariz.'][1] = value - polarization_changed = True - - # Set refinement flag - if refine_flag is not None: - proj.data[hist.name]['Instrument Parameters'][0]['Polariz.'][2] = refine_flag - - if print_info: - if polarization_changed: - print(f"Set instrument polarization to {value} with refine_flag={refine_flag}") - else: - print(f"No change to instrument polarization. Refine_flag={refine_flag}") - - # Broadening parameters (U, V, W, X, Y, Z) - broadening_dict = instrument_param_dict.get('broadening', {}) - for param_key in broadening_dict.keys(): - broadening_param = broadening_dict.get(param_key, None) - if broadening_param is not None: - value, refine_flag, min_val, max_val = unpack_refinement_parameter(broadening_param, f"broadening.{param_key}") - - broadening_changed = False - - # Set broadening parameter value - if value is not None: - proj.data[hist.name]['Instrument Parameters'][0][param_key][1] = value - broadening_changed = True - - # Set refinement flag - if refine_flag is not None: - proj.data[hist.name]['Instrument Parameters'][0][param_key][2] = refine_flag - - if print_info: - if broadening_changed: - # Print changed parameter - print(f"Set instrument broadening parameter '{param_key}' to {value} with refine_flag={refine_flag}") - - # Always print refinement flag even if value not changed - else: - print(f"No change to instrument broadening parameter '{param_key}'. Refine_flag={refine_flag}") - - - # Corrections parameters (zero_shift, axial_divergence, sample_height_displacement) - corrections_dict = instrument_param_dict.get('corrections', {}) - for param_key in corrections_dict.keys(): - correction_param = corrections_dict.get(param_key, None) - if correction_param is not None: # only loop over provided params - - if param_key == 'zero_shift': - gsas_key = 'Zero' - elif param_key == 'axial_divergence': - gsas_key = 'SH/L' - #elif param_key == 'sample_height_displacement': # irrelevant to area detector data, future work for Bragg-Brentano geometry - # gsas_key = 'SampHt' - else: - raise ValueError(f"Unknown instrument correction parameter key '{param_key}'.") - - value, refine_flag, min_val, max_val = correction_param - correction_changed = False - - # Set correction parameter value - if value is not None: - proj.data[hist.name]['Instrument Parameters'][0][gsas_key][1] = value - correction_changed = True - - # Set refinement flag - if refine_flag is not None: - proj.data[hist.name]['Instrument Parameters'][0][gsas_key][2] = refine_flag - - if print_info: - if correction_changed: - # Print changed parameter - print(f"Set instrument correction parameter '{param_key}' to {value} with refine_flag={refine_flag}") - - # Always print refinement flag even if value not changed - else: - print(f"No change to instrument correction parameter '{param_key}'. Refine_flag={refine_flag}") - - # Print instrument parameters set and flags if requested - if print_info: - # Check if 1st and 2nd indices are different for any instrument parameteters - # If they are all the same, then no parameters were changed - params_changed = False - for param in proj.data[hist.name]['Instrument Parameters'][0].values(): - if param[0] != param[1]: - params_changed = True - break - if not params_changed: - print("No instrument parameters were changed from their default values.") - - # print refine flags for all instrument parameters - print("Instrument parameter refinement flags:") - for param_key, param in proj.data[hist.name]['Instrument Parameters'][0].items(): - print(f" {param_key}: refine_flag={param[2]}") - - -def calculate_cell_esds_from_A_matrix(phase_idx: int, proj: Any, phase_name: str) -> List[Optional[float]]: - """ - Calculate unit cell parameter ESDs using GSAS-II's reciprocal metric tensor conversion. - - GSAS-II refines reciprocal metric tensor components (A-matrix: A11, A22, A33, A12, A13, A23) - and this function converts those ESDs to direct lattice parameter ESDs (a, b, c, α, β, γ). - - Args: - phase_idx: Phase index (0-based) for parameter naming (e.g., "0::A0") - proj: GSAS-II project object after refinement - phase_name: Name of the phase - - Returns: - list[float | None]: The 7 ESDs, in order - ``[esd_a, esd_b, esd_c, esd_alpha, esd_beta, esd_gamma, esd_volume]``. - - Raises: - RuntimeError: If covariance data is unavailable or the ESD calculation fails. - - Note: - The A-matrix parameters (A0-A5) in GSAS-II correspond to: - A0=A11, A1=A22, A2=A33, A3=A12, A4=A13, A5=A23 (reciprocal metric tensor) - NOT direct cell parameters a, b, c, α, β, γ. - """ - try: - # Get covariance data - cov_data = proj.data.get('Covariance', {}).get('data', {}) - if not cov_data: - return [None] * 7 - - # Get space group data for this phase - SGData = proj.data['Phases'][phase_name]['General'].get('SGData') - if not SGData: - return [None] * 7 - - # Get current cell parameters and convert to A-matrix - cell = proj.data['Phases'][phase_name]['General']['Cell'][1:7] # a, b, c, alpha, beta, gamma - A = G2lat.cell2A(cell) # Convert to reciprocal metric tensor - - # Call GSAS-II's getCellEsd function - # pfx format: "phase_idx::" (e.g., "0::" for first phase) - pfx = f"{phase_idx}::" - cell_esds = G2lat.getCellEsd(pfx, SGData, A, cov_data) - - # getCellEsd returns [esd_a, esd_b, esd_c, esd_alpha, esd_beta, esd_gamma, esd_volume] - return cell_esds - - except Exception as e: - raise RuntimeError( - f"Cell ESD calculation from covariance matrix failed for phase '{phase_name}'. " - f"Ensure refinement completed successfully and covariance data is present. " - f"Original error: {e}" - ) from e - - -def extract_refined_params_from_project(proj: Any, verbose: bool = False) -> Dict[str, Dict[str, Any]]: - """ - Extract all refined parameters with their values and ESDs from proj.data. - - Uses the covariance data stored in proj.data['Covariance']['data'] after refinement. - This includes both independent and dependent parameters (via ComputeDepESD). - - Args: - proj: GSAS-II project object after refinement - verbose: If True, print progress messages. - - Returns: - dict: Mapping of parameter names to ``{"value": float, "esd": float}``. - Returns an empty dict if no covariance data is available. - - Raises: - RuntimeError: If ComputeDepESD fails (dependent parameter ESDs cannot be calculated). - - Example: - >>> params = extract_refined_params_from_project(proj) - >>> params[":0:U"] - {"value": 47.406, "esd": 8.314} - """ - cov_data = proj.data.get('Covariance', {}).get('data', {}) - - if not cov_data: - return {} - - vary_list = cov_data.get('varyList', []) - variables = cov_data.get('variables', []) - sig = cov_data.get('sig', []) - - # Check if any are empty (works for both lists and numpy arrays) - if len(vary_list) == 0 or len(variables) == 0 or len(sig) == 0: - return {} - - # Create parameter dictionary with values and ESDs for independent parameters - param_dict = {} - for param_name, value, esd in zip(vary_list, variables, sig): - param_dict[param_name] = { - "value": float(value), - "esd": float(esd) - } - - # Add dependent parameter ESDs using GSAS-II's ComputeDepESD - cov_matrix = cov_data.get('covMatrix') - # Check if cov_matrix exists and is not empty (works for None, empty array, etc.) - if cov_matrix is not None and hasattr(cov_matrix, '__len__') and len(cov_matrix) > 0: - try: - dep_sig_dict = G2mv.ComputeDepESD(cov_matrix, vary_list) - # dep_sig_dict only contains ESDs; values are already in param_dict from - # the independent-parameter loop above — just update the esd entries. - for param_name, esd in dep_sig_dict.items(): - if param_name in param_dict: - param_dict[param_name]["esd"] = float(esd) - # If param not in param_dict, it's a dependent param we haven't seen. - # For now, skip it as we don't have its value easily accessible. - except Exception as e: - raise RuntimeError( - f"ComputeDepESD failed; dependent parameter ESDs cannot be calculated. " - f"Original error: {e}" - ) from e - elif verbose: - print(" Note: covariance matrix is absent; dependent parameter ESDs skipped.") - - return param_dict - - -def extract_refined_params_from_lst(lst_file: Path) -> Dict[str, Dict[str, Any]]: - """ - PRESERVED (disabled at call site) — see commented block in run_refinement() for context. - - Extract all refined parameters with values and ESDs from .lst file. - - NOTE: This function is incomplete and its call site has been intentionally disabled. - The covariance matrix path (extract_refined_params_from_project) is the only supported - extraction method. This function does not cover atom parameters and uses a custom naming - scheme (e.g. "cell:a") that differs from the GSAS-II-native names in proj.data. - - # TODO: Remove this function once a test is written confirming that covariance matrix - # ESD output (extract_refined_params_from_project) matches what .lst parsing previously - # produced for the parameters it did cover (instrument, background, unit cell). - # Do not delete until that regression test exists and passes. - - Parses the GSAS-II .lst file to extract parameter names, values, and ESDs. - This is used as a fallback or complement to proj.data extraction. - - Args: - lst_file: Path to the .lst file - - Returns: - Dictionary mapping parameter names to {"value": float, "esd": float|None} - Parameters without ESDs (fixed parameters) have esd=None. - - Note: - Currently extracts instrument parameters, background, and unit cell. - Additional parameter types (atoms, etc.) can be added as needed. - """ - if not lst_file.exists(): - return {} - - param_dict = {} - content = lst_file.read_text() - lines = content.split('\n') - - i = 0 - while i < len(lines): - line = lines[i] - - # Instrument parameters section - if 'Instrument Parameters:' in line: - # Look for the "names :" line - i += 1 - while i < len(lines) and not lines[i].strip().startswith('names :'): - i += 1 - - if i < len(lines): - names_line = lines[i] - # Next line should be "value :" - i += 1 - if i < len(lines) and lines[i].strip().startswith('value :'): - values_line = lines[i] - # Next line should be "sig :" (ESDs) - i += 1 - sig_line = "" - if i < len(lines) and lines[i].strip().startswith('sig :'): - sig_line = lines[i] - - # Parse the three lines - names = names_line.split(':')[1].strip().split() - values = values_line.split(':')[1].strip().split() - sigs = sig_line.split(':')[1].strip().split() if sig_line else [] - - for j, name in enumerate(names): - if j < len(values): - try: - value = float(values[j]) - esd = float(sigs[j]) if j < len(sigs) and sigs[j] else None - # Use GSAS-II naming convention for instrument params - param_name = f":0:{name}" - param_dict[param_name] = {"value": value, "esd": esd} - except (ValueError, IndexError): - pass - - # Background coefficients section - elif 'Background function:' in line and 'chebyschev' in line: - # Next line should be "value :" - i += 1 - if i < len(lines) and lines[i].strip().startswith('value :'): - values_line = lines[i] - # Next line should be "sig :" - i += 1 - sig_line = "" - if i < len(lines) and lines[i].strip().startswith('sig :'): - sig_line = lines[i] - - values = values_line.split(':')[1].strip().split() - sigs = sig_line.split(':')[1].strip().split() if sig_line else [] - - for j, value_str in enumerate(values): - try: - value = float(value_str) - esd = float(sigs[j]) if j < len(sigs) and sigs[j] else None - param_name = f":0:Back;{j}" - param_dict[param_name] = {"value": value, "esd": esd} - except (ValueError, IndexError): - pass - - # Unit cell parameters section - elif 'New unit cell:' in line: - # Look for values line - i += 1 - while i < len(lines) and not lines[i].strip().startswith('values:'): - i += 1 - - if i < len(lines): - values_line = lines[i] - # Next line should be "esds :" - i += 1 - esds_line = "" - if i < len(lines) and lines[i].strip().startswith('esds :'): - esds_line = lines[i] - - # Parse - note that unit cell params are phase-specific - # For now, store with generic name (can be enhanced later to include phase name) - values = values_line.split(':')[1].strip().split() - esds = esds_line.split(':')[1].strip().split() if esds_line else [] - - cell_param_names = ['a', 'b', 'c', 'alpha', 'beta', 'gamma', 'volume'] - for j, name in enumerate(cell_param_names): - if j < len(values): - try: - value = float(values[j]) - esd = float(esds[j]) if j < len(esds) and esds[j] else None - # Store with generic cell param naming - param_name = f"cell:{name}" - param_dict[param_name] = {"value": value, "esd": esd} - except (ValueError, IndexError): - pass - - i += 1 - - return param_dict - - -def get_descriptive_param_name(param_name: str) -> str: - """ - Convert GSAS-II internal parameter names to human-readable descriptions. - - Args: - param_name: GSAS-II parameter name (e.g., ":0:U", "0::A0", ":0:Back;3") - - Returns: - Human-readable description of the parameter - - Examples: - >>> get_descriptive_param_name(":0:U") - "instrument_broadening_U" - >>> get_descriptive_param_name("0::A0") - "phase_0_A11_reciprocal_metric_tensor" - >>> get_descriptive_param_name(":0:Scale") - "phase_scale_factor" - >>> get_descriptive_param_name(":0:Back;3") - "background_coefficient_3" - """ - # Handle phase-specific reciprocal metric tensor (A-matrix) - # Check for A0-A5 specifically (not AUiso, Afrac, etc.) - if '::A' in param_name: - parts = param_name.split('::') - if len(parts) == 2: - phase_idx = parts[0] - a_param = parts[1] # e.g., "A0", "A1", etc. - - # Only handle A0-A5 (reciprocal metric tensor) - if a_param in ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']: - # A0-A5 map to A11, A22, A33, A12, A13, A23 - a_mapping = { - 'A0': 'A11', 'A1': 'A22', 'A2': 'A33', - 'A3': 'A12', 'A4': 'A13', 'A5': 'A23' - } - tensor_component = a_mapping[a_param] - return f"phase_{phase_idx}_reciprocal_metric_tensor_{tensor_component}" - - # Handle other phase parameters (e.g., "0::Afrac:0", "0::Ax:0") - if '::' in param_name: - parts = param_name.split('::') - phase_idx = parts[0] - param_type = parts[1] - - if ':' in param_type: - # Format: "0::Afrac:0" or "0::Ax:0" - sub_parts = param_type.split(':') - param_base = sub_parts[0] - atom_idx = sub_parts[1] - - if param_base == 'Afrac': - return f"phase_{phase_idx}_atom_{atom_idx}_occupancy" - elif param_base == 'AUiso': - return f"phase_{phase_idx}_atom_{atom_idx}_isotropic_displacement" - elif param_base == 'Ax': - return f"phase_{phase_idx}_atom_{atom_idx}_x_coordinate" - elif param_base == 'Ay': - return f"phase_{phase_idx}_atom_{atom_idx}_y_coordinate" - elif param_base == 'Az': - return f"phase_{phase_idx}_atom_{atom_idx}_z_coordinate" - elif param_base.startswith('AU'): - # Anisotropic displacement parameters (AU11, AU22, etc.) - return f"phase_{phase_idx}_atom_{atom_idx}_anisotropic_displacement_{param_base}" - else: - return f"phase_{phase_idx}_atom_{atom_idx}_{param_base}" - else: - return f"phase_{phase_idx}_{param_type}" - - # Handle histogram parameters (format: ":hist_idx:param") - if param_name.startswith(':') and param_name.count(':') >= 2: - parts = param_name.split(':') - # parts[0] is empty, parts[1] is hist_idx, parts[2] is param - hist_idx = parts[1] - param = parts[2] if len(parts) > 2 else "" - - # Instrument broadening parameters - if param == 'U': - return "instrument_broadening_U" - elif param == 'V': - return "instrument_broadening_V" - elif param == 'W': - return "instrument_broadening_W" - elif param == 'X': - return "instrument_broadening_X" - elif param == 'Y': - return "instrument_broadening_Y" - elif param == 'Z': - return "instrument_broadening_Z" - - # Instrument parameters - elif param == 'Lam': - return "wavelength" - elif param == 'Zero': - return "zero_point_correction" - elif param == 'SH/L': - return "axial_divergence" - elif param == 'Polariz': - return "polarization_correction" - - # Scale factor - elif param == 'Scale': - return "phase_scale_factor" - - # Background coefficients - elif param.startswith('Back;'): - coeff_idx = param.split(';')[1] - return f"background_coefficient_{coeff_idx}" - - # Background peaks - elif param.startswith('BkPk'): - # Format: "BkPkpos;0", "BkPkint;0", "BkPksig;0", "BkPkgam;0" - # Extract type (pos/int/sig/gam) and index - if ';' in param: - # Remove 'BkPk' prefix and split - without_prefix = param[4:] # Remove "BkPk" - parts = without_prefix.split(';') - pk_type = parts[0] # pos, int, sig, gam - pk_idx = parts[1] if len(parts) > 1 else "0" - - type_mapping = { - 'pos': 'position', - 'int': 'intensity', - 'sig': 'sigma', - 'gam': 'gamma' - } - return f"background_peak_{pk_idx}_{type_mapping.get(pk_type, pk_type)}" - else: - return f"background_peak_{param}" - - else: - return f"histogram_{hist_idx}_{param}" - - # Handle phase-histogram parameters (format: "phase_idx:hist_idx:param") - # This includes Scale and other HAP (Histogram-Atom-Phase) parameters - if ':' in param_name and not param_name.startswith(':'): - parts = param_name.split(':') - if len(parts) >= 3: - phase_idx = parts[0] - hist_idx = parts[1] - param = parts[2] - - if param == 'Scale': - return f"phase_{phase_idx}_scale_factor" - elif param.startswith('Mustrain'): - return f"phase_{phase_idx}_mustrain_{param.split(';')[1]}" - elif param.startswith('Size'): - return f"phase_{phase_idx}_crystallite_size_{param.split(';')[1]}" - else: - return f"phase_{phase_idx}_histogram_{hist_idx}_{param}" - - # Handle cell parameters from .lst parsing - if param_name.startswith('cell:'): - cell_param = param_name.split(':')[1] - param_mapping = { - 'a': 'lattice_parameter_a', - 'b': 'lattice_parameter_b', - 'c': 'lattice_parameter_c', - 'alpha': 'lattice_angle_alpha', - 'beta': 'lattice_angle_beta', - 'gamma': 'lattice_angle_gamma', - 'volume': 'unit_cell_volume' - } - return param_mapping.get(cell_param, f"cell_{cell_param}") - - # Fallback - return param_name - - -def parse_parameter_associations(param_name: str) -> dict: - """ - Parse GSAS-II parameter name to extract phase and atom associations. - - Args: - param_name: GSAS-II parameter name (e.g., "0::Afrac:2", ":0:U", "1:0:Scale") - - Returns: - Dictionary with keys 'phase_idx' and 'atom_idx' (both int or None) - - Examples: - >>> parse_parameter_associations("0::Afrac:2") - {"phase_idx": 0, "atom_idx": 2} - >>> parse_parameter_associations("1::A0") - {"phase_idx": 1, "atom_idx": None} - >>> parse_parameter_associations("0:0:Scale") - {"phase_idx": 0, "atom_idx": None} - >>> parse_parameter_associations(":0:U") - {"phase_idx": None, "atom_idx": None} - """ - phase_idx = None - atom_idx = None - - # Pattern 1: Phase-atom parameters (format: "phase_idx::param:atom_idx") - # Examples: "0::Afrac:2", "1::AUiso:0", "0::Ax:3" - if '::' in param_name: - parts = param_name.split('::') - try: - phase_idx = int(parts[0]) - except (ValueError, IndexError): - pass - - # Check if there's an atom index - if len(parts) > 1 and ':' in parts[1]: - sub_parts = parts[1].split(':') - if len(sub_parts) > 1: - try: - atom_idx = int(sub_parts[1]) - except (ValueError, IndexError): - pass - - # Pattern 2: Phase-histogram parameters (format: "phase_idx:hist_idx:param") - # Examples: "0:0:Scale", "1:0:Mustrain;i", "0:0:Size;mx" - elif ':' in param_name and not param_name.startswith(':'): - parts = param_name.split(':') - if len(parts) >= 2: - try: - phase_idx = int(parts[0]) - except (ValueError, IndexError): - pass - - # Pattern 3: Histogram-only parameters (format: ":hist_idx:param") - # Examples: ":0:U", ":0:Back;3", ":0:BkPkpos;1" - # These have no phase or atom association (already None) - - return {"phase_idx": phase_idx, "atom_idx": atom_idx} - - -def build_phase_name_mapping(proj: Any) -> Dict[int, str]: - """ - Build mapping from phase index to phase name. - - Args: - proj: GSAS-II project object - - Returns: - Dictionary mapping phase index (int) to phase name (str) - - Example: - >>> mapping = build_phase_name_mapping(proj) - >>> mapping - {0: "LaB6", 1: "DRX_33"} - """ - phase_mapping = {} - try: - phase_names = [p.name for p in proj.phases() if p is not None] - for phase_idx, phase_name in enumerate(phase_names): - phase_mapping[phase_idx] = phase_name - except Exception as e: - print(f" Warning: Failed to build phase name mapping: {e}") - return phase_mapping - - -def build_atom_name_mapping(proj: Any) -> Dict[int, Dict[int, str]]: - """ - Build mapping from (phase_idx, atom_idx) to atom label. - - Args: - proj: GSAS-II project object - - Returns: - Nested dictionary: {phase_idx: {atom_idx: atom_label}} - - Example: - >>> mapping = build_atom_name_mapping(proj) - >>> mapping - {0: {0: "La", 1: "B"}, 1: {0: "Li", 1: "Mg", 2: "Mn1"}} - """ - atom_mapping = {} - try: - phase_names = [p.name for p in proj.phases() if p is not None] - for phase_idx, phase_name in enumerate(phase_names): - atom_mapping[phase_idx] = {} - try: - atoms_list = proj.data['Phases'][phase_name]['Atoms'] - for atom_idx, atom_record in enumerate(atoms_list): - # atom_record[0] is the atom label - atom_label = atom_record[0] - atom_mapping[phase_idx][atom_idx] = atom_label - except (KeyError, IndexError, TypeError) as e: - print(f" Warning: Failed to extract atoms for phase '{phase_name}': {e}") - except Exception as e: - print(f" Warning: Failed to build atom name mapping: {e}") - return atom_mapping - - -def export_refined_parameters_csv( - param_dict: Dict[str, Dict[str, Any]], - output_file: Path, - proj: Any = None, - include_category: bool = True -) -> Optional[pd.DataFrame]: - """ - Export refined parameters to CSV file and return the DataFrame. - - Args: - param_dict: Dictionary from extract_refined_params_* functions - output_file: Path to output CSV file - proj: GSAS-II project object (optional, needed for phase/atom names) - include_category: If True, add 'category' and 'descriptive_name' columns (default: True) - - Returns: - DataFrame with the exported parameters, or None if param_dict is empty. - - Output CSV / DataFrame columns: - - parameter_name: GSAS-II internal parameter name - - descriptive_name: Human-readable parameter description (if include_category=True) - - phase_name: Name of associated phase (None if not phase-specific) - - phase_idx: Index of associated phase (None if not phase-specific) - - atom_name: Label of associated atom (None if not atom-specific) - - atom_idx: Index of associated atom (None if not atom-specific) - - value: Refined value - - esd: Estimated standard deviation (None for fixed parameters) - - category: Parameter category (instrument, background, cell, etc.) if include_category=True - """ - if len(param_dict) == 0: - return None - - # Build phase and atom mappings if proj is available - phase_mapping = {} - atom_mapping = {} - if proj is not None: - phase_mapping = build_phase_name_mapping(proj) - atom_mapping = build_atom_name_mapping(proj) - - rows = [] - for param_name, param_data in param_dict.items(): - # Parse parameter associations - associations = parse_parameter_associations(param_name) - phase_idx = associations["phase_idx"] - atom_idx = associations["atom_idx"] - - # Lookup names from mappings - phase_name = phase_mapping.get(phase_idx) if phase_idx is not None else None - atom_name = atom_mapping.get(phase_idx, {}).get(atom_idx) if phase_idx is not None and atom_idx is not None else None - - row = { - "parameter_name": param_name, - "value": param_data["value"], - "esd": param_data.get("esd"), - "phase_name": phase_name, - "phase_idx": phase_idx, - "atom_name": atom_name, - "atom_idx": atom_idx - } - - if include_category: - # Add descriptive name - row["descriptive_name"] = get_descriptive_param_name(param_name) - - # Determine category from parameter name - if '::A' in param_name and len(param_name.split('::')[1]) <= 2: - # Reciprocal metric tensor (A0-A5) - category = 'reciprocal_metric_tensor' - elif '::' in param_name: - # Other phase parameters (atoms, etc.) - param_type = param_name.split('::')[1] - if 'frac' in param_type: - category = 'atom_occupancy' - elif 'Uiso' in param_type: - category = 'atom_displacement_isotropic' - elif param_type.startswith('AU') and len(param_type) > 2: - category = 'atom_displacement_anisotropic' - elif param_type.startswith('A') and param_type[1] in ['x', 'y', 'z']: - category = 'atom_position' - else: - category = 'phase_other' - elif param_name.startswith('cell:'): - category = 'unit_cell' - elif ':' in param_name: - parts = param_name.split(':') - if len(parts) >= 3: - param_part = parts[2] - if param_part.startswith('Back;'): - category = 'background' - elif param_part.startswith('BkPk'): - category = 'background_peak' - elif param_part == 'Scale': - category = 'scale' - elif param_part in ['U', 'V', 'W', 'X', 'Y', 'Z']: - category = 'instrument_broadening' - elif param_part in ['Lam', 'Zero', 'SH/L', 'Polariz']: - category = 'instrument' - else: - category = 'other' - else: - category = 'other' - else: - category = 'other' - - row["category"] = category - - rows.append(row) - - # Sort by category, then parameter name - if include_category: - rows.sort(key=lambda x: (x["category"], x["parameter_name"])) - else: - rows.sort(key=lambda x: x["parameter_name"]) - - # Reorder columns: parameter_name, descriptive_name, phase_name, phase_idx, atom_name, atom_idx, value, esd, category - if include_category: - df = pd.DataFrame(rows, columns=["parameter_name", "descriptive_name", "phase_name", "phase_idx", "atom_name", "atom_idx", "value", "esd", "category"]) - else: - df = pd.DataFrame(rows, columns=["parameter_name", "phase_name", "phase_idx", "atom_name", "atom_idx", "value", "esd"]) - - # Convert index columns to nullable integer type (Int64) to avoid scientific notation formatting - df['phase_idx'] = df['phase_idx'].astype('Int64') - df['atom_idx'] = df['atom_idx'].astype('Int64') - - # Format float columns independently: values need 6 decimal places, ESDs need 8 - df['value'] = df['value'].apply(lambda x: f"{x:.6e}" if pd.notna(x) else "") - df['esd'] = df['esd'].apply(lambda x: f"{x:.8e}" if pd.notna(x) else "") - - df.to_csv(output_file, index=False, lineterminator="\n") - return df - - -def set_refinement_cycles(proj: Any, num_cycles: int, print_info: bool = False) -> None: - """ - Set the number of refinement cycles in the GSAS-II project. - - Parameters: - proj : GSAS-II project object - The GSAS-II project to set the refinement cycles for. - num_cycles : int - The number of refinement cycles to set. - print_info : bool, optional - If True, print information about the refinement cycles being set. Default is False. - - Returns: - None - """ - - proj.set_Controls('cycles', num_cycles) - if print_info: - print(f"Set number of refinement cycles to {num_cycles}") - - -def _refine_with_message(proj) -> tuple[bool, str]: - """Run the project refinement, returning (ok, GSAS-II failure message). - - ``G2Project.refine()`` calls ``G2strMain.Refine`` and DISCARDS its - ``(OK, Rvals)`` return, so failure text like "Invalid metric tensor for - phase #0" reaches only the console — callers see a silent no-Rwp failure. - Mirror the non-sequential branch of ``refine()`` (index, constraint - check, Refine, reload) to keep ``Rvals['msg']``. Any surprise from - GSAS-II internals falls back to the plain ``proj.refine()`` so behavior - is never worse than before. - """ - try: - from GSASII import GSASIIstrIO as G2stIO - from GSASII import GSASIIstrMain as G2strMain - - seq_setting = proj.data['Controls']['data'].get('Seq Data', []) - if not seq_setting: - proj.index_ids() # saves the project, as refine() does - errmsg, _warnmsg = G2stIO.ReadCheckConstraints(proj.filename) - if errmsg: - return False, f"Constraint error: {errmsg}" - ret = G2strMain.Refine(proj.filename, makeBack=False) - proj.reload() - ok, rvals = (ret if isinstance(ret, tuple) and len(ret) == 2 - else (True, {})) - msg = rvals.get('msg', '') if isinstance(rvals, dict) else '' - msg = msg.replace('**** ERROR: Refinement failed ****', '').strip() - return bool(ok), msg - except (ImportError, AttributeError, KeyError, TypeError): - pass # GSAS-II internals changed: fall back to the plain call below - - proj.refine() - return True, '' - - -def execute_rietveld_refinement( - proj: Any, - hist: Any, - recipe: RecipeModel, - verbose: bool -) -> dict: - """ - Execute standard GSAS-II Rietveld refinement. - - This replaces the previous "structural_only" strategy. - - Args: - proj: GSAS-II project object - hist: Histogram object - recipe: Validated recipe model - verbose: Print detailed progress - - Returns: - Result dict with success, rwp, elapsed_time - """ - controls = recipe.payload.refinement_controls - - if verbose: - print(f"\n{'='*60}") - print(f"Executing Rietveld Refinement") - print(f" Cycles: {controls.refinement_cycles}") - print(f"{'='*60}\n") - - # Execute refinement (keeping GSAS-II's failure message, which - # G2Project.refine() would otherwise discard) - refine_ok, g2_msg = _refine_with_message(proj) - - # Extract Rwp - rwp_final = hist.residuals.get("wR") - - if not refine_ok or rwp_final is None: - if g2_msg: - error = f"Rietveld refinement failed: {' '.join(g2_msg.split())}" - else: - error = ("Rietveld refinement produced no Rwp — proj.refine() " - "may have failed silently") - return { - 'success': False, - 'rwp': None, - 'error': error, - } - - if verbose: - print(f"Rietveld refinement complete. Final Rwp: {rwp_final:.3f}%\n") - - return { - 'success': True, - 'rwp': rwp_final - } - - -def execute_spf_refinement( - proj: Any, - hist: Any, - recipe: RecipeModel, - verbose: bool -) -> dict: - """ - Execute single peak fitting refinement. - - This replaces the previous "peaks_only" strategy. - - Args: - proj: GSAS-II project object - hist: Histogram object - recipe: Validated recipe model - verbose: Print detailed progress - - Returns: - Result dict with success, rwp, elapsed_time - """ - controls = recipe.payload.refinement_controls - spf_mode = "useIP" if controls.single_peak_fitting_mode.use_instrument_profile else "hold" - - if verbose: - print(f"\n{'='*60}") - print(f"Executing Single Peak Fitting") - print(f" Mode: {spf_mode} ({'use instrument profile' if spf_mode == 'useIP' else 'refine peak widths'})") - print(f" Cycles: {controls.refinement_cycles}") - print(f"{'='*60}\n") - - # Execute single peak fitting (cycles already set in step 10) - peak_result = hist.refine_peaks(mode=spf_mode) - - # Extract Rwp from peak_result - rwp_final = peak_result[3].get("Rwp") if len(peak_result) > 3 else None - - if rwp_final is None: - return { - 'success': False, - 'rwp': None, - 'error': "Single peak fitting produced no Rwp — hist.refine_peaks() may have failed silently", - } + (True, "filename or path contains 'template'") - if verbose: - print(f"Single peak fitting complete. Final Rwp: {rwp_final:.3f}%\n") + >>> is_template_file({"schema_name": "GSASII_Rietveld", "payload": {"xrd_data": {...}}}, Path("example_LaB6/input.json")) + (False, None) + """ + # Check 1: Path contains "template" + if "template" in str(input_path).lower(): + return True, "filename or path contains 'template'" - return { - 'success': True, - 'rwp': rwp_final - } + # Check 2: Missing payload or schema-specific required fields + payload = recipe_dict.get('payload', {}) + if not payload: + return True, "missing payload" + # Check for schema-specific required fields + schema_name = recipe_dict.get('schema_name') + if schema_name == 'GSASII_Rietveld': + required_fields = ['xrd_data', 'instrument', 'phases', 'refinement_controls'] + missing = [field for field in required_fields if field not in payload or payload[field] is None] + if missing: + return True, f"GSASII_Rietveld schema missing required fields: {missing}" + elif schema_name == 'GSASII_SPF': + required_fields = ['xrd_data', 'instrument', 'single_peaks', 'refinement_controls'] + missing = [field for field in required_fields if field not in payload or payload[field] is None] + if missing: + return True, f"GSASII_SPF schema missing required fields: {missing}" + else: + # Fallback: check for common core fields if schema unknown + core_fields = ['xrd_data', 'instrument', 'refinement_controls'] + missing_core = [field for field in core_fields if field not in payload] + if len(missing_core) == len(core_fields): + return True, "missing all required fields in payload (xrd_data, instrument, refinement_controls)" -# Schema executor registry -SCHEMA_EXECUTORS = { - 'GSASII_Rietveld': execute_rietveld_refinement, - 'GSASII_SPF': execute_spf_refinement -} + return False, None -######################################## -# Post-refinement extraction helpers -######################################## +def validate_simulation_mode_parameters(recipe: RecipeModel, verbose: bool = False) -> tuple[bool, List[str]]: + """ + Validate that simulation mode examples have all refinement parameters locked. -def _extract_fit_profile(hist: Any, output_dir: Path) -> dict: - """Extract fit profile arrays from histogram and save fit_profile.txt. + Simulation mode (refinement_cycles=1 with all parameters fixed) must have deterministic + output. This function checks for any `refine_flag: true` in structural or background + parameters that would violate determinism. Args: - hist: GSAS-II histogram object after refinement. - output_dir: Directory to write ``fit_profile.txt``. + recipe: Validated RecipeModel instance (uses payload structure) + verbose: If True, print detailed parameter checks Returns: - dict: Column-oriented data (JSON-serializable) with keys ``two_theta``, - ``y_obs``, ``y_weights``, ``y_calc``, ``y_diff``, ``y_bkg``, ``q_values``, - ``d_spacings``. - """ - two_theta = hist.getdata(datatype="X") - q_values = hist.getdata(datatype="Q") - d_spacings = hist.getdata(datatype="d") - y_obs = hist.getdata(datatype="Yobs") - y_weights = hist.getdata(datatype="Yweight") - y_calc = hist.getdata(datatype="Ycalc") - y_bkg = hist.getdata(datatype="Background") - y_diff = hist.getdata(datatype="Residual") - - fit_profile_df = pd.DataFrame({ - "two_theta": two_theta, - "y_obs": y_obs, - "y_weights": y_weights, - "y_calc": y_calc, - "y_diff": y_diff, - "y_bkg": y_bkg, - "q_values": q_values, - "d_spacings": d_spacings, - }) - fit_profile_df.to_csv( - output_dir / "fit_profile.txt", sep="\t", float_format="%.8f", - header=True, index=False, lineterminator="\n" - ) - return {col: fit_profile_df[col].tolist() for col in fit_profile_df.columns} - - -def _extract_spf_peak_report( - proj: Any, hist: Any, recipe: RecipeModel, output_dir: Path, verbose: bool -) -> tuple[dict, dict]: - """Extract single peak fitting results and save report files. + (is_valid, warnings): is_valid is True if all parameters are properly locked, + warnings is a list of issues found (empty if valid). - Called only for ``GSASII_SPF`` runs where ``recipe.payload.single_peaks`` - is set. Returns two column-oriented dicts (JSON-serializable) that are - normalised to DataFrames by ``run()``. + Examples: + >>> is_valid, warnings = validate_simulation_mode_parameters(recipe) + >>> if not is_valid: + ... for warning in warnings: + ... print(f"WARNING: {warning}") + """ + is_valid = True + warnings: List[str] = [] - Also writes: - - ``single_peaks_report.txt`` — per-peak widths and convergence status - - ``peak_convergence_diagnostics.txt`` — only when peaks have issues + # Get refinement controls (in payload) + controls = recipe.payload.refinement_controls - Args: - proj: GSAS-II project object after refinement. - hist: GSAS-II histogram object. - recipe: Validated RecipeModel. - output_dir: Directory to write report files. - verbose: If True, print convergence warnings to stdout. + # Only check simulation mode (refinement_cycles == 1) + if controls.refinement_cycles != 1: + return True, [] # Not simulation mode, skip validation - Returns: - ``(spf_peaks_data, spf_diagnostics_data)`` where each is a - column-oriented dict, or ``({}, {})`` when single peaks are not used. - """ - if recipe.payload.single_peaks is None: - return {}, {} - - peak_list = proj.data.get(hist.name, {}).get('Peak List', {}).get('peaks', []) - if not peak_list: - return {}, {} - - peak_data = [] - convergence_diagnostics = [] - converged_count = 0 - aphysical_count = 0 - - for i, peak in enumerate(peak_list): - pos, pos_flag, intensity, int_flag, sig_sq, sig_sq_flag, gamma, gam_flag = peak - - # Determine convergence status - status = "converged" - if np.isnan(sig_sq) or np.isnan(gamma): - status = "NaN_failed" - elif sig_sq <= 0 and gamma < 0: - status = "negative_sigma_sq_and_gamma_warning" - aphysical_count += 1 - elif sig_sq <= 0: - status = "zero_or_negative_sigma_sq_warning" - aphysical_count += 1 - elif gamma < 0: - status = "negative_gamma_warning" - aphysical_count += 1 - else: - converged_count += 1 + if verbose: + print("Validating simulation mode constraints...") - # Copy GSAS-II behavior for PV calc — use a small positive default for - # aphysical (zero/negative) sigma_sq or gamma values - sigma = np.sqrt(sig_sq) if sig_sq > 0 else DEFAULT_SPF_SIGMA_MIN - # NOTE: GSAS-II gamma = FWHM_L (not HWHM), so we use gamma directly - gamma_calc = gamma if gamma > 0 else DEFAULT_SPF_GAMMA_MIN + # Check background parameters + if recipe.payload.background is not None: + if recipe.payload.background.chebyshev is not None: + if recipe.payload.background.chebyshev.refine_flag: + msg = "CRITICAL: Chebyshev background has refine_flag=true in simulation mode (refinement_cycles=1). " \ + "This violates determinism - all parameters must be locked. Set refine_flag=false." + warnings.append(msg) + is_valid = False + if verbose: + print(f" {CROSS} {msg}") - # Calculate widths in degrees (GSAS-II stores in centidegrees) - fwhm_g, fwhm_l, fwhm_pv, ib_g, ib_l, ib_pv, valid, warning_msg = calculate_peak_widths( - sigma / 100, gamma_calc * 0.5 / 100 - ) + if recipe.payload.background.single_peaks is not None: + # Check single peak parameters + param_lists = [ + (recipe.payload.background.single_peaks.positions, "single_peaks.positions"), + (recipe.payload.background.single_peaks.intensities, "single_peaks.intensities"), + (recipe.payload.background.single_peaks.pv_gaussian_sigma, "single_peaks.pv_gaussian_sigma"), + (recipe.payload.background.single_peaks.pv_lorentzian_gamma, "single_peaks.pv_lorentzian_gamma"), + ] + for param_list, param_name in param_lists: + if param_list is not None: + for i, param in enumerate(param_list): + if param[1]: # refine_flag is second element + msg = f"WARNING: {param_name}[{i}] has refine_flag=true in simulation mode. " \ + "Set refine_flag=false for deterministic output." + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") - # Get GSAS-II verification (may fail for aphysical values) - try: - # GSAS-II uses gamma directly as FWHM_L (differs from scipy, TOPAS, literature) - fwhm_gsas = G2pwd.getgamFW(gamma_calc / 100, sigma / 100) - except Exception: - fwhm_gsas = np.nan - - converged_bool = status == "converged" - peak_data.append([ - pos, intensity, sigma, sig_sq, gamma_calc, - fwhm_g, fwhm_l, fwhm_pv, ib_g, ib_l, ib_pv, - fwhm_gsas, converged_bool, status - ]) + # Check instrument parameterization + if recipe.payload.instrument.parameterization is not None: + param_dict = recipe.payload.instrument.parameterization.model_dump(mode='json') - if status != "converged": - convergence_diagnostics.append({ - 'peak_index': i, - 'position_2theta': pos, - 'final_sigma_sq': sig_sq, - 'final_gamma': gamma, - 'status': status, - 'notes': warning_msg if warning_msg else "" - }) - - # Build DataFrames - spf_cols = [ - "position_2theta", "intensity", "sigma", "sigma_squared", "gamma", - "fwhm_gaussian", "fwhm_lorentzian", "fwhm_pseudovoigt", - "integral_breadth_gaussian", "integral_breadth_lorentzian", - "integral_breadth_pseudovoigt", "fwhm_gsas_verification", - "converged", "convergence_detail" - ] - spf_peaks_df = pd.DataFrame(peak_data, columns=spf_cols) - diag_df = pd.DataFrame(convergence_diagnostics) if convergence_diagnostics else pd.DataFrame( - columns=['peak_index', 'position_2theta', 'final_sigma_sq', 'final_gamma', 'status', 'notes'] - ) + # Check wavelength + if param_dict.get('wavelength') and param_dict['wavelength'][1]: + msg = "WARNING: instrument.parameterization.wavelength has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") - # Write single_peaks_report.txt (custom mixed-type formatting) - header_comment = ( - f"{converged_count} of {len(peak_list)} peaks converged; " - f"{aphysical_count} peaks have aphysical values (warnings)" - ) - header_cols = "\t".join(spf_cols) - peak_array = np.array(peak_data, dtype=object) - with open(output_dir / "single_peaks_report.txt", 'w', newline="\n") as f: - f.write(f"# {header_comment}\n") - f.write(f"{header_cols}\n") - for row in peak_array: - formatted_row = [] - for j, val in enumerate(row): - col_name = spf_cols[j] - if col_name == "converged": - formatted_row.append(str(val).lower()) - elif col_name == "convergence_detail": - formatted_row.append(str(val)) - else: - formatted_row.append("nan" if np.isnan(val) else f"{val:.8f}") - f.write("\t".join(formatted_row) + "\n") - - # Write diagnostics file if there are issues - if convergence_diagnostics: - diag_df.to_csv( - output_dir / "peak_convergence_diagnostics.txt", sep="\t", - float_format="%.8f", header=True, index=False, lineterminator="\n" - ) - if verbose: - print( - f"\nWarning: {len(convergence_diagnostics)} of {len(peak_list)} " - f"peaks have convergence issues" - ) - print(f" See {output_dir / 'peak_convergence_diagnostics.txt'} for details\n") - - return ( - {col: spf_peaks_df[col].tolist() for col in spf_peaks_df.columns}, - {col: diag_df[col].tolist() for col in diag_df.columns}, - ) + # Check broadening parameters + if param_dict.get('broadening'): + for param_key, param_value in param_dict['broadening'].items(): + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: instrument.parameterization.broadening.{param_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + # Check corrections + if param_dict.get('corrections'): + for param_key, param_value in param_dict['corrections'].items(): + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: instrument.parameterization.corrections.{param_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") -def _extract_phase_reports( - proj: Any, hist: Any, recipe: RecipeModel, param_dict: dict, output_dir: Path -) -> tuple[dict, dict]: - """Extract unit cell and peak list reports for all phases. + # Check phase-level parameters (only if phases exist) + if recipe.payload.phases is not None: + phases_dict = recipe.payload.model_dump(mode='json')['phases'] + for phase_name, phase_info in phases_dict.items(): + param_dict = phase_info.get('parameterization', {}) - Writes ``{phase}_unit_cell_report.csv`` and ``{phase}_peak_list_report.csv`` - for each phase. + # Check scale + if param_dict.get('scale') and param_dict['scale'][1]: + msg = f"WARNING: phases.{phase_name}.parameterization.scale has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") - Args: - proj: GSAS-II project object after refinement. - hist: GSAS-II histogram object. - recipe: Validated RecipeModel (used to check if phases exist). - param_dict: Refined parameter dict from - ``extract_refined_params_from_project()`` (needed for cell ESDs). - output_dir: Directory to write CSV files. + # Check unit cell + unit_cell = param_dict.get('unit_cell', {}) + if unit_cell: + for cell_param, param_value in unit_cell.items(): + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: phases.{phase_name}.parameterization.unit_cell.{cell_param} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") - Returns: - ``(unit_cell_data, peak_list_data)`` — each is a - ``{phase_name: list-of-records}`` dict (JSON-serializable). - """ - unit_cell_data: dict = {} - peak_list_data: dict = {} - - if recipe.payload.phases is None or len(recipe.payload.phases) == 0: - return unit_cell_data, peak_list_data - - phase_names = [p.name for p in proj.phases() if p is not None] - - for phase_idx, phase_name in enumerate(phase_names): - try: - unit_cell = proj.data['Phases'][phase_name]['General']['Cell'][1:8] - except (KeyError, IndexError): - continue - - cell_params = ["cell_a", "cell_b", "cell_c", "cell_alpha", "cell_beta", "cell_gamma", "cell_volume"] - esds = calculate_cell_esds_from_A_matrix(phase_idx, proj, phase_name) - - # NOTE: .lst fallback for cell ESDs is disabled — preserved for Phase 2 reference. - # calculate_cell_esds_from_A_matrix raises RuntimeError on failure rather than - # returning [None]*7, so the fallback block below is unreachable. - # if all(esd is None for esd in esds): - # cell_param_keys = ['a', 'b', 'c', 'alpha', 'beta', 'gamma', 'volume'] - # esds = [param_dict.get(f"cell:{k}", {}).get("esd") for k in cell_param_keys] - - unit_cell_df = pd.DataFrame({ - "parameter": cell_params, - "value": unit_cell, - "esd": esds, - }) - unit_cell_df.to_csv( - output_dir / f"{phase_name}_unit_cell_report.csv", - float_format="%.8f", index=False, lineterminator="\n" - ) - unit_cell_data[phase_name] = json.loads(unit_cell_df.to_json(orient='records')) - - # Peak list for each phase - reflection_lists = proj.data.get(hist.name, {}).get('Reflection Lists', {}) - for phase_name in phase_names: - if phase_name not in reflection_lists: - continue - phase_ref = reflection_lists[phase_name] - if 'RefList' not in phase_ref: - continue - reflection_list = phase_ref['RefList'] - headers = [ - "h", "k", "l", "multiplicity", "d_spacing", "2theta", - "sigma_squared", "gamma", "F_obs_squared", "F_calc_squared", - "phase", "I_corr", "Prfo", "Trans", "ExtP" - ] - peak_list_df = pd.DataFrame(reflection_list, columns=headers) - peak_list_df.to_csv( - output_dir / f"{phase_name}_peak_list_report.csv", - float_format="%.8f", index=False, lineterminator="\n" - ) - peak_list_data[phase_name] = json.loads(peak_list_df.to_json(orient='records')) + # Check peak broadening + peak_broadening = param_dict.get('peak_broadening', {}) + if peak_broadening: + # Check size broadening + if peak_broadening.get('size_broadening'): + for param_key, param_value in peak_broadening['size_broadening'].items(): + if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) + continue + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.size_broadening.{param_key} has refine_flag=true" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") - return unit_cell_data, peak_list_data + # Check strain broadening + if peak_broadening.get('strain_broadening'): + for param_key, param_value in peak_broadening['strain_broadening'].items(): + if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) + continue + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.strain_broadening.{param_key} has refine_flag=true" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + # Check atom parameters (using same logic as has_active_refinement_parameter for consistency) + atoms = param_dict.get('atoms', {}) + if atoms: + for atom_label, atom_params in atoms.items(): + for param_key, param_value in atom_params.items(): + # Skip ADP field (it's a string, not a RefinementParameter) + if param_key == 'ADP': + continue -def _extract_refined_parameters( - param_dict: dict, output_dir: Path, proj: Any, verbose: bool -) -> list: - """Export refined parameters to CSV and return as list-of-records. + # Handle Uaniso nested dict + if param_key == 'Uaniso' and isinstance(param_value, dict): + for uaniso_key, uaniso_value in param_value.items(): + if isinstance(uaniso_value, list) and len(uaniso_value) >= 2 and uaniso_value[1]: + msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.Uaniso.{uaniso_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") - Args: - param_dict: From ``extract_refined_params_from_project()``. - output_dir: Directory to write ``refined_parameters.csv``. - proj: GSAS-II project object (for phase/atom name mappings). - verbose: If True, print export status to stdout. + # Check regular RefinementParameter lists (use elif to avoid checking lists after Uaniso) + elif isinstance(param_value, list) and len(param_value) >= 2 and param_value[1]: + msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.{param_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") - Returns: - List of dicts (records) with the 9-column schema. Returns ``[]`` - when ``param_dict`` is empty (simulation mode, SPF, etc.). - """ - if not param_dict: - if verbose: - print(" No refined parameters found to export") - return [] + if verbose: + if is_valid: + print(f"{CHECK} All parameters properly locked for simulation mode determinism") - try: - refined_params_csv = output_dir / "refined_parameters.csv" - refined_params_df = export_refined_parameters_csv( - param_dict, refined_params_csv, proj=proj - ) - if refined_params_df is not None: - if verbose: - print(f" Exported {len(param_dict)} refined parameters to {refined_params_csv.name}") - return refined_params_df.to_dict('records') - except Exception as e: - if verbose: - print(f" Warning: Failed to export refined parameters CSV: {e}") - return [] + return is_valid, warnings ######################################## @@ -3584,316 +607,6 @@ def run( return result -######################################## -# Kicker script for PowderLine -######################################## - -def run_refinement(recipe: RecipeModel, output_dir: Path, verbose: bool = False, method: str = 'server') -> dict: - """ - Internal execution engine: run a GSAS-II refinement using already-loaded libraries. - - This function is the single execution entry point used by all paths: - - ``gsas_server.py`` calls it directly after receiving an HTTP request - (``method='server'``). - - ``GSASClient._submit_via_subprocess()`` calls it in-process as the - subprocess fallback (``method='subprocess'``). Despite the method name, - no OS subprocess is spawned; see :meth:`GSASClient._submit_via_subprocess`. - - For programmatic use, prefer ``powderline.run()`` which validates the recipe, - dispatches to the appropriate backend, and normalises all structured data - fields to pandas DataFrames. - - Args: - recipe: Validated RecipeModel instance (call ``powderline.validate()`` - first if starting from a raw dict). - output_dir: Directory where output files are written (``dummy.gpx``, - ``dummy.lst``, CSV reports, ``fit_profile.txt``). Must exist or be - creatable. - verbose: If True, print detailed progress to stdout. - method: Execution method identifier string stored in the return dict. - Callers set this to ``'server'`` or ``'subprocess'`` so downstream - consumers know how the run was executed. Default ``'server'``. - - Returns: - dict with keys: - - - ``success`` (bool) - - ``run_id`` (str) — UUID4 string - - ``rwp`` (float | None) - - ``elapsed_time`` (float) — wall-clock seconds - - ``method`` (str) — value of the ``method`` argument - - ``output_files`` (list[str]) — paths of all files written to - ``output_dir`` (informational) - - ``fit_profile`` (dict) — column-oriented dict (JSON-serializable); - normalised to ``pd.DataFrame`` by ``run()`` - - ``unit_cell_data`` (dict) — ``{phase: list-of-records}`` - - ``peak_list_data`` (dict) — ``{phase: list-of-records}`` - - ``refined_parameters`` (list) — list-of-records (9-column schema) - - ``spf_peaks`` (dict) — column-oriented dict; populated for - ``GSASII_SPF`` runs, empty dict otherwise - - ``spf_convergence_diagnostics`` (dict) — column-oriented dict; - populated when SPF peaks have convergence issues, empty dict otherwise - - ``error`` (str) — present when ``success=False`` - - ``traceback`` (str) — present when an unhandled exception occurred - - Example:: - - from powderline.kicker import run_refinement - from powderline.schema import RecipeModel - recipe = RecipeModel.model_validate(recipe_dict) - result = run_refinement(recipe, Path('output'), verbose=True) - print(f"Rwp: {result['rwp']:.3f}% [run_id={result['run_id']}]") - """ - # Assign a unique ID for this refinement run immediately, before any work begins, - # so every exit path (success, GSAS-II failure, unexpected exception) can include - # it in the returned dict and server logs. - run_id = str(uuid.uuid4()) - import time - start_time = time.time() - - try: - # 1. Get xrd_data from validated model (file-less: no sample_name) - xrd_data = recipe.payload.xrd_data - - # 2. Construct name and initialize project using standard naming - gpx_path = output_dir / OUTPUT_NAMING.gpx_filename - proj = G2.G2Project(newgpx=str(gpx_path)) - - # 3. Instrument initialization - now a list of dicts [Iparm1, Iparm2] - instrument_init = recipe.payload.instrument.initialization - - # 4. Add histogram - phase1B update: xrd_data is now a dict with arrays, instrument_init is list of dicts - try: - hist = add_powder_histogram_from_arrays( - proj=proj, - tth_array=xrd_data.tth, - intensity_array=xrd_data.Itth, - intensity_weights_array=xrd_data.Itth_weights, - histogram_name=OUTPUT_NAMING.histogram_name, - instrument_prm_dict=instrument_init[0], # Use Iparm1 (first dict) - comments=None, - phases=None, # Optionally could link to phases if order of operations - ) - except Exception as e: - import traceback as _tb - tb = _tb.format_exc() - elapsed_time = time.time() - start_time - return { - 'success': False, - 'rwp': None, - 'run_id': run_id, - 'error': f"Failed to load XRD data or instrument parameters: {str(e)}", - 'traceback': tb, - 'elapsed_time': elapsed_time, - 'method': method - } - - # After adding histogram, set hist scale and refine flag to defaults - set_hist_scale(proj, hist, hist_scale_val=DEFAULT_HIST_SCALE_VAL, hist_scale_refine_flag=DEFAULT_HIST_SCALE_REFINE_FLAG, print_info=verbose) - - # 5. Set fit range - fit_range = recipe.payload.fit_range if recipe.payload.fit_range else (None, None) - if fit_range != (None, None): - set_fit_range_hist(hist, fit_range, print_info=verbose) - - # 6. Set background - Chebyshev and single peaks - if recipe.payload.background is not None: - background_dict = recipe.payload.background.model_dump(mode='json') - if recipe.payload.background.chebyshev is not None: - chebyshev_dict = background_dict.get('chebyshev') - set_chebyshev_background(proj, hist, chebyshev_dict, print_info=verbose) - if recipe.payload.background.single_peaks is not None: - bkg_single_peaks_dict = background_dict.get('single_peaks') - set_single_peak_background(proj, hist, bkg_single_peaks_dict, print_info=verbose) - - # 6b. Set single peaks (Peak List mode for non-background peaks) - if recipe.payload.single_peaks is not None: - single_peaks_dict = recipe.payload.single_peaks.model_dump(mode='json') - # Check if dict has any actual peak data before calling setter - has_peak_data = False - for key in ['positions', 'intensities', 'pv_gaussian_sigma_sq', 'pv_lorentzian_gamma']: - if key in single_peaks_dict and single_peaks_dict[key] and len(single_peaks_dict[key]) > 0: - has_peak_data = True - break - if has_peak_data: - set_single_peaks(proj, hist, single_peaks_dict, print_info=verbose) - - # 7. Add phases (if present) - if recipe.payload.phases is not None and len(recipe.payload.phases) > 0: - phases_dict = recipe.payload.model_dump(mode='json')['phases'] - add_phases_from_dict(proj, hist, phases_dict, print_info=verbose) - - # 8. Parameterize phases - holds = set_phase_parameterization(proj, hist, phases_dict, print_info=verbose) - - # 8b. Apply Hold constraints for per-parameter refine flags - # (schema 0.26: fixed members of partially-refined DOF groups). - # The isinstance guard keeps mocked-setter unit tests inert. - if isinstance(holds, list) and holds: - proj.add_HoldConstr(holds) - if verbose: - print(f"Applied {len(holds)} Hold constraint(s): {holds}") - - # 9. Set instrument parameterization - instrument_param_dict = recipe.payload.instrument.parameterization.model_dump(mode='json') if recipe.payload.instrument.parameterization else None - if instrument_param_dict is not None: - instrument_param_changes = False - for key, value in instrument_param_dict.items(): - if isinstance(value, dict): - if any(v is not None for v in value.values()): - instrument_param_changes = True - break - elif value is not None: - instrument_param_changes = True - break - if instrument_param_changes: - set_instrument_parameterization(proj, hist, instrument_param_dict, print_info=verbose) - - # 10. Get refinement controls and set refinement cycles - controls = recipe.payload.refinement_controls - - # 10a. Validate single_peak_fitting_mode requirements (only for GSASII_SPF) - if recipe.schema_name == 'GSASII_SPF': - if controls.single_peak_fitting_mode is None: - raise ValueError( - f"Schema '{recipe.schema_name}' requires " - f"'single_peak_fitting_mode' to be configured in refinement_controls." - ) - - num_cycles = controls.refinement_cycles - if num_cycles != proj.get_Controls('cycles'): - set_refinement_cycles(proj, num_cycles, print_info=verbose) - - # 11. Execute refinement using schema-based dispatch - executor = SCHEMA_EXECUTORS.get(recipe.schema_name) - if executor is None: - raise ValueError(f"Unknown schema_name: {recipe.schema_name}. Valid options: {list(SCHEMA_EXECUTORS.keys())}") - - try: - result = executor(proj, hist, recipe, verbose) - - # Check if executor succeeded - if not result.get('success', False): - elapsed_time = time.time() - start_time - return { - 'success': False, - 'rwp': None, - 'run_id': run_id, - 'error': result.get( - 'error', - f"Refinement executor '{recipe.schema_name}' returned success=False without an error message", - ), - 'traceback': result.get('traceback'), - 'elapsed_time': elapsed_time, - 'method': method - } - - except Exception as e: - import traceback as _tb - tb = _tb.format_exc() - elapsed_time = time.time() - start_time - return { - 'success': False, - 'rwp': None, - 'run_id': run_id, - 'error': f"Refinement failed: {str(e)}", - 'traceback': tb, - 'elapsed_time': elapsed_time, - 'method': method - } - - # Save GPX file after successful refinement - proj.save(str(gpx_path)) - - # 12. Extract final Rwp from result - rwp = result.get('rwp') - - # --- Post-refinement data extraction --- - # Each helper writes its own output files and returns JSON-serializable data. - # run() normalises all dicts/lists to DataFrames for programmatic callers. - - fit_profile_data = _extract_fit_profile(hist, output_dir) - - spf_peaks_data, spf_diagnostics_data = _extract_spf_peak_report( - proj, hist, recipe, output_dir, verbose - ) - - # Extract refined parameters (needed for unit cell ESDs in _extract_phase_reports) - if verbose: - print("\nExtracting refined parameters with ESDs...") - - # NOTE: .lst fallback (extract_refined_params_from_lst) is preserved for Phase 2 - # reference but its call site is intentionally disabled: .lst parsing is incomplete - # (no atom/HAP params; different naming scheme) and obscured covariance failures. - param_dict = extract_refined_params_from_project(proj, verbose=verbose) - - # Only raise if GSAS-II populated a varyList (i.e. parameters were actually varied) - # but we still got nothing back. An empty param_dict with an empty varyList is - # expected and correct for simulation mode (refinement_cycles=1, all params locked) - # and for GSASII_SPF (no standard covariance matrix produced). - cov_vary_list = ( - proj.data.get('Covariance', {}).get('data', {}).get('varyList', []) - ) - if len(param_dict) == 0 and len(cov_vary_list) > 0: - raise RuntimeError( - "GSAS-II populated a varyList but refined parameter extraction returned " - "empty results; covariance data may be corrupt. " - "Ensure refinement completed successfully. " - "Check the .lst file for GSAS-II error details." - ) - - # --- .lst fallback (disabled) --- - # NOTE: preserved for Phase 2 reference — .lst parsing is incomplete - # (no atom/HAP params; different naming scheme); covariance extraction is the - # only supported path. - # if len(param_dict) == 0: - # lst_file = output_dir / OUTPUT_NAMING.lst_filename - # if lst_file.exists(): - # if verbose: - # print(" Covariance data not available, parsing .lst file...") - # param_dict = extract_refined_params_from_lst(lst_file) - - unit_cell_data, peak_list_data = _extract_phase_reports( - proj, hist, recipe, param_dict, output_dir - ) - - refined_parameters_data = _extract_refined_parameters( - param_dict, output_dir, proj, verbose - ) - - elapsed_time = time.time() - start_time - return { - 'success': True, - 'run_id': run_id, - 'rwp': rwp, - 'elapsed_time': elapsed_time, - 'method': method, - 'output_files': [str(f) for f in output_dir.glob('*')], - 'fit_profile': fit_profile_data, - 'unit_cell_data': unit_cell_data, - 'peak_list_data': peak_list_data, - 'refined_parameters': refined_parameters_data, - 'spf_peaks': spf_peaks_data, - 'spf_convergence_diagnostics': spf_diagnostics_data, - } - - except Exception as e: - import traceback - tb = traceback.format_exc() - import logging - logging.getLogger(__name__).error("run_refinement failed:\n%s", tb) - elapsed_time = time.time() - start_time - return { - 'success': False, - 'rwp': None, - 'run_id': run_id, - 'error': str(e), - 'traceback': tb, - 'elapsed_time': elapsed_time, - 'method': method - } - - if __name__ == "__main__": # Ensure emoji/Unicode output works on Windows consoles that default to a # legacy code page (e.g. cp1252), which cannot encode the status emoji below. From 1384755dc45d58e80f65b7932324675a58acd618 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:51:43 -0400 Subject: [PATCH 005/259] test: retarget patches of moved GSAS-II internals to their new modules run_refinement now resolves its callees from powderline.gateways.gsasii.executors (and _extract_phase_reports from .extractors), so patch("powderline.kicker.") no longer intercepts them. Retarget those patch strings (pure substitution, 83 targets; powderline.kicker.G2.G2Project unchanged - it patches the shared module object) and point test_gsas_server_unit at the real server module so its PID_FILE/_pid_alive monkeypatches take effect. Maintainer decision A47. Co-Authored-By: Claude Opus 5.5 --- tests/test_gsas_server_unit.py | 2 +- tests/test_run_refinement_missing_keys.py | 166 +++++++++++----------- 2 files changed, 84 insertions(+), 84 deletions(-) diff --git a/tests/test_gsas_server_unit.py b/tests/test_gsas_server_unit.py index 34c418d..debf998 100644 --- a/tests/test_gsas_server_unit.py +++ b/tests/test_gsas_server_unit.py @@ -18,7 +18,7 @@ pytest.importorskip("pydantic") -from powderline import gsas_server +from powderline.gateways.gsasii import server as gsas_server # The ProcessLookupError/PermissionError semantics below are specific to the diff --git a/tests/test_run_refinement_missing_keys.py b/tests/test_run_refinement_missing_keys.py index 291e6e9..a3a40d7 100644 --- a/tests/test_run_refinement_missing_keys.py +++ b/tests/test_run_refinement_missing_keys.py @@ -129,16 +129,16 @@ def _run_with_mocked_gsas(mock_recipe, tmp_path, proj, hist): output_dir.mkdir() with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"), \ - patch("powderline.kicker.calculate_cell_esds_from_A_matrix", + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"), \ + patch("powderline.gateways.gsasii.extractors.calculate_cell_esds_from_A_matrix", return_value=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir, verbose=False, method='test') @@ -277,7 +277,7 @@ def test_histogram_load_error_returns_failure(self, mock_recipe, tmp_path): output_dir.mkdir() with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", side_effect=ValueError("bad instrument params")): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir, verbose=False, method='test') @@ -292,7 +292,7 @@ def test_histogram_load_error_includes_run_id(self, mock_recipe, tmp_path): output_dir.mkdir() with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", side_effect=IOError("file not found")): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir, verbose=False, method='test') @@ -308,16 +308,16 @@ def test_executor_raises_exception_returns_failure(self, mock_recipe, tmp_path): proj, hist, _ = _make_mock_hist("PWDR test", residuals={"wR": 5.0}) with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"), \ - patch("powderline.kicker.SCHEMA_EXECUTORS", + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"), \ + patch("powderline.gateways.gsasii.executors.SCHEMA_EXECUTORS", {"GSASII_Rietveld": MagicMock(side_effect=RuntimeError("diverged"))}): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir=tmp_path, verbose=False, method='test') @@ -331,16 +331,16 @@ def test_executor_returns_failure_dict(self, mock_recipe, tmp_path): failing_executor = MagicMock(return_value={"success": False, "rwp": None}) with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"), \ - patch("powderline.kicker.SCHEMA_EXECUTORS", {"GSASII_Rietveld": failing_executor}): + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"), \ + patch("powderline.gateways.gsasii.executors.SCHEMA_EXECUTORS", {"GSASII_Rietveld": failing_executor}): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir=tmp_path, verbose=False, method='test') @@ -357,15 +357,15 @@ def test_unknown_schema_name_returns_failure(self, mock_recipe, tmp_path): proj, hist, _ = _make_mock_hist("PWDR test", residuals={"wR": 5.0}) with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"): + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir=tmp_path, verbose=False, method='test') @@ -383,18 +383,18 @@ def test_nonempty_varylist_with_empty_params_returns_failure(self, mock_recipe, proj.data["Covariance"]["data"]["varyList"] = [":0:Back;0"] with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"), \ - patch("powderline.kicker.calculate_cell_esds_from_A_matrix", + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"), \ + patch("powderline.gateways.gsasii.extractors.calculate_cell_esds_from_A_matrix", return_value=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), \ - patch("powderline.kicker.extract_refined_params_from_project", + patch("powderline.gateways.gsasii.executors.extract_refined_params_from_project", return_value={}): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir=tmp_path, verbose=False, method='test') @@ -415,7 +415,7 @@ def test_exit1_histogram_load_failure_has_traceback(self, mock_recipe, tmp_path) output_dir.mkdir() with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", side_effect=ValueError("bad instrument params")): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir, verbose=False, method='test') @@ -433,16 +433,16 @@ def test_exit3_executor_exception_has_traceback(self, mock_recipe, tmp_path): output_dir.mkdir() with patch("powderline.kicker.G2.G2Project", return_value=proj), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"), \ - patch("powderline.kicker.SCHEMA_EXECUTORS", + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"), \ + patch("powderline.gateways.gsasii.executors.SCHEMA_EXECUTORS", {"GSASII_Rietveld": MagicMock(side_effect=RuntimeError("diverged"))}): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir=output_dir, verbose=False, method='test') @@ -467,16 +467,16 @@ def test_exit2_executor_failure_dict_with_traceback_forwards_it(self, mock_recip output_dir.mkdir() with patch("powderline.kicker.G2.G2Project", return_value=MagicMock()), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"), \ - patch("powderline.kicker.SCHEMA_EXECUTORS", {"GSASII_Rietveld": failing_executor}): + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"), \ + patch("powderline.gateways.gsasii.executors.SCHEMA_EXECUTORS", {"GSASII_Rietveld": failing_executor}): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir=output_dir, verbose=False, method='test') @@ -491,16 +491,16 @@ def test_exit2_executor_failure_dict_without_traceback_gives_none(self, mock_rec output_dir.mkdir() with patch("powderline.kicker.G2.G2Project", return_value=MagicMock()), \ - patch("powderline.kicker.add_powder_histogram_from_arrays", return_value=hist), \ - patch("powderline.kicker.set_hist_scale"), \ - patch("powderline.kicker.set_fit_range_hist"), \ - patch("powderline.kicker.set_chebyshev_background"), \ - patch("powderline.kicker.set_single_peak_background"), \ - patch("powderline.kicker.add_phases_from_dict"), \ - patch("powderline.kicker.set_phase_parameterization"), \ - patch("powderline.kicker.set_instrument_parameterization"), \ - patch("powderline.kicker.set_refinement_cycles"), \ - patch("powderline.kicker.SCHEMA_EXECUTORS", {"GSASII_Rietveld": failing_executor}): + patch("powderline.gateways.gsasii.executors.add_powder_histogram_from_arrays", return_value=hist), \ + patch("powderline.gateways.gsasii.executors.set_hist_scale"), \ + patch("powderline.gateways.gsasii.executors.set_fit_range_hist"), \ + patch("powderline.gateways.gsasii.executors.set_chebyshev_background"), \ + patch("powderline.gateways.gsasii.executors.set_single_peak_background"), \ + patch("powderline.gateways.gsasii.executors.add_phases_from_dict"), \ + patch("powderline.gateways.gsasii.executors.set_phase_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_instrument_parameterization"), \ + patch("powderline.gateways.gsasii.executors.set_refinement_cycles"), \ + patch("powderline.gateways.gsasii.executors.SCHEMA_EXECUTORS", {"GSASII_Rietveld": failing_executor}): from powderline.kicker import run_refinement result = run_refinement(mock_recipe, output_dir=output_dir, verbose=False, method='test') From 6603574dbfa19b11311e44222ad5894458eb143f Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:52:16 -0400 Subject: [PATCH 006/259] fix(gsasii): repoint server/client __file__-relative paths after the move The relocated client computed the src dir and the server script path relative to its old location (src/powderline/gsas_client.py), so server autostart would spawn a nonexistent gateways/gsasii/gsas_server.py. Point src_dir at parents[3] (= src/) in client.py and server.py and spawn gateways/gsasii/server.py. Three lines; not GSAS-II project-dict code (outside the A39 freeze) - maintainer decision A48, flagged OTHER for the re/01 review. The old-path gsas_server.py shim keeps __main__, so the gsas-server pixi task and docs are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/powderline/gateways/gsasii/client.py | 4 ++-- src/powderline/gateways/gsasii/server.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/powderline/gateways/gsasii/client.py b/src/powderline/gateways/gsasii/client.py index a28401b..5b4bd86 100644 --- a/src/powderline/gateways/gsasii/client.py +++ b/src/powderline/gateways/gsasii/client.py @@ -275,8 +275,8 @@ def _start_server_background(self, verbose: bool = False) -> bool: try: # Build command to start server - src_dir = Path(__file__).parent.parent - server_script = Path(__file__).parent / 'gsas_server.py' + src_dir = Path(__file__).parents[3] + server_script = Path(__file__).parent / 'server.py' # Prepare environment env = os.environ.copy() diff --git a/src/powderline/gateways/gsasii/server.py b/src/powderline/gateways/gsasii/server.py index 72cd717..e8d0816 100644 --- a/src/powderline/gateways/gsasii/server.py +++ b/src/powderline/gateways/gsasii/server.py @@ -141,7 +141,7 @@ def __init__(self, logger: logging.Logger = None): import_start = time.time() # Set PYTHONPATH to include src directory - src_dir = Path(__file__).parent.parent + src_dir = Path(__file__).parents[3] if str(src_dir) not in sys.path: sys.path.insert(0, str(src_dir)) From c471b19806b391d36253b1b099cf428c14ebad22 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:52:22 -0400 Subject: [PATCH 007/259] build(hash): re-scope the code-hash tripwire to the gsasii gateway modules _code_hash.json becomes a manifest of MD5s for the frozen GSAS-II code: gateways/gsasii/{helpers,project,setters,executors,extractors, constraints}.py (kicker.py is now a facade; server/client are not hashed). update_code_hash.py regenerates the manifest (drops the obsolete kicker_hash key, errors if a module is missing); test_code_hash.py checks the manifest covers exactly those six modules (independent tripwire list) and each file's hash. constraints.py hash is unchanged from the pre-move file. Co-Authored-By: Claude Opus 5.5 --- scripts/update_code_hash.py | 60 +++++++++++++++++++++++++++----- src/powderline/_code_hash.json | 11 ++++-- tests/test_code_hash.py | 62 ++++++++++++++++++++++++++-------- 3 files changed, 107 insertions(+), 26 deletions(-) diff --git a/scripts/update_code_hash.py b/scripts/update_code_hash.py index f26009a..f537829 100644 --- a/scripts/update_code_hash.py +++ b/scripts/update_code_hash.py @@ -1,4 +1,4 @@ -"""Regenerate _code_hash.json after kicker.py changes. +"""Regenerate _code_hash.json after editing GSAS-II gateway modules. Usage: pixi run update-code-hash """ @@ -6,23 +6,65 @@ import hashlib import json from pathlib import Path +import sys SRC_DIR = Path(__file__).parent.parent / "src" / "powderline" -KICKER_PATH = SRC_DIR / "kicker.py" +GATEWAY_DIR = SRC_DIR / "gateways" / "gsasii" HASH_FILE = SRC_DIR / "_code_hash.json" +HASHED_MODULES = ( + "helpers.py", + "project.py", + "setters.py", + "executors.py", + "extractors.py", + "constraints.py", +) + def main(): - current = json.loads(HASH_FILE.read_text()) - new_hash = hashlib.md5(KICKER_PATH.read_bytes()).hexdigest() + current = json.loads(HASH_FILE.read_text(encoding="utf-8")) + schema_version = current.get("schema_version") + + # Compute new hashes + new_hashes = {} + for module_name in HASHED_MODULES: + module_path = GATEWAY_DIR / module_name + if not module_path.exists(): + print(f"ERROR: Expected module not found: {module_path}", file=sys.stderr) + sys.exit(1) + new_hashes[module_name] = hashlib.md5(module_path.read_bytes()).hexdigest() + + # Compare against stored manifest + old_manifest = current.get("gsasii_gateway_hashes", {}) + changed = [] + unchanged = [] - if new_hash == current["kicker_hash"]: - print(f"Hash unchanged: {new_hash}") + for module_name in HASHED_MODULES: + old_hash = old_manifest.get(module_name) + new_hash = new_hashes[module_name] + if old_hash == new_hash: + unchanged.append(f"{module_name}: {new_hash}") + else: + changed.append(f"{module_name}: {old_hash} -> {new_hash}") + + if not changed: + print("All hashes unchanged:") + for line in unchanged: + print(f" {line}") return - current["kicker_hash"] = new_hash - HASH_FILE.write_text(json.dumps(current, indent=2) + "\n") - print(f"Updated _code_hash.json: {new_hash}") + # Write updated manifest + manifest = {"schema_version": schema_version, "gsasii_gateway_hashes": new_hashes} + HASH_FILE.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n") + + print("Updated _code_hash.json:") + for line in changed: + print(f" {line}") + if unchanged: + print("Unchanged:") + for line in unchanged: + print(f" {line}") if __name__ == "__main__": diff --git a/src/powderline/_code_hash.json b/src/powderline/_code_hash.json index 489cd31..f83bfc6 100644 --- a/src/powderline/_code_hash.json +++ b/src/powderline/_code_hash.json @@ -1,4 +1,11 @@ { - "schema_version": "0.26.0", - "kicker_hash": "e2156ec7355642a3557f75f687d124f1" + "gsasii_gateway_hashes": { + "constraints.py": "dc7a28029d0a071cf35dd352e76eaee9", + "executors.py": "a59bf71961245fe6a30842b092b7bb11", + "extractors.py": "7e57b8b0e48ec677d9a90f0441d8cee9", + "helpers.py": "d288784c535123f95d5d2ccc5083e806", + "project.py": "f074993af296685f632db2cb94504486", + "setters.py": "f7e1082b26194ff2ed86e9bde5e4eab2" + }, + "schema_version": "0.26.0" } diff --git a/tests/test_code_hash.py b/tests/test_code_hash.py index bdb9105..aea7ab9 100644 --- a/tests/test_code_hash.py +++ b/tests/test_code_hash.py @@ -1,8 +1,9 @@ -"""Test that kicker.py code changes are accompanied by a version bump. +"""Test that GSAS-II gateway module code changes are accompanied by a version bump. WHY THIS EXISTS: - The GSAS-II server loads kicker.py once at startup and caches it in memory. - If kicker.py changes on disk, running servers still use the old code. The + The GSAS-II server loads the GSAS-II gateway modules + (src/powderline/gateways/gsasii/) once at startup and caches them in memory. + If those modules change on disk, running servers still use the old code. The schema_version in each recipe is validated against EXPECTED_SCHEMA_VERSION in schema.py, so bumping the version forces stale servers to reject new recipes and restart with fresh code. Without this, tests pass locally @@ -10,7 +11,7 @@ uses stale cached code). WHEN THIS TEST FAILS: - kicker.py was modified but _code_hash.json was not updated. Fix it: + A GSAS-II gateway module was modified but _code_hash.json was not updated. Fix it: 1. If output behavior changed (new files, format changes, column additions): bump EXPECTED_SCHEMA_VERSION in schema.py and update schema_version @@ -24,17 +25,43 @@ import hashlib import json from pathlib import Path +import pytest SRC_DIR = Path(__file__).parent.parent / "src" / "powderline" -KICKER_PATH = SRC_DIR / "kicker.py" +GATEWAY_DIR = SRC_DIR / "gateways" / "gsasii" HASH_FILE = SRC_DIR / "_code_hash.json" +# Expected modules in the manifest (independent tripwire) +EXPECTED_MODULES = ( + "helpers.py", + "project.py", + "setters.py", + "executors.py", + "extractors.py", + "constraints.py", +) -def test_kicker_hash_matches(): - """Verify kicker.py hash matches the stored hash in _code_hash.json. - If this test fails, it means kicker.py was modified without updating +def test_gateway_manifest_covers_expected_modules(): + """Verify the manifest covers exactly the expected GSAS-II gateway modules.""" + assert HASH_FILE.exists(), f"_code_hash.json not found at {HASH_FILE}" + + stored = json.loads(HASH_FILE.read_text(encoding="utf-8")) + manifest = stored.get("gsasii_gateway_hashes", {}) + + assert set(manifest.keys()) == set(EXPECTED_MODULES), ( + f"\nManifest modules mismatch!\n" + f" Expected: {set(EXPECTED_MODULES)}\n" + f" Got: {set(manifest.keys())}\n" + ) + + +@pytest.mark.parametrize("module_name", EXPECTED_MODULES) +def test_gateway_hashes_match(module_name): + """Verify each GSAS-II gateway module hash matches the stored hash. + + If this test fails, it means a gateway module was modified without updating the code hash. To fix: 1. If output behavior changed: bump EXPECTED_SCHEMA_VERSION in schema.py @@ -42,17 +69,22 @@ def test_kicker_hash_matches(): 2. Run: pixi run update-code-hash 3. Commit the updated _code_hash.json along with your changes. """ - assert KICKER_PATH.exists(), f"kicker.py not found at {KICKER_PATH}" + module_path = GATEWAY_DIR / module_name + assert module_path.exists(), f"{module_name} not found at {module_path}" assert HASH_FILE.exists(), f"_code_hash.json not found at {HASH_FILE}" - current_hash = hashlib.md5(KICKER_PATH.read_bytes()).hexdigest() - stored = json.loads(HASH_FILE.read_text()) + current_hash = hashlib.md5(module_path.read_bytes()).hexdigest() + stored = json.loads(HASH_FILE.read_text(encoding="utf-8")) + manifest = stored.get("gsasii_gateway_hashes", {}) + + assert module_name in manifest, f"{module_name} not in manifest" + stored_hash = manifest[module_name] - assert current_hash == stored["kicker_hash"], ( - f"\nkicker.py has changed but _code_hash.json was not updated!\n" - f" Stored hash: {stored['kicker_hash']}\n" + assert current_hash == stored_hash, ( + f"\n{module_name} has changed but _code_hash.json was not updated!\n" + f" Stored hash: {stored_hash}\n" f" Current hash: {current_hash}\n\n" - f"If kicker.py output behavior changed, bump EXPECTED_SCHEMA_VERSION in schema.py.\n" + f"If gateway module output behavior changed, bump EXPECTED_SCHEMA_VERSION in schema.py.\n" f"Then run: pixi run update-code-hash\n" f"See docs/DEVELOPMENT.md 'Schema Version Discipline' for details." ) From fe49fd0bc20f94b428abb06220ae3dc2134b22c8 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:48:53 -0400 Subject: [PATCH 008/259] feat(core): add the exceptions module and structured-warning shape PowderLineError base plus RecipeValidationError, GatewayNotInstalledError, EngineNotAvailableError (also an ImportError, A52), EngineVersionError (A44) and EngineExecutionError; StructuredWarning = {code, message, field_path}. Engine-free. The registry and gateways raise these from the next commits. Co-Authored-By: Claude Opus 5.5 --- src/powderline/exceptions.py | 105 +++++++++++++++++++++++++++++++++++ tests/test_exceptions.py | 77 +++++++++++++++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 src/powderline/exceptions.py create mode 100644 tests/test_exceptions.py diff --git a/src/powderline/exceptions.py b/src/powderline/exceptions.py new file mode 100644 index 0000000..92455c2 --- /dev/null +++ b/src/powderline/exceptions.py @@ -0,0 +1,105 @@ +"""PowderLine exception hierarchy and the structured-warning shape (engine-free). + +Every PowderLine-raised error derives from :class:`PowderLineError`. The +gateway errors split along the schema/runtime layers (master plan A23, A5/A8): + +- :class:`GatewayNotInstalledError` — no gateway of that name is registered at + all (an out-of-tree plugin that is not installed). The only case where + ``validate()`` cannot run. +- :class:`EngineNotAvailableError` — the gateway is present but its engine + dependency is missing from this environment. Raised at ``run()`` time only, + never by ``validate()``/``validate_only``. Also an :class:`ImportError`, so + callers that caught the underlying import failure keep working (A52). +- :class:`EngineVersionError` — the installed engine is outside the gateway's + supported ``ENGINE_VERSION_SPEC``. A hard error (A44). +- :class:`EngineExecutionError` — the engine ran and failed. +- :class:`RecipeValidationError` — a recipe failed validation. + +This module must never import an engine (enforced by an import-block test). +""" + +from __future__ import annotations + +from typing import Optional, TypedDict + + +class PowderLineError(Exception): + """Base class for all PowderLine errors.""" + + +class RecipeValidationError(PowderLineError, ValueError): + """A recipe failed validation. + + Wraps (and may annotate) the underlying pydantic errors. ``errors`` holds + pydantic's ``ValidationError.errors()`` list when built from one. + """ + + def __init__(self, message: str, *, errors: Optional[list] = None, + schema_name: Optional[str] = None) -> None: + super().__init__(message) + self.errors = list(errors or []) + self.schema_name = schema_name + + @classmethod + def from_pydantic(cls, exc, *, schema_name: Optional[str] = None) -> "RecipeValidationError": + """Build from a ``pydantic.ValidationError``, keeping its error list.""" + prefix = f"{schema_name} recipe" if schema_name else "recipe" + err = cls(f"{prefix} failed validation:\n{exc}", errors=exc.errors(), + schema_name=schema_name) + err.__cause__ = exc + return err + + +class GatewayNotInstalledError(PowderLineError): + """No gateway of this name is registered (the gateway package is absent).""" + + def __init__(self, message: str, *, gateway: str) -> None: + super().__init__(message) + self.gateway = gateway + + +class EngineNotAvailableError(PowderLineError, ImportError): + """The gateway is present, but its engine dependency is not installed here.""" + + def __init__(self, *, gateway: str, dependency: str, env: str, + install_command: str) -> None: + super().__init__( + f"the {gateway!r} gateway needs {dependency}, which is not installed " + f"in this environment; use the {env!r} pixi environment " + f"(install it with: {install_command})" + ) + self.gateway = gateway + self.dependency = dependency + self.env = env + self.install_command = install_command + + +class EngineVersionError(PowderLineError): + """The installed engine version is outside the gateway's supported range.""" + + def __init__(self, *, gateway: str, engine: str, installed: str, supported: str) -> None: + super().__init__( + f"the {gateway!r} gateway supports {engine} {supported}, but {installed} " + "is installed; install a supported version" + ) + self.gateway = gateway + self.engine = engine + self.installed = installed + self.supported = supported + + +class EngineExecutionError(PowderLineError): + """The engine ran and failed.""" + + +class StructuredWarning(TypedDict): + """One entry of the ``warnings`` list in results and ``validate()`` output. + + ``field_path`` is the dotted recipe path the warning refers to, or ``None`` + when it is not tied to one field. Plumbed into results per gateway in + re/04-06. + """ + + code: str + message: str + field_path: Optional[str] diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py new file mode 100644 index 0000000..5ae9aaf --- /dev/null +++ b/tests/test_exceptions.py @@ -0,0 +1,77 @@ +"""Unit tests for powderline.exceptions (hierarchy, messages, warning shape). + +Pure tests: no engine, no network. +""" +import pytest +from pydantic import BaseModel, ValidationError + +from powderline.exceptions import ( + EngineExecutionError, + EngineNotAvailableError, + EngineVersionError, + GatewayNotInstalledError, + PowderLineError, + RecipeValidationError, + StructuredWarning, +) + + +@pytest.mark.parametrize("cls", [ + RecipeValidationError, GatewayNotInstalledError, EngineNotAvailableError, + EngineVersionError, EngineExecutionError, +]) +def test_all_derive_from_powderline_error(cls): + assert issubclass(cls, PowderLineError) + + +def test_engine_not_available_is_an_import_error(): + # A52: callers that caught the underlying ImportError keep working. + err = EngineNotAvailableError(gateway="easydiffraction", dependency="easydiffraction", + env="easydiff", install_command="pixi install -e easydiff") + with pytest.raises(ImportError): + raise err + + +def test_engine_not_available_message_names_gateway_env_and_command(): + err = EngineNotAvailableError(gateway="easydiffraction", dependency="easydiffraction", + env="easydiff", install_command="pixi install -e easydiff") + msg = str(err) + assert "'easydiffraction' gateway" in msg + assert "'easydiff' pixi environment" in msg + assert "pixi install -e easydiff" in msg + assert (err.gateway, err.env) == ("easydiffraction", "easydiff") + + +def test_engine_version_error_message(): + err = EngineVersionError(gateway="gsasii", engine="GSAS-II", installed="5.8.0", + supported="==5.7.9") + assert str(err) == ("the 'gsasii' gateway supports GSAS-II ==5.7.9, but 5.8.0 is " + "installed; install a supported version") + assert (err.installed, err.supported) == ("5.8.0", "==5.7.9") + + +def test_gateway_not_installed_keeps_name(): + err = GatewayNotInstalledError("no gateway 'foo'", gateway="foo") + assert err.gateway == "foo" + assert str(err) == "no gateway 'foo'" + + +class _M(BaseModel): + x: int + + +def test_recipe_validation_error_from_pydantic(): + with pytest.raises(ValidationError) as info: + _M.model_validate({"x": "not-an-int"}) + err = RecipeValidationError.from_pydantic(info.value, schema_name="GSASII_Rietveld") + assert isinstance(err, ValueError) + assert err.schema_name == "GSASII_Rietveld" + assert err.errors and err.errors[0]["loc"] == ("x",) + assert err.__cause__ is info.value + assert str(err).startswith("GSASII_Rietveld recipe failed validation:") + + +def test_structured_warning_shape(): + assert set(StructuredWarning.__annotations__) == {"code", "message", "field_path"} + w: StructuredWarning = {"code": "W001", "message": "m", "field_path": None} + assert w["field_path"] is None From b9767a7060482efe06c3916c7c17c3c8bf196eac Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:48:53 -0400 Subject: [PATCH 009/259] refactor(gsasii): move validate + validate_simulation_mode_parameters to an engine-free module (verbatim) Both functions read only the recipe (no GSAS-II references), but lived in kicker.py, which imports GSAS-II at module top. Moving them verbatim to gateways/gsasii/validation.py lets the gsasii gateway's schema layer validate without GSAS-II installed (A51). kicker re-exports both, so powderline.validate and every powderline.kicker.* import are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/powderline/gateways/gsasii/validation.py | 252 +++++++++++++++++++ src/powderline/kicker.py | 243 +----------------- 2 files changed, 257 insertions(+), 238 deletions(-) create mode 100644 src/powderline/gateways/gsasii/validation.py diff --git a/src/powderline/gateways/gsasii/validation.py b/src/powderline/gateways/gsasii/validation.py new file mode 100644 index 0000000..dace7a4 --- /dev/null +++ b/src/powderline/gateways/gsasii/validation.py @@ -0,0 +1,252 @@ +"""Engine-free recipe validation for the GSAS-II gateway. + +``validate`` and ``validate_simulation_mode_parameters`` moved here verbatim from +``powderline.kicker`` (multi-engine refactor, re/02, A51) so the gateway's schema +layer can validate a recipe without GSAS-II installed. ``powderline.kicker`` +re-exports both, so existing imports keep working. + +This module must never import GSAS-II (enforced by an import-block test). +""" +from __future__ import annotations +from typing import List +from pydantic import ValidationError +from powderline.schema import RecipeModel +from powderline._status import CHECK, CROSS, WARN + + +def validate_simulation_mode_parameters(recipe: RecipeModel, verbose: bool = False) -> tuple[bool, List[str]]: + """ + Validate that simulation mode examples have all refinement parameters locked. + + Simulation mode (refinement_cycles=1 with all parameters fixed) must have deterministic + output. This function checks for any `refine_flag: true` in structural or background + parameters that would violate determinism. + + Args: + recipe: Validated RecipeModel instance (uses payload structure) + verbose: If True, print detailed parameter checks + + Returns: + (is_valid, warnings): is_valid is True if all parameters are properly locked, + warnings is a list of issues found (empty if valid). + + Examples: + >>> is_valid, warnings = validate_simulation_mode_parameters(recipe) + >>> if not is_valid: + ... for warning in warnings: + ... print(f"WARNING: {warning}") + """ + is_valid = True + warnings: List[str] = [] + + # Get refinement controls (in payload) + controls = recipe.payload.refinement_controls + + # Only check simulation mode (refinement_cycles == 1) + if controls.refinement_cycles != 1: + return True, [] # Not simulation mode, skip validation + + if verbose: + print("Validating simulation mode constraints...") + + # Check background parameters + if recipe.payload.background is not None: + if recipe.payload.background.chebyshev is not None: + if recipe.payload.background.chebyshev.refine_flag: + msg = "CRITICAL: Chebyshev background has refine_flag=true in simulation mode (refinement_cycles=1). " \ + "This violates determinism - all parameters must be locked. Set refine_flag=false." + warnings.append(msg) + is_valid = False + if verbose: + print(f" {CROSS} {msg}") + + if recipe.payload.background.single_peaks is not None: + # Check single peak parameters + param_lists = [ + (recipe.payload.background.single_peaks.positions, "single_peaks.positions"), + (recipe.payload.background.single_peaks.intensities, "single_peaks.intensities"), + (recipe.payload.background.single_peaks.pv_gaussian_sigma, "single_peaks.pv_gaussian_sigma"), + (recipe.payload.background.single_peaks.pv_lorentzian_gamma, "single_peaks.pv_lorentzian_gamma"), + ] + for param_list, param_name in param_lists: + if param_list is not None: + for i, param in enumerate(param_list): + if param[1]: # refine_flag is second element + msg = f"WARNING: {param_name}[{i}] has refine_flag=true in simulation mode. " \ + "Set refine_flag=false for deterministic output." + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check instrument parameterization + if recipe.payload.instrument.parameterization is not None: + param_dict = recipe.payload.instrument.parameterization.model_dump(mode='json') + + # Check wavelength + if param_dict.get('wavelength') and param_dict['wavelength'][1]: + msg = "WARNING: instrument.parameterization.wavelength has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check broadening parameters + if param_dict.get('broadening'): + for param_key, param_value in param_dict['broadening'].items(): + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: instrument.parameterization.broadening.{param_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check corrections + if param_dict.get('corrections'): + for param_key, param_value in param_dict['corrections'].items(): + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: instrument.parameterization.corrections.{param_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check phase-level parameters (only if phases exist) + if recipe.payload.phases is not None: + phases_dict = recipe.payload.model_dump(mode='json')['phases'] + for phase_name, phase_info in phases_dict.items(): + param_dict = phase_info.get('parameterization', {}) + + # Check scale + if param_dict.get('scale') and param_dict['scale'][1]: + msg = f"WARNING: phases.{phase_name}.parameterization.scale has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check unit cell + unit_cell = param_dict.get('unit_cell', {}) + if unit_cell: + for cell_param, param_value in unit_cell.items(): + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: phases.{phase_name}.parameterization.unit_cell.{cell_param} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check peak broadening + peak_broadening = param_dict.get('peak_broadening', {}) + if peak_broadening: + # Check size broadening + if peak_broadening.get('size_broadening'): + for param_key, param_value in peak_broadening['size_broadening'].items(): + if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) + continue + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.size_broadening.{param_key} has refine_flag=true" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check strain broadening + if peak_broadening.get('strain_broadening'): + for param_key, param_value in peak_broadening['strain_broadening'].items(): + if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) + continue + if param_value and param_value[1]: # refine_flag + msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.strain_broadening.{param_key} has refine_flag=true" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check atom parameters (using same logic as has_active_refinement_parameter for consistency) + atoms = param_dict.get('atoms', {}) + if atoms: + for atom_label, atom_params in atoms.items(): + for param_key, param_value in atom_params.items(): + # Skip ADP field (it's a string, not a RefinementParameter) + if param_key == 'ADP': + continue + + # Handle Uaniso nested dict + if param_key == 'Uaniso' and isinstance(param_value, dict): + for uaniso_key, uaniso_value in param_value.items(): + if isinstance(uaniso_value, list) and len(uaniso_value) >= 2 and uaniso_value[1]: + msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.Uaniso.{uaniso_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + # Check regular RefinementParameter lists (use elif to avoid checking lists after Uaniso) + elif isinstance(param_value, list) and len(param_value) >= 2 and param_value[1]: + msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.{param_key} has refine_flag=true in simulation mode" + warnings.append(msg) + is_valid = False + if verbose: + print(f" {WARN} {msg}") + + if verbose: + if is_valid: + print(f"{CHECK} All parameters properly locked for simulation mode determinism") + + return is_valid, warnings + + +def validate(recipe: RecipeModel | dict, verbose: bool = False) -> RecipeModel: + """Validate a PowderLine recipe without running a refinement. + + Performs full Pydantic schema validation and simulation-mode consistency + checks. Raises ``pydantic.ValidationError`` immediately on any schema + violation so callers receive structured, actionable error information. + + This function is useful when batch-creating recipes and you want to + confirm each one is valid before committing to a refinement run. + + Note: The ``is_template_file()`` guard is **not** applied here. That + check is CLI-only (guards against accidentally running bare template + files from disk). When calling ``validate()`` programmatically the + caller is responsible for ensuring the recipe contains real data. + + Args: + recipe: A fully-populated ``RecipeModel`` instance or equivalent + dict. XRD data must already be present in + ``recipe.payload.xrd_data``. + verbose: If True, print simulation-mode warnings to stdout. + + Returns: + Validated ``RecipeModel`` instance. + + Raises: + pydantic.ValidationError: If the recipe fails schema validation. + ValueError: If simulation-mode constraints are violated (all + ``refine_flag`` fields must be ``false`` when + ``refinement_cycles == 1``). + + Example:: + + import json + import powderline + + recipe_dict = json.load(open("my_recipe.json")) + recipe_model = powderline.validate(recipe_dict) + print(f"Schema: {recipe_model.schema_name}, phases: {len(recipe_model.payload.phases or [])}") + """ + from pydantic import ValidationError # already imported at module level, re-stated for clarity + + if not isinstance(recipe, RecipeModel): + recipe = RecipeModel.model_validate(recipe) # raises ValidationError on failure + + is_sim_valid, sim_warnings = validate_simulation_mode_parameters(recipe, verbose=verbose) + if not is_sim_valid: + raise ValueError( + "Simulation mode validation failed. All refine_flag fields must be false " + f"when refinement_cycles == 1.\nConstraints violated:\n" + + "\n".join(f" - {w}" for w in sim_warnings) + ) + + return recipe diff --git a/src/powderline/kicker.py b/src/powderline/kicker.py index 36f3ddc..c723e87 100644 --- a/src/powderline/kicker.py +++ b/src/powderline/kicker.py @@ -97,6 +97,11 @@ _extract_refined_parameters, ) +from powderline.gateways.gsasii.validation import ( # noqa: F401 + validate_simulation_mode_parameters, + validate, +) + def load_recipe_asset(recipe_path: Path) -> dict: """Load a recipe asset from .json, .yaml/.yml, or .txt (YAML).""" @@ -164,248 +169,10 @@ def is_template_file(recipe_dict: dict, input_path: Path) -> tuple[bool, str | N return False, None -def validate_simulation_mode_parameters(recipe: RecipeModel, verbose: bool = False) -> tuple[bool, List[str]]: - """ - Validate that simulation mode examples have all refinement parameters locked. - - Simulation mode (refinement_cycles=1 with all parameters fixed) must have deterministic - output. This function checks for any `refine_flag: true` in structural or background - parameters that would violate determinism. - - Args: - recipe: Validated RecipeModel instance (uses payload structure) - verbose: If True, print detailed parameter checks - - Returns: - (is_valid, warnings): is_valid is True if all parameters are properly locked, - warnings is a list of issues found (empty if valid). - - Examples: - >>> is_valid, warnings = validate_simulation_mode_parameters(recipe) - >>> if not is_valid: - ... for warning in warnings: - ... print(f"WARNING: {warning}") - """ - is_valid = True - warnings: List[str] = [] - - # Get refinement controls (in payload) - controls = recipe.payload.refinement_controls - - # Only check simulation mode (refinement_cycles == 1) - if controls.refinement_cycles != 1: - return True, [] # Not simulation mode, skip validation - - if verbose: - print("Validating simulation mode constraints...") - - # Check background parameters - if recipe.payload.background is not None: - if recipe.payload.background.chebyshev is not None: - if recipe.payload.background.chebyshev.refine_flag: - msg = "CRITICAL: Chebyshev background has refine_flag=true in simulation mode (refinement_cycles=1). " \ - "This violates determinism - all parameters must be locked. Set refine_flag=false." - warnings.append(msg) - is_valid = False - if verbose: - print(f" {CROSS} {msg}") - - if recipe.payload.background.single_peaks is not None: - # Check single peak parameters - param_lists = [ - (recipe.payload.background.single_peaks.positions, "single_peaks.positions"), - (recipe.payload.background.single_peaks.intensities, "single_peaks.intensities"), - (recipe.payload.background.single_peaks.pv_gaussian_sigma, "single_peaks.pv_gaussian_sigma"), - (recipe.payload.background.single_peaks.pv_lorentzian_gamma, "single_peaks.pv_lorentzian_gamma"), - ] - for param_list, param_name in param_lists: - if param_list is not None: - for i, param in enumerate(param_list): - if param[1]: # refine_flag is second element - msg = f"WARNING: {param_name}[{i}] has refine_flag=true in simulation mode. " \ - "Set refine_flag=false for deterministic output." - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check instrument parameterization - if recipe.payload.instrument.parameterization is not None: - param_dict = recipe.payload.instrument.parameterization.model_dump(mode='json') - - # Check wavelength - if param_dict.get('wavelength') and param_dict['wavelength'][1]: - msg = "WARNING: instrument.parameterization.wavelength has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check broadening parameters - if param_dict.get('broadening'): - for param_key, param_value in param_dict['broadening'].items(): - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: instrument.parameterization.broadening.{param_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check corrections - if param_dict.get('corrections'): - for param_key, param_value in param_dict['corrections'].items(): - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: instrument.parameterization.corrections.{param_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check phase-level parameters (only if phases exist) - if recipe.payload.phases is not None: - phases_dict = recipe.payload.model_dump(mode='json')['phases'] - for phase_name, phase_info in phases_dict.items(): - param_dict = phase_info.get('parameterization', {}) - - # Check scale - if param_dict.get('scale') and param_dict['scale'][1]: - msg = f"WARNING: phases.{phase_name}.parameterization.scale has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check unit cell - unit_cell = param_dict.get('unit_cell', {}) - if unit_cell: - for cell_param, param_value in unit_cell.items(): - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: phases.{phase_name}.parameterization.unit_cell.{cell_param} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check peak broadening - peak_broadening = param_dict.get('peak_broadening', {}) - if peak_broadening: - # Check size broadening - if peak_broadening.get('size_broadening'): - for param_key, param_value in peak_broadening['size_broadening'].items(): - if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) - continue - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.size_broadening.{param_key} has refine_flag=true" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check strain broadening - if peak_broadening.get('strain_broadening'): - for param_key, param_value in peak_broadening['strain_broadening'].items(): - if param_key == 'model': # Skip model field (string literal, not [value, refine_flag]) - continue - if param_value and param_value[1]: # refine_flag - msg = f"WARNING: phases.{phase_name}.parameterization.peak_broadening.strain_broadening.{param_key} has refine_flag=true" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check atom parameters (using same logic as has_active_refinement_parameter for consistency) - atoms = param_dict.get('atoms', {}) - if atoms: - for atom_label, atom_params in atoms.items(): - for param_key, param_value in atom_params.items(): - # Skip ADP field (it's a string, not a RefinementParameter) - if param_key == 'ADP': - continue - - # Handle Uaniso nested dict - if param_key == 'Uaniso' and isinstance(param_value, dict): - for uaniso_key, uaniso_value in param_value.items(): - if isinstance(uaniso_value, list) and len(uaniso_value) >= 2 and uaniso_value[1]: - msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.Uaniso.{uaniso_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - # Check regular RefinementParameter lists (use elif to avoid checking lists after Uaniso) - elif isinstance(param_value, list) and len(param_value) >= 2 and param_value[1]: - msg = f"WARNING: phases.{phase_name}.parameterization.atoms.{atom_label}.{param_key} has refine_flag=true in simulation mode" - warnings.append(msg) - is_valid = False - if verbose: - print(f" {WARN} {msg}") - - if verbose: - if is_valid: - print(f"{CHECK} All parameters properly locked for simulation mode determinism") - - return is_valid, warnings - - ######################################## # Public programmatic API ######################################## -def validate(recipe: RecipeModel | dict, verbose: bool = False) -> RecipeModel: - """Validate a PowderLine recipe without running a refinement. - - Performs full Pydantic schema validation and simulation-mode consistency - checks. Raises ``pydantic.ValidationError`` immediately on any schema - violation so callers receive structured, actionable error information. - - This function is useful when batch-creating recipes and you want to - confirm each one is valid before committing to a refinement run. - - Note: The ``is_template_file()`` guard is **not** applied here. That - check is CLI-only (guards against accidentally running bare template - files from disk). When calling ``validate()`` programmatically the - caller is responsible for ensuring the recipe contains real data. - - Args: - recipe: A fully-populated ``RecipeModel`` instance or equivalent - dict. XRD data must already be present in - ``recipe.payload.xrd_data``. - verbose: If True, print simulation-mode warnings to stdout. - - Returns: - Validated ``RecipeModel`` instance. - - Raises: - pydantic.ValidationError: If the recipe fails schema validation. - ValueError: If simulation-mode constraints are violated (all - ``refine_flag`` fields must be ``false`` when - ``refinement_cycles == 1``). - - Example:: - - import json - import powderline - - recipe_dict = json.load(open("my_recipe.json")) - recipe_model = powderline.validate(recipe_dict) - print(f"Schema: {recipe_model.schema_name}, phases: {len(recipe_model.payload.phases or [])}") - """ - from pydantic import ValidationError # already imported at module level, re-stated for clarity - - if not isinstance(recipe, RecipeModel): - recipe = RecipeModel.model_validate(recipe) # raises ValidationError on failure - - is_sim_valid, sim_warnings = validate_simulation_mode_parameters(recipe, verbose=verbose) - if not is_sim_valid: - raise ValueError( - "Simulation mode validation failed. All refine_flag fields must be false " - f"when refinement_cycles == 1.\nConstraints violated:\n" - + "\n".join(f" - {w}" for w in sim_warnings) - ) - - return recipe - - def run( recipe: RecipeModel | dict, output_dir: Path, From b3eec021920d0f622a6c068a70793e70ab8f6c6c Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:56:07 -0400 Subject: [PATCH 010/259] refactor(core): promote symmetry out of topas/ into powderline.symmetry Moves src/powderline/topas/symmetry.py to src/powderline/symmetry.py, ending the easydiff -> topas cross-adapter import. Importers updated (topas writer, easydiff policy + builder, test_topas_symmetry); no shim. One deviation from a verbatim move (A56): the module's relative 'from .errors import TopasTranslationError' cannot survive the move, and an absolute import at module top is circular (topas/__init__ -> writer -> symmetry). The import now happens inside the two raising functions, so the raised type is unchanged. Interim: re/03 makes core symmetry raise a core error that each gateway translates. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- src/powderline/easydiff/builder.py | 2 +- src/powderline/easydiff/policy.py | 2 +- src/powderline/{topas => }/symmetry.py | 9 ++++++++- src/powderline/topas/writer.py | 2 +- tests/test_topas_symmetry.py | 4 ++-- 6 files changed, 14 insertions(+), 7 deletions(-) rename src/powderline/{topas => }/symmetry.py (96%) diff --git a/CLAUDE.md b/CLAUDE.md index 582b4bf..8e5b8e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -70,7 +70,7 @@ Python ≥3.12): - `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 + validates space groups via `powderline.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 diff --git a/src/powderline/easydiff/builder.py b/src/powderline/easydiff/builder.py index a8fcec9..6cd44c9 100644 --- a/src/powderline/easydiff/builder.py +++ b/src/powderline/easydiff/builder.py @@ -23,7 +23,7 @@ from powderline.easydiff.errors import EasyDiffractionTranslationError from powderline.easydiff.policy import check_unsupported, param_flag, param_value from powderline.topas.errors import TopasTranslationError -from powderline.topas.symmetry import cell_constraints +from powderline.symmetry import cell_constraints @dataclass diff --git a/src/powderline/easydiff/policy.py b/src/powderline/easydiff/policy.py index b140f1e..3cf9a6f 100644 --- a/src/powderline/easydiff/policy.py +++ b/src/powderline/easydiff/policy.py @@ -35,7 +35,7 @@ def _iparm_current(iparm1: dict, key: str, default=0.0): def check_unsupported(recipe: dict) -> list[str]: - from powderline.topas.symmetry import cell_constraints + from powderline.symmetry import cell_constraints from powderline.topas.errors import TopasTranslationError warnings: list[str] = [] diff --git a/src/powderline/topas/symmetry.py b/src/powderline/symmetry.py similarity index 96% rename from src/powderline/topas/symmetry.py rename to src/powderline/symmetry.py index f75d405..e38aedf 100644 --- a/src/powderline/topas/symmetry.py +++ b/src/powderline/symmetry.py @@ -20,7 +20,6 @@ import gemmi import numpy as np -from .errors import TopasTranslationError # Fractional-coordinate tolerances (plan §5). _POS_TOL = 1e-5 # position / orbit equality mod 1 @@ -97,6 +96,10 @@ def resolve_space_group(space_group: str) -> gemmi.SpaceGroup: passed without an explicit ``:1``/``:2`` selector also error rather than guess an origin (plan §5(6); demo groups are single-origin). """ + # Lazy: importing powderline.topas at module top is circular (topas/__init__ + # -> writer -> symmetry). Interim until re/03 raises a core error here (A56). + from powderline.topas.errors import TopasTranslationError + raw = str(space_group) sg = gemmi.find_spacegroup_by_name(raw) if sg is None: @@ -138,6 +141,10 @@ def _monoclinic_unique_axis(ops: list[tuple[np.ndarray, np.ndarray]]) -> str: The single proper 2-fold (det +1, trace -1) fixes the unique axis; its invariant direction maps to the dominant cell axis a/b/c. """ + # Lazy: importing powderline.topas at module top is circular (topas/__init__ + # -> writer -> symmetry). Interim until re/03 raises a core error here (A56). + from powderline.topas.errors import TopasTranslationError + for R, _t in ops: if abs(np.linalg.det(R) - 1.0) < _MAT_TOL and abs(np.trace(R) + 1.0) < _MAT_TOL: evals, evecs = np.linalg.eig(R) diff --git a/src/powderline/topas/writer.py b/src/powderline/topas/writer.py index c14cea1..e3e9978 100644 --- a/src/powderline/topas/writer.py +++ b/src/powderline/topas/writer.py @@ -24,7 +24,7 @@ from . import conversions as cv from .errors import TopasTranslationError -from .symmetry import adp_dof, cell_constraints, site_dof +from powderline.symmetry import adp_dof, cell_constraints, site_dof SCHEMA_RIETVELD = "GSASII_Rietveld" SCHEMA_SPF = "GSASII_SPF" diff --git a/tests/test_topas_symmetry.py b/tests/test_topas_symmetry.py index f45bc34..27295c1 100644 --- a/tests/test_topas_symmetry.py +++ b/tests/test_topas_symmetry.py @@ -1,10 +1,10 @@ -"""Tests for powderline.topas.symmetry (plan §5 targets + error cases).""" +"""Tests for powderline.symmetry (plan §5 targets + error cases).""" from __future__ import annotations import pytest -from powderline.topas import symmetry as sym +from powderline import symmetry as sym from powderline.topas.errors import TopasTranslationError From a42a8a7bb98d0e245287b64285a56e3ec9f2c545 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:56:16 -0400 Subject: [PATCH 011/259] feat(core): add fitstats - uniform Rwp, Rexp, GoF, reduced chi-squared Pure-numpy standard fit statistics (A23), computed once in core. R factors in percent, GoF/chi2_red dimensionless (A55). N = points inside the fit-range mask with w > 0 (A55; evidence in the dossier's tasks/fitstats-n-convention.md); P is the engine-reported varied-parameter count, supplied by each gateway (A41/A45). Created + unit-tested only; gateways adopt it in re/04-06. The LaB6 characterization test documents how it differs from GSAS-II's own numbers: Rwp/GoF agree; GSAS-II's wRmin omits P; N differs by one edge point. Co-Authored-By: Claude Opus 5.5 --- src/powderline/fitstats.py | 99 +++++++++++++++++++++++++++++++ tests/test_fitstats.py | 117 +++++++++++++++++++++++++++++++++++++ 2 files changed, 216 insertions(+) create mode 100644 src/powderline/fitstats.py create mode 100644 tests/test_fitstats.py diff --git a/src/powderline/fitstats.py b/src/powderline/fitstats.py new file mode 100644 index 0000000..7b4938b --- /dev/null +++ b/src/powderline/fitstats.py @@ -0,0 +1,99 @@ +"""Uniform fit statistics computed once in core (master plan A23, A41, A45). + +Every gateway reports the same standard keys (Rwp, Rexp, GoF, reduced χ²) +computed here from the observed/calculated profile, so the numbers mean the +same thing whichever engine ran. Engine-reported values are preserved +separately (``engine_details``); how and why they differ is documented, not +hidden. + +Formulas (the user-docs formulas), with sums over the included points ``i``:: + + Rwp = 100 · sqrt( Σ w_i (yobs_i − ycalc_i)² / Σ w_i yobs_i² ) [%] + Rexp = 100 · sqrt( (N − P) / Σ w_i yobs_i² ) [%] + GoF = Rwp / Rexp = sqrt( Σ w_i (yobs_i − ycalc_i)² / (N − P) ) + χ²_red = Σ w_i (yobs_i − ycalc_i)² / (N − P) (= GoF²) + +- **Included points / N**: inside the fit-range ``mask`` *and* with + ``w_i > 0``. Excluded and out-of-range points are left out of N and the sums + (the convention across GSAS-II, TOPAS and FullProf). Zero-weight points are + also left out: they add no equation to the weighted least-squares problem, so + they add no degree of freedom. GSAS-II counts in-range zero-weight points in + its ``Nobs``; see ``tasks/fitstats-n-convention.md`` in the dossier. +- **P** (``n_params``): the engine's own count of independently varied + parameters after engine-applied constraints, read from the engine **after the + run** (A41, A45) — never derived from recipe refine flags. Each gateway + supplies it. +- R factors are in percent; GoF and χ²_red are dimensionless. +- Undefined values are ``nan``: Rexp, GoF and χ²_red when ``N − P <= 0``; + Rwp and Rexp when ``Σ w yobs² == 0``. + +Pure numpy; imports no engine. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Optional + +import numpy as np + + +@dataclass(frozen=True) +class FitStatistics: + """Standard fit statistics; see the module docstring for the formulas.""" + + rwp: float + rexp: float + gof: float + chi2_red: float + n_points: int + n_params: int + + +def compute_fit_statistics(yobs, ycalc, weights, n_params: int, + mask: Optional[np.ndarray] = None) -> FitStatistics: + """Compute Rwp, Rexp, GoF and reduced χ² over the included points. + + Args: + yobs, ycalc, weights: 1-D arrays of equal length (weights ``>= 0``). + n_params: P, the engine-reported number of varied parameters. + mask: optional boolean array, True = inside the fit range; default all + points. + + Raises: + ValueError: on mismatched shapes, negative weights, a negative + ``n_params``, or non-finite values among the included points. + """ + yobs = np.asarray(yobs, dtype=float) + ycalc = np.asarray(ycalc, dtype=float) + weights = np.asarray(weights, dtype=float) + if yobs.ndim != 1 or yobs.shape != ycalc.shape or yobs.shape != weights.shape: + raise ValueError("yobs, ycalc and weights must be 1-D arrays of equal length") + if mask is None: + mask = np.ones(yobs.shape, dtype=bool) + else: + mask = np.asarray(mask, dtype=bool) + if mask.shape != yobs.shape: + raise ValueError("mask must have the same length as yobs") + if int(n_params) != n_params or n_params < 0: + raise ValueError(f"n_params must be a non-negative integer, got {n_params!r}") + n_params = int(n_params) + if np.any(weights[mask] < 0): + raise ValueError("weights must be >= 0") + + included = mask & (weights > 0) + yo, yc, w = yobs[included], ycalc[included], weights[included] + if not (np.all(np.isfinite(yo)) and np.all(np.isfinite(yc)) and np.all(np.isfinite(w))): + raise ValueError("yobs, ycalc and weights must be finite inside the fit range") + + n_points = int(included.sum()) + sum_wyo2 = float(np.sum(w * yo**2)) + sum_wr2 = float(np.sum(w * (yo - yc) ** 2)) + dof = n_points - n_params + + rwp = 100.0 * np.sqrt(sum_wr2 / sum_wyo2) if sum_wyo2 > 0 else float("nan") + rexp = 100.0 * np.sqrt(dof / sum_wyo2) if (sum_wyo2 > 0 and dof > 0) else float("nan") + chi2_red = sum_wr2 / dof if dof > 0 else float("nan") + gof = float(np.sqrt(chi2_red)) if dof > 0 else float("nan") + return FitStatistics(rwp=float(rwp), rexp=float(rexp), gof=gof, chi2_red=float(chi2_red), + n_points=n_points, n_params=n_params) diff --git a/tests/test_fitstats.py b/tests/test_fitstats.py new file mode 100644 index 0000000..c2bc674 --- /dev/null +++ b/tests/test_fitstats.py @@ -0,0 +1,117 @@ +"""Unit tests for powderline.fitstats (uniform Rwp / Rexp / GoF / reduced χ²). + +Pure tests: no engine. Synthetic cases are hand-computed; the LaB6 case +characterizes (does not assert equality with) GSAS-II's own reported values. +""" +import json +import math +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from powderline.fitstats import FitStatistics, compute_fit_statistics + +EXAMPLES = Path(__file__).resolve().parent.parent / "examples" + + +def test_hand_computed_case(): + # yobs=[10,20,30,40], ycalc=[11,19,30,42], w=[1,0.5,0.25,0.1], P=1 + # Σw·yobs² = 100 + 200 + 225 + 160 = 685 + # Σw·(yobs−ycalc)² = 1 + 0.5 + 0 + 0.4 = 1.9 + # N = 4, N−P = 3 + s = compute_fit_statistics([10, 20, 30, 40], [11, 19, 30, 42], [1, 0.5, 0.25, 0.1], 1) + assert s.rwp == pytest.approx(100 * math.sqrt(1.9 / 685)) + assert s.rexp == pytest.approx(100 * math.sqrt(3 / 685)) + assert s.chi2_red == pytest.approx(1.9 / 3) + assert s.gof == pytest.approx(math.sqrt(1.9 / 3)) + assert s.gof == pytest.approx(s.rwp / s.rexp) + assert (s.n_points, s.n_params) == (4, 1) + + +def test_perfect_fit_is_zero(): + s = compute_fit_statistics([1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1, 1, 1], 0) + assert s.rwp == 0.0 and s.gof == 0.0 and s.chi2_red == 0.0 + assert s.rexp == pytest.approx(100 * math.sqrt(3 / 14)) + + +def test_mask_and_zero_weights_are_excluded_from_n_and_sums(): + base = compute_fit_statistics([10, 20], [11, 19], [1, 0.5], 1) + padded = compute_fit_statistics( + [10, 20, 999, 5], [11, 19, 0, 7], [1, 0.5, 1, 0], 1, + mask=[True, True, False, True], # point 2 out of range; point 3 has w=0 + ) + assert padded == base + assert padded.n_points == 2 + + +def test_undefined_values_are_nan(): + s = compute_fit_statistics([1.0, 2.0], [1.5, 2.5], [1, 1], 2) # N − P = 0 + assert s.rwp == pytest.approx(100 * math.sqrt(0.5 / 5)) + assert math.isnan(s.rexp) and math.isnan(s.gof) and math.isnan(s.chi2_red) + z = compute_fit_statistics([0.0, 0.0], [1.0, 1.0], [1, 1], 0) # Σw·yobs² = 0 + assert math.isnan(z.rwp) and math.isnan(z.rexp) + assert z.chi2_red == pytest.approx(1.0) + + +@pytest.mark.parametrize("kwargs, match", [ + (dict(yobs=[1, 2], ycalc=[1], weights=[1, 1], n_params=0), "equal length"), + (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, -1], n_params=0), ">= 0"), + (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, 1], n_params=-1), "non-negative integer"), + (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, 1], n_params=1.5), "non-negative integer"), + (dict(yobs=[1, np.nan], ycalc=[1, 2], weights=[1, 1], n_params=0), "finite"), + (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, 1], n_params=0, mask=[True]), "mask"), +]) +def test_invalid_input_raises(kwargs, match): + with pytest.raises(ValueError, match=match): + compute_fit_statistics(**kwargs) + + +def test_non_finite_outside_fit_range_is_ignored(): + s = compute_fit_statistics([1.0, np.nan], [1.0, 0.0], [1, 1], 0, mask=[True, False]) + assert s.n_points == 1 + + +def test_result_is_frozen(): + s = compute_fit_statistics([1.0], [1.0], [1.0], 0) + assert isinstance(s, FitStatistics) + with pytest.raises(AttributeError): + s.rwp = 1.0 + + +def test_lab6_characterization_vs_gsasii(): + """Characterize (not assert equality with) GSAS-II on the committed LaB6 fit. + + Inputs: ``examples/example_LaB6/output/fit_profile.txt`` (4096 points, values + rounded to 8 decimals), fit range [1, 15]° 2θ from the recipe, P = 17 from + ``dummy.lst`` ("No. of parameters: 17"). + + GSAS-II (``dummy.lst``): wR = 6.53 %, wRmin = 12.48 %, GOF = 0.52, + chi**2 = 1030.77, 3768 observations. + PowderLine fitstats: Rwp = 6.527 %, Rexp = 12.450 %, GoF = 0.524, + N = 3767. + + How and why they differ (A23): + - Rwp and GoF agree to the reported precision. + - N: GSAS-II slices the fit range by index (``x[xB:xF]``) and counts one + more point than the inclusive 2θ mask [1, 15] used here (3768 vs 3767). + - Rexp vs GSAS-II ``wRmin``: GSAS-II's ``wRmin`` = sqrt(N / Σw·yobs²), i.e. + it does **not** subtract P; fitstats uses the standard sqrt((N − P) / + Σw·yobs²). sqrt(3768/3751) accounts for the 12.48 vs 12.45 gap. + - GSAS-II's ``chi**2`` is the un-reduced Σw·(yobs − ycalc)²; χ²_red here is + that sum divided by (N − P). + """ + recipe = json.loads((EXAMPLES / "example_LaB6" / "input.json").read_text(encoding="utf-8")) + lo, hi = recipe["payload"]["fit_range"] + prof = pd.read_csv(EXAMPLES / "example_LaB6" / "output" / "fit_profile.txt", sep="\t") + tth = prof["two_theta"].to_numpy() + s = compute_fit_statistics(prof["y_obs"], prof["y_calc"], prof["y_weights"], 17, + mask=(tth >= lo) & (tth <= hi)) + assert s.n_points == 3767 + assert s.rwp == pytest.approx(6.53, abs=0.005) + assert s.gof == pytest.approx(0.52, abs=0.005) + assert s.rexp == pytest.approx(12.45, abs=0.005) + # GSAS-II's wRmin omits P: reproduce it from the same sums to prove the claim. + gsas_wrmin = s.rexp * math.sqrt(3768 / (3767 - 17)) + assert gsas_wrmin == pytest.approx(12.48, abs=0.005) From 9c241093d347f4438ffa02a85b5d3d05c12690f9 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:56:16 -0400 Subject: [PATCH 012/259] feat(core): add reports - shared writers for the standardized report files Engine-free writers for refined_parameters.csv, _unit_cell_report.csv, fit_profile.txt and _peak_list_report.csv: they own file naming, column order, header, delimiter and quoting (csv QUOTE_MINIMAL, like pandas), UTF-8 + LF; number formatting stays with the caller. Created + unit-tested only (byte-identical round-trip of all 37 committed GSAS-II references); gateways adopt them in re/04-06 with byte-identical checks. Co-Authored-By: Claude Opus 5.5 --- src/powderline/reports.py | 196 +++++++++++++++++++ tests/test_reports.py | 399 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 595 insertions(+) create mode 100644 src/powderline/reports.py create mode 100644 tests/test_reports.py diff --git a/src/powderline/reports.py b/src/powderline/reports.py new file mode 100644 index 0000000..2126c41 --- /dev/null +++ b/src/powderline/reports.py @@ -0,0 +1,196 @@ +"""Shared writers for PowderLine's standardized report files. + +This module provides engine-free writers for the standardized report files +emitted by all PowderLine engines: ``refined_parameters.csv``, +``_unit_cell_report.csv``, ``fit_profile.txt``, and +``_peak_list_report.csv``. + +The writers own file naming, column order, header, delimiter, and quoting +(csv QUOTE_MINIMAL, like pandas). All files are written with UTF-8 encoding +and LF line endings (``encoding="utf-8", newline=""`` on open with csv +``lineterminator="\\n"``), ensuring deterministic output on all platforms. + +**Number formatting stays with the caller**: engines format values differently, +so this module does not impose a format. A value that is a ``str`` is written +as-is, ``None`` is written as an empty field, and anything else is converted +via ``str(value)``. + +Usage example:: + + from powderline.reports import write_refined_parameters, REFINED_PARAMETERS_COLUMNS + + rows = [ + { + "parameter_name": ":0:Scale", + "descriptive_name": "scale", + "phase_name": "", + "phase_idx": None, + "atom_name": "", + "atom_idx": None, + "value": "1.234567e+00", + "esd": "2.345678e-03", + "category": "scale", + }, + ] + path = write_refined_parameters(output_dir, rows) +""" + +from __future__ import annotations + +import csv +from pathlib import Path +from typing import Iterable, Mapping, Sequence, Union + +#: Column order for refined_parameters.csv (9 columns). +REFINED_PARAMETERS_COLUMNS = ( + "parameter_name", + "descriptive_name", + "phase_name", + "phase_idx", + "atom_name", + "atom_idx", + "value", + "esd", + "category", +) + +#: Column order for _unit_cell_report.csv (3 columns). +UNIT_CELL_COLUMNS = ("parameter", "value", "esd") + +#: Column order for fit_profile.txt (8 columns, tab-delimited). +FIT_PROFILE_COLUMNS = ( + "two_theta", + "y_obs", + "y_weights", + "y_calc", + "y_diff", + "y_bkg", + "q_values", + "d_spacings", +) + + +def _write_table( + path: Path, + columns: Sequence[str], + rows: Iterable[Union[Mapping[str, object], Sequence[object]]], + delimiter: str, +) -> None: + """Write a table to disk with the specified columns, rows, and delimiter. + + Args: + path: Output file path. + columns: Column names in order. + rows: Iterable of mappings (column -> value) or sequences (in column order). + delimiter: Field delimiter (',' or '\\t'). + + Notes: + - Values are written as-is if already strings, None becomes empty, else str(value). + - UTF-8 encoding with LF line endings on all platforms. + - CSV QUOTE_MINIMAL (only when necessary). + """ + path.parent.mkdir(parents=True, exist_ok=True) + + with path.open("w", encoding="utf-8", newline="") as f: + writer = csv.writer(f, delimiter=delimiter, lineterminator="\n") + writer.writerow(columns) + + for row in rows: + if isinstance(row, Mapping): + values = [row.get(col) for col in columns] + else: + values = list(row) + if len(values) != len(columns): + raise ValueError( + f"{path.name}: row has {len(values)} values, expected " + f"{len(columns)} ({', '.join(columns)})" + ) + + # Convert values: str as-is, None -> "", else str(value) + formatted = [ + "" if v is None else (v if isinstance(v, str) else str(v)) + for v in values + ] + writer.writerow(formatted) + + +def write_refined_parameters( + output_dir: Path, + rows: Iterable[Union[Mapping[str, object], Sequence[object]]], +) -> Path: + """Write refined_parameters.csv with the standardized 9-column schema. + + Args: + output_dir: Directory to write the file (created if needed). + rows: Iterable of mappings (column -> value) or sequences in + REFINED_PARAMETERS_COLUMNS order. + + Returns: + Path to the written file (output_dir / "refined_parameters.csv"). + """ + path = Path(output_dir) / "refined_parameters.csv" + _write_table(path, REFINED_PARAMETERS_COLUMNS, rows, delimiter=",") + return path + + +def write_unit_cell_report( + output_dir: Path, + phase_name: str, + rows: Iterable[Union[Mapping[str, object], Sequence[object]]], +) -> Path: + """Write _unit_cell_report.csv with the 3-column schema. + + Args: + output_dir: Directory to write the file (created if needed). + phase_name: Phase name (used in the filename). + rows: Iterable of mappings (column -> value) or sequences in + UNIT_CELL_COLUMNS order. + + Returns: + Path to the written file (output_dir / "_unit_cell_report.csv"). + """ + path = Path(output_dir) / f"{phase_name}_unit_cell_report.csv" + _write_table(path, UNIT_CELL_COLUMNS, rows, delimiter=",") + return path + + +def write_fit_profile( + output_dir: Path, + rows: Iterable[Union[Mapping[str, object], Sequence[object]]], +) -> Path: + """Write fit_profile.txt with the 8-column tab-delimited schema. + + Args: + output_dir: Directory to write the file (created if needed). + rows: Iterable of mappings (column -> value) or sequences in + FIT_PROFILE_COLUMNS order. + + Returns: + Path to the written file (output_dir / "fit_profile.txt"). + """ + path = Path(output_dir) / "fit_profile.txt" + _write_table(path, FIT_PROFILE_COLUMNS, rows, delimiter="\t") + return path + + +def write_peak_list_report( + output_dir: Path, + phase_name: str, + rows: Iterable[Union[Mapping[str, object], Sequence[object]]], + columns: Sequence[str], +) -> Path: + """Write _peak_list_report.csv with engine-specific columns. + + Args: + output_dir: Directory to write the file (created if needed). + phase_name: Phase name (used in the filename). + rows: Iterable of mappings (column -> value) or sequences in + the columns order. + columns: Column names in order (varies per engine). + + Returns: + Path to the written file (output_dir / "_peak_list_report.csv"). + """ + path = Path(output_dir) / f"{phase_name}_peak_list_report.csv" + _write_table(path, columns, rows, delimiter=",") + return path diff --git a/tests/test_reports.py b/tests/test_reports.py new file mode 100644 index 0000000..2849249 --- /dev/null +++ b/tests/test_reports.py @@ -0,0 +1,399 @@ +"""Unit tests for powderline.reports (shared report writers). + +Tests cover byte-identical round-trip against committed GSAS-II references, +mapping vs. sequence row handling, None → empty field, UTF-8 non-ASCII, LF-only +line endings, output_dir creation, and the engine-free guarantee (no GSASII import). +""" + +from __future__ import annotations + +import csv +import subprocess +import sys +from pathlib import Path + +import pytest + +from powderline import reports + + +# Discover all reference files in examples/*/output/ (excluding topas/ subdirs) +_EXAMPLES_ROOT = Path(__file__).parent.parent / "examples" + + +def _discover_reference_files(pattern: str) -> list[Path]: + """Find all files matching pattern in examples/*/output/, excluding topas/.""" + found = [] + for path in _EXAMPLES_ROOT.rglob(pattern): + # Exclude files under topas/ subdirectories + if "topas" in path.parts: + continue + # Only include files under output/ directories + if "output" in path.parts: + found.append(path) + return sorted(found) + + +_REFINED_PARAMS_FILES = _discover_reference_files("refined_parameters.csv") +_UNIT_CELL_FILES = _discover_reference_files("*_unit_cell_report.csv") +_FIT_PROFILE_FILES = _discover_reference_files("fit_profile.txt") +_PEAK_LIST_FILES = _discover_reference_files("*_peak_list_report.csv") + + +# --- Byte round-trip tests --- + + +@pytest.mark.parametrize( + "ref_path", + _REFINED_PARAMS_FILES, + ids=[str(p.relative_to(_EXAMPLES_ROOT)) for p in _REFINED_PARAMS_FILES], +) +def test_refined_parameters_roundtrip(ref_path, tmp_path): + """Byte-identical round-trip for refined_parameters.csv.""" + original_bytes = ref_path.read_bytes() + + # Read with csv module as strings + with ref_path.open("r", encoding="utf-8", newline="") as f: + reader = csv.DictReader(f) + rows = list(reader) + + # Write through the shared writer + written_path = reports.write_refined_parameters(tmp_path, rows) + written_bytes = written_path.read_bytes() + + assert written_bytes == original_bytes, ( + f"Round-trip failed for {ref_path.name}. " + f"First difference at byte {_first_diff_idx(original_bytes, written_bytes)}" + ) + + +@pytest.mark.parametrize( + "ref_path", + _UNIT_CELL_FILES, + ids=[str(p.relative_to(_EXAMPLES_ROOT)) for p in _UNIT_CELL_FILES], +) +def test_unit_cell_report_roundtrip(ref_path, tmp_path): + """Byte-identical round-trip for *_unit_cell_report.csv.""" + original_bytes = ref_path.read_bytes() + + # Extract phase name from filename (remove _unit_cell_report.csv suffix) + phase_name = ref_path.stem.replace("_unit_cell_report", "") + + # Read with csv module as strings + with ref_path.open("r", encoding="utf-8", newline="") as f: + reader = csv.DictReader(f) + rows = list(reader) + + # Write through the shared writer + written_path = reports.write_unit_cell_report(tmp_path, phase_name, rows) + written_bytes = written_path.read_bytes() + + assert written_bytes == original_bytes, ( + f"Round-trip failed for {ref_path.name}. " + f"First difference at byte {_first_diff_idx(original_bytes, written_bytes)}" + ) + + +@pytest.mark.parametrize( + "ref_path", + _FIT_PROFILE_FILES, + ids=[str(p.relative_to(_EXAMPLES_ROOT)) for p in _FIT_PROFILE_FILES], +) +def test_fit_profile_roundtrip(ref_path, tmp_path): + """Byte-identical round-trip for fit_profile.txt (tab-delimited).""" + original_bytes = ref_path.read_bytes() + + # Read with csv module as strings (tab-delimited) + with ref_path.open("r", encoding="utf-8", newline="") as f: + reader = csv.DictReader(f, delimiter="\t") + rows = list(reader) + + # Write through the shared writer + written_path = reports.write_fit_profile(tmp_path, rows) + written_bytes = written_path.read_bytes() + + assert written_bytes == original_bytes, ( + f"Round-trip failed for {ref_path.name}. " + f"First difference at byte {_first_diff_idx(original_bytes, written_bytes)}" + ) + + +@pytest.mark.parametrize( + "ref_path", + _PEAK_LIST_FILES, + ids=[str(p.relative_to(_EXAMPLES_ROOT)) for p in _PEAK_LIST_FILES], +) +def test_peak_list_report_roundtrip(ref_path, tmp_path): + """Byte-identical round-trip for *_peak_list_report.csv.""" + original_bytes = ref_path.read_bytes() + + # Extract phase name from filename (remove _peak_list_report.csv suffix) + phase_name = ref_path.stem.replace("_peak_list_report", "") + + # Read with csv module as strings + with ref_path.open("r", encoding="utf-8", newline="") as f: + reader = csv.DictReader(f) + columns = reader.fieldnames + rows = list(reader) + + # Write through the shared writer + written_path = reports.write_peak_list_report(tmp_path, phase_name, rows, columns) + written_bytes = written_path.read_bytes() + + assert written_bytes == original_bytes, ( + f"Round-trip failed for {ref_path.name}. " + f"First difference at byte {_first_diff_idx(original_bytes, written_bytes)}" + ) + + +def _first_diff_idx(a: bytes, b: bytes) -> int: + """Return the index of the first differing byte, or -1 if equal.""" + for i, (x, y) in enumerate(zip(a, b)): + if x != y: + return i + if len(a) != len(b): + return min(len(a), len(b)) + return -1 + + +# --- Mapping vs sequence rows --- + + +def test_refined_parameters_mapping_vs_sequence(tmp_path): + """Mapping rows and sequence rows produce identical output.""" + # Write using mapping rows + mapping_rows = [ + { + "parameter_name": "test_param", + "descriptive_name": "Test Parameter", + "phase_name": "TestPhase", + "phase_idx": "1", + "atom_name": "TestAtom", + "atom_idx": "2", + "value": "1.234", + "esd": "0.056", + "category": "test_category", + } + ] + path1 = reports.write_refined_parameters(tmp_path / "mapping", mapping_rows) + + # Write using sequence rows (in REFINED_PARAMETERS_COLUMNS order) + sequence_rows = [ + ["test_param", "Test Parameter", "TestPhase", "1", "TestAtom", "2", "1.234", "0.056", "test_category"] + ] + path2 = reports.write_refined_parameters(tmp_path / "sequence", sequence_rows) + + assert path1.read_bytes() == path2.read_bytes() + + +def test_unit_cell_mapping_vs_sequence(tmp_path): + """Mapping rows and sequence rows produce identical output.""" + mapping_rows = [{"parameter": "cell_a", "value": "4.123", "esd": "0.001"}] + path1 = reports.write_unit_cell_report(tmp_path / "mapping", "Phase1", mapping_rows) + + sequence_rows = [["cell_a", "4.123", "0.001"]] + path2 = reports.write_unit_cell_report(tmp_path / "sequence", "Phase1", sequence_rows) + + assert path1.read_bytes() == path2.read_bytes() + + +def test_fit_profile_mapping_vs_sequence(tmp_path): + """Mapping rows and sequence rows produce identical output.""" + mapping_rows = [ + { + "two_theta": "1.0", + "y_obs": "2.0", + "y_weights": "3.0", + "y_calc": "4.0", + "y_diff": "5.0", + "y_bkg": "6.0", + "q_values": "7.0", + "d_spacings": "8.0", + } + ] + path1 = reports.write_fit_profile(tmp_path / "mapping", mapping_rows) + + sequence_rows = [["1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "7.0", "8.0"]] + path2 = reports.write_fit_profile(tmp_path / "sequence", sequence_rows) + + assert path1.read_bytes() == path2.read_bytes() + + +def test_peak_list_mapping_vs_sequence(tmp_path): + """Mapping rows and sequence rows produce identical output.""" + columns = ["h", "k", "l", "d_spacing"] + mapping_rows = [{"h": "1", "k": "2", "l": "3", "d_spacing": "4.56"}] + path1 = reports.write_peak_list_report(tmp_path / "mapping", "Phase1", mapping_rows, columns) + + sequence_rows = [["1", "2", "3", "4.56"]] + path2 = reports.write_peak_list_report(tmp_path / "sequence", "Phase1", sequence_rows, columns) + + assert path1.read_bytes() == path2.read_bytes() + + +# --- None → empty field --- + + +def test_none_becomes_empty_field(tmp_path): + """None values are written as empty fields.""" + rows = [ + { + "parameter_name": "param1", + "descriptive_name": None, + "phase_name": "", + "phase_idx": None, + "atom_name": None, + "atom_idx": None, + "value": "1.0", + "esd": None, + "category": "test", + } + ] + path = reports.write_refined_parameters(tmp_path, rows) + content = path.read_text(encoding="utf-8") + + # Check the data row (second line after header) + lines = content.strip().split("\n") + assert len(lines) == 2 + data_line = lines[1] + # descriptive_name (None), phase_name (""), phase_idx (None), atom_name (None), atom_idx (None), esd (None) should be empty + assert data_line == "param1,,,,,,1.0,,test" + + +# --- LF-only line endings --- + + +def test_lf_only_no_crlf(tmp_path): + """Output files contain only LF line endings, never CRLF.""" + rows = [{"parameter": "cell_a", "value": "4.0", "esd": "0.001"}] + path = reports.write_unit_cell_report(tmp_path, "TestPhase", rows) + content_bytes = path.read_bytes() + + assert b"\r" not in content_bytes, "File contains CRLF (\\r\\n) but should be LF-only" + + +# --- UTF-8 non-ASCII round-trip --- + + +def test_utf8_non_ascii_roundtrip(tmp_path): + """UTF-8 non-ASCII characters (e.g., subscripts) round-trip correctly.""" + rows = [ + { + "parameter_name": "test_param", + "descriptive_name": "Test", + "phase_name": "Fe₂O₃", # Unicode subscripts + "phase_idx": "1", + "atom_name": "Fe", + "atom_idx": "1", + "value": "1.0", + "esd": "0.01", + "category": "test", + } + ] + path = reports.write_refined_parameters(tmp_path, rows) + + # Read back and verify the phase name + with path.open("r", encoding="utf-8", newline="") as f: + reader = csv.DictReader(f) + row = next(reader) + assert row["phase_name"] == "Fe₂O₃" + + +# --- output_dir creation --- + + +def test_output_dir_created(tmp_path): + """Output directory is created if it doesn't exist.""" + nested_dir = tmp_path / "nested" / "path" / "output" + assert not nested_dir.exists() + + rows = [{"parameter": "cell_a", "value": "4.0", "esd": "0.001"}] + path = reports.write_unit_cell_report(nested_dir, "Phase1", rows) + + assert nested_dir.exists() + assert path.exists() + assert path == nested_dir / "Phase1_unit_cell_report.csv" + + +# --- Engine-free guarantee (no GSASII import) --- + + +def test_no_gsasii_import(): + """Importing powderline.reports does not import GSASII.""" + # Run in a subprocess to get a fresh import environment + code = """ +import sys +import importlib.abc + +# Block GSASII import using MetaPathFinder +class _BlockGSASII(importlib.abc.MetaPathFinder): + def find_spec(self, name, path, target=None): + if name == "GSASII" or name.startswith("GSASII."): + raise ImportError(f"Blocked import of {name} (should not be needed)") + return None + +sys.meta_path.insert(0, _BlockGSASII()) + +# Now try to import powderline.reports +import powderline.reports + +# Verify GSASII was not imported +assert "GSASII" not in sys.modules, "GSASII was imported (should not happen)" +print("OK") +""" + result = subprocess.run( + [sys.executable, "-c", code], + cwd=Path(__file__).parent.parent, + env={**subprocess.os.environ, "PYTHONPATH": str(Path(__file__).parent.parent / "src")}, + capture_output=True, + text=True, + ) + + assert result.returncode == 0, ( + f"Subprocess failed:\n" + f"STDOUT: {result.stdout}\n" + f"STDERR: {result.stderr}" + ) + assert "OK" in result.stdout + + +# --- Column constants --- + + +def test_refined_parameters_columns_constant(): + """REFINED_PARAMETERS_COLUMNS has the expected 9 columns in order.""" + assert reports.REFINED_PARAMETERS_COLUMNS == ( + "parameter_name", + "descriptive_name", + "phase_name", + "phase_idx", + "atom_name", + "atom_idx", + "value", + "esd", + "category", + ) + + +def test_unit_cell_columns_constant(): + """UNIT_CELL_COLUMNS has the expected 3 columns in order.""" + assert reports.UNIT_CELL_COLUMNS == ("parameter", "value", "esd") + + +def test_fit_profile_columns_constant(): + """FIT_PROFILE_COLUMNS has the expected 8 columns in order.""" + assert reports.FIT_PROFILE_COLUMNS == ( + "two_theta", + "y_obs", + "y_weights", + "y_calc", + "y_diff", + "y_bkg", + "q_values", + "d_spacings", + ) + + +def test_sequence_row_length_mismatch_raises(tmp_path): + with pytest.raises(ValueError, match="row has 2 values, expected 3"): + reports.write_unit_cell_report(tmp_path, "LaB6", [("a", "1.0")]) From 8d98e6dc92a285ea6c9a5d273eb1d8692ab793f9 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:56:27 -0400 Subject: [PATCH 013/259] feat(core): gateway registry + engine-free gateway factories; dispatcher routed through it - powderline.registry: lazy discovery of the 'powderline.gateways' entry-point group (ep.load on first get), register_gateway() escape hatch, GatewayNotInstalledError, and a clear stale-install-metadata error when the group is empty. Gateway = frozen dataclass (A54); check_engine_version() enforces the PEP 440 ENGINE_VERSION_SPEC as a hard error (A44). - Engine-free gateway.py per gateway (gsasii, topas, easydiff): schema layer validate()/capabilities() runs with no engine installed (A50); runtime run() wraps today's kicker.run / run_topas_recipe / run_easydiffraction_recipe unchanged, importing the engine lazily. Real runs check the engine version (GSASII.__version__; configured TOPAS version, skipped when unset; easydiffraction distribution version) with a gateway-level allow_unsupported_engine_version bypass (A53); a missing engine raises EngineNotAvailableError (an ImportError, A52). Specs: GSAS-II ==5.7.9, TOPAS >=7,<8, easydiffraction >=0.20.1,<0.21. - powderline.engine.run: old engine= names map 1:1 to registry names; public signature and per-engine outputs unchanged (LaB6 gsasii + topas outputs byte-identical to ae415c8). - pyproject: [project.entry-points."powderline.gateways"]; packaging>=22 declared in pyproject + pixi.toml (lock: requires_dist only). CLAUDE.md notes the reinstall needed after entry-point edits. - Tests: registry (escape hatch, laziness, error texts, real entry points, PYTHONPATH=src mode) + gateways (specs, validate, version checks, dispatcher forwarding, import-block schema-only path with GSAS-II/easydiffraction blocked). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 + pixi.lock | 1 + pixi.toml | 1 + pyproject.toml | 10 + src/powderline/easydiff/gateway.py | 74 +++ src/powderline/engine.py | 33 +- src/powderline/gateways/gsasii/__init__.py | 2 +- src/powderline/gateways/gsasii/gateway.py | 76 +++ src/powderline/registry.py | 148 ++++++ src/powderline/topas/gateway.py | 72 +++ tests/test_gateways.py | 524 +++++++++++++++++++++ tests/test_registry.py | 284 +++++++++++ 12 files changed, 1209 insertions(+), 20 deletions(-) create mode 100644 src/powderline/easydiff/gateway.py create mode 100644 src/powderline/gateways/gsasii/gateway.py create mode 100644 src/powderline/registry.py create mode 100644 src/powderline/topas/gateway.py create mode 100644 tests/test_gateways.py create mode 100644 tests/test_registry.py diff --git a/CLAUDE.md b/CLAUDE.md index 8e5b8e2..045b204 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,6 +105,10 @@ The 6-name public API is in `src/powderline/__init__.py` `__all__`: - `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 reinstall powderline` — required after editing `[project.entry-points]` in + `pyproject.toml`: entry-point metadata is written at install time, and the gateway + registry (`powderline.registry`, group `powderline.gateways`) finds nothing until + the editable package is re-installed. - `pixi run update-code-hash` — regenerate `src/powderline/_code_hash.json` after editing `kicker.py` (guarded by `tests/test_code_hash.py`). diff --git a/pixi.lock b/pixi.lock index a4e13ee..b51a946 100644 --- a/pixi.lock +++ b/pixi.lock @@ -17366,6 +17366,7 @@ packages: - h5py>=3.12 - httpx>=0.28 - numpy>=2.0 + - packaging>=22 - pandas>=2.0 - pybaselines>=1.2 - pydantic>=2.0 diff --git a/pixi.toml b/pixi.toml index 27d717e..834faf8 100644 --- a/pixi.toml +++ b/pixi.toml @@ -59,6 +59,7 @@ fastapi = ">=0.115.0,<1" uvicorn = ">=0.34.0,<1" httpx = ">=0.28.0,<1" gemmi = ">=0.7.5,<0.8" +packaging = ">=22" # GSAS-II is built as a conda package via pixi-build (see `preview` above) from # the tacaswell fork, which adds the conda recipe. This installs GSAS-II on ALL # platforms (linux-64/win-64/osx-arm64), unlike the former linux-64-only pip pin. diff --git a/pyproject.toml b/pyproject.toml index 4af4d36..b0fc914 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,8 +52,18 @@ dependencies = [ "uvicorn>=0.34", "httpx>=0.28", "gemmi>=0.7,<0.8", + "packaging>=22", ] +# Gateway plugins (master plan A17): each entry targets an engine-free factory +# module. Entry-point metadata is written at install time -- after editing this +# table, re-install the editable package (`pixi reinstall powderline`) or the +# registry finds no gateways. +[project.entry-points."powderline.gateways"] +gsasii = "powderline.gateways.gsasii.gateway:get_gateway" +topas = "powderline.topas.gateway:get_gateway" +easydiffraction = "powderline.easydiff.gateway:get_gateway" + [project.urls] Homepage = "https://github.com/NSLS2/PowderLine" Documentation = "https://nsls2.github.io/PowderLine/" diff --git a/src/powderline/easydiff/gateway.py b/src/powderline/easydiff/gateway.py new file mode 100644 index 0000000..dae0738 --- /dev/null +++ b/src/powderline/easydiff/gateway.py @@ -0,0 +1,74 @@ +"""Engine-free factory for the easydiffraction gateway (entry point +``powderline.gateways:easydiffraction``). + +- **Schema layer** — ``validate`` / ``capabilities``: builds the ``RecipeModel`` + then runs the policy pre-flight, exactly the check ``validate_only`` runs today + (raises ``EasyDiffractionTranslationError``; no easydiffraction import). +- **Runtime layer** — ``run``: a thin wrapper over + ``powderline.easydiff.engine.run_easydiffraction_recipe`` (behavior unchanged). + On a real run it first reads the installed easydiffraction version: missing ⇒ + ``EngineNotAvailableError``; outside ``ENGINE_VERSION_SPEC`` ⇒ + ``EngineVersionError``. +""" + +from __future__ import annotations + +from powderline.exceptions import EngineNotAvailableError +from powderline.registry import Gateway, check_engine_version +from powderline.schema import RecipeModel + +NAME = "easydiffraction" +#: Supported easydiffraction versions (A41/A44); mirrors the pixi pin. +ENGINE_VERSION_SPEC = ">=0.20.1,<0.21" +#: Workflows served (0.26.0 schema name until re/06; no SPF — A13.3). +WORKFLOWS = ("GSASII_Rietveld",) +#: pixi environment providing easydiffraction + how to install it (renamed in re/08, A42). +ENV = "easydiff" +INSTALL_COMMAND = "pixi install -e easydiff" + + +def capabilities() -> dict: + return {"name": NAME, "workflows": WORKFLOWS, "engine_version_spec": ENGINE_VERSION_SPEC} + + +def validate(recipe): + """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50).""" + from powderline.easydiff.policy import check_unsupported + + model = recipe if isinstance(recipe, RecipeModel) else RecipeModel.model_validate(recipe) + check_unsupported(model.model_dump()) # may raise EasyDiffractionTranslationError + return model + + +def installed_engine_version() -> str: + """The installed easydiffraction version (distribution == runtime there).""" + from importlib.metadata import PackageNotFoundError, version + + try: + return version("easydiffraction") + except PackageNotFoundError as exc: + raise EngineNotAvailableError(gateway=NAME, dependency="easydiffraction", env=ENV, + install_command=INSTALL_COMMAND) from exc + + +def run(recipe, output_dir, *, verbose: bool = False, validate_only: bool = False, + allow_unsupported_engine_version: bool = False) -> dict: + """Run through ``run_easydiffraction_recipe``; see its docstring for the result dict. + + ``allow_unsupported_engine_version`` is the test-only bypass of the engine + version check (A53); the check is skipped for ``validate_only``. + """ + if not validate_only: + check_engine_version(gateway=NAME, engine="easydiffraction", + installed=installed_engine_version(), spec=ENGINE_VERSION_SPEC, + allow_unsupported=allow_unsupported_engine_version) + # Bind the module (not the function) so tests can monkeypatch + # ``run_easydiffraction_recipe`` on it. + from powderline.easydiff import engine as _easydiff_engine + + return _easydiff_engine.run_easydiffraction_recipe(recipe, output_dir, verbose=verbose, + validate_only=validate_only) + + +def get_gateway() -> Gateway: + return Gateway(name=NAME, capabilities=capabilities, validate=validate, run=run) diff --git a/src/powderline/engine.py b/src/powderline/engine.py index 9619112..3b7ee3d 100644 --- a/src/powderline/engine.py +++ b/src/powderline/engine.py @@ -7,11 +7,19 @@ time — the GSAS-II backend is imported lazily only for ``engine="gsasii"``, so ``powderline.run(engine="topas")`` or ``powderline.run(engine="easydiffraction")`` works on machines without GSAS-II. + +Dispatch goes through the gateway registry (``powderline.registry``, entry-point +group ``powderline.gateways``); each old ``engine=`` name maps 1:1 to a registry +name. Each gateway's runtime layer imports its engine lazily. """ from __future__ import annotations +from powderline import registry + _ENGINES = ("gsasii", "topas", "easydiffraction") +#: Old ``engine=`` names -> registry names (1:1; the ``engine=`` argument is removed in re/07). +_ENGINE_TO_GATEWAY = {"gsasii": "gsasii", "topas": "topas", "easydiffraction": "easydiffraction"} def run( @@ -42,10 +50,11 @@ def run( The return dict shape is identical across engines (see ``tests/test_api.py``). """ + if engine not in _ENGINES: + raise ValueError(f"unknown engine {engine!r}; expected one of {_ENGINES}") + gateway = registry.get(_ENGINE_TO_GATEWAY[engine]) if engine == "gsasii": - from powderline.kicker import run as _gsas_run # lazy: imports GSAS-II - - return _gsas_run( + return gateway.run( recipe, output_dir, verbose=verbose, @@ -53,9 +62,7 @@ def run( execution_mode=execution_mode, ) if engine == "topas": - from powderline.topas.engine import run_topas_recipe # GSAS-II-free - - return run_topas_recipe( + return gateway.run( recipe, output_dir, verbose=verbose, @@ -63,16 +70,4 @@ def run( topas_dir=topas_dir, topas_version=topas_version, ) - if engine == "easydiffraction": - # GSAS-II-free; lazy import so this dispatcher loads without - # easydiffraction installed. Bind the module (not the function) so tests - # can monkeypatch ``run_easydiffraction_recipe`` on it. - from powderline.easydiff import engine as _easydiff_engine - - return _easydiff_engine.run_easydiffraction_recipe( - recipe, - output_dir, - verbose=verbose, - validate_only=validate_only, - ) - raise ValueError(f"unknown engine {engine!r}; expected one of {_ENGINES}") + return gateway.run(recipe, output_dir, verbose=verbose, validate_only=validate_only) diff --git a/src/powderline/gateways/gsasii/__init__.py b/src/powderline/gateways/gsasii/__init__.py index d1444ad..84e84f4 100644 --- a/src/powderline/gateways/gsasii/__init__.py +++ b/src/powderline/gateways/gsasii/__init__.py @@ -2,5 +2,5 @@ Do not import runtime modules (setters, project, executors, extractors, ...) here: they import GSAS-II at module top. The engine-free gateway factory -arrives in a later branch (re/02) as ``gateways/gsasii/gateway.py``. +(the ``powderline.gateways`` entry point) is ``gateways/gsasii/gateway.py``. """ diff --git a/src/powderline/gateways/gsasii/gateway.py b/src/powderline/gateways/gsasii/gateway.py new file mode 100644 index 0000000..1cab87b --- /dev/null +++ b/src/powderline/gateways/gsasii/gateway.py @@ -0,0 +1,76 @@ +"""Engine-free factory for the GSAS-II gateway (entry point ``powderline.gateways:gsasii``). + +- **Schema layer** — ``validate`` / ``capabilities``: engine-free; runs with + GSAS-II not installed (``gateways.gsasii.validation`` is recipe-only). +- **Runtime layer** — ``run``: a thin wrapper over ``powderline.kicker.run`` + (behavior unchanged), imported inside the function. On a real run it first + reads the installed GSAS-II version and enforces ``ENGINE_VERSION_SPEC``. + +Never import ``powderline.kicker`` or the gateway's runtime modules (helpers, +project, setters, executors, extractors) at module top: they import GSAS-II. +Enforced by an import-block test. +""" + +from __future__ import annotations + +from powderline.exceptions import EngineNotAvailableError +from powderline.gateways.gsasii.validation import validate as _validate_recipe +from powderline.registry import Gateway, check_engine_version + +NAME = "gsasii" +#: Supported GSAS-II runtime versions (A41/A44); pixi pins align in re/08. +ENGINE_VERSION_SPEC = "==5.7.9" +#: Workflows served (0.26.0 schema names until re/04 introduces ``gsasii.*``). +WORKFLOWS = ("GSASII_Rietveld", "GSASII_SPF") +#: pixi environment providing GSAS-II + how to install it (names final in re/08). +ENV = "default" +INSTALL_COMMAND = "pixi install" + + +def capabilities() -> dict: + return {"name": NAME, "workflows": WORKFLOWS, "engine_version_spec": ENGINE_VERSION_SPEC} + + +def validate(recipe, *, verbose: bool = False): + """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50).""" + return _validate_recipe(recipe, verbose=verbose) + + +def installed_engine_version() -> str: + """The GSAS-II **runtime** version (``GSASII.__version__``), never distribution metadata. + + The pixi-built conda distribution reports ``gsas-ii 2.0.0`` (the fork recipe's + version); the runtime reports ``5.7.9``. Fallback: ``GSASIIpath.GetVersionTag()`` + (``v5.7.9``) with the ``v`` stripped. + """ + try: + import GSASII + except ImportError as exc: + raise EngineNotAvailableError(gateway=NAME, dependency="GSAS-II", env=ENV, + install_command=INSTALL_COMMAND) from exc + version = getattr(GSASII, "__version__", None) + if not version: + from GSASII import GSASIIpath + version = GSASIIpath.GetVersionTag().lstrip("v") + return str(version) + + +def run(recipe, output_dir, *, verbose: bool = False, validate_only: bool = False, + execution_mode: str = "auto", allow_unsupported_engine_version: bool = False) -> dict: + """Run through ``powderline.kicker.run``; see its docstring for the result dict. + + ``allow_unsupported_engine_version`` is the test-only bypass of the engine + version check (A53); the check is skipped for ``validate_only``. + """ + if not validate_only: + check_engine_version(gateway=NAME, engine="GSAS-II", installed=installed_engine_version(), + spec=ENGINE_VERSION_SPEC, + allow_unsupported=allow_unsupported_engine_version) + from powderline.kicker import run as _gsas_run # lazy: imports GSAS-II + + return _gsas_run(recipe, output_dir, verbose=verbose, validate_only=validate_only, + execution_mode=execution_mode) + + +def get_gateway() -> Gateway: + return Gateway(name=NAME, capabilities=capabilities, validate=validate, run=run) diff --git a/src/powderline/registry.py b/src/powderline/registry.py new file mode 100644 index 0000000..d2163d8 --- /dev/null +++ b/src/powderline/registry.py @@ -0,0 +1,148 @@ +"""Gateway registry: discovers PowderLine gateways from the ``powderline.gateways`` +entry-point group (master plan A17, A7). + +Discovery is lazy: entry points are listed on first use and a gateway's +factory is imported (``ep.load()``) only when that gateway is first requested, +so importing this module (or ``powderline``) never imports an engine. + +Each entry point targets an engine-free ``get_gateway`` factory returning a +:class:`Gateway` with two layers: the **schema layer** (``validate``, +``capabilities``) runs with no engine installed; the **runtime layer** +(``run``) imports its engine lazily and raises +:class:`~powderline.exceptions.EngineNotAvailableError` when it is missing. + +``register_gateway(name, factory)`` is the explicit-registration escape hatch +for tests and development; an explicit registration takes precedence over an +entry point of the same name. + +Entry-point metadata is written when the package is installed: after editing +``[project.entry-points]`` in ``pyproject.toml``, re-install the editable +package (``pixi reinstall powderline``) or discovery finds nothing. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from importlib.metadata import entry_points +from typing import Any, Callable, Dict, Optional + +from packaging.specifiers import SpecifierSet +from packaging.version import InvalidVersion, Version + +from powderline.exceptions import EngineVersionError, GatewayNotInstalledError + +ENTRY_POINT_GROUP = "powderline.gateways" + + +@dataclass(frozen=True) +class Gateway: + """A gateway's contract (A54). + + - ``name``: registry name (``"gsasii"``, ``"topas"``, ``"easydiffraction"``). + - ``capabilities()``: dict with at least ``name``, ``workflows`` and + ``engine_version_spec`` (a PEP 440 specifier string, A41). + - ``validate(recipe, **opts)``: schema layer, engine-free. Takes a recipe + dict or an already-validated model, raises on an invalid recipe, returns + the validated model (A50). + - ``run(recipe, output_dir, **opts)``: runtime layer; imports the engine + lazily; returns the standardized result dict. + """ + + name: str + capabilities: Callable[[], Dict[str, Any]] + validate: Callable[..., Any] + run: Callable[..., dict] + + +_explicit: Dict[str, Callable[[], Gateway]] = {} +_entry_points: Optional[Dict[str, Any]] = None +_instances: Dict[str, Gateway] = {} + + +def _discovered() -> Dict[str, Any]: + """Entry points of the ``powderline.gateways`` group, listed once (not loaded).""" + global _entry_points + if _entry_points is None: + _entry_points = {ep.name: ep for ep in entry_points(group=ENTRY_POINT_GROUP)} + return _entry_points + + +def register_gateway(name: str, factory: Callable[[], Gateway]) -> None: + """Register a gateway factory explicitly (tests/dev escape hatch). + + Takes precedence over an entry point of the same name. + """ + _explicit[name] = factory + _instances.pop(name, None) + + +def unregister_gateway(name: str) -> None: + """Remove an explicit registration (entry-point gateways are unaffected).""" + _explicit.pop(name, None) + _instances.pop(name, None) + + +def available() -> list[str]: + """Sorted names of every registered gateway (explicit and entry-point).""" + return sorted(set(_explicit) | set(_discovered())) + + +def get(name: str) -> Gateway: + """Return the gateway registered as ``name``, loading its factory on first use. + + Raises: + GatewayNotInstalledError: no gateway of that name is registered at all. + When the entry-point group is empty the message says the install + metadata is stale (the in-repo gateways are always declared). + """ + if name in _instances: + return _instances[name] + if name in _explicit: + factory = _explicit[name] + else: + eps = _discovered() + if name not in eps: + raise GatewayNotInstalledError(_not_installed_message(name, eps), gateway=name) + factory = eps[name].load() + gateway = factory() + if not isinstance(gateway, Gateway): + raise TypeError(f"gateway factory for {name!r} returned {type(gateway).__name__}, " + "expected powderline.registry.Gateway") + _instances[name] = gateway + return gateway + + +def _not_installed_message(name: str, eps: Dict[str, Any]) -> str: + if not eps: + return ( + f"no PowderLine gateway named {name!r}: no {ENTRY_POINT_GROUP!r} entry " + "points were found at all, although powderline is importable. The " + "package's install metadata is stale or missing; re-install it " + "(`pixi reinstall powderline`, or `pip install -e .`)." + ) + return ( + f"no PowderLine gateway named {name!r} is installed (available: " + f"{', '.join(available())}). Gateways are discovered from the " + f"{ENTRY_POINT_GROUP!r} entry-point group: install the package that " + "provides it (e.g. `pip install `), or register it with " + "powderline.registry.register_gateway()." + ) + + +def check_engine_version(*, gateway: str, engine: str, installed, spec: str, + allow_unsupported: bool = False) -> None: + """Raise :class:`EngineVersionError` unless ``installed`` satisfies ``spec`` (A44). + + A hard error. ``allow_unsupported=True`` is the explicit test-only bypass + for compatibility testing of candidate engine versions (A53); gateways + expose it as ``allow_unsupported_engine_version`` on their ``run()``. + """ + if allow_unsupported: + return + try: + ok = Version(str(installed)) in SpecifierSet(spec) + except InvalidVersion: + ok = False + if not ok: + raise EngineVersionError(gateway=gateway, engine=engine, installed=str(installed), + supported=spec) diff --git a/src/powderline/topas/gateway.py b/src/powderline/topas/gateway.py new file mode 100644 index 0000000..9beb886 --- /dev/null +++ b/src/powderline/topas/gateway.py @@ -0,0 +1,72 @@ +"""Engine-free factory for the TOPAS gateway (entry point ``powderline.gateways:topas``). + +- **Schema layer** — ``validate`` / ``capabilities``: builds the ``RecipeModel`` + then renders the INP in memory, exactly the check ``validate_only`` runs + today (raises ``TopasTranslationError`` on untranslatable input). +- **Runtime layer** — ``run``: a thin wrapper over + ``powderline.topas.engine.run_topas_recipe`` (behavior unchanged). + +TOPAS has no Python engine dependency, so ``EngineNotAvailableError`` never +applies: without ``tc.exe`` the run degrades to generate-only, as today. TOPAS +also has no queryable runtime version: the version check uses the *configured* +version (``topas_version`` argument, else ``.powderline_config.yaml`` +``topas.version``) and is skipped when none is configured (A53) — it checks what +the user configured, not the binary. +""" + +from __future__ import annotations + +from powderline.registry import Gateway, check_engine_version +from powderline.schema import RecipeModel + +NAME = "topas" +#: Supported TOPAS versions (A41/A44). +ENGINE_VERSION_SPEC = ">=7,<8" +#: Workflows served (0.26.0 schema names until re/05 introduces ``topas.*``). +WORKFLOWS = ("GSASII_Rietveld", "GSASII_SPF") + + +def capabilities() -> dict: + return {"name": NAME, "workflows": WORKFLOWS, "engine_version_spec": ENGINE_VERSION_SPEC} + + +def validate(recipe): + """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50).""" + from powderline.topas.writer import render_topas + + model = recipe if isinstance(recipe, RecipeModel) else RecipeModel.model_validate(recipe) + render_topas(model.model_dump(), "topas") # validates translatability; may raise + return model + + +def configured_engine_version(topas_version=None): + """The configured TOPAS version, or ``None`` when none is configured.""" + if topas_version is not None: + return topas_version + from powderline.topas.runner import _read_topas_config + + return _read_topas_config().get("version") + + +def run(recipe, output_dir, *, verbose: bool = False, validate_only: bool = False, + topas_dir=None, topas_version=None, + allow_unsupported_engine_version: bool = False) -> dict: + """Run through ``run_topas_recipe``; see its docstring for the result dict. + + ``allow_unsupported_engine_version`` is the test-only bypass of the engine + version check (A53); the check is skipped for ``validate_only``. + """ + if not validate_only: + version = configured_engine_version(topas_version) + if version is not None: + check_engine_version(gateway=NAME, engine="TOPAS", installed=version, + spec=ENGINE_VERSION_SPEC, + allow_unsupported=allow_unsupported_engine_version) + from powderline.topas.engine import run_topas_recipe + + return run_topas_recipe(recipe, output_dir, verbose=verbose, validate_only=validate_only, + topas_dir=topas_dir, topas_version=topas_version) + + +def get_gateway() -> Gateway: + return Gateway(name=NAME, capabilities=capabilities, validate=validate, run=run) diff --git a/tests/test_gateways.py b/tests/test_gateways.py new file mode 100644 index 0000000..f7cd33b --- /dev/null +++ b/tests/test_gateways.py @@ -0,0 +1,524 @@ +"""Tests for the three built-in gateways: schema layer, version checking, import-block guarantee. + +Coverage: +- ENGINE_VERSION_SPEC consistency across all gateways +- validate() for each gateway (LaB6 recipe) +- Version-check behavior (gsasii, topas, easydiffraction) +- Dispatcher routing (registry.get → gateway.run) +- Import-block guarantee: capabilities/validate work with engines unavailable +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path +from unittest.mock import Mock + +import pytest +from packaging.specifiers import SpecifierSet +from pydantic import ValidationError + +from powderline import registry, schema +from powderline.exceptions import EngineNotAvailableError, EngineVersionError +from powderline.gateways.gsasii import gateway as gsasii_gateway +from powderline.topas import gateway as topas_gateway +from powderline.easydiff import gateway as easydiff_gateway +from subprocess_utils import run_subprocess_utf8 + +REPO = Path(__file__).resolve().parent.parent +EXAMPLES = REPO / "examples" + + +def _lab6_recipe(): + """Load the LaB6 example recipe as a dict.""" + return json.loads((EXAMPLES / "example_LaB6" / "input.json").read_text()) + + +# --- ENGINE_VERSION_SPEC consistency --- + + +@pytest.mark.parametrize( + "gateway_module,expected_spec", + [ + (gsasii_gateway, "==5.7.9"), + (topas_gateway, ">=7,<8"), + (easydiff_gateway, ">=0.20.1,<0.21"), + ], +) +def test_engine_version_spec_parses_and_matches_capabilities(gateway_module, expected_spec): + """Each gateway's ENGINE_VERSION_SPEC parses and equals capabilities()['engine_version_spec'].""" + spec_str = gateway_module.ENGINE_VERSION_SPEC + SpecifierSet(spec_str) # must parse + assert spec_str == expected_spec + caps = gateway_module.capabilities() + assert caps["engine_version_spec"] == expected_spec + + +@pytest.mark.parametrize( + "gateway_module", + [gsasii_gateway, topas_gateway, easydiff_gateway], +) +def test_get_gateway_returns_gateway_with_correct_name(gateway_module): + """Each gateway module's get_gateway() returns a Gateway whose name == NAME.""" + gw = gateway_module.get_gateway() + assert gw.name == gateway_module.NAME + assert isinstance(gw, registry.Gateway) + + +# --- validate() --- + + +@pytest.mark.parametrize( + "gateway_module", + [gsasii_gateway, topas_gateway], +) +def test_validate_lab6_recipe_dict_returns_recipe_model(gateway_module): + """Validating the LaB6 recipe dict returns a RecipeModel. + + Note: easydiffraction is excluded because the LaB6 recipe has a Z broadening + parameter flagged for refinement, which easydiffraction does not support. + """ + recipe = _lab6_recipe() + result = gateway_module.validate(recipe) + assert isinstance(result, schema.RecipeModel) + + +@pytest.mark.parametrize( + "gateway_module", + [gsasii_gateway, topas_gateway], +) +def test_validate_recipe_model_is_idempotent(gateway_module): + """Passing a RecipeModel to validate() returns a RecipeModel (idempotent). + + Note: easydiffraction is excluded because the LaB6 recipe has a Z broadening + parameter flagged for refinement, which easydiffraction does not support. + """ + recipe = _lab6_recipe() + model = schema.RecipeModel.model_validate(recipe) + result = gateway_module.validate(model) + assert isinstance(result, schema.RecipeModel) + + +@pytest.mark.parametrize( + "gateway_module,invalid_recipe", + [ + (gsasii_gateway, {"schema_name": "GSASII_Rietveld"}), + (topas_gateway, {"schema_name": "GSASII_Rietveld"}), + (easydiff_gateway, {"schema_name": "GSASII_Rietveld"}), + (gsasii_gateway, {}), + (topas_gateway, {}), + (easydiff_gateway, {}), + ], +) +def test_validate_invalid_recipe_raises(gateway_module, invalid_recipe): + """An invalid recipe raises ValidationError (from pydantic or wrapped).""" + with pytest.raises((ValidationError, Exception)): # may be wrapped + gateway_module.validate(invalid_recipe) + + +def test_easydiff_validate_lab6_raises_translation_error(): + """Easydiffraction validate raises on the LaB6 recipe due to unsupported Z parameter.""" + from powderline.easydiff.errors import EasyDiffractionTranslationError + + recipe = _lab6_recipe() + with pytest.raises(EasyDiffractionTranslationError, match="Z is flagged for refinement"): + easydiff_gateway.validate(recipe) + + +# --- gsasii version checking --- + + +@pytest.mark.skipif( + importlib.util.find_spec("GSASII") is None, reason="GSAS-II not installed" +) +def test_gsasii_installed_engine_version_satisfies_spec(): + """When GSAS-II is installed, installed_engine_version() satisfies ENGINE_VERSION_SPEC.""" + version = gsasii_gateway.installed_engine_version() + spec = SpecifierSet(gsasii_gateway.ENGINE_VERSION_SPEC) + assert version in spec, f"installed {version} not in {spec}" + + +def test_gsasii_version_check_raises_when_version_out_of_range(tmp_path, monkeypatch): + """When the installed version is out of range, run() raises EngineVersionError.""" + monkeypatch.setattr(gsasii_gateway, "installed_engine_version", lambda: "5.8.0") + # Mock the kicker.run so it doesn't actually run + import powderline.kicker + + fake_run = Mock() + monkeypatch.setattr(powderline.kicker, "run", fake_run) + + with pytest.raises(EngineVersionError): + gsasii_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=False) + assert not fake_run.called, "kicker.run should not be called when version check fails" + + +def test_gsasii_version_check_bypassed_with_allow_unsupported(tmp_path, monkeypatch): + """With allow_unsupported_engine_version=True, the version check is bypassed.""" + monkeypatch.setattr(gsasii_gateway, "installed_engine_version", lambda: "5.8.0") + import powderline.kicker + + fake_run = Mock(return_value={}) + monkeypatch.setattr(powderline.kicker, "run", fake_run) + + gsasii_gateway.run( + _lab6_recipe(), + str(tmp_path), + validate_only=False, + verbose=True, + execution_mode="auto", + allow_unsupported_engine_version=True, + ) + assert fake_run.called + call_kwargs = fake_run.call_args[1] + assert call_kwargs["verbose"] is True + assert call_kwargs["validate_only"] is False + assert call_kwargs["execution_mode"] == "auto" + + +def test_gsasii_validate_only_skips_version_check(tmp_path, monkeypatch): + """With validate_only=True, the version check is skipped.""" + called = [] + + def failing_version_check(): + called.append(True) + raise AssertionError("version check should not be called for validate_only=True") + + monkeypatch.setattr(gsasii_gateway, "installed_engine_version", failing_version_check) + import powderline.kicker + + fake_run = Mock(return_value={}) + monkeypatch.setattr(powderline.kicker, "run", fake_run) + + gsasii_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=True) + assert not called, "installed_engine_version should not be called for validate_only=True" + + +# --- topas version checking --- + + +def test_topas_no_version_configured_skips_check(tmp_path, monkeypatch): + """When no version is configured, the version check is skipped.""" + from powderline.topas import runner, engine + + monkeypatch.setattr(runner, "_read_topas_config", lambda: {}) + fake_run = Mock(return_value={}) + monkeypatch.setattr(engine, "run_topas_recipe", fake_run) + + topas_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=False) + assert fake_run.called + + +def test_topas_version_kwarg_out_of_range_raises(tmp_path, monkeypatch): + """topas_version=6 (out of range) raises EngineVersionError.""" + from powderline.topas import engine + + fake_run = Mock() + monkeypatch.setattr(engine, "run_topas_recipe", fake_run) + + with pytest.raises(EngineVersionError): + topas_gateway.run(_lab6_recipe(), str(tmp_path), topas_version=6, validate_only=False) + assert not fake_run.called + + +def test_topas_version_kwarg_in_range_calls_engine(tmp_path, monkeypatch): + """topas_version=7 (in range) calls run_topas_recipe.""" + from powderline.topas import engine + + fake_run = Mock(return_value={}) + monkeypatch.setattr(engine, "run_topas_recipe", fake_run) + + topas_gateway.run(_lab6_recipe(), str(tmp_path), topas_version=7, validate_only=False) + assert fake_run.called + + +def test_topas_config_version_out_of_range_raises(tmp_path, monkeypatch): + """Config {"version": 6} with topas_version=None raises EngineVersionError.""" + from powderline.topas import runner, engine + + monkeypatch.setattr(runner, "_read_topas_config", lambda: {"version": 6}) + fake_run = Mock() + monkeypatch.setattr(engine, "run_topas_recipe", fake_run) + + with pytest.raises(EngineVersionError): + topas_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=False) + assert not fake_run.called + + +def test_topas_allow_unsupported_bypasses_version_check(tmp_path, monkeypatch): + """allow_unsupported_engine_version=True bypasses the version check.""" + from powderline.topas import engine + + fake_run = Mock(return_value={}) + monkeypatch.setattr(engine, "run_topas_recipe", fake_run) + + topas_gateway.run( + _lab6_recipe(), + str(tmp_path), + topas_version=6, + allow_unsupported_engine_version=True, + validate_only=False, + ) + assert fake_run.called + + +def test_topas_validate_only_skips_version_check(tmp_path, monkeypatch): + """With validate_only=True, the version check is skipped even with topas_version=6.""" + from powderline.topas import engine + + fake_run = Mock(return_value={}) + monkeypatch.setattr(engine, "run_topas_recipe", fake_run) + + topas_gateway.run(_lab6_recipe(), str(tmp_path), topas_version=6, validate_only=True) + assert fake_run.called + + +# --- easydiffraction version checking --- + + +def test_easydiff_version_out_of_range_raises(tmp_path, monkeypatch): + """When installed_engine_version() returns '0.21.0', run() raises EngineVersionError.""" + monkeypatch.setattr(easydiff_gateway, "installed_engine_version", lambda: "0.21.0") + from powderline.easydiff import engine + + fake_run = Mock() + monkeypatch.setattr(engine, "run_easydiffraction_recipe", fake_run) + + with pytest.raises(EngineVersionError): + easydiff_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=False) + assert not fake_run.called + + +def test_easydiff_version_in_range_calls_engine(tmp_path, monkeypatch): + """When installed_engine_version() returns '0.20.1', run() calls the engine.""" + monkeypatch.setattr(easydiff_gateway, "installed_engine_version", lambda: "0.20.1") + from powderline.easydiff import engine + + fake_run = Mock(return_value={}) + monkeypatch.setattr(engine, "run_easydiffraction_recipe", fake_run) + + easydiff_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=False) + assert fake_run.called + + +@pytest.mark.skipif( + importlib.util.find_spec("easydiffraction") is not None, + reason="easydiffraction is installed", +) +def test_easydiff_not_installed_raises_engine_not_available_error(tmp_path): + """When easydiffraction is not installed, run() raises EngineNotAvailableError.""" + with pytest.raises(EngineNotAvailableError) as exc_info: + easydiff_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=False) + assert isinstance(exc_info.value, ImportError) + assert "pixi install -e easydiff" in str(exc_info.value) + + +@pytest.mark.skipif( + importlib.util.find_spec("easydiffraction") is not None, + reason="easydiffraction is installed", +) +def test_easydiff_not_installed_validate_only_does_not_raise(tmp_path, monkeypatch): + """When easydiffraction is not installed, validate_only=True does not raise.""" + from powderline.easydiff import engine + + fake_run = Mock(return_value={}) + monkeypatch.setattr(engine, "run_easydiffraction_recipe", fake_run) + + # validate_only should not trigger the import that raises EngineNotAvailableError + easydiff_gateway.run(_lab6_recipe(), str(tmp_path), validate_only=True) + assert fake_run.called + + +@pytest.mark.skipif( + importlib.util.find_spec("easydiffraction") is None, + reason="easydiffraction not installed", +) +def test_easydiff_installed_version_satisfies_spec(): + """When easydiffraction is installed, its version satisfies ENGINE_VERSION_SPEC. + + easydiffraction 0.20.1 has no ``__version__``; its own runtime version source + is ``utils.package_version`` (distribution metadata), which must agree. + """ + from easydiffraction.utils.utils import package_version + + version = easydiff_gateway.installed_engine_version() + assert version == package_version("easydiffraction") + spec = SpecifierSet(easydiff_gateway.ENGINE_VERSION_SPEC) + assert version in spec + + +# --- Dispatcher routing --- + + +def test_dispatcher_routes_through_registry_get(tmp_path, monkeypatch): + """powderline.engine.run(..., engine=X) routes through registry.get(X).run(...).""" + from powderline import engine as dispatcher_module + + # Register fake gateways that record calls + calls = {} + + def make_fake_gateway(name): + def fake_run(recipe, output_dir, **kwargs): + calls[name] = kwargs + return {} + + return registry.Gateway( + name=name, + capabilities=lambda: {"name": name, "workflows": [], "engine_version_spec": ">=1"}, + validate=lambda recipe, **opts: recipe, + run=fake_run, + ) + + for name in ["gsasii", "topas", "easydiffraction"]: + registry.register_gateway(name, lambda n=name: make_fake_gateway(n)) + + # Test gsasii routing + dispatcher_module.run( + _lab6_recipe(), + str(tmp_path), + engine="gsasii", + verbose=True, + validate_only=False, + execution_mode="subprocess", + ) + assert "gsasii" in calls + assert calls["gsasii"]["verbose"] is True + assert calls["gsasii"]["validate_only"] is False + assert calls["gsasii"]["execution_mode"] == "subprocess" + + # Test topas routing + calls.clear() + dispatcher_module.run( + _lab6_recipe(), + str(tmp_path), + engine="topas", + verbose=False, + validate_only=True, + topas_dir="/fake", + topas_version=7, + ) + assert "topas" in calls + assert calls["topas"]["verbose"] is False + assert calls["topas"]["validate_only"] is True + assert calls["topas"]["topas_dir"] == "/fake" + assert calls["topas"]["topas_version"] == 7 + + # Test easydiffraction routing + calls.clear() + dispatcher_module.run( + _lab6_recipe(), + str(tmp_path), + engine="easydiffraction", + verbose=True, + validate_only=False, + ) + assert "easydiffraction" in calls + assert calls["easydiffraction"]["verbose"] is True + assert calls["easydiffraction"]["validate_only"] is False + + # Unregister the fake gateways + for name in ["gsasii", "topas", "easydiffraction"]: + registry.unregister_gateway(name) + + +def test_dispatcher_unknown_engine_raises_value_error(): + """powderline.engine.run(..., engine='bogus') raises ValueError.""" + from powderline import engine as dispatcher_module + + with pytest.raises(ValueError, match="unknown engine"): + dispatcher_module.run(_lab6_recipe(), "/tmp", engine="bogus") + + +# --- Import-block guarantee --- + + +def test_import_block_schema_layer_and_validate(): + """Schema-layer imports (registry, gateways, capabilities, validate) work with engines blocked.""" + recipe_path = str(EXAMPLES / "example_LaB6" / "input.json") + easydiff_recipe_path = str(EXAMPLES / "example_LaB6_easydiff" / "input.json") + script = f""" +import sys, importlib.abc, json +from pathlib import Path + +# Block GSASII and easydiffraction imports +class _Block(importlib.abc.MetaPathFinder): + def find_spec(self, name, path, target=None): + if name in ("GSASII", "easydiffraction") or name.startswith(("GSASII.", "easydiffraction.")): + raise ImportError(f"{{name}} blocked for import-block test") + return None + +sys.meta_path.insert(0, _Block()) + +# Import the engine-free core + schema-layer modules +import powderline +import powderline.registry +import powderline.exceptions +import powderline.fitstats +import powderline.reports +import powderline.symmetry +import powderline.gateways.gsasii +import powderline.gateways.gsasii.gateway +import powderline.gateways.gsasii.validation +import powderline.topas.gateway +import powderline.easydiff.gateway +from powderline import registry + +recipes = {{ + "gsasii": json.loads(Path(r'{recipe_path}').read_text(encoding="utf-8")), + "topas": json.loads(Path(r'{recipe_path}').read_text(encoding="utf-8")), + # the GSAS-II LaB6 recipe refines Z, which easydiffraction rejects + "easydiffraction": json.loads(Path(r'{easydiff_recipe_path}').read_text(encoding="utf-8")), +}} + +# The schema-only consumer path, through the registry (entry points) +for name, recipe in recipes.items(): + gw = registry.get(name) + caps = gw.capabilities() + assert caps["name"] == name and "engine_version_spec" in caps + assert type(gw.validate(recipe)).__name__ == "RecipeModel" + +# Assert GSASII and easydiffraction are NOT in sys.modules +assert "GSASII" not in sys.modules, "GSASII was imported despite the block" +assert "easydiffraction" not in sys.modules, "easydiffraction was imported despite the block" + +print("OK") +""" + proc = run_subprocess_utf8([sys.executable, "-c", script], capture_output=True, text=True) + assert proc.returncode == 0, f"stdout={proc.stdout!r} stderr={proc.stderr!r}" + assert "OK" in proc.stdout + + +def test_import_block_run_raises_engine_not_available_error(tmp_path): + """With GSASII blocked, gsasii gateway run() raises EngineNotAvailableError.""" + recipe_path = str(EXAMPLES / "example_LaB6" / "input.json") + output_path = str(tmp_path) + script = f""" +import sys, importlib.abc, json +from pathlib import Path + +# Block GSASII import +class _Block(importlib.abc.MetaPathFinder): + def find_spec(self, name, path, target=None): + if name == "GSASII" or name.startswith("GSASII."): + raise ImportError("GSASII blocked for import-block test") + return None + +sys.meta_path.insert(0, _Block()) + +from powderline.gateways.gsasii import gateway as gsasii_gw +from powderline.exceptions import EngineNotAvailableError + +recipe = json.loads(Path(r'{recipe_path}').read_text()) + +try: + gsasii_gw.run(recipe, r'{output_path}', validate_only=False) + print("ERROR: should have raised EngineNotAvailableError") + sys.exit(1) +except EngineNotAvailableError as e: + assert isinstance(e, ImportError) + print("OK") +""" + proc = run_subprocess_utf8([sys.executable, "-c", script], capture_output=True, text=True) + assert proc.returncode == 0, f"stdout={proc.stdout!r} stderr={proc.stderr!r}" + assert "OK" in proc.stdout diff --git a/tests/test_registry.py b/tests/test_registry.py new file mode 100644 index 0000000..657fc44 --- /dev/null +++ b/tests/test_registry.py @@ -0,0 +1,284 @@ +"""Tests for the gateway registry: entry-point discovery, explicit registration, version checks. + +Key invariants (A17/A7/A54): +- Discovery is lazy: available() lists entry points without loading them; get() loads on first use. +- register_gateway() takes precedence over an entry point of the same name. +- A factory returning a non-Gateway raises TypeError. +- check_engine_version enforces PEP 440 specs; allow_unsupported=True bypasses. +- Entry points are only present after re-installing the editable package (pixi reinstall powderline). +""" + +from __future__ import annotations + +import sys +from pathlib import Path +from unittest.mock import Mock + +import pytest +from packaging.specifiers import SpecifierSet + +from powderline import registry +from powderline.exceptions import EngineVersionError, GatewayNotInstalledError +from subprocess_utils import run_subprocess_utf8 + +REPO = Path(__file__).resolve().parent.parent + + +@pytest.fixture(autouse=True) +def _reset_registry_caches(monkeypatch): + """Snapshot and restore the module-level registry caches before/after each test.""" + original_explicit = registry._explicit.copy() + original_instances = registry._instances.copy() + original_entry_points = registry._entry_points + + yield + + # Restore the original state + registry._explicit.clear() + registry._explicit.update(original_explicit) + registry._instances.clear() + registry._instances.update(original_instances) + # Reset entry points to force re-discovery + monkeypatch.setattr(registry, "_entry_points", original_entry_points) + + +def _fake_gateway(name="fake"): + """Build a minimal Gateway for testing.""" + return registry.Gateway( + name=name, + capabilities=lambda: {"name": name, "workflows": [], "engine_version_spec": ">=1"}, + validate=lambda recipe, **opts: recipe, + run=lambda recipe, output_dir, **opts: {}, + ) + + +def _fake_entry_point(name, gateway): + """Build a fake entry point that tracks load() calls.""" + ep = Mock() + ep.name = name + ep.load_called = False + original_gateway = gateway + + def load(): + ep.load_called = True + return lambda: original_gateway + + ep.load = load + return ep + + +# --- register_gateway escape hatch --- + + +def test_register_gateway_makes_get_return_it(): + factory = lambda: _fake_gateway("test_gw") + registry.register_gateway("test_gw", factory) + assert registry.get("test_gw").name == "test_gw" + + +def test_register_gateway_is_cached(monkeypatch): + call_count = 0 + + def factory(): + nonlocal call_count + call_count += 1 + return _fake_gateway("cached") + + registry.register_gateway("cached", factory) + registry.get("cached") + registry.get("cached") + assert call_count == 1, "factory should be called exactly once (cached)" + + +def test_explicit_registration_takes_precedence_over_entry_point(monkeypatch): + """An explicit registration shadows an entry point of the same name.""" + gw_from_ep = _fake_gateway("from_ep") + gw_explicit = _fake_gateway("from_explicit") + ep = _fake_entry_point("shadowed", gw_from_ep) + monkeypatch.setattr(registry, "_entry_points", {"shadowed": ep}) + + registry.register_gateway("shadowed", lambda: gw_explicit) + assert registry.get("shadowed").name == "from_explicit" + assert not ep.load_called, "entry point should not be loaded when shadowed" + + +def test_unregister_gateway_removes_explicit(): + registry.register_gateway("to_remove", lambda: _fake_gateway("to_remove")) + registry.get("to_remove") # cache it + registry.unregister_gateway("to_remove") + with pytest.raises(GatewayNotInstalledError, match="to_remove"): + registry.get("to_remove") + + +def test_available_lists_explicit_and_entry_point_names_sorted(monkeypatch): + registry.register_gateway("explicit_a", lambda: _fake_gateway("explicit_a")) + registry.register_gateway("explicit_z", lambda: _fake_gateway("explicit_z")) + ep1 = _fake_entry_point("ep_b", _fake_gateway("ep_b")) + ep2 = _fake_entry_point("ep_y", _fake_gateway("ep_y")) + monkeypatch.setattr(registry, "_entry_points", {"ep_b": ep1, "ep_y": ep2}) + + names = registry.available() + assert names == ["ep_b", "ep_y", "explicit_a", "explicit_z"] + assert not ep1.load_called, "available() should not load entry points" + assert not ep2.load_called, "available() should not load entry points" + + +# --- Lazy loading --- + + +def test_available_does_not_load_entry_points(monkeypatch): + ep = _fake_entry_point("lazy_test", _fake_gateway("lazy_test")) + monkeypatch.setattr(registry, "_entry_points", {"lazy_test": ep}) + registry.available() + assert not ep.load_called, "available() should not call ep.load()" + + +def test_get_loads_entry_point_exactly_once(monkeypatch): + load_count = 0 + gw = _fake_gateway("lazy_gw") + + def load(): + nonlocal load_count + load_count += 1 + return lambda: gw + + ep = Mock() + ep.name = "lazy_gw" + ep.load = load + monkeypatch.setattr(registry, "_entry_points", {"lazy_gw": ep}) + + registry.get("lazy_gw") + registry.get("lazy_gw") + assert load_count == 1, "entry point load() should be called exactly once" + + +# --- get() of unregistered name --- + + +def test_get_unregistered_name_raises_gateway_not_installed_error(monkeypatch): + monkeypatch.setattr(registry, "_entry_points", {"known": Mock()}) + with pytest.raises(GatewayNotInstalledError) as exc_info: + registry.get("unknown") + assert exc_info.value.gateway == "unknown" + msg = str(exc_info.value) + assert "unknown" in msg + assert "pip install" in msg or "register_gateway" in msg + + +def test_zero_entry_points_message_mentions_stale_metadata(monkeypatch): + """When no entry points are found at all, message says re-install.""" + monkeypatch.setattr(registry, "_entry_points", {}) + with pytest.raises(GatewayNotInstalledError) as exc_info: + registry.get("anything") + msg = str(exc_info.value) + assert "no 'powderline.gateways' entry points were found" in msg + assert "pixi reinstall powderline" in msg + + +# --- factory returning non-Gateway --- + + +def test_factory_returning_non_gateway_raises_type_error(monkeypatch): + registry.register_gateway("bad", lambda: "not a Gateway") + with pytest.raises(TypeError, match="expected powderline.registry.Gateway"): + registry.get("bad") + + +# --- check_engine_version --- + + +def test_check_engine_version_in_range_passes(): + registry.check_engine_version( + gateway="test", engine="TestEngine", installed="1.2.3", spec=">=1,<2" + ) + + +def test_check_engine_version_out_of_range_raises(): + with pytest.raises(EngineVersionError) as exc_info: + registry.check_engine_version( + gateway="test", engine="TestEngine", installed="0.9.0", spec=">=1,<2" + ) + assert exc_info.value.installed == "0.9.0" + assert exc_info.value.supported == ">=1,<2" + + +def test_check_engine_version_invalid_version_raises(): + with pytest.raises(EngineVersionError): + registry.check_engine_version( + gateway="test", engine="TestEngine", installed="not-a-version", spec=">=1,<2" + ) + + +def test_check_engine_version_allow_unsupported_bypasses(): + registry.check_engine_version( + gateway="test", + engine="TestEngine", + installed="0.9.0", + spec=">=1,<2", + allow_unsupported=True, + ) + + +def test_check_engine_version_topas_bare_int(): + """TOPAS-style bare int '7' against '>=7,<8' passes.""" + registry.check_engine_version( + gateway="topas", engine="TOPAS", installed="7", spec=">=7,<8" + ) + + +def test_check_engine_version_topas_bare_int_out_of_range(): + """TOPAS-style bare int '6' against '>=7,<8' fails.""" + with pytest.raises(EngineVersionError): + registry.check_engine_version( + gateway="topas", engine="TOPAS", installed="6", spec=">=7,<8" + ) + + +# --- REAL entry points (requires re-install) --- + + +def test_real_entry_points_available(monkeypatch): + """With caches reset, available() includes the three built-in gateways.""" + # Reset to force discovery + monkeypatch.setattr(registry, "_entry_points", None) + monkeypatch.setattr(registry, "_instances", {}) + names = registry.available() + # Expected to fail until `pixi reinstall powderline` is run + assert {"gsasii", "topas", "easydiffraction"} <= set(names) + + +def test_real_entry_points_get_returns_gateway(monkeypatch): + """With caches reset, get(name) returns a Gateway for each built-in.""" + monkeypatch.setattr(registry, "_entry_points", None) + monkeypatch.setattr(registry, "_instances", {}) + for name in ["gsasii", "topas", "easydiffraction"]: + gw = registry.get(name) + assert gw.name == name + assert isinstance(gw, registry.Gateway) + + +# --- PYTHONPATH=src mode --- + + +def test_pythonpath_src_mode_sees_entry_points(): + """Subprocess with PYTHONPATH=src sees the three built-in entry points.""" + import os + + script = """ +import sys +import os +from importlib.metadata import entry_points + +sys.path.insert(0, os.environ.get("PYTHONPATH", "")) +eps = entry_points(group="powderline.gateways") +names = sorted(ep.name for ep in eps) +print(",".join(names)) +""" + env = {"PYTHONPATH": str(REPO / "src")} + proc = run_subprocess_utf8( + [sys.executable, "-c", script], capture_output=True, text=True, env={**os.environ, **env} + ) + assert proc.returncode == 0, f"stdout={proc.stdout!r} stderr={proc.stderr!r}" + names = proc.stdout.strip().split(",") + # Expected to fail until re-install + assert set(names) >= {"easydiffraction", "gsasii", "topas"} From 4e1bc1b4fce8b03193dc4155b2718b873597b4c5 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:53:04 -0400 Subject: [PATCH 014/259] fix(core): route every symmetry raise through one lazy error helper (G1 KI-13) The A56 relocation re-imported TopasTranslationError lazily in only two of the four raising functions; cell_constraints and site_dof would have raised NameError on their (unreachable with real gemmi groups) fallthrough paths. All six raise sites now use _translation_error(), the module's single reference to a gateway, so re/03's switch to a core error is one line (A57). Tests force all three defensive paths; an undefined-name probe over every module changed since v0.1.1 reports none. Co-Authored-By: Claude Opus 5.5 --- src/powderline/symmetry.py | 34 ++++++++++++++++++++-------------- tests/test_topas_symmetry.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 14 deletions(-) diff --git a/src/powderline/symmetry.py b/src/powderline/symmetry.py index e38aedf..09db7e7 100644 --- a/src/powderline/symmetry.py +++ b/src/powderline/symmetry.py @@ -84,6 +84,20 @@ def classification(self, axis: str) -> str: return self.axes[_AXIS_LETTERS.index(axis)] +def _translation_error(message: str) -> Exception: + """Build the error raised for unsupported symmetry input (A56, interim). + + Returns ``powderline.topas.errors.TopasTranslationError``, the type callers + catch today. Imported here, lazily, because importing ``powderline.topas`` at + module top is circular (topas/__init__ -> writer -> symmetry). This is the + module's only reference to a gateway; re/03 replaces it with a core error + that each gateway translates. + """ + from powderline.topas.errors import TopasTranslationError + + return TopasTranslationError(message) + + # --- space-group resolution ------------------------------------------------- @@ -96,25 +110,21 @@ def resolve_space_group(space_group: str) -> gemmi.SpaceGroup: passed without an explicit ``:1``/``:2`` selector also error rather than guess an origin (plan §5(6); demo groups are single-origin). """ - # Lazy: importing powderline.topas at module top is circular (topas/__init__ - # -> writer -> symmetry). Interim until re/03 raises a core error here (A56). - from powderline.topas.errors import TopasTranslationError - raw = str(space_group) sg = gemmi.find_spacegroup_by_name(raw) if sg is None: sg = gemmi.find_spacegroup_by_name(raw.replace(" ", "")) if sg is None: - raise TopasTranslationError( + raise _translation_error( f"unrecognized space-group symbol {space_group!r} (gemmi could not resolve it)" ) if sg.ext == "R": - raise TopasTranslationError( + raise _translation_error( f"rhombohedral ':R' setting not supported for {space_group!r}; " "use the hexagonal (:H) setting" ) if sg.ext in ("1", "2") and ":" not in raw: - raise TopasTranslationError( + raise _translation_error( f"space group {space_group!r} has two origin choices; specify one " "explicitly (e.g. append ':2' for the GSAS-II origin-2 convention)" ) @@ -141,10 +151,6 @@ def _monoclinic_unique_axis(ops: list[tuple[np.ndarray, np.ndarray]]) -> str: The single proper 2-fold (det +1, trace -1) fixes the unique axis; its invariant direction maps to the dominant cell axis a/b/c. """ - # Lazy: importing powderline.topas at module top is circular (topas/__init__ - # -> writer -> symmetry). Interim until re/03 raises a core error here (A56). - from powderline.topas.errors import TopasTranslationError - for R, _t in ops: if abs(np.linalg.det(R) - 1.0) < _MAT_TOL and abs(np.trace(R) + 1.0) < _MAT_TOL: evals, evecs = np.linalg.eig(R) @@ -152,7 +158,7 @@ def _monoclinic_unique_axis(ops: list[tuple[np.ndarray, np.ndarray]]) -> str: if abs(evals[i].real - 1.0) < _MAT_TOL and abs(evals[i].imag) < _MAT_TOL: direction = np.abs(evecs[:, i].real) return _LENGTHS[int(np.argmax(direction))] - raise TopasTranslationError( + raise _translation_error( "could not determine the monoclinic unique axis (no proper 2-fold found)" ) @@ -187,7 +193,7 @@ def cell_constraints(space_group: str) -> CellRules: if system == "triclinic": return CellRules(system, singles, (), _ANGLES) - raise TopasTranslationError( + raise _translation_error( f"unsupported crystal system {system!r} for space group {space_group!r}" ) @@ -229,7 +235,7 @@ def site_dof(space_group: str, xyz) -> SiteDof: stab_rots = [R for (R, t) in ops if np.all(np.abs(_wrap_symmetric(R @ x + t - x)) < _POS_TOL)] if not stab_rots: # pragma: no cover - identity is always in the group - raise TopasTranslationError("empty stabilizer (should be impossible)") + raise _translation_error("empty stabilizer (should be impossible)") projector = sum(stab_rots) / len(stab_rots) diff --git a/tests/test_topas_symmetry.py b/tests/test_topas_symmetry.py index 27295c1..5288a84 100644 --- a/tests/test_topas_symmetry.py +++ b/tests/test_topas_symmetry.py @@ -168,3 +168,35 @@ def test_adp_dof_c2m_unique_b_off_diagonals_fixed(): def test_adp_dof_rejects_bad_shape(): with pytest.raises(ValueError): sym.adp_dof("P m -3 m", (0.0, 0.0)) + + +# --- defensive raise paths (unreachable with real gemmi groups; KI-13) ------- + + +class _UnknownSystem: + """Stand-in space group whose crystal system no rule handles.""" + + def crystal_system_str(self): + return "not-a-system" + + +def test_unsupported_crystal_system_raises_translation_error(monkeypatch): + monkeypatch.setattr(sym, "resolve_space_group", lambda _sg: _UnknownSystem()) + with pytest.raises(TopasTranslationError, match="unsupported crystal system"): + sym.cell_constraints("P1") + + +def test_empty_stabilizer_raises_translation_error(monkeypatch): + import numpy as np + + # A single translation-only op fixes no point, so the stabiliser is empty. + monkeypatch.setattr(sym, "_expanded_ops", lambda _sg: [(np.eye(3), np.full(3, 0.5))]) + with pytest.raises(TopasTranslationError, match="empty stabilizer"): + sym.site_dof("P1", [0.1, 0.2, 0.3]) + + +def test_monoclinic_unique_axis_failure_raises_translation_error(): + import numpy as np + + with pytest.raises(TopasTranslationError, match="monoclinic unique axis"): + sym._monoclinic_unique_axis([(np.eye(3), np.zeros(3))]) From 04b136861a7d8ad80fa56c6551b060442c863018 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:53:04 -0400 Subject: [PATCH 015/259] fix(core): fitstats rejects non-finite weights inside the fit range (G1 nit) NaN > 0 is False, so a NaN weight was silently dropped from N instead of raising as documented. Weights are now checked over the whole fit range before the w > 0 filter. Co-Authored-By: Claude Opus 5.5 --- src/powderline/fitstats.py | 6 +++++- tests/test_fitstats.py | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/powderline/fitstats.py b/src/powderline/fitstats.py index 7b4938b..e175888 100644 --- a/src/powderline/fitstats.py +++ b/src/powderline/fitstats.py @@ -78,12 +78,16 @@ def compute_fit_statistics(yobs, ycalc, weights, n_params: int, if int(n_params) != n_params or n_params < 0: raise ValueError(f"n_params must be a non-negative integer, got {n_params!r}") n_params = int(n_params) + # Check weights over the whole fit range *before* the w > 0 filter: NaN > 0 + # is False, so a NaN weight would otherwise be silently dropped from N. + if not np.all(np.isfinite(weights[mask])): + raise ValueError("yobs, ycalc and weights must be finite inside the fit range") if np.any(weights[mask] < 0): raise ValueError("weights must be >= 0") included = mask & (weights > 0) yo, yc, w = yobs[included], ycalc[included], weights[included] - if not (np.all(np.isfinite(yo)) and np.all(np.isfinite(yc)) and np.all(np.isfinite(w))): + if not (np.all(np.isfinite(yo)) and np.all(np.isfinite(yc))): raise ValueError("yobs, ycalc and weights must be finite inside the fit range") n_points = int(included.sum()) diff --git a/tests/test_fitstats.py b/tests/test_fitstats.py index c2bc674..4247031 100644 --- a/tests/test_fitstats.py +++ b/tests/test_fitstats.py @@ -61,6 +61,8 @@ def test_undefined_values_are_nan(): (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, 1], n_params=-1), "non-negative integer"), (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, 1], n_params=1.5), "non-negative integer"), (dict(yobs=[1, np.nan], ycalc=[1, 2], weights=[1, 1], n_params=0), "finite"), + (dict(yobs=[1, 2, 3], ycalc=[1, 2, 3], weights=[1, np.nan, 1], n_params=0), "finite"), + (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, np.inf], n_params=0), "finite"), (dict(yobs=[1, 2], ycalc=[1, 2], weights=[1, 1], n_params=0, mask=[True]), "mask"), ]) def test_invalid_input_raises(kwargs, match): From 33f510c053271eb9096ba166a4332c83a5a8096d Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:53:05 -0400 Subject: [PATCH 016/259] fix(gateways): uniform validate(recipe, *, verbose=False) contract; test hygiene (G1 nits) - Every gateway's validate() takes the same explicit keywords (A59); topas and easydiffraction previously took none, so registry.get(n).validate(r, verbose=True) raised TypeError for them. Tests assert the signature and the call through the registry for all three. - The dispatcher-routing test restores the registry via a fixture, even on failure (it cleaned up only on success). - Recipe reads in test_gateways pin encoding="utf-8" (Windows, G3). Co-Authored-By: Claude Opus 5.5 --- src/powderline/easydiff/gateway.py | 8 +++-- src/powderline/gateways/gsasii/gateway.py | 2 +- src/powderline/registry.py | 7 ++-- src/powderline/topas/gateway.py | 8 +++-- tests/test_gateways.py | 43 +++++++++++++++++++---- 5 files changed, 53 insertions(+), 15 deletions(-) diff --git a/src/powderline/easydiff/gateway.py b/src/powderline/easydiff/gateway.py index dae0738..57728ae 100644 --- a/src/powderline/easydiff/gateway.py +++ b/src/powderline/easydiff/gateway.py @@ -31,8 +31,12 @@ def capabilities() -> dict: return {"name": NAME, "workflows": WORKFLOWS, "engine_version_spec": ENGINE_VERSION_SPEC} -def validate(recipe): - """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50).""" +def validate(recipe, *, verbose: bool = False): + """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50, A59). + + ``verbose`` is part of the uniform gateway contract; this gateway prints + nothing extra today. + """ from powderline.easydiff.policy import check_unsupported model = recipe if isinstance(recipe, RecipeModel) else RecipeModel.model_validate(recipe) diff --git a/src/powderline/gateways/gsasii/gateway.py b/src/powderline/gateways/gsasii/gateway.py index 1cab87b..5ea97a1 100644 --- a/src/powderline/gateways/gsasii/gateway.py +++ b/src/powderline/gateways/gsasii/gateway.py @@ -32,7 +32,7 @@ def capabilities() -> dict: def validate(recipe, *, verbose: bool = False): - """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50).""" + """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50, A59).""" return _validate_recipe(recipe, verbose=verbose) diff --git a/src/powderline/registry.py b/src/powderline/registry.py index d2163d8..732b193 100644 --- a/src/powderline/registry.py +++ b/src/powderline/registry.py @@ -41,9 +41,10 @@ class Gateway: - ``name``: registry name (``"gsasii"``, ``"topas"``, ``"easydiffraction"``). - ``capabilities()``: dict with at least ``name``, ``workflows`` and ``engine_version_spec`` (a PEP 440 specifier string, A41). - - ``validate(recipe, **opts)``: schema layer, engine-free. Takes a recipe - dict or an already-validated model, raises on an invalid recipe, returns - the validated model (A50). + - ``validate(recipe, *, verbose=False)``: schema layer, engine-free. Takes a + recipe dict or an already-validated model, raises on an invalid recipe, + returns the validated model (A50). The same explicit keywords on every + gateway (A59); new options are added to the contract deliberately. - ``run(recipe, output_dir, **opts)``: runtime layer; imports the engine lazily; returns the standardized result dict. """ diff --git a/src/powderline/topas/gateway.py b/src/powderline/topas/gateway.py index 9beb886..b782426 100644 --- a/src/powderline/topas/gateway.py +++ b/src/powderline/topas/gateway.py @@ -30,8 +30,12 @@ def capabilities() -> dict: return {"name": NAME, "workflows": WORKFLOWS, "engine_version_spec": ENGINE_VERSION_SPEC} -def validate(recipe): - """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50).""" +def validate(recipe, *, verbose: bool = False): + """Validate a recipe (dict or ``RecipeModel``); return the ``RecipeModel`` (A50, A59). + + ``verbose`` is part of the uniform gateway contract; this gateway prints + nothing extra today. + """ from powderline.topas.writer import render_topas model = recipe if isinstance(recipe, RecipeModel) else RecipeModel.model_validate(recipe) diff --git a/tests/test_gateways.py b/tests/test_gateways.py index f7cd33b..a1e8cc8 100644 --- a/tests/test_gateways.py +++ b/tests/test_gateways.py @@ -33,7 +33,19 @@ def _lab6_recipe(): """Load the LaB6 example recipe as a dict.""" - return json.loads((EXAMPLES / "example_LaB6" / "input.json").read_text()) + return json.loads((EXAMPLES / "example_LaB6" / "input.json").read_text(encoding="utf-8")) + + +@pytest.fixture +def isolated_registry(): + """Snapshot the registry caches; restore them even if the test fails.""" + saved = (registry._explicit.copy(), registry._instances.copy(), registry._entry_points) + yield registry + registry._explicit.clear() + registry._explicit.update(saved[0]) + registry._instances.clear() + registry._instances.update(saved[1]) + registry._entry_points = saved[2] # --- ENGINE_VERSION_SPEC consistency --- @@ -351,7 +363,7 @@ def test_easydiff_installed_version_satisfies_spec(): # --- Dispatcher routing --- -def test_dispatcher_routes_through_registry_get(tmp_path, monkeypatch): +def test_dispatcher_routes_through_registry_get(tmp_path, monkeypatch, isolated_registry): """powderline.engine.run(..., engine=X) routes through registry.get(X).run(...).""" from powderline import engine as dispatcher_module @@ -417,10 +429,6 @@ def fake_run(recipe, output_dir, **kwargs): assert calls["easydiffraction"]["verbose"] is True assert calls["easydiffraction"]["validate_only"] is False - # Unregister the fake gateways - for name in ["gsasii", "topas", "easydiffraction"]: - registry.unregister_gateway(name) - def test_dispatcher_unknown_engine_raises_value_error(): """powderline.engine.run(..., engine='bogus') raises ValueError.""" @@ -509,7 +517,7 @@ def find_spec(self, name, path, target=None): from powderline.gateways.gsasii import gateway as gsasii_gw from powderline.exceptions import EngineNotAvailableError -recipe = json.loads(Path(r'{recipe_path}').read_text()) +recipe = json.loads(Path(r'{recipe_path}').read_text(encoding="utf-8")) try: gsasii_gw.run(recipe, r'{output_path}', validate_only=False) @@ -522,3 +530,24 @@ def find_spec(self, name, path, target=None): proc = run_subprocess_utf8([sys.executable, "-c", script], capture_output=True, text=True) assert proc.returncode == 0, f"stdout={proc.stdout!r} stderr={proc.stderr!r}" assert "OK" in proc.stdout + + +# --- Uniform validate() contract (A59) --- + + +@pytest.mark.parametrize("gateway_module", [gsasii_gateway, topas_gateway, easydiff_gateway], + ids=["gsasii", "topas", "easydiffraction"]) +def test_validate_signature_is_uniform(gateway_module): + import inspect + + params = inspect.signature(gateway_module.validate).parameters + assert list(params) == ["recipe", "verbose"] + assert params["verbose"].kind is inspect.Parameter.KEYWORD_ONLY + assert params["verbose"].default is False + + +@pytest.mark.parametrize("name", ["gsasii", "topas", "easydiffraction"]) +def test_validate_accepts_verbose_through_the_registry(name): + example = "example_LaB6_easydiff" if name == "easydiffraction" else "example_LaB6" + recipe = json.loads((EXAMPLES / example / "input.json").read_text(encoding="utf-8")) + assert isinstance(registry.get(name).validate(recipe, verbose=True), schema.RecipeModel) From a84fd39028c65c1bbc1174f68a875824e24668b1 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:53:05 -0400 Subject: [PATCH 017/259] docs(known_issues): KI-13 - engine dispatch depends on entry-point metadata (watch) Filed by the G1 review (as KI-14; renumbered because the review's KI-13, a re/02 regression, was fixed before merge and never entered the register). Decision A58: entry points stay the only discovery path; re/08 adds install-health guidance, re/10 documents the re-install step. Co-Authored-By: Claude Opus 5.5 --- docs/known_issues.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/known_issues.md b/docs/known_issues.md index 08e103e..12b57b2 100644 --- a/docs/known_issues.md +++ b/docs/known_issues.md @@ -356,3 +356,35 @@ supported topology. Needs protocol versioning for already-running servers. **Revisit.** Next branch touching the server protocol, or when the HPC deployment work starts. + +--- + +## KI-13 — Engine dispatch depends on install-time entry-point metadata `watch · minor` + +**What.** Since re/02, `powderline.run()` resolves every engine through the +gateway registry. That includes the default `engine="gsasii"` and the in-repo +gateways. The registry reads the `powderline.gateways` entry points from the +installed distribution's metadata. If a checkout's editable install predates +the `[project.entry-points]` table, is half-installed, or powderline is +imported from source (`PYTHONPATH=src`) with no dist-info at all, then every +`run()` call fails with `GatewayNotInstalledError`. Before re/02 the +dispatcher imported the backends directly and did not depend on install +metadata. The error message is clear and names the fix. However, each existing +dev environment has to be re-installed once (`pixi reinstall powderline`). +During re/02 the maintainer's `easydiff` env was left half-installed with no +error shown, and it failed this way. + +**Evidence.** `src/powderline/engine.py:53` (`registry.get(...)` for all +engines); `src/powderline/registry.py` `get` / `_not_installed_message`; +`CLAUDE.md` (the `pixi reinstall powderline` note); the execution-log re/02 +entry (env notes). + +**Decision.** Keep entry points as the **only** discovery path (A17, A58): the +in-repo gateways use exactly the plugin mechanism a third-party engine will +use, and a hard-coded fallback would add a second discovery path and hide a +stale install. The registry's error already names the fix. re/08 adds +install-health guidance (and possibly a check command); re/10 documents the +re-install step for contributors. + +**Revisit.** re/08 (entry points finalized) and re/10 (migration guide / dev +docs). From 6074ebad3d07341c7e637aabb994c0f08d1fcaa5 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 29 Sep 2026 17:06:16 -0400 Subject: [PATCH 018/259] refactor(core): symmetry raises a core SymmetryError; gateways convert it (A61, A62) Closes the A56/A57 obligation: powderline.symmetry no longer references a gateway. The _translation_error() helper is gone; every raise is powderline.exceptions.SymmetryError(PowderLineError, ValueError). - TOPAS writer: one _symmetry() helper wraps its three symmetry calls, converts SymmetryError to TopasTranslationError (chained) and applies TOPAS's own rejection of the rhombohedral :R setting (same message). - easydiffraction policy/builder catch SymmetryError instead of TopasTranslationError (no longer importing the TOPAS gateway); the policy rejects :R itself. - Core resolve_space_group/site_dof/adp_dof accept :R (A62); cell_constraints refuses :R explicitly (its tied angles are not expressible as CellRules). Gateway-raised error types are unchanged. Direct callers of powderline.symmetry see SymmetryError, and :R is accepted by the resolver. Both are recorded in the devkit deliberate-changes table (A34). Test IDs relabelled: three test_topas_symmetry *_raises_translation_error tests became *_raises_symmetry_error; the :R test was split in two. Co-Authored-By: Claude Opus 5.5 --- src/powderline/easydiff/builder.py | 4 +- src/powderline/easydiff/policy.py | 11 ++++-- src/powderline/exceptions.py | 13 ++++++ src/powderline/symmetry.py | 63 ++++++++++++++---------------- src/powderline/topas/writer.py | 27 +++++++++++-- tests/test_easydiff_policy.py | 8 ++++ tests/test_exceptions.py | 3 +- tests/test_topas_symmetry.py | 43 ++++++++++++++------ tests/test_topas_writer.py | 16 ++++++++ 9 files changed, 131 insertions(+), 57 deletions(-) diff --git a/src/powderline/easydiff/builder.py b/src/powderline/easydiff/builder.py index 6cd44c9..c97dc54 100644 --- a/src/powderline/easydiff/builder.py +++ b/src/powderline/easydiff/builder.py @@ -22,7 +22,7 @@ ) from powderline.easydiff.errors import EasyDiffractionTranslationError from powderline.easydiff.policy import check_unsupported, param_flag, param_value -from powderline.topas.errors import TopasTranslationError +from powderline.exceptions import SymmetryError from powderline.symmetry import cell_constraints @@ -359,7 +359,7 @@ def build_project(recipe: dict, workdir) -> BuildResult: # Get symmetry rules try: rules = cell_constraints(sg_name) - except TopasTranslationError as e: + except SymmetryError as e: raise EasyDiffractionTranslationError(str(e)) from e length_map = { diff --git a/src/powderline/easydiff/policy.py b/src/powderline/easydiff/policy.py index 3cf9a6f..c004294 100644 --- a/src/powderline/easydiff/policy.py +++ b/src/powderline/easydiff/policy.py @@ -35,8 +35,8 @@ def _iparm_current(iparm1: dict, key: str, default=0.0): def check_unsupported(recipe: dict) -> list[str]: - from powderline.symmetry import cell_constraints - from powderline.topas.errors import TopasTranslationError + from powderline.exceptions import SymmetryError + from powderline.symmetry import cell_constraints, resolve_space_group warnings: list[str] = [] schema_name = recipe.get("schema_name") @@ -106,8 +106,13 @@ def check_unsupported(recipe: dict) -> list[str]: sg_name = structure.get("space_group") if sg_name: try: + if resolve_space_group(sg_name).ext == "R": + raise EasyDiffractionTranslationError( + f"rhombohedral ':R' setting not supported for {sg_name!r}; " + "use the hexagonal (:H) setting" + ) cell_constraints(sg_name) - except TopasTranslationError as exc: + except SymmetryError as exc: raise EasyDiffractionTranslationError(str(exc)) from exc pz = phase.get("parameterization") or {} diff --git a/src/powderline/exceptions.py b/src/powderline/exceptions.py index 92455c2..c129b7c 100644 --- a/src/powderline/exceptions.py +++ b/src/powderline/exceptions.py @@ -14,6 +14,9 @@ supported ``ENGINE_VERSION_SPEC``. A hard error (A44). - :class:`EngineExecutionError` — the engine ran and failed. - :class:`RecipeValidationError` — a recipe failed validation. +- :class:`SymmetryError` — core symmetry helpers (``powderline.symmetry``) + cannot interpret a space group or site. Gateways convert it to their own + error type (A61). This module must never import an engine (enforced by an import-block test). """ @@ -50,6 +53,16 @@ def from_pydantic(cls, exc, *, schema_name: Optional[str] = None) -> "RecipeVali return err +class SymmetryError(PowderLineError, ValueError): + """A space group or atomic site cannot be interpreted (``powderline.symmetry``). + + A ``ValueError`` so that, raised inside a pydantic validator, it is reported + as a validation error with the field location. Gateways that call the + symmetry helpers outside validation convert it to their own error type + (A56, A61). + """ + + class GatewayNotInstalledError(PowderLineError): """No gateway of this name is registered (the gateway package is absent).""" diff --git a/src/powderline/symmetry.py b/src/powderline/symmetry.py index 09db7e7..fc10510 100644 --- a/src/powderline/symmetry.py +++ b/src/powderline/symmetry.py @@ -1,6 +1,6 @@ -"""gemmi-backed crystallographic rules for the TOPAS writer (plan §5). +"""gemmi-backed crystallographic rules (engine-free core module). -Two pure capabilities, both GSAS-II-free: +Two pure capabilities, both engine-free: * :func:`cell_constraints` -- crystal-system cell equalities and fixed angles, so the writer can share one ``prm`` name across equal cell lengths and emit @@ -11,6 +11,10 @@ Space-group operations come from gemmi; the stabiliser / projector math is our own (~small, spec in plan §5). ``gemmi`` is an approved runtime dependency (D3). + +Errors are :class:`~powderline.exceptions.SymmetryError`; each gateway converts +it to its own error type and applies its engine's own restrictions (e.g. TOPAS +rejects the rhombohedral ``:R`` setting) (A61, A62). """ from __future__ import annotations @@ -20,6 +24,8 @@ import gemmi import numpy as np +from powderline.exceptions import SymmetryError + # Fractional-coordinate tolerances (plan §5). _POS_TOL = 1e-5 # position / orbit equality mod 1 @@ -84,20 +90,6 @@ def classification(self, axis: str) -> str: return self.axes[_AXIS_LETTERS.index(axis)] -def _translation_error(message: str) -> Exception: - """Build the error raised for unsupported symmetry input (A56, interim). - - Returns ``powderline.topas.errors.TopasTranslationError``, the type callers - catch today. Imported here, lazily, because importing ``powderline.topas`` at - module top is circular (topas/__init__ -> writer -> symmetry). This is the - module's only reference to a gateway; re/03 replaces it with a core error - that each gateway translates. - """ - from powderline.topas.errors import TopasTranslationError - - return TopasTranslationError(message) - - # --- space-group resolution ------------------------------------------------- @@ -105,26 +97,22 @@ def resolve_space_group(space_group: str) -> gemmi.SpaceGroup: """Resolve a recipe space-group string to a gemmi ``SpaceGroup``. Tries the symbol verbatim, then whitespace-stripped (gemmi accepts both - ``"P m -3 m"`` and ``"Pm-3m"``). Rhombohedral ``:R`` settings and - unresolvable symbols raise :class:`TopasTranslationError`. Two-origin groups - passed without an explicit ``:1``/``:2`` selector also error rather than - guess an origin (plan §5(6); demo groups are single-origin). + ``"P m -3 m"`` and ``"Pm-3m"``). Unresolvable symbols raise + :class:`SymmetryError`. Two-origin groups passed without an explicit + ``:1``/``:2`` selector also error rather than guess an origin (plan §5(6)). + Both rhombohedral settings (``:H``, ``:R``) are accepted; engines that + cannot handle ``:R`` reject it themselves (A62). """ raw = str(space_group) sg = gemmi.find_spacegroup_by_name(raw) if sg is None: sg = gemmi.find_spacegroup_by_name(raw.replace(" ", "")) if sg is None: - raise _translation_error( + raise SymmetryError( f"unrecognized space-group symbol {space_group!r} (gemmi could not resolve it)" ) - if sg.ext == "R": - raise _translation_error( - f"rhombohedral ':R' setting not supported for {space_group!r}; " - "use the hexagonal (:H) setting" - ) if sg.ext in ("1", "2") and ":" not in raw: - raise _translation_error( + raise SymmetryError( f"space group {space_group!r} has two origin choices; specify one " "explicitly (e.g. append ':2' for the GSAS-II origin-2 convention)" ) @@ -158,7 +146,7 @@ def _monoclinic_unique_axis(ops: list[tuple[np.ndarray, np.ndarray]]) -> str: if abs(evals[i].real - 1.0) < _MAT_TOL and abs(evals[i].imag) < _MAT_TOL: direction = np.abs(evecs[:, i].real) return _LENGTHS[int(np.argmax(direction))] - raise _translation_error( + raise SymmetryError( "could not determine the monoclinic unique axis (no proper 2-fold found)" ) @@ -166,8 +154,9 @@ def _monoclinic_unique_axis(ops: list[tuple[np.ndarray, np.ndarray]]) -> str: def cell_constraints(space_group: str) -> CellRules: """Cell-length equality groups and fixed/free angles for ``space_group``. - See :class:`CellRules`. Rhombohedral ``:R`` and unknown symbols raise - :class:`TopasTranslationError` (via :func:`resolve_space_group`). + See :class:`CellRules`. Unknown symbols raise :class:`SymmetryError` (via + :func:`resolve_space_group`), as does the rhombohedral ``:R`` setting (its + tied angles are not expressible as :class:`CellRules`). """ sg = resolve_space_group(space_group) system = sg.crystal_system_str() @@ -180,8 +169,14 @@ def cell_constraints(space_group: str) -> CellRules: if system == "tetragonal": return CellRules(system, (("a", "b"), ("c",)), all_angles_fixed, ()) if system in ("hexagonal", "trigonal"): - # trigonal reaches here only in the hexagonal (:H) setting -- :R errored - # out in resolve_space_group. Cell is a=b, 90/90/120. + if sg.ext == "R": + # Rhombohedral axes need alpha=beta=gamma tied together, which + # CellRules cannot express; refuse rather than return wrong rules. + raise SymmetryError( + f"cell rules for the rhombohedral ':R' setting are not implemented " + f"({space_group!r}); use the hexagonal (:H) setting" + ) + # Hexagonal axes (incl. the :H setting of rhombohedral groups): a=b, 90/90/120. return CellRules(system, (("a", "b"), ("c",)), all_angles_fixed, ()) if system == "orthorhombic": return CellRules(system, singles, all_angles_fixed, ()) @@ -193,7 +188,7 @@ def cell_constraints(space_group: str) -> CellRules: if system == "triclinic": return CellRules(system, singles, (), _ANGLES) - raise _translation_error( + raise SymmetryError( f"unsupported crystal system {system!r} for space group {space_group!r}" ) @@ -235,7 +230,7 @@ def site_dof(space_group: str, xyz) -> SiteDof: stab_rots = [R for (R, t) in ops if np.all(np.abs(_wrap_symmetric(R @ x + t - x)) < _POS_TOL)] if not stab_rots: # pragma: no cover - identity is always in the group - raise _translation_error("empty stabilizer (should be impossible)") + raise SymmetryError("empty stabilizer (should be impossible)") projector = sum(stab_rots) / len(stab_rots) diff --git a/src/powderline/topas/writer.py b/src/powderline/topas/writer.py index e3e9978..0f9cc10 100644 --- a/src/powderline/topas/writer.py +++ b/src/powderline/topas/writer.py @@ -24,7 +24,8 @@ from . import conversions as cv from .errors import TopasTranslationError -from powderline.symmetry import adp_dof, cell_constraints, site_dof +from powderline.exceptions import SymmetryError +from powderline.symmetry import adp_dof, cell_constraints, resolve_space_group, site_dof SCHEMA_RIETVELD = "GSASII_Rietveld" SCHEMA_SPF = "GSASII_SPF" @@ -708,8 +709,26 @@ def _emit_str(lines, phase_name, phase, payload, ctx, phase_idx=0) -> None: _emit_peak_lists(lines, phase_name) +def _symmetry(fn, space_group, *args): + """Call a core symmetry helper under the TOPAS gateway's rules (A61, A62). + + TOPAS rejects the rhombohedral ``:R`` setting, and core + :class:`~powderline.exceptions.SymmetryError` becomes + :class:`TopasTranslationError`, the type this gateway raises. + """ + try: + if resolve_space_group(space_group).ext == "R": + raise TopasTranslationError( + f"rhombohedral ':R' setting not supported for {space_group!r}; " + "use the hexagonal (:H) setting" + ) + return fn(space_group, *args) + except SymmetryError as exc: + raise TopasTranslationError(str(exc)) from exc + + def _emit_cell(lines, phase_name, pname, structure, param, ctx, phase_idx=0) -> None: - rules = cell_constraints(structure.get("space_group")) + rules = _symmetry(cell_constraints, structure.get("space_group")) ucell = structure.get("unit_cell", {}) pflags = param.get("unit_cell", {}) or {} @@ -832,7 +851,7 @@ def _emit_one_site(lines, phase_name, pname, space_group, xyz, members, atoms, p site_label = cv.sanitize(first) # Multiplicity cross-check: warn (never error) on orbit-size mismatch (plan §5(5)). - dof = site_dof(space_group, xyz) + dof = _symmetry(site_dof, space_group, xyz) for label in members: mult = atoms[label].get("Multiplicity") if mult is not None and int(mult) != dof.orbit_size: @@ -925,7 +944,7 @@ def _uaniso_tokens(pname, label, atom, patom, space_group, xyz, ctx, phase_name, """Emit the six ``u_ij`` for an anisotropic ADP atom (permissive; warns on a refine flag on a symmetry-restricted component but does not enforce it).""" aniso = patom.get("Uaniso") or {} - dof = adp_dof(space_group, xyz) + dof = _symmetry(adp_dof, space_group, xyz) tokens = [] for tkey, rkey in _UANISO_KEYS: entry = aniso.get(rkey) diff --git a/tests/test_easydiff_policy.py b/tests/test_easydiff_policy.py index 50542e6..2c38450 100644 --- a/tests/test_easydiff_policy.py +++ b/tests/test_easydiff_policy.py @@ -192,3 +192,11 @@ def test_unknown_space_group_raises(): r["payload"]["phases"]["LaB6"]["structure"]["space_group"] = "NOT A GROUP" with pytest.raises(EasyDiffractionTranslationError, match="NOT A GROUP"): check_unsupported(r) + + +def test_rhombohedral_R_setting_rejected(): + # A62: the easydiffraction layer rejects :R itself (core accepts it). + r = base_recipe() + r["payload"]["phases"]["LaB6"]["structure"]["space_group"] = "R -3 m :R" + with pytest.raises(EasyDiffractionTranslationError, match="rhombohedral ':R'"): + check_unsupported(r) diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 5ae9aaf..2018344 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -13,12 +13,13 @@ PowderLineError, RecipeValidationError, StructuredWarning, + SymmetryError, ) @pytest.mark.parametrize("cls", [ RecipeValidationError, GatewayNotInstalledError, EngineNotAvailableError, - EngineVersionError, EngineExecutionError, + EngineVersionError, EngineExecutionError, SymmetryError, ]) def test_all_derive_from_powderline_error(cls): assert issubclass(cls, PowderLineError) diff --git a/tests/test_topas_symmetry.py b/tests/test_topas_symmetry.py index 5288a84..71deb03 100644 --- a/tests/test_topas_symmetry.py +++ b/tests/test_topas_symmetry.py @@ -5,7 +5,7 @@ import pytest from powderline import symmetry as sym -from powderline.topas.errors import TopasTranslationError +from powderline.exceptions import PowderLineError, SymmetryError # --- (a) cell rules --------------------------------------------------------- @@ -67,19 +67,36 @@ def test_trigonal_hex_setting_is_hexagonal_cell(): def test_unknown_symbol_errors(): - with pytest.raises(TopasTranslationError, match="unrecognized"): + with pytest.raises(SymmetryError, match="unrecognized"): sym.cell_constraints("NotASpaceGroup") -def test_rhombohedral_R_setting_errors(): - with pytest.raises(TopasTranslationError, match="rhombohedral"): +def test_rhombohedral_R_setting_accepted_by_core(): + # A62: core resolves both rhombohedral settings; engines that cannot handle + # :R (TOPAS, easydiffraction) reject it in their own layer. + assert sym.resolve_space_group("R -3 m :R").ext == "R" + assert sym.site_dof("R -3 m :R", (0.0, 0.0, 0.0)).orbit_size == 1 + assert sym.site_dof("R -3 m :H", (0.0, 0.0, 0.0)).orbit_size == 3 + + +def test_rhombohedral_R_cell_rules_not_implemented(): + # alpha=beta=gamma ties are not expressible as CellRules: refuse, don't guess. + with pytest.raises(SymmetryError, match="not implemented"): sym.cell_constraints("R -3 m :R") - with pytest.raises(TopasTranslationError, match="rhombohedral"): - sym.site_dof("R -3 m :R", (0.0, 0.0, 0.0)) + + +def test_symmetry_error_is_a_core_value_error(): + # A61: a ValueError (pydantic reports it with the field location inside a + # validator) and a PowderLineError; no gateway error type involved. + with pytest.raises(SymmetryError) as info: + sym.resolve_space_group("NotASpaceGroup") + assert isinstance(info.value, ValueError) + assert isinstance(info.value, PowderLineError) + assert type(info.value).__module__ == "powderline.exceptions" def test_two_origin_without_selector_errors(): - with pytest.raises(TopasTranslationError, match="two origin"): + with pytest.raises(SymmetryError, match="two origin"): sym.cell_constraints("F d -3 m") # explicit origin is accepted assert sym.cell_constraints("F d -3 m:2").crystal_system == "cubic" @@ -180,23 +197,23 @@ def crystal_system_str(self): return "not-a-system" -def test_unsupported_crystal_system_raises_translation_error(monkeypatch): +def test_unsupported_crystal_system_raises_symmetry_error(monkeypatch): monkeypatch.setattr(sym, "resolve_space_group", lambda _sg: _UnknownSystem()) - with pytest.raises(TopasTranslationError, match="unsupported crystal system"): + with pytest.raises(SymmetryError, match="unsupported crystal system"): sym.cell_constraints("P1") -def test_empty_stabilizer_raises_translation_error(monkeypatch): +def test_empty_stabilizer_raises_symmetry_error(monkeypatch): import numpy as np # A single translation-only op fixes no point, so the stabiliser is empty. monkeypatch.setattr(sym, "_expanded_ops", lambda _sg: [(np.eye(3), np.full(3, 0.5))]) - with pytest.raises(TopasTranslationError, match="empty stabilizer"): + with pytest.raises(SymmetryError, match="empty stabilizer"): sym.site_dof("P1", [0.1, 0.2, 0.3]) -def test_monoclinic_unique_axis_failure_raises_translation_error(): +def test_monoclinic_unique_axis_failure_raises_symmetry_error(): import numpy as np - with pytest.raises(TopasTranslationError, match="monoclinic unique axis"): + with pytest.raises(SymmetryError, match="monoclinic unique axis"): sym._monoclinic_unique_axis([(np.eye(3), np.zeros(3))]) diff --git a/tests/test_topas_writer.py b/tests/test_topas_writer.py index 5e84930..bc9a978 100644 --- a/tests/test_topas_writer.py +++ b/tests/test_topas_writer.py @@ -280,6 +280,22 @@ def test_rhombohedral_R_setting_rejected(): render_topas(recipe, "x") +@pytest.mark.parametrize("space_group, match", [ + ("NotASpaceGroup", "unrecognized"), + ("F d -3 m", "two origin"), +]) +def test_core_symmetry_error_becomes_translation_error(space_group, match): + # A61: core raises SymmetryError; the TOPAS gateway raises its own type, + # chaining the core error. + from powderline.exceptions import SymmetryError + + recipe = _recipe("example_LaB6") + recipe["payload"]["phases"]["LaB6"]["structure"]["space_group"] = space_group + with pytest.raises(TopasTranslationError, match=match) as info: + render_topas(recipe, "x") + assert isinstance(info.value.__cause__, SymmetryError) + + def test_template_skeleton_rejected_cleanly(): # The fill-in-the-blanks example_template (null instrument.parameterization, # empty tth) must fail with a clear TopasTranslationError, not a raw crash. From d7489039a6d36a24342dfe4043307eb2f069f99c Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:50:13 -0400 Subject: [PATCH 019/259] feat(core): schema_core: core schema 1.0.0 models (unused by the runtime until re/04) - Parameter models (A20, A32, A71, A72): RefinableParameter [value, flag] and BoundedRefinableParameter [value, flag, min, max]. A 4-list where bounds are unsupported is an error naming the field. The Structure* variants allow value null (start from the phase structure's value). Strict boolean flags; list-only JSON shape; the JSON Schema describes the arrays. - XRDData: the 0.26.0 validators ported verbatim; unit metadata (A19). - FitRange [min, max]: max > min, finite; check_fit_range_within_data for engine payloads (A68). ChebyshevBackground ported, strict flag. - CoreRecipe frame: schema_name ".", core/engine schema versions (core checked against SUPPORTED_CORE_SCHEMAS, A40), metadata JSON-serializable and capped at METADATA_MAX_BYTES = 1 MiB (A64). - check_element_symbol: a bare symbol spelled exactly as in gemmi's table; charged types rejected, never stripped (A63). - extra='forbid' everywhere (A21). Co-Authored-By: Claude Opus 5.5 --- src/powderline/schema_core.py | 514 +++++++++++++++++++ tests/test_schema_core.py | 903 ++++++++++++++++++++++++++++++++++ 2 files changed, 1417 insertions(+) create mode 100644 src/powderline/schema_core.py create mode 100644 tests/test_schema_core.py diff --git a/src/powderline/schema_core.py b/src/powderline/schema_core.py new file mode 100644 index 0000000..567d3cf --- /dev/null +++ b/src/powderline/schema_core.py @@ -0,0 +1,514 @@ +"""Core recipe schema (core schema 1.0.0): the models every engine schema shares. + +Engine-free and pure pydantic. Engine schemas (``gsasii.*``, ``topas.*``, +``easydiffraction.*``; re/04-06) build their payloads from these models; nothing +at runtime routes through this module until then (re/03). + +Conventions (master plan A19-A21, A32): + +- every model is ``extra='forbid'``; +- units are fixed per field in the schema (``json_schema_extra={"unit": ...}``), + never carried by a recipe; +- a refinable quantity is a :class:`RefinableParameter` (JSON + ``[value, refine_flag]``) or, where the engine honors bounds, a + :class:`BoundedRefinableParameter` (JSON ``[value, refine_flag, min, max]``); +- plain (non-refinable) values get field-specific validation. + +This module must never import an engine (enforced by an import-block test). +""" + +from __future__ import annotations + +import json +import math +from typing import Any, Optional + +import gemmi +import numpy as np +from packaging.specifiers import SpecifierSet +from packaging.version import InvalidVersion, Version +from pydantic import ( + BaseModel, + ConfigDict, + Field, + StrictBool, + field_validator, + model_serializer, + model_validator, +) + +# --- versions (A40, A65) --------------------------------------------------- + +#: The core schema version new recipes are written against. +CORE_SCHEMA_VERSION = "1.0.0" +#: Core schema versions this PowderLine accepts (PEP 440 specifier). Widened +#: explicitly when a new core version is compatible; never inferred (A40). +SUPPORTED_CORE_SCHEMAS = "==1.0.0" + +#: Size cap on the serialized ``metadata`` block, in bytes of UTF-8 JSON (A64). +#: A sanity limit against accidents (e.g. a pasted pattern); amend here and in +#: docs/SCHEMA_HISTORY.md. +METADATA_MAX_BYTES = 1024 * 1024 + +#: ``schema_name`` format: ``"."`` (A1, A18). +SCHEMA_NAME_PATTERN = r"^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$" + + +def parse_version(field: str, value: str) -> Version: + """Parse a PEP 440 version string, raising ``ValueError`` naming ``field``.""" + try: + return Version(value) + except InvalidVersion: + raise ValueError(f"{field} {value!r} is not a valid version (PEP 440, e.g. '1.0.0')") from None + + +def check_core_schema_version(version: str) -> None: + """Raise ``ValueError`` unless ``version`` is in :data:`SUPPORTED_CORE_SCHEMAS`.""" + if parse_version("core_schema_version", version) not in SpecifierSet(SUPPORTED_CORE_SCHEMAS): + from powderline import __version__ + + raise ValueError( + f"core_schema_version {version!r} is not supported by PowderLine {__version__} " + f"(accepted: {SUPPORTED_CORE_SCHEMAS}; current: {CORE_SCHEMA_VERSION})" + ) + + +# --- units (A19) ------------------------------------------------------------ + +#: Unit strings used in ``json_schema_extra={"unit": ...}``. +UNIT_DEG_2THETA = "degree 2theta" +UNIT_DEGREE = "degree" +UNIT_ANGSTROM = "angstrom" +UNIT_ANGSTROM2 = "angstrom^2" +UNIT_ARBITRARY = "arbitrary" +UNIT_INV_INTENSITY2 = "1/intensity^2" + + +def _unit(unit: str) -> dict: + return {"unit": unit} + + +def _array_schema(title: str, items: list[dict], description: str, **extra) -> dict: + """JSON Schema for a model whose recipe JSON shape is a fixed-length list.""" + return {"title": title, "description": description, "type": "array", + "prefixItems": items, "minItems": len(items), "maxItems": len(items), **extra} + + +_NUMBER = {"type": "number"} +_NUMBER_OR_NULL = {"anyOf": [{"type": "number"}, {"type": "null"}]} +_BOOLEAN = {"type": "boolean"} + + +_STRICT = ConfigDict(extra="forbid") + + +# --- parameter models (A20, A32, A71) --------------------------------------- + + +def _finite(name: str, v: Optional[float]) -> Optional[float]: + if v is not None and not math.isfinite(v): + raise ValueError(f"{name} must be finite, got {v!r}") + return v + + +class RefinableParameter(BaseModel): + """A refinable value with no bounds concept: JSON ``[value, refine_flag]``. + + Used where the engine has no native bounds for the quantity. A 4-element + list here is an error, never silently truncated (A20). ``value`` is + required; see :class:`StructureRefinableParameter` for the quantities whose + starting value may come from the phase structure. + """ + + model_config = _STRICT + + value: float + refine_flag: StrictBool + + @model_validator(mode="before") + @classmethod + def _from_list(cls, data: Any) -> Any: + if isinstance(data, (list, tuple)): + if len(data) == 4: + raise ValueError( + "bounds are not supported for this parameter in this engine schema: " + "expected [value, refine_flag], got a 4-element " + "[value, refine_flag, min, max] list" + ) + if len(data) != 2: + raise ValueError( + f"expected [value, refine_flag], got a {len(data)}-element list" + ) + return {"value": data[0], "refine_flag": data[1]} + raise ValueError( + f"expected a [value, refine_flag] list, got {type(data).__name__}" + ) + + @field_validator("value") + @classmethod + def _value_finite(cls, v): + return _finite("value", v) + + @model_serializer + def _to_list(self) -> list: + return [self.value, self.refine_flag] + + @classmethod + def __get_pydantic_json_schema__(cls, core_schema, handler) -> dict: + nullable = cls.model_fields["value"].annotation is not float + return _array_schema(cls.__name__, [_NUMBER_OR_NULL if nullable else _NUMBER, _BOOLEAN], + "[value, refine_flag]" + (_NULL_VALUE_NOTE if nullable else "")) + + +class BoundedRefinableParameter(BaseModel): + """A refinable value with optional bounds: JSON ``[value, refine_flag, min, max]``. + + ``min``/``max`` may each be ``null`` (unbounded on that side). When given, + ``min <= max`` and ``min <= value <= max``. Used only where the engine + honors the bounds natively (A20, A33). ``value`` is required; see + :class:`StructureBoundedRefinableParameter`. + """ + + model_config = _STRICT + + value: float + refine_flag: StrictBool + min: Optional[float] = None + max: Optional[float] = None + + @model_validator(mode="before") + @classmethod + def _from_list(cls, data: Any) -> Any: + if isinstance(data, (list, tuple)): + if len(data) != 4: + raise ValueError( + "expected [value, refine_flag, min, max] (min/max may be null), " + f"got a {len(data)}-element list" + ) + return {"value": data[0], "refine_flag": data[1], "min": data[2], "max": data[3]} + raise ValueError( + f"expected a [value, refine_flag, min, max] list, got {type(data).__name__}" + ) + + @field_validator("value", "min", "max") + @classmethod + def _finite(cls, v, info): + return _finite(info.field_name, v) + + @model_validator(mode="after") + def _bounds(self) -> "BoundedRefinableParameter": + lo, hi = self.min, self.max + if lo is not None and hi is not None and lo > hi: + raise ValueError(f"min ({lo}) must be <= max ({hi})") + if self.value is not None: + check_within_bounds(self.value, self, "value") + return self + + @model_serializer + def _to_list(self) -> list: + return [self.value, self.refine_flag, self.min, self.max] + + @classmethod + def __get_pydantic_json_schema__(cls, core_schema, handler) -> dict: + nullable = cls.model_fields["value"].annotation is not float + return _array_schema(cls.__name__, + [_NUMBER_OR_NULL if nullable else _NUMBER, _BOOLEAN, + _NUMBER_OR_NULL, _NUMBER_OR_NULL], + "[value, refine_flag, min, max]; min/max may be null" + + (_NULL_VALUE_NOTE if nullable else "")) + + +_NULL_VALUE_NOTE = "; value null = start from the phase structure's value" + + +class StructureRefinableParameter(RefinableParameter): + """:class:`RefinableParameter` for a quantity that mirrors a phase-structure value. + + For cell lengths/angles and atom x/y/z, occupancy, Uiso/Uaniso only (A71): + ``value`` may be ``null``, meaning "start from the structure's value" + (today's behavior: the GSAS-II setters skip a null value). + """ + + value: Optional[float] + + +class StructureBoundedRefinableParameter(BoundedRefinableParameter): + """:class:`BoundedRefinableParameter` for a quantity that mirrors a phase-structure value. + + ``value`` may be ``null`` (start from the structure's value, A71); the + bounds are then checked against that value by the phase-level validator + (:func:`check_within_bounds`). + """ + + value: Optional[float] + + +def check_within_bounds(value: float, param: BoundedRefinableParameter, field: str) -> None: + """Raise ``ValueError`` unless ``param.min <= value <= param.max`` (open ends pass). + + Also used at the phase level for a null-valued + :class:`StructureBoundedRefinableParameter`, with the structure's value. + """ + if param.min is not None and value < param.min: + raise ValueError(f"{field} ({value}) is below min ({param.min})") + if param.max is not None and value > param.max: + raise ValueError(f"{field} ({value}) is above max ({param.max})") + + +# --- plain-value checks (A32) ---------------------------------------------- + + +def check_element_symbol(symbol: str) -> str: + """Return ``symbol`` if it is a bare element symbol in gemmi's table, exactly spelled. + + Raises ``ValueError`` otherwise. gemmi's own lookup is too lenient to use + alone: it accepts any case (``"FE"``), reduces charged types to the neutral + atom (``"Fe3+"`` -> Fe, which would change the X-ray scattering), and maps + unknown symbols to ``X``. Charged scattering types are not supported in core + schema 1.0.0 yet (A63 obligation); they are rejected, never stripped. + """ + element = gemmi.Element(symbol) + if element.atomic_number > 0 and element.name == symbol: + return symbol + if any(c in symbol for c in "+-") or (symbol[-1:].isdigit()): + raise ValueError( + f"element {symbol!r}: charged scattering types are not supported in core schema " + f"{CORE_SCHEMA_VERSION} yet; give the bare element symbol" + ) + if element.atomic_number > 0: + raise ValueError(f"element {symbol!r}: write the element symbol as {element.name!r}") + raise ValueError(f"element {symbol!r} is not a known element symbol") + + +# --- diffraction data ------------------------------------------------------- + + +class XRDData(BaseModel): + """Measured pattern: 2theta, intensity, weights (ported from schema 0.26 ``XRDDataModel``). + + Every engine consumes ``tth`` in degrees 2theta and ``Itth_weights`` as + 1/sigma^2, as-is. + """ + + model_config = _STRICT + + tth: list[float] = Field(description="Two-theta values", json_schema_extra=_unit(UNIT_DEG_2THETA)) + Itth: list[float] = Field(description="Intensity values", json_schema_extra=_unit(UNIT_ARBITRARY)) + Itth_weights: list[float] = Field(description="Intensity weights (1/sigma^2)", + json_schema_extra=_unit(UNIT_INV_INTENSITY2)) + filename: str | None = Field(default=None, description="Original filename for reference") + + @model_validator(mode='after') + def validate_all_arrays_same_length(self): + """Ensure tth, Itth, and Itth_weights have the same length.""" + lengths = [len(self.tth), len(self.Itth), len(self.Itth_weights)] + if len(set(lengths)) > 1: + raise ValueError( + f"XRD data arrays must have the same length. " + f"Got tth={len(self.tth)}, Itth={len(self.Itth)}, Itth_weights={len(self.Itth_weights)}" + ) + return self + + @model_validator(mode='after') + def validate_arrays_wellformed(self): + """Reject ill-formed XRD data. PowderLine never repairs data — it rejects it. + + Transforming raw data (unit conversion, weight derivation, handling + background-subtracted negatives) is the job of the reader/parser that builds + this block, not PowderLine. Here we only enforce that what arrives is usable: + + * arrays must be non-empty; + * every tth / Itth / Itth_weights value must be finite (no NaN or inf) — + this catches, e.g., a weight computed as 1/esd**2 with esd == 0 (inf); + * tth must be strictly increasing (a powder pattern is monotonic in 2-theta); + * weights must be >= 0 (a 0 weight legitimately excludes a point; a negative + weight is nonsensical) and at least one weight must be > 0 (all-zero = + nothing to fit). + + A negative *intensity* is explicitly allowed: background-subtracted data + legitimately dips below zero, so Itth is checked for finiteness only, not sign. + """ + if len(self.tth) == 0: + raise ValueError( + "XRD data arrays must be non-empty (tth/Itth/Itth_weights have length 0)." + ) + + tth = np.asarray(self.tth, dtype=float) + Itth = np.asarray(self.Itth, dtype=float) + weights = np.asarray(self.Itth_weights, dtype=float) + + # All values finite (rejects NaN and +/-inf across all three arrays). + for name, arr in (("tth", tth), ("Itth", Itth), ("Itth_weights", weights)): + bad = np.where(~np.isfinite(arr))[0] + if bad.size: + i = int(bad[0]) + raise ValueError( + f"XRD data '{name}' contains non-finite values (NaN/inf); first at " + f"index {i} (value {float(arr[i])!r}). Fix the data upstream — " + "PowderLine does not repair xrd_data." + ) + + # tth must be strictly increasing. + bad = np.where(np.diff(tth) <= 0)[0] + if bad.size: + i = int(bad[0]) + raise ValueError( + f"XRD 'tth' must be strictly increasing; tth[{i + 1}]={float(tth[i + 1])!r} " + f"<= tth[{i}]={float(tth[i])!r}. Sort/deduplicate the pattern upstream." + ) + + # Weights: non-negative, with at least one strictly positive. + bad = np.where(weights < 0)[0] + if bad.size: + i = int(bad[0]) + raise ValueError( + f"XRD 'Itth_weights' must be >= 0; first negative at index {i} " + f"(value {float(weights[i])!r}). A 0 weight excludes a point; " + "negative weights are invalid." + ) + if not np.any(weights > 0): + raise ValueError( + "XRD 'Itth_weights' are all zero — nothing to fit. At least one " + "weight must be > 0." + ) + + return self + + +class FitRange(BaseModel): + """Fit window in 2theta: JSON ``[min, max]``; either end may be ``null`` (open).""" + + model_config = _STRICT + + min: Optional[float] = None + max: Optional[float] = None + + @model_validator(mode="before") + @classmethod + def _from_list(cls, data: Any) -> Any: + if isinstance(data, (list, tuple)): + if len(data) != 2: + raise ValueError( + f"fit_range must be a list of exactly 2 elements [min, max], got {len(data)}" + ) + return {"min": data[0], "max": data[1]} + raise ValueError(f"fit_range must be a [min, max] list, got {type(data).__name__}") + + @field_validator("min", "max") + @classmethod + def _finite(cls, v, info): + return _finite(info.field_name, v) + + @model_validator(mode="after") + def _ordered(self) -> "FitRange": + if self.min is not None and self.max is not None and not self.max > self.min: + raise ValueError(f"fit_range max ({self.max}) must be greater than min ({self.min})") + return self + + @model_serializer + def _to_list(self) -> list: + return [self.min, self.max] + + @classmethod + def __get_pydantic_json_schema__(cls, core_schema, handler) -> dict: + return _array_schema("FitRange", [_NUMBER_OR_NULL, _NUMBER_OR_NULL], + "[min, max]; either end may be null (open)", + unit=UNIT_DEG_2THETA) + + +def check_fit_range_within_data(fit_range: Optional[FitRange], xrd_data: XRDData) -> None: + """Raise ``ValueError`` unless both ``fit_range`` ends lie within the data's 2theta span. + + A payload-level check (it needs the pattern): engine payload models call it + from a model validator (A68). ``None`` (or an open end) means "the data limit". + """ + if fit_range is None: + return + lo, hi = xrd_data.tth[0], xrd_data.tth[-1] + for name, end in (("min", fit_range.min), ("max", fit_range.max)): + if end is not None and not lo <= end <= hi: + raise ValueError( + f"fit_range {name} ({end}) is outside the data's 2theta range [{lo}, {hi}]" + ) + + +# --- background ------------------------------------------------------------- + + +class ChebyshevBackground(BaseModel): + """Chebyshev polynomial background (ported from schema 0.26). + + Coefficient semantics (scaling, which polynomial basis) are engine-specific + and documented in each engine schema (A22.7), not here. + """ + + model_config = _STRICT + + num_coefficients: int = Field(gt=0, description="Number of Chebyshev coefficients") + coefficients: list[float] = Field(description="Coefficient values") + refine_flag: StrictBool = Field(description="Whether to refine background") + + @field_validator('coefficients') + @classmethod + def validate_coefficients_length(cls, v, info): + """Ensure number of coefficients matches num_coefficients.""" + num_coef = info.data.get('num_coefficients') + if num_coef is not None and len(v) != num_coef: + raise ValueError(f"Number of coefficients ({len(v)}) must match num_coefficients ({num_coef})") + return v + + +# --- top-level recipe frame (A1, A18, A21, A40) ------------------------------ + + +def _check_metadata(v: Optional[dict]) -> Optional[dict]: + if v is None: + return v + try: + text = json.dumps(v, allow_nan=False, ensure_ascii=False) + except (TypeError, ValueError) as exc: + raise ValueError(f"metadata must be JSON-serializable: {exc}") from None + size = len(text.encode("utf-8")) + if size > METADATA_MAX_BYTES: + raise ValueError( + f"metadata is {size} bytes as JSON; the limit is {METADATA_MAX_BYTES} " + "(schema_core.METADATA_MAX_BYTES)" + ) + return v + + +class CoreRecipe(BaseModel): + """The core-owned top level of every recipe; engine schemas subclass it. + + An engine schema narrows ``schema_name`` to its own names, types ``payload``, + and checks ``engine_schema_version`` against its declarations + (:mod:`powderline.compat`). ``metadata`` is never interpreted: it is checked + for JSON-serializability and size, and echoed into results (A21, A64). + """ + + model_config = _STRICT + + schema_name: str = Field(pattern=SCHEMA_NAME_PATTERN, + description='Engine and workflow, e.g. "gsasii.rietveld"') + core_schema_version: str = Field(description="Core schema version the recipe is written against") + engine_schema_version: str = Field(description="Engine schema version the recipe is written against") + metadata: Optional[dict[str, Any]] = Field( + default=None, description="Free-form, JSON-serializable; echoed into results") + payload: Any = Field(description="Engine-specific; typed by the engine schema") + + @field_validator("core_schema_version") + @classmethod + def _core_version(cls, v: str) -> str: + check_core_schema_version(v) + return v + + @field_validator("engine_schema_version") + @classmethod + def _engine_version(cls, v: str) -> str: + parse_version("engine_schema_version", v) + return v + + @field_validator("metadata") + @classmethod + def _metadata(cls, v): + return _check_metadata(v) diff --git a/tests/test_schema_core.py b/tests/test_schema_core.py new file mode 100644 index 0000000..dfec521 --- /dev/null +++ b/tests/test_schema_core.py @@ -0,0 +1,903 @@ +"""Direct tests for powderline.schema_core validators. + +Pure pydantic, engine-free. Tests the core schema 1.0.0 models that every +engine schema shares (re/03). +""" +import json + +import pytest +from pydantic import ValidationError + +from powderline.schema_core import ( + CORE_SCHEMA_VERSION, + METADATA_MAX_BYTES, + SUPPORTED_CORE_SCHEMAS, + UNIT_DEG_2THETA, + ChebyshevBackground, + CoreRecipe, + FitRange, + XRDData, + check_core_schema_version, + check_fit_range_within_data, +) + + +# --- XRDData ---------------------------------------------------------------- + + +def test_xrd_arrays_same_length_mismatch_raises(): + with pytest.raises(ValidationError, match="same length"): + XRDData(tth=[1.0, 2.0, 3.0], Itth=[10.0, 20.0], Itth_weights=[1.0, 1.0]) + + +def test_xrd_arrays_same_length_ok(): + m = XRDData(tth=[1.0, 2.0], Itth=[10.0, 20.0], Itth_weights=[1.0, 1.0]) + assert len(m.tth) == 2 + + +def test_xrd_empty_arrays_raise(): + with pytest.raises(ValidationError, match="non-empty"): + XRDData(tth=[], Itth=[], Itth_weights=[]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_xrd_non_finite_tth_raises(bad): + with pytest.raises(ValidationError, match="non-finite"): + XRDData(tth=[1.0, bad, 3.0], Itth=[10.0, 20.0, 30.0], Itth_weights=[1.0, 1.0, 1.0]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_xrd_non_finite_intensity_raises(bad): + with pytest.raises(ValidationError, match="non-finite"): + XRDData(tth=[1.0, 2.0], Itth=[10.0, bad], Itth_weights=[1.0, 1.0]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_xrd_non_finite_weight_raises(bad): + with pytest.raises(ValidationError, match="non-finite"): + XRDData(tth=[1.0, 2.0], Itth=[10.0, 20.0], Itth_weights=[1.0, bad]) + + +@pytest.mark.parametrize( + "tth", + [ + [1.0, 1.0, 2.0], # equal neighbors -> not strictly increasing + [1.0, 3.0, 2.0], # out of order + [3.0, 2.0, 1.0], # descending + ], +) +def test_xrd_non_monotonic_tth_raises(tth): + with pytest.raises(ValidationError, match="strictly increasing"): + XRDData(tth=tth, Itth=[10.0, 20.0, 30.0], Itth_weights=[1.0, 1.0, 1.0]) + + +def test_xrd_negative_weight_raises(): + with pytest.raises(ValidationError, match=">= 0"): + XRDData(tth=[1.0, 2.0], Itth=[10.0, 20.0], Itth_weights=[1.0, -0.5]) + + +def test_xrd_all_zero_weights_raise(): + with pytest.raises(ValidationError, match="all zero"): + XRDData(tth=[1.0, 2.0], Itth=[10.0, 20.0], Itth_weights=[0.0, 0.0]) + + +def test_xrd_negative_intensity_ok(): + # Background-subtracted data legitimately dips below zero. + m = XRDData(tth=[1.0, 2.0, 3.0], Itth=[-5.0, 20.0, -1.0], Itth_weights=[1.0, 1.0, 1.0]) + assert m.Itth[0] == -5.0 + + +def test_xrd_extra_key_rejected(): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + XRDData(tth=[1.0, 2.0], Itth=[10.0, 20.0], Itth_weights=[1.0, 1.0], unknown_field="foo") + + +def test_xrd_unit_metadata(): + schema = XRDData.model_json_schema() + assert schema["properties"]["tth"]["unit"] == UNIT_DEG_2THETA + + +# --- FitRange --------------------------------------------------------------- + + +def test_fit_range_roundtrip_model_dump(): + fr = FitRange.model_validate([5.0, 40.0]) + assert fr.model_dump() == [5.0, 40.0] + + +def test_fit_range_roundtrip_model_dump_json(): + fr = FitRange.model_validate([5.0, 40.0]) + assert json.loads(fr.model_dump_json()) == [5.0, 40.0] + + +def test_fit_range_null_ends_allowed(): + fr = FitRange.model_validate([None, None]) + assert fr.model_dump() == [None, None] + + +def test_fit_range_one_null_end_ok(): + fr1 = FitRange.model_validate([5.0, None]) + assert fr1.model_dump() == [5.0, None] + fr2 = FitRange.model_validate([None, 40.0]) + assert fr2.model_dump() == [None, 40.0] + + +def test_fit_range_wrong_length_rejected(): + with pytest.raises(ValidationError, match="exactly 2 elements"): + FitRange.model_validate([5.0, 10.0, 15.0]) + + +def test_fit_range_non_list_rejected(): + with pytest.raises(ValidationError, match="must be a \\[min, max\\] list"): + FitRange.model_validate({"min": 5.0, "max": 10.0}) + + +def test_fit_range_max_equals_min_rejected(): + with pytest.raises(ValidationError, match="must be greater than"): + FitRange.model_validate([10.0, 10.0]) + + +def test_fit_range_max_less_than_min_rejected(): + with pytest.raises(ValidationError, match="must be greater than"): + FitRange.model_validate([20.0, 10.0]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_fit_range_non_finite_min_rejected(bad): + with pytest.raises(ValidationError, match="must be finite"): + FitRange.model_validate([bad, 40.0]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_fit_range_non_finite_max_rejected(bad): + with pytest.raises(ValidationError, match="must be finite"): + FitRange.model_validate([5.0, bad]) + + +def test_fit_range_json_schema(): + schema = FitRange.model_json_schema() + assert schema["type"] == "array" + assert schema["prefixItems"] == [{"anyOf": [{"type": "number"}, {"type": "null"}]}, + {"anyOf": [{"type": "number"}, {"type": "null"}]}] + assert len(schema["prefixItems"]) == 2 + assert schema["unit"] == UNIT_DEG_2THETA + + +# --- check_fit_range_within_data -------------------------------------------- + + +def test_check_fit_range_within_data_none_passes(): + data = XRDData(tth=[10.0, 20.0, 30.0], Itth=[100.0, 200.0, 150.0], Itth_weights=[1.0, 1.0, 1.0]) + check_fit_range_within_data(None, data) # no error + + +def test_check_fit_range_within_data_inside_passes(): + data = XRDData(tth=[10.0, 20.0, 30.0], Itth=[100.0, 200.0, 150.0], Itth_weights=[1.0, 1.0, 1.0]) + fr = FitRange.model_validate([15.0, 25.0]) + check_fit_range_within_data(fr, data) # no error + + +def test_check_fit_range_within_data_exactly_at_limits_passes(): + data = XRDData(tth=[10.0, 20.0, 30.0], Itth=[100.0, 200.0, 150.0], Itth_weights=[1.0, 1.0, 1.0]) + fr = FitRange.model_validate([10.0, 30.0]) + check_fit_range_within_data(fr, data) # no error + + +def test_check_fit_range_within_data_below_min_raises(): + data = XRDData(tth=[10.0, 20.0, 30.0], Itth=[100.0, 200.0, 150.0], Itth_weights=[1.0, 1.0, 1.0]) + fr = FitRange.model_validate([5.0, 25.0]) + with pytest.raises(ValueError, match="min"): + check_fit_range_within_data(fr, data) + + +def test_check_fit_range_within_data_above_max_raises(): + data = XRDData(tth=[10.0, 20.0, 30.0], Itth=[100.0, 200.0, 150.0], Itth_weights=[1.0, 1.0, 1.0]) + fr = FitRange.model_validate([15.0, 35.0]) + with pytest.raises(ValueError, match="max"): + check_fit_range_within_data(fr, data) + + +def test_check_fit_range_within_data_open_ends_pass(): + data = XRDData(tth=[10.0, 20.0, 30.0], Itth=[100.0, 200.0, 150.0], Itth_weights=[1.0, 1.0, 1.0]) + fr1 = FitRange.model_validate([None, 25.0]) + check_fit_range_within_data(fr1, data) # no error + fr2 = FitRange.model_validate([15.0, None]) + check_fit_range_within_data(fr2, data) # no error + fr3 = FitRange.model_validate([None, None]) + check_fit_range_within_data(fr3, data) # no error + + +# --- ChebyshevBackground ---------------------------------------------------- + + +def test_chebyshev_coefficient_count_mismatch_rejected(): + with pytest.raises(ValidationError, match="must match num_coefficients"): + ChebyshevBackground(num_coefficients=3, coefficients=[1.0, 2.0], refine_flag=False) + + +def test_chebyshev_coefficient_count_match_ok(): + m = ChebyshevBackground(num_coefficients=3, coefficients=[1.0, 2.0, 3.0], refine_flag=False) + assert len(m.coefficients) == 3 + + +def test_chebyshev_num_coefficients_must_be_positive(): + with pytest.raises(ValidationError, match="greater than 0"): + ChebyshevBackground(num_coefficients=0, coefficients=[], refine_flag=False) + + +def test_chebyshev_refine_flag_null_rejected(): + with pytest.raises(ValidationError): + ChebyshevBackground(num_coefficients=1, coefficients=[1.0], refine_flag=None) + + +def test_chebyshev_refine_flag_string_rejected(): + with pytest.raises(ValidationError): + ChebyshevBackground(num_coefficients=1, coefficients=[1.0], refine_flag="true") + + +def test_chebyshev_refine_flag_int_rejected(): + with pytest.raises(ValidationError): + ChebyshevBackground(num_coefficients=1, coefficients=[1.0], refine_flag=1) + + +def test_chebyshev_extra_key_rejected(): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + ChebyshevBackground(num_coefficients=1, coefficients=[1.0], refine_flag=False, unknown="bar") + + +# --- CoreRecipe ------------------------------------------------------------- + + +def test_core_recipe_minimal_valid(): + r = CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + payload={} + ) + assert r.schema_name == "gsasii.rietveld" + + +@pytest.mark.parametrize( + "bad_name", + [ + "GSASII_Rietveld", # uppercase + "gsasii", # missing workflow + "Gsasii.rietveld", # uppercase first letter + "gsasii.rietveld.x", # too many dots + "gsasii.Rietveld", # uppercase in workflow + "1gsasii.rietveld", # starts with digit + ], +) +def test_core_recipe_schema_name_pattern_rejected(bad_name): + with pytest.raises(ValidationError, match="String should match pattern"): + CoreRecipe( + schema_name=bad_name, + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + payload={} + ) + + +def test_core_recipe_schema_name_pattern_ok(): + r = CoreRecipe( + schema_name="topas.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + payload={} + ) + assert r.schema_name == "topas.rietveld" + + +def test_core_recipe_core_schema_version_1_1_0_rejected(): + with pytest.raises(ValidationError) as exc_info: + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.1.0", + engine_schema_version="1.0.0", + payload={} + ) + err_msg = str(exc_info.value) + assert SUPPORTED_CORE_SCHEMAS in err_msg + assert "PowderLine" in err_msg + + +def test_core_recipe_core_schema_version_2_0_0_rejected(): + with pytest.raises(ValidationError) as exc_info: + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="2.0.0", + engine_schema_version="1.0.0", + payload={} + ) + err_msg = str(exc_info.value) + assert SUPPORTED_CORE_SCHEMAS in err_msg + assert "PowderLine" in err_msg + + +def test_core_recipe_core_schema_version_invalid_string_rejected(): + with pytest.raises(ValidationError, match="not a valid version"): + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="abc", + engine_schema_version="1.0.0", + payload={} + ) + + +def test_core_recipe_engine_schema_version_invalid_string_rejected(): + with pytest.raises(ValidationError, match="not a valid version"): + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="abc", + payload={} + ) + + +def test_core_recipe_metadata_none_ok(): + r = CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + metadata=None, + payload={} + ) + assert r.metadata is None + + +def test_core_recipe_metadata_nested_json_ok(): + r = CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + metadata={"user": "test", "nested": {"key": "value"}}, + payload={} + ) + assert r.metadata["nested"]["key"] == "value" + + +def test_core_recipe_metadata_non_serializable_set_rejected(): + with pytest.raises(ValidationError, match="JSON-serializable"): + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + metadata={"bad": {1, 2, 3}}, + payload={} + ) + + +def test_core_recipe_metadata_non_serializable_object_rejected(): + with pytest.raises(ValidationError, match="JSON-serializable"): + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + metadata={"bad": object()}, + payload={} + ) + + +def test_core_recipe_metadata_nan_rejected(): + with pytest.raises(ValidationError, match="JSON-serializable"): + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + metadata={"bad": float("nan")}, + payload={} + ) + + +def test_core_recipe_metadata_over_size_rejected(): + # Build a string just over METADATA_MAX_BYTES. + # JSON encoding of {"data": "x" * N} is roughly {"data":"xxx..."}. + # Start with a string that's definitely over the limit. + big_string = "x" * (METADATA_MAX_BYTES + 100) + metadata = {"data": big_string} + # Verify it's over the limit + size = len(json.dumps(metadata, allow_nan=False, ensure_ascii=False).encode("utf-8")) + assert size > METADATA_MAX_BYTES + + with pytest.raises(ValidationError) as exc_info: + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + metadata=metadata, + payload={} + ) + err_msg = str(exc_info.value) + assert "METADATA_MAX_BYTES" in err_msg or str(METADATA_MAX_BYTES) in err_msg + + +def test_core_recipe_metadata_exactly_at_limit_ok(): + # Build metadata that's exactly at the limit. + # Start with a reasonable guess and adjust. + base_overhead = len(json.dumps({"data": ""}, allow_nan=False, ensure_ascii=False).encode("utf-8")) + target_string_size = METADATA_MAX_BYTES - base_overhead + big_string = "x" * target_string_size + metadata = {"data": big_string} + + # Fine-tune to get exactly at the limit + while True: + size = len(json.dumps(metadata, allow_nan=False, ensure_ascii=False).encode("utf-8")) + if size == METADATA_MAX_BYTES: + break + elif size > METADATA_MAX_BYTES: + big_string = big_string[:-1] + metadata = {"data": big_string} + else: + big_string += "x" + metadata = {"data": big_string} + + r = CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + metadata=metadata, + payload={} + ) + assert r.metadata == metadata + + +def test_core_recipe_unknown_key_rejected(): + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + CoreRecipe( + schema_name="gsasii.rietveld", + core_schema_version="1.0.0", + engine_schema_version="1.0.0", + payload={}, + unknown_field="bad" + ) + + +def test_core_recipe_multiple_errors_reported(): + # Create a recipe with multiple independent errors + with pytest.raises(ValidationError) as exc_info: + CoreRecipe( + schema_name="INVALID_NAME", # error 1: pattern mismatch + core_schema_version="abc", # error 2: invalid version + engine_schema_version="xyz", # error 3: invalid version + payload={}, + unknown_key="bad" # error 4: extra field + ) + # pydantic reports every independent problem in one ValidationError. + locs = {e["loc"] for e in exc_info.value.errors()} + assert locs == {("schema_name",), ("core_schema_version",), + ("engine_schema_version",), ("unknown_key",)} + + +# --- check_core_schema_version ---------------------------------------------- + + +def test_check_core_schema_version_accepts_current(): + check_core_schema_version(CORE_SCHEMA_VERSION) # no error + + +def test_check_core_schema_version_rejects_unsupported(): + with pytest.raises(ValueError, match="not supported"): + check_core_schema_version("2.0.0") + + +# --- parameter models (RefinableParameter, BoundedRefinableParameter, etc.) ---- + + +from powderline.schema_core import ( + BoundedRefinableParameter, + RefinableParameter, + StructureBoundedRefinableParameter, + StructureRefinableParameter, + check_within_bounds, +) +from pydantic import BaseModel + + +# Wrapper models for testing error locs +class _WrapperRP(BaseModel): + """Wrapper for RefinableParameter testing.""" + a: RefinableParameter + + +class _WrapperBRP(BaseModel): + """Wrapper for BoundedRefinableParameter testing.""" + a: BoundedRefinableParameter + + +class _WrapperSRP(BaseModel): + """Wrapper for StructureRefinableParameter testing.""" + a: StructureRefinableParameter + + +class _WrapperSBRP(BaseModel): + """Wrapper for StructureBoundedRefinableParameter testing.""" + a: StructureBoundedRefinableParameter + + +# --- 1. JSON shape round-trip ----------------------------------------------- + + +def test_refinable_parameter_model_dump(): + rp = RefinableParameter.model_validate([1.5, True]) + assert rp.model_dump() == [1.5, True] + + +def test_refinable_parameter_model_dump_json(): + rp = RefinableParameter.model_validate([1.5, True]) + assert json.loads(rp.model_dump_json()) == [1.5, True] + + +def test_bounded_refinable_parameter_model_dump(): + brp = BoundedRefinableParameter.model_validate([1.5, True, 0.0, 2.0]) + assert brp.model_dump() == [1.5, True, 0.0, 2.0] + + +def test_bounded_refinable_parameter_model_dump_json(): + brp = BoundedRefinableParameter.model_validate([1.5, True, 0.0, 2.0]) + assert json.loads(brp.model_dump_json()) == [1.5, True, 0.0, 2.0] + + +def test_structure_refinable_parameter_model_dump(): + srp = StructureRefinableParameter.model_validate([None, True]) + assert srp.model_dump() == [None, True] + + +def test_structure_refinable_parameter_model_dump_with_value(): + srp = StructureRefinableParameter.model_validate([1.5, False]) + assert srp.model_dump() == [1.5, False] + + +def test_structure_bounded_refinable_parameter_model_dump(): + sbrp = StructureBoundedRefinableParameter.model_validate([None, True, 0.0, 2.0]) + assert sbrp.model_dump() == [None, True, 0.0, 2.0] + + +def test_structure_bounded_refinable_parameter_model_dump_with_value(): + sbrp = StructureBoundedRefinableParameter.model_validate([1.5, True, 0.0, 2.0]) + assert sbrp.model_dump() == [1.5, True, 0.0, 2.0] + + +# --- 2. RefinableParameter validation --------------------------------------- + + +def test_refinable_parameter_4_element_list_rejected(): + with pytest.raises(ValidationError) as exc_info: + _WrapperRP(a=[1.5, True, 0.0, 2.0]) + err = exc_info.value + assert any("bounds are not supported" in e["msg"] for e in err.errors()) + assert any(e["loc"] == ("a",) for e in err.errors()) + + +def test_refinable_parameter_1_element_list_rejected(): + with pytest.raises(ValidationError, match="expected \\[value, refine_flag\\]"): + _WrapperRP(a=[1.5]) + + +def test_refinable_parameter_3_element_list_rejected(): + with pytest.raises(ValidationError, match="expected \\[value, refine_flag\\]"): + _WrapperRP(a=[1.5, True, 0.0]) + + +def test_refinable_parameter_dict_rejected(): + with pytest.raises(ValidationError) as exc_info: + _WrapperRP(a={"value": 1.5, "refine_flag": True}) + err = exc_info.value + assert any("got dict" in e["msg"] for e in err.errors()) + + +def test_refinable_parameter_scalar_rejected(): + with pytest.raises(ValidationError, match="expected a \\[value, refine_flag\\] list"): + _WrapperRP(a=1.5) + + +def test_refinable_parameter_null_value_rejected(): + with pytest.raises(ValidationError): + _WrapperRP(a=[None, True]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_refinable_parameter_non_finite_value_rejected(bad): + with pytest.raises(ValidationError, match="must be finite"): + _WrapperRP(a=[bad, True]) + + +def test_refinable_parameter_refine_flag_null_rejected(): + with pytest.raises(ValidationError): + _WrapperRP(a=[1.5, None]) + + +def test_refinable_parameter_refine_flag_string_rejected(): + with pytest.raises(ValidationError): + _WrapperRP(a=[1.5, "true"]) + + +def test_refinable_parameter_refine_flag_int_1_rejected(): + with pytest.raises(ValidationError): + _WrapperRP(a=[1.5, 1]) + + +def test_refinable_parameter_refine_flag_int_0_rejected(): + with pytest.raises(ValidationError): + _WrapperRP(a=[1.5, 0]) + + +def test_refinable_parameter_int_value_accepted_and_dumped_as_float(): + w = _WrapperRP(a=[2, True]) + assert w.model_dump()["a"] == [2.0, True] + + +# --- 3. BoundedRefinableParameter validation -------------------------------- + + +def test_bounded_refinable_parameter_2_element_list_rejected(): + with pytest.raises(ValidationError, match="expected \\[value, refine_flag, min, max\\]"): + _WrapperBRP(a=[1.5, True]) + + +def test_bounded_refinable_parameter_null_min_accepted(): + brp = BoundedRefinableParameter.model_validate([1.5, True, None, 2.0]) + assert brp.min is None + assert brp.max == 2.0 + + +def test_bounded_refinable_parameter_null_max_accepted(): + brp = BoundedRefinableParameter.model_validate([1.5, True, 0.0, None]) + assert brp.min == 0.0 + assert brp.max is None + + +def test_bounded_refinable_parameter_null_both_bounds_accepted(): + brp = BoundedRefinableParameter.model_validate([1.5, True, None, None]) + assert brp.min is None + assert brp.max is None + + +def test_bounded_refinable_parameter_min_greater_than_max_rejected(): + with pytest.raises(ValidationError, match="min .* must be <= max"): + _WrapperBRP(a=[1.5, True, 2.0, 1.0]) + + +def test_bounded_refinable_parameter_value_below_min_rejected(): + with pytest.raises(ValidationError, match="below min"): + _WrapperBRP(a=[0.5, True, 1.0, 2.0]) + + +def test_bounded_refinable_parameter_value_above_max_rejected(): + with pytest.raises(ValidationError, match="above max"): + _WrapperBRP(a=[2.5, True, 1.0, 2.0]) + + +def test_bounded_refinable_parameter_value_equals_min_accepted(): + brp = BoundedRefinableParameter.model_validate([1.0, True, 1.0, 2.0]) + assert brp.value == 1.0 + + +def test_bounded_refinable_parameter_value_equals_max_accepted(): + brp = BoundedRefinableParameter.model_validate([2.0, True, 1.0, 2.0]) + assert brp.value == 2.0 + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_bounded_refinable_parameter_non_finite_min_rejected(bad): + with pytest.raises(ValidationError, match="must be finite"): + _WrapperBRP(a=[1.5, True, bad, 2.0]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")]) +def test_bounded_refinable_parameter_non_finite_max_rejected(bad): + with pytest.raises(ValidationError, match="must be finite"): + _WrapperBRP(a=[1.5, True, 0.0, bad]) + + +def test_bounded_refinable_parameter_null_value_rejected(): + with pytest.raises(ValidationError): + _WrapperBRP(a=[None, True, 0.0, 2.0]) + + +# --- 4. StructureRefinableParameter / StructureBoundedRefinableParameter ---- + + +def test_structure_refinable_parameter_null_value_accepted_refine_true(): + srp = StructureRefinableParameter.model_validate([None, True]) + assert srp.value is None + assert srp.refine_flag is True + + +def test_structure_refinable_parameter_null_value_accepted_refine_false(): + srp = StructureRefinableParameter.model_validate([None, False]) + assert srp.value is None + assert srp.refine_flag is False + + +def test_structure_refinable_parameter_4_element_list_rejected(): + with pytest.raises(ValidationError) as exc_info: + _WrapperSRP(a=[1.5, True, 0.0, 2.0]) + err = exc_info.value + assert any("bounds are not supported" in e["msg"] for e in err.errors()) + + +def test_structure_refinable_parameter_refine_flag_null_rejected(): + with pytest.raises(ValidationError): + _WrapperSRP(a=[None, None]) + + +def test_structure_bounded_refinable_parameter_null_value_accepted(): + sbrp = StructureBoundedRefinableParameter.model_validate([None, True, 0.0, 2.0]) + assert sbrp.value is None + assert sbrp.refine_flag is True + + +def test_structure_bounded_refinable_parameter_null_value_min_max_order_enforced(): + with pytest.raises(ValidationError, match="min .* must be <= max"): + _WrapperSBRP(a=[None, True, 2.0, 1.0]) + + +def test_structure_bounded_refinable_parameter_non_null_value_enforces_bounds_below(): + with pytest.raises(ValidationError, match="below min"): + _WrapperSBRP(a=[0.5, True, 1.0, 2.0]) + + +def test_structure_bounded_refinable_parameter_non_null_value_enforces_bounds_above(): + with pytest.raises(ValidationError, match="above max"): + _WrapperSBRP(a=[2.5, True, 1.0, 2.0]) + + +def test_structure_bounded_refinable_parameter_refine_flag_null_rejected(): + with pytest.raises(ValidationError): + _WrapperSBRP(a=[None, None, 0.0, 2.0]) + + +# --- 5. check_within_bounds ------------------------------------------------- + + +def test_check_within_bounds_inside_passes(): + param = BoundedRefinableParameter.model_validate([1.5, True, 1.0, 2.0]) + check_within_bounds(1.5, param, "test_field") # no error + + +def test_check_within_bounds_on_min_passes(): + param = BoundedRefinableParameter.model_validate([1.0, True, 1.0, 2.0]) + check_within_bounds(1.0, param, "test_field") # no error + + +def test_check_within_bounds_on_max_passes(): + param = BoundedRefinableParameter.model_validate([2.0, True, 1.0, 2.0]) + check_within_bounds(2.0, param, "test_field") # no error + + +def test_check_within_bounds_open_min_passes(): + param = BoundedRefinableParameter.model_validate([0.5, True, None, 2.0]) + check_within_bounds(0.5, param, "test_field") # no error + + +def test_check_within_bounds_open_max_passes(): + param = BoundedRefinableParameter.model_validate([2.5, True, 1.0, None]) + check_within_bounds(2.5, param, "test_field") # no error + + +def test_check_within_bounds_open_both_passes(): + param = BoundedRefinableParameter.model_validate([100.0, True, None, None]) + check_within_bounds(100.0, param, "test_field") # no error + + +def test_check_within_bounds_below_min_raises(): + param = BoundedRefinableParameter.model_validate([1.5, True, 1.0, 2.0]) + with pytest.raises(ValueError, match="test_field.*below min"): + check_within_bounds(0.5, param, "test_field") + + +def test_check_within_bounds_above_max_raises(): + param = BoundedRefinableParameter.model_validate([1.5, True, 1.0, 2.0]) + with pytest.raises(ValueError, match="test_field.*above max"): + check_within_bounds(2.5, param, "test_field") + + +# --- 6. JSON schema --------------------------------------------------------- + + +def test_refinable_parameter_json_schema(): + schema = _WrapperRP.model_json_schema() + param_schema = schema["$defs"]["RefinableParameter"] + assert param_schema["type"] == "array" + assert len(param_schema["prefixItems"]) == 2 + assert param_schema["minItems"] == 2 + assert param_schema["maxItems"] == 2 + assert param_schema["prefixItems"][0] == {"type": "number"} + assert param_schema["prefixItems"][1] == {"type": "boolean"} + + +def test_bounded_refinable_parameter_json_schema(): + schema = _WrapperBRP.model_json_schema() + param_schema = schema["$defs"]["BoundedRefinableParameter"] + assert param_schema["type"] == "array" + assert len(param_schema["prefixItems"]) == 4 + assert param_schema["minItems"] == 4 + assert param_schema["maxItems"] == 4 + assert param_schema["prefixItems"][0] == {"type": "number"} + assert param_schema["prefixItems"][1] == {"type": "boolean"} + assert param_schema["prefixItems"][2] == {"anyOf": [{"type": "number"}, {"type": "null"}]} + assert param_schema["prefixItems"][3] == {"anyOf": [{"type": "number"}, {"type": "null"}]} + + +def test_structure_refinable_parameter_json_schema(): + schema = _WrapperSRP.model_json_schema() + param_schema = schema["$defs"]["StructureRefinableParameter"] + assert param_schema["type"] == "array" + assert len(param_schema["prefixItems"]) == 2 + assert param_schema["minItems"] == 2 + assert param_schema["maxItems"] == 2 + assert param_schema["prefixItems"][0] == {"anyOf": [{"type": "number"}, {"type": "null"}]} + assert param_schema["prefixItems"][1] == {"type": "boolean"} + assert "structure" in param_schema["description"].lower() + + +def test_structure_bounded_refinable_parameter_json_schema(): + schema = _WrapperSBRP.model_json_schema() + param_schema = schema["$defs"]["StructureBoundedRefinableParameter"] + assert param_schema["type"] == "array" + assert len(param_schema["prefixItems"]) == 4 + assert param_schema["minItems"] == 4 + assert param_schema["maxItems"] == 4 + assert param_schema["prefixItems"][0] == {"anyOf": [{"type": "number"}, {"type": "null"}]} + assert param_schema["prefixItems"][1] == {"type": "boolean"} + assert param_schema["prefixItems"][2] == {"anyOf": [{"type": "number"}, {"type": "null"}]} + assert param_schema["prefixItems"][3] == {"anyOf": [{"type": "number"}, {"type": "null"}]} + assert "structure" in param_schema["description"].lower() + + +# --- 7. Identity preservation ----------------------------------------------- + + +def test_refinable_parameter_instance_identity_preserved(): + p = RefinableParameter.model_validate([1.5, True]) + w = _WrapperRP(a=p) + assert w.a is p + + +def test_bounded_refinable_parameter_instance_identity_preserved(): + p = BoundedRefinableParameter.model_validate([1.5, True, 0.0, 2.0]) + w = _WrapperBRP(a=p) + assert w.a is p + + +def test_structure_refinable_parameter_instance_identity_preserved(): + p = StructureRefinableParameter.model_validate([1.5, True]) + w = _WrapperSRP(a=p) + assert w.a is p + + +def test_structure_bounded_refinable_parameter_instance_identity_preserved(): + p = StructureBoundedRefinableParameter.model_validate([1.5, True, 0.0, 2.0]) + w = _WrapperSBRP(a=p) + assert w.a is p + + +# --- check_element_symbol (A32, A63) ---------------------------------------- + +from powderline.schema_core import check_element_symbol # noqa: E402 + + +@pytest.mark.parametrize("symbol", ["Fe", "O", "La", "B", "D", "Og"]) +def test_element_symbol_accepted(symbol): + assert check_element_symbol(symbol) == symbol + + +@pytest.mark.parametrize("symbol, canonical", [("fe", "Fe"), ("FE", "Fe"), ("la", "La"), ("Fe ", "Fe")]) +def test_element_symbol_misspelled_rejected_with_spelling(symbol, canonical): + with pytest.raises(ValueError, match=f"write the element symbol as '{canonical}'"): + check_element_symbol(symbol) + + +@pytest.mark.parametrize("symbol", ["Fe3+", "Fe+3", "O2-", "O-2", "Fe3"]) +def test_charged_types_rejected_not_stripped(symbol): + # A63: gemmi reduces e.g. "Fe3+" to Fe, which would change the scattering; + # core rejects charged types until they are supported. + with pytest.raises(ValueError, match="charged scattering types are not supported"): + check_element_symbol(symbol) + + +@pytest.mark.parametrize("symbol", ["X", "Xx", "", " Fe"]) +def test_unknown_element_rejected(symbol): + with pytest.raises(ValueError, match="not a known element symbol"): + check_element_symbol(symbol) From 3e8ba5cb29b903d6e81320c01a3f96b97cdbd507 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:50:14 -0400 Subject: [PATCH 020/259] feat(core): compat: declared schema-version support + powderline.support_matrix() (A40, A65) Gateways declare engine_schema_version / supported_engine_schemas / requires_core_schema (a specifier, or a mapping per engine-schema range) as capabilities() keys. check_engine_schema_version raises ValueError so that engine schema models can call it from a validator. support_matrix() walks the registry (engine-free); the in-repo gateways are undeclared until re/04-06. powderline.support_matrix is re-exported, outside __all__. The import-block test now imports schema_core and compat and calls support_matrix() with GSAS-II and easydiffraction blocked. Co-Authored-By: Claude Opus 5.5 --- src/powderline/__init__.py | 3 + src/powderline/compat.py | 139 +++++++++++++++++++++ tests/test_compat.py | 244 +++++++++++++++++++++++++++++++++++++ tests/test_gateways.py | 5 + 4 files changed, 391 insertions(+) create mode 100644 src/powderline/compat.py create mode 100644 tests/test_compat.py diff --git a/src/powderline/__init__.py b/src/powderline/__init__.py index efd69dd..77713fd 100644 --- a/src/powderline/__init__.py +++ b/src/powderline/__init__.py @@ -14,6 +14,9 @@ # requiring GSAS-II. The remaining GSAS-II-backed helpers are imported eagerly # when GSAS-II is available and skipped otherwise (the TOPAS path stays usable). from powderline.engine import run +# Declared schema-version support per gateway (A65); outside __all__ until the +# public-API rework. +from powderline.compat import support_matrix try: # GSAS-II-backed helpers + client (require the GSAS-II package) from powderline.kicker import ( diff --git a/src/powderline/compat.py b/src/powderline/compat.py new file mode 100644 index 0000000..7f2c0c5 --- /dev/null +++ b/src/powderline/compat.py @@ -0,0 +1,139 @@ +"""Schema-version compatibility: declared support sets, never version arithmetic (A40, A65). + +Declarations: + +- core (:mod:`powderline.schema_core`): ``CORE_SCHEMA_VERSION`` and + ``SUPPORTED_CORE_SCHEMAS`` (a PEP 440 specifier); +- each gateway, as keys of its ``capabilities()`` dict (re/04-06): + + - ``engine_schema_version`` -- the version new recipes are written against; + - ``supported_engine_schemas`` -- specifier of accepted engine schema versions; + - ``requires_core_schema`` -- specifier of the core versions it needs, or a + mapping ``{engine-schema specifier: core specifier}`` when different engine + schema versions need different core versions. + +A gateway that does not declare these yet is reported as undeclared by +:func:`support_matrix` and rejected by :func:`check_engine_schema_version`. +All checks raise ``ValueError`` so engine schema models can call them from a +pydantic validator and have them reported with the other validation errors. + +Engine-free (enforced by an import-block test). +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Mapping, Optional, Union + +from packaging.specifiers import InvalidSpecifier, SpecifierSet + +from powderline.schema_core import ( + CORE_SCHEMA_VERSION, + SUPPORTED_CORE_SCHEMAS, + check_core_schema_version, + parse_version, +) + +DECLARATION_KEYS = ("engine_schema_version", "supported_engine_schemas", "requires_core_schema") + +RequiresCore = Union[str, Mapping[str, str]] + + +def _powderline_version() -> str: + from powderline import __version__ + + return __version__ + + +def _specifier(what: str, spec: str) -> SpecifierSet: + try: + return SpecifierSet(spec) + except InvalidSpecifier: + raise ValueError(f"{what} {spec!r} is not a valid PEP 440 specifier") from None + + +def declarations(capabilities: Mapping[str, Any]) -> Optional[Dict[str, Any]]: + """The schema declarations in a gateway's ``capabilities()``, or ``None`` if absent. + + Raises ``ValueError`` when only some of the keys are declared. + """ + present = [k for k in DECLARATION_KEYS if k in capabilities] + if not present: + return None + if len(present) != len(DECLARATION_KEYS): + missing = sorted(set(DECLARATION_KEYS) - set(present)) + raise ValueError(f"gateway {capabilities.get('name')!r} declares {present} but not {missing}") + return {k: capabilities[k] for k in DECLARATION_KEYS} + + +def required_core_schemas(requires: RequiresCore, engine_schema_version: str) -> str: + """The core specifier that ``engine_schema_version`` requires. + + ``requires`` is a single specifier, or a mapping whose first key (in + declaration order) containing ``engine_schema_version`` applies. + """ + if isinstance(requires, str): + return requires + version = parse_version("engine_schema_version", engine_schema_version) + for engine_spec, core_spec in requires.items(): + if version in _specifier("requires_core_schema key", engine_spec): + return core_spec + raise ValueError( + f"requires_core_schema has no entry for engine schema {engine_schema_version} " + f"(keys: {', '.join(requires)})" + ) + + +def check_engine_schema_version(core_schema_version: str, engine_schema_version: str, *, + gateway: str, capabilities: Mapping[str, Any]) -> None: + """Raise ``ValueError`` unless the recipe's version pair is accepted. + + Checks, in order: the core version against :data:`SUPPORTED_CORE_SCHEMAS`; the + engine version against the gateway's ``supported_engine_schemas``; the core + version against what that engine version ``requires_core_schema``. + """ + check_core_schema_version(core_schema_version) + decl = declarations(capabilities) + if decl is None: + raise ValueError(f"gateway {gateway!r} declares no supported engine schema versions") + pair = (f"core_schema_version {core_schema_version!r}, " + f"engine_schema_version {engine_schema_version!r}") + engine_v = parse_version("engine_schema_version", engine_schema_version) + supported = decl["supported_engine_schemas"] + if engine_v not in _specifier("supported_engine_schemas", supported): + raise ValueError( + f"{pair}: the {gateway!r} gateway of PowderLine {_powderline_version()} accepts " + f"engine schema {supported} (current: {decl['engine_schema_version']})" + ) + needs = required_core_schemas(decl["requires_core_schema"], engine_schema_version) + if parse_version("core_schema_version", core_schema_version) not in _specifier( + "requires_core_schema", needs): + raise ValueError( + f"{pair}: {gateway!r} engine schema {engine_schema_version} requires core " + f"schema {needs} (PowderLine {_powderline_version()})" + ) + + +def support_matrix() -> List[Dict[str, Any]]: + """One row per registered gateway: its declarations plus core's (A40). + + Loads each gateway's engine-free factory through the registry; imports no + engine. Undeclared gateways get ``"declared": False``. Consumed by the docs + generation in re/10. + """ + from powderline import registry + + rows = [] + for name in registry.available(): + caps = registry.get(name).capabilities() + decl = declarations(caps) + rows.append({ + "gateway": name, + "powderline_version": _powderline_version(), + "core_schema_version": CORE_SCHEMA_VERSION, + "supported_core_schemas": SUPPORTED_CORE_SCHEMAS, + "workflows": tuple(caps.get("workflows", ())), + "engine_version_spec": caps.get("engine_version_spec"), + "declared": decl is not None, + **(decl or {k: None for k in DECLARATION_KEYS}), + }) + return rows diff --git a/tests/test_compat.py b/tests/test_compat.py new file mode 100644 index 0000000..de73256 --- /dev/null +++ b/tests/test_compat.py @@ -0,0 +1,244 @@ +"""Direct tests for powderline.compat schema-version compatibility functions. + +Engine-free, no GSAS-II import (re/03). +""" +import pytest + +from powderline import registry +from powderline.compat import ( + check_engine_schema_version, + declarations, + required_core_schemas, + support_matrix, +) +from powderline.schema_core import CORE_SCHEMA_VERSION + + +# --- declarations ----------------------------------------------------------- + + +def test_declarations_none_when_no_keys(): + caps = {"name": "test", "workflows": ["rietveld"]} + assert declarations(caps) is None + + +def test_declarations_dict_when_all_three_present(): + caps = { + "name": "test", + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "==1.0.0", + "requires_core_schema": "==1.0.0", + } + decl = declarations(caps) + assert decl is not None + assert decl["engine_schema_version"] == "1.0.0" + assert decl["supported_engine_schemas"] == "==1.0.0" + assert decl["requires_core_schema"] == "==1.0.0" + + +def test_declarations_raises_when_only_some_present(): + caps = { + "name": "test", + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "==1.0.0", + # missing requires_core_schema + } + with pytest.raises(ValueError, match="declares.*but not"): + declarations(caps) + + +# --- required_core_schemas -------------------------------------------------- + + +def test_required_core_schemas_plain_string_returned_as_is(): + result = required_core_schemas("==1.0.0", "1.0.0") + assert result == "==1.0.0" + + +def test_required_core_schemas_mapping_picks_first_matching_key(): + requires = { + ">=2.0.0": "==2.0.0", + ">=1.0.0": "==1.0.0", + } + result = required_core_schemas(requires, "1.5.0") + assert result == "==1.0.0" + + +def test_required_core_schemas_mapping_picks_highest_version_match(): + requires = { + ">=2.0.0": "==2.0.0", + ">=1.0.0": "==1.0.0", + } + result = required_core_schemas(requires, "2.5.0") + assert result == "==2.0.0" + + +def test_required_core_schemas_no_matching_key_raises(): + requires = { + ">=2.0.0": "==2.0.0", + } + with pytest.raises(ValueError, match="no entry for engine schema"): + required_core_schemas(requires, "1.0.0") + + +# --- check_engine_schema_version -------------------------------------------- + + +def test_check_engine_schema_version_accepted_pair_passes(): + caps = { + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "==1.0.0", + "requires_core_schema": "==1.0.0", + } + # Should not raise + check_engine_schema_version("1.0.0", "1.0.0", gateway="test", capabilities=caps) + + +def test_check_engine_schema_version_engine_version_outside_supported_raises(): + caps = { + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "==1.0.0", + "requires_core_schema": "==1.0.0", + } + with pytest.raises(ValueError) as exc_info: + check_engine_schema_version("1.0.0", "2.0.0", gateway="test", capabilities=caps) + err_msg = str(exc_info.value) + assert "test" in err_msg + assert "==1.0.0" in err_msg + + +def test_check_engine_schema_version_core_version_not_in_requires_raises(): + caps = { + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "==1.0.0", + "requires_core_schema": "==2.0.0", # requires different core version + } + with pytest.raises(ValueError, match="requires core"): + check_engine_schema_version("1.0.0", "1.0.0", gateway="test", capabilities=caps) + + +def test_check_engine_schema_version_unsupported_core_version_raises(): + caps = { + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "==1.0.0", + "requires_core_schema": "==1.0.0", + } + with pytest.raises(ValueError, match="not supported by PowderLine"): + check_engine_schema_version("2.0.0", "1.0.0", gateway="test", capabilities=caps) + + +def test_check_engine_schema_version_gateway_with_no_declarations_raises(): + caps = {"name": "test"} # no declarations + with pytest.raises(ValueError, match="declares no supported engine schema versions"): + check_engine_schema_version("1.0.0", "1.0.0", gateway="test", capabilities=caps) + + +def test_check_engine_schema_version_invalid_specifier_in_supported_engine_schemas_raises(): + caps = { + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "not-a-valid-specifier", + "requires_core_schema": "==1.0.0", + } + with pytest.raises(ValueError, match="not a valid PEP 440 specifier"): + check_engine_schema_version("1.0.0", "1.0.0", gateway="test", capabilities=caps) + + +def test_check_engine_schema_version_invalid_specifier_in_requires_core_schema_raises(): + caps = { + "engine_schema_version": "1.0.0", + "supported_engine_schemas": "==1.0.0", + "requires_core_schema": "not-a-valid-specifier", + } + with pytest.raises(ValueError, match="not a valid PEP 440 specifier"): + check_engine_schema_version("1.0.0", "1.0.0", gateway="test", capabilities=caps) + + +# --- support_matrix --------------------------------------------------------- + + +@pytest.fixture +def fake_gateway_declared(): + """Register a fake gateway with declarations, unregister on teardown.""" + name = "test_declared" + + def factory(): + return registry.Gateway( + name=name, + capabilities=lambda: { + "name": name, + "workflows": ["rietveld"], + "engine_schema_version": "1.5.0", + "supported_engine_schemas": ">=1.0.0", + "requires_core_schema": "==1.0.0", + }, + validate=lambda r, *, verbose=False: r, + run=lambda *a, **k: {}, + ) + + registry.register_gateway(name, factory) + yield name + registry.unregister_gateway(name) + + +@pytest.fixture +def fake_gateway_undeclared(): + """Register a fake gateway without declarations, unregister on teardown.""" + name = "test_undeclared" + + def factory(): + return registry.Gateway( + name=name, + capabilities=lambda: { + "name": name, + "workflows": ["spf"], + }, + validate=lambda r, *, verbose=False: r, + run=lambda *a, **k: {}, + ) + + registry.register_gateway(name, factory) + yield name + registry.unregister_gateway(name) + + +def test_support_matrix_declared_gateway_has_values(fake_gateway_declared): + matrix = support_matrix() + rows = [r for r in matrix if r["gateway"] == fake_gateway_declared] + assert len(rows) == 1 + row = rows[0] + assert row["declared"] is True + assert row["engine_schema_version"] == "1.5.0" + assert row["supported_engine_schemas"] == ">=1.0.0" + assert row["requires_core_schema"] == "==1.0.0" + + +def test_support_matrix_undeclared_gateway_has_none_values(fake_gateway_undeclared): + matrix = support_matrix() + rows = [r for r in matrix if r["gateway"] == fake_gateway_undeclared] + assert len(rows) == 1 + row = rows[0] + assert row["declared"] is False + assert row["engine_schema_version"] is None + assert row["supported_engine_schemas"] is None + assert row["requires_core_schema"] is None + + +def test_support_matrix_every_row_has_core_schema_version(): + matrix = support_matrix() + for row in matrix: + assert row["core_schema_version"] == CORE_SCHEMA_VERSION + + +def test_support_matrix_is_powderline_support_matrix(): + # Check that powderline.support_matrix is the same as compat.support_matrix + import powderline + assert powderline.support_matrix is support_matrix + + +def test_support_matrix_has_in_repo_gateways(): + matrix = support_matrix() + gateway_names = {r["gateway"] for r in matrix} + # The three in-repo gateways (undeclared until re/04-06) + assert "gsasii" in gateway_names + assert "topas" in gateway_names + assert "easydiffraction" in gateway_names diff --git a/tests/test_gateways.py b/tests/test_gateways.py index a1e8cc8..1156041 100644 --- a/tests/test_gateways.py +++ b/tests/test_gateways.py @@ -465,6 +465,8 @@ def find_spec(self, name, path, target=None): import powderline.fitstats import powderline.reports import powderline.symmetry +import powderline.schema_core +import powderline.compat import powderline.gateways.gsasii import powderline.gateways.gsasii.gateway import powderline.gateways.gsasii.validation @@ -486,6 +488,9 @@ def find_spec(self, name, path, target=None): assert caps["name"] == name and "engine_version_spec" in caps assert type(gw.validate(recipe)).__name__ == "RecipeModel" +# The support matrix loads every gateway factory (A65) +assert {{row["gateway"] for row in powderline.support_matrix()}} >= set(recipes) + # Assert GSASII and easydiffraction are NOT in sys.modules assert "GSASII" not in sys.modules, "GSASII was imported despite the block" assert "easydiffraction" not in sys.modules, "easydiffraction was imported despite the block" From 0072a6884dbc9cd40eb5f46217d6b6db8c98eefb Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:50:14 -0400 Subject: [PATCH 021/259] refactor(core): drop RecipeValidationError; invalid recipes raise pydantic's ValidationError (A70) All recipe checks live in the schema models, so pydantic's own ValidationError reports every problem with its location; a wrapper only duplicated it (and would have broken except-ValidationError callers, superseding A60). The class was unused outside its unit test. A new test shows a SymmetryError raised in a validator joining the aggregated error. Co-Authored-By: Claude Opus 5.5 --- src/powderline/exceptions.py | 28 ++++------------------------ tests/test_exceptions.py | 31 +++++++++++++++++++------------ 2 files changed, 23 insertions(+), 36 deletions(-) diff --git a/src/powderline/exceptions.py b/src/powderline/exceptions.py index c129b7c..ec7aeb2 100644 --- a/src/powderline/exceptions.py +++ b/src/powderline/exceptions.py @@ -13,11 +13,14 @@ - :class:`EngineVersionError` — the installed engine is outside the gateway's supported ``ENGINE_VERSION_SPEC``. A hard error (A44). - :class:`EngineExecutionError` — the engine ran and failed. -- :class:`RecipeValidationError` — a recipe failed validation. - :class:`SymmetryError` — core symmetry helpers (``powderline.symmetry``) cannot interpret a space group or site. Gateways convert it to their own error type (A61). +An invalid recipe raises pydantic's own ``ValidationError``, which lists every +problem with its field location. Recipe checks live in the schema models +(core + engine), so there is no PowderLine wrapper for it (A70). + This module must never import an engine (enforced by an import-block test). """ @@ -30,29 +33,6 @@ class PowderLineError(Exception): """Base class for all PowderLine errors.""" -class RecipeValidationError(PowderLineError, ValueError): - """A recipe failed validation. - - Wraps (and may annotate) the underlying pydantic errors. ``errors`` holds - pydantic's ``ValidationError.errors()`` list when built from one. - """ - - def __init__(self, message: str, *, errors: Optional[list] = None, - schema_name: Optional[str] = None) -> None: - super().__init__(message) - self.errors = list(errors or []) - self.schema_name = schema_name - - @classmethod - def from_pydantic(cls, exc, *, schema_name: Optional[str] = None) -> "RecipeValidationError": - """Build from a ``pydantic.ValidationError``, keeping its error list.""" - prefix = f"{schema_name} recipe" if schema_name else "recipe" - err = cls(f"{prefix} failed validation:\n{exc}", errors=exc.errors(), - schema_name=schema_name) - err.__cause__ = exc - return err - - class SymmetryError(PowderLineError, ValueError): """A space group or atomic site cannot be interpreted (``powderline.symmetry``). diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 2018344..134a370 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -11,14 +11,13 @@ EngineVersionError, GatewayNotInstalledError, PowderLineError, - RecipeValidationError, StructuredWarning, SymmetryError, ) @pytest.mark.parametrize("cls", [ - RecipeValidationError, GatewayNotInstalledError, EngineNotAvailableError, + GatewayNotInstalledError, EngineNotAvailableError, EngineVersionError, EngineExecutionError, SymmetryError, ]) def test_all_derive_from_powderline_error(cls): @@ -57,19 +56,27 @@ def test_gateway_not_installed_keeps_name(): assert str(err) == "no gateway 'foo'" -class _M(BaseModel): - x: int +def test_symmetry_error_raised_in_a_validator_is_reported_by_pydantic(): + # A61/A70: a SymmetryError raised inside a validator joins pydantic's + # aggregated ValidationError with its field location. + from pydantic import field_validator + from powderline.exceptions import SymmetryError + + class _S(BaseModel): + sg: str + n: int + + @field_validator("sg") + @classmethod + def _sg(cls, v): + raise SymmetryError(f"bad group {v!r}") -def test_recipe_validation_error_from_pydantic(): with pytest.raises(ValidationError) as info: - _M.model_validate({"x": "not-an-int"}) - err = RecipeValidationError.from_pydantic(info.value, schema_name="GSASII_Rietveld") - assert isinstance(err, ValueError) - assert err.schema_name == "GSASII_Rietveld" - assert err.errors and err.errors[0]["loc"] == ("x",) - assert err.__cause__ is info.value - assert str(err).startswith("GSASII_Rietveld recipe failed validation:") + _S.model_validate({"sg": "Q", "n": "x"}) + locs = {e["loc"]: e["msg"] for e in info.value.errors()} + assert set(locs) == {("sg",), ("n",)} + assert "bad group 'Q'" in locs[("sg",)] def test_structured_warning_shape(): From 4ceea800ceb4cb05f671959ab46dd8fe363d7086 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:50:14 -0400 Subject: [PATCH 022/259] docs: restructure SCHEMA_HISTORY into core + per-engine sections with a 0.21-0.26 archive (A37) Core 1.0.0 is documented as in development and not yet used. The engine sections are placeholders for re/04-06. The existing history is kept verbatim below, with headings moved one level down. A banner states that the runtime still validates schema 0.26.0 until re/07. Co-Authored-By: Claude Opus 5.5 --- docs/SCHEMA_HISTORY.md | 94 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 81 insertions(+), 13 deletions(-) diff --git a/docs/SCHEMA_HISTORY.md b/docs/SCHEMA_HISTORY.md index c7c65b2..449da94 100644 --- a/docs/SCHEMA_HISTORY.md +++ b/docs/SCHEMA_HISTORY.md @@ -1,10 +1,78 @@ # 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). + +> **Refactor in progress (v0.2.0).** The schemas below are being introduced on +> the `refactor/multi-engine` branch. Until the 0.26.0 schema is removed (re/07), +> `powderline.run()` / `validate()` still validate recipes against the +> **unified 0.26.0 schema** documented in the archive at the bottom of this page. + +--- + +## Core schema + +### 1.0.0 — introduced in PowderLine 0.2.0 (in development) + +Defined in `src/powderline/schema_core.py`. Not used by any gateway yet: the +engine schemas adopt it in re/04–06. + +- **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). A bounded list + where bounds aren't supported is an error. `refine_flag` is a JSON boolean. + `value` may be `null` (= start from the phase structure's value) only for + quantities that mirror a structure value. +- **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. +- **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. +- **Accepted core versions** (this release): `==1.0.0`. + +Phase structure and symmetry validation (space-group setting, element symbols, +special positions) are documented here when they land. + +## gsasii engine schema + +### 1.0.0 — introduced in PowderLine 0.2.0 + +Entries added by re/04 (`gsasii.rietveld`, `gsasii.spf`). + +## topas engine schema + +### 1.0.0 — introduced in PowderLine 0.2.0 + +Entries added by re/05 (`topas.rietveld`, `topas.spf`). + +## easydiffraction engine schema + +### 1.0.0 — introduced in PowderLine 0.2.0 + +Entries added by re/06 (`easydiffraction.rietveld`). + +--- + +## Archive: unified-schema era (0.21–0.26) + +The single schema shared by all engines up to PowderLine 0.1.1, kept verbatim +(headings moved one level down). + This document provides a concise summary of PowderLine's schema evolution for context. For detailed commit history, see the repository's git log. Current schema: **0.26.0** --- -## Schema 0.26.0: Per-Parameter Refinement Flags Honored (Current) +### Schema 0.26.0: Per-Parameter Refinement Flags Honored (Current) **Status**: Active (Q3 2026) @@ -64,7 +132,7 @@ file reader/parser that builds the block. --- -## Schema 0.25.4: Consistent Failure Metadata +### Schema 0.25.4: Consistent Failure Metadata **Status**: Superseded by 0.26.0 @@ -90,7 +158,7 @@ No other recipe changes required. --- -## Schema 0.25.3: Refinement Failure Detection and Windows Support +### Schema 0.25.3: Refinement Failure Detection and Windows Support **Status**: Superseded by 0.25.4 @@ -110,7 +178,7 @@ No other recipe changes required. --- -## Schema 0.25.2: Programmatic Python API +### Schema 0.25.2: Programmatic Python API **Status**: Superseded by 0.25.3 @@ -147,7 +215,7 @@ No other recipe changes required. --- -## Schema 0.25.1: Refined Parameters Export + Extended SPF Returns +### Schema 0.25.1: Refined Parameters Export + Extended SPF Returns **Status**: Superseded by 0.25.2 @@ -175,7 +243,7 @@ No other recipe changes required. --- -## Schema 0.25: Simplification +### Schema 0.25: Simplification **Status**: Superseded by 0.25.1 @@ -202,7 +270,7 @@ No other recipe changes required. --- -## Schema 0.24: Multi-Strategy Refinement System +### Schema 0.24: Multi-Strategy Refinement System **Status**: Deprecated (replaced by schema 0.25) @@ -222,7 +290,7 @@ No other recipe changes required. --- -## Schema 0.23: Initial Multi-Strategy Exploration +### Schema 0.23: Initial Multi-Strategy Exploration **Status**: Deprecated @@ -235,7 +303,7 @@ No other recipe changes required. --- -## Schema 0.22: ADP Field Requirements +### Schema 0.22: ADP Field Requirements **Status**: Deprecated @@ -249,7 +317,7 @@ No other recipe changes required. --- -## Schema 0.21 and Earlier +### Schema 0.21 and Earlier **Status**: Historical @@ -262,7 +330,7 @@ Early development versions focused on basic Rietveld refinement capabilities: --- -## Origin (Schema 0.21–0.24) +### Origin (Schema 0.21–0.24) PowderLine began as a minimal proof-of-concept to confirm that GSAS-II could be driven from a JSON file via the G2scripts API. The initial scope established the directory @@ -276,7 +344,7 @@ configuration system, programmatic Python API) were subsequently delivered in sc --- -## Schema Design Philosophy +### Schema Design Philosophy **Example-Driven Development**: Features are added when real refinement examples need them, not speculatively. Schema evolution is guided by committed examples in `examples/` directory. @@ -288,7 +356,7 @@ configuration system, programmatic Python API) were subsequently delivered in sc --- -## Migration Philosophy +### Migration Philosophy - **Explicit schema versions**: Every recipe declares its `"schema_version"`. The code accepts one current version — **0.26.0** — and recipes written for older versions must From 2632ac9cba289dfca185e32e53714b85334c6a11 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:13:32 -0400 Subject: [PATCH 023/259] feat(core): symmetry.analyze_site (special positions, A69/A73); correct site DOF classification analyze_site(space_group, xyz) is the core schema's site validation (KI-03): - the space group must name its setting (two-origin :1/:2, rhombohedral :H/:R; A62); - symmetry images closer than 5e-6 put the operation in the stabilizer (>= 6 decimals declare a special position); - an image between 5e-6 and 2e-3 raises SymmetryError naming the exact special position and its multiplicity (ambiguous band); - canonical coordinates: the barycenter of the stabilizer images, with fixed axes set to their exact fraction (denominator <= 48); `adjusted` reports a difference above 1e-12; - multiplicity = |G| / |stabilizer|, with consistency checks; coordinate and Uij DOF classification. DOF classification fix (P1): FIXED is now a row test on the stabilizer projector, FREE a column test. The old column-only test misread trigonal and hexagonal sites, whose rotations are not orthogonal in fractional coordinates (e.g. 6h (x, 2x, 1/4) gave x FIXED). The legacy site_dof/adp_dof (0.26.0 TOPAS writer warnings) share the corrected helper. Recorded as a deliberate change. tests/test_symmetry_characterization.py compares multiplicity, coordinate DOF and Uij DOF with GSAS-II's SytSym/GetCSxinel/GetCSuinel for all 230 space groups (GSAS-II symbol verified per group by matching the orbits), plus canonicalization, ambiguous-band and committed-example checks. With the old column test reinstated, 13 trigonal/hexagonal groups fail. Skipped without GSAS-II. Co-Authored-By: Claude Opus 5.5 --- src/powderline/symmetry.py | 247 +++++++++++++++++++----- tests/test_symmetry_characterization.py | 177 +++++++++++++++++ 2 files changed, 379 insertions(+), 45 deletions(-) create mode 100644 tests/test_symmetry_characterization.py diff --git a/src/powderline/symmetry.py b/src/powderline/symmetry.py index fc10510..0523e8a 100644 --- a/src/powderline/symmetry.py +++ b/src/powderline/symmetry.py @@ -1,6 +1,6 @@ """gemmi-backed crystallographic rules (engine-free core module). -Two pure capabilities, both engine-free: +Pure, engine-free capabilities: * :func:`cell_constraints` -- crystal-system cell equalities and fixed angles, so the writer can share one ``prm`` name across equal cell lengths and emit @@ -9,6 +9,11 @@ COUPLED) plus the orbit size, so the writer can decide whether a *refined* atomic coordinate is legal and warn on suspicious multiplicities. +* :func:`analyze_site` -- the core schema's site validation (KI-03; A35, A69, + A73): multiplicity + DOF from the space group, the ambiguous-band error, and + the canonical (exact) special-position coordinates every gateway sends to its + engine. Policy and evidence: devkit ``tasks/re03-symmetry-tolerance.md``. + Space-group operations come from gemmi; the stabiliser / projector math is our own (~small, spec in plan §5). ``gemmi`` is an approved runtime dependency (D3). @@ -20,6 +25,7 @@ from __future__ import annotations from dataclasses import dataclass +from fractions import Fraction import gemmi import numpy as np @@ -28,9 +34,20 @@ # Fractional-coordinate tolerances (plan §5). -_POS_TOL = 1e-5 # position / orbit equality mod 1 +_POS_TOL = 1e-5 # position / orbit equality mod 1 (legacy site_dof/adp_dof) _MAT_TOL = 1e-6 # rotation-matrix / projector comparisons +#: Core schema special-position rules (A69, A73), as a fractional *image +#: distance* d = max_i |wrap(R x + t - x)_i|: d < SPECIAL_POSITION_TOL means x is +#: fixed by that operation (>= 6 decimals declare a special position); +#: SPECIAL_POSITION_TOL <= d < AMBIGUOUS_BAND is an error (ambiguous intent). +SPECIAL_POSITION_TOL = 5e-6 +AMBIGUOUS_BAND = 2e-3 +#: Canonical coordinates that differ from the stated ones by more than this are +#: reported as adjusted (floating-point noise is not). +ADJUSTMENT_REPORT_TOL = 1e-12 +_MAX_DENOMINATOR = 48 # fixed special-position coordinates are multiples of 1/24 + _AXIS_LETTERS = ("x", "y", "z") _LENGTHS = ("a", "b", "c") _ANGLES = ("alpha", "beta", "gamma") @@ -93,7 +110,7 @@ def classification(self, axis: str) -> str: # --- space-group resolution ------------------------------------------------- -def resolve_space_group(space_group: str) -> gemmi.SpaceGroup: +def resolve_space_group(space_group: str, *, explicit_setting: bool = False) -> gemmi.SpaceGroup: """Resolve a recipe space-group string to a gemmi ``SpaceGroup``. Tries the symbol verbatim, then whitespace-stripped (gemmi accepts both @@ -101,7 +118,9 @@ def resolve_space_group(space_group: str) -> gemmi.SpaceGroup: :class:`SymmetryError`. Two-origin groups passed without an explicit ``:1``/``:2`` selector also error rather than guess an origin (plan §5(6)). Both rhombohedral settings (``:H``, ``:R``) are accepted; engines that - cannot handle ``:R`` reject it themselves (A62). + cannot handle ``:R`` reject it themselves (A62). With + ``explicit_setting=True`` (the core schema rule, A62) a rhombohedral group + must also name its setting (gemmi would otherwise assume ``:H``). """ raw = str(space_group) sg = gemmi.find_spacegroup_by_name(raw) @@ -111,6 +130,11 @@ def resolve_space_group(space_group: str) -> gemmi.SpaceGroup: raise SymmetryError( f"unrecognized space-group symbol {space_group!r} (gemmi could not resolve it)" ) + if explicit_setting and sg.ext in ("H", "R") and ":" not in raw: + raise SymmetryError( + f"space group {space_group!r} is rhombohedral; specify the setting " + "explicitly: append ':H' (hexagonal axes) or ':R' (rhombohedral axes)" + ) if sg.ext in ("1", "2") and ":" not in raw: raise SymmetryError( f"space group {space_group!r} has two origin choices; specify one " @@ -210,6 +234,42 @@ def _orbit_size(ops, xyz: np.ndarray) -> int: return len(points) +def _classify(projector: np.ndarray) -> list[str]: + """Per-component DOF from a projector ``P`` onto the allowed displacements. + + FIXED: row j of P is zero (no allowed displacement changes component j). + FREE: ``P e_j == e_j`` (component j changes on its own). Otherwise COUPLED. + Rows and columns of P differ when the rotations are not orthogonal in + fractional coordinates (hexagonal/trigonal axes), so the FIXED test must use + the row: e.g. 6h ``(x, 2x, 1/4)`` in P6_3/mmc has x COUPLED, not FIXED. The + classification is checked against GSAS-II's site-symmetry tables for all 230 + space groups (``tests/test_symmetry_characterization.py``). + """ + n = projector.shape[0] + out = [] + for j in range(n): + unit = np.zeros(n) + unit[j] = 1.0 + if np.linalg.norm(projector[j, :]) < _MAT_TOL: + out.append("FIXED") + elif np.linalg.norm(projector[:, j] - unit) < _MAT_TOL: + out.append("FREE") + else: + out.append("COUPLED") + return out + + +def _adp_projector(stab_rots) -> np.ndarray: + """Projector onto site-allowed U tensors (``U -> R U R^T``) in u11..u23 coordinates.""" + projector = np.zeros((6, 6)) + for R in stab_rots: + for j in range(6): + basis = np.zeros(6) + basis[j] = 1.0 + projector[:, j] += _vec_from_sym(R @ _sym_from_vec(basis) @ R.T) + return projector / len(stab_rots) + + def site_dof(space_group: str, xyz) -> SiteDof: """Classify the site DOF of fractional position ``xyz`` in ``space_group``. @@ -218,10 +278,9 @@ def site_dof(space_group: str, xyz) -> SiteDof: 1. Expand all symmetry operations (with centering). 2. Stabiliser = ops with ``R x + t == x (mod 1)`` within ``_POS_TOL``. 3. Allowed-displacement subspace = fixed space of the stabiliser rotations, - given by the Reynolds projector ``P = mean(R_i)`` (an orthogonal - projector for a group of orthogonal matrices). - 4. Per axis ``e_j``: ``P e_j == e_j`` -> FREE; ``P e_j == 0`` -> FIXED; - otherwise -> COUPLED (subspace not axis-aligned along ``j``). + given by the Reynolds projector ``P = mean(R_i)``. + 4. Per axis: see :func:`_classify` (FIXED = row of P is zero, FREE = + ``P e_j == e_j``, else COUPLED). """ x = np.asarray(xyz, dtype=float) if x.shape != (3,): @@ -232,21 +291,8 @@ def site_dof(space_group: str, xyz) -> SiteDof: if not stab_rots: # pragma: no cover - identity is always in the group raise SymmetryError("empty stabilizer (should be impossible)") - projector = sum(stab_rots) / len(stab_rots) - - axes: list[str] = [] - coupled: list[str] = [] - for j in range(3): - col = projector[:, j] - unit = np.zeros(3) - unit[j] = 1.0 - if np.linalg.norm(col - unit) < _MAT_TOL: - axes.append("FREE") - elif np.linalg.norm(col) < _MAT_TOL: - axes.append("FIXED") - else: - axes.append("COUPLED") - coupled.append(_AXIS_LETTERS[j]) + axes = _classify(sum(stab_rots) / len(stab_rots)) + coupled = [_AXIS_LETTERS[j] for j in range(3) if axes[j] == "COUPLED"] return SiteDof( axes=(axes[0], axes[1], axes[2]), @@ -294,33 +340,144 @@ def adp_dof(space_group: str, xyz) -> AdpDof: The symmetric U tensor transforms as ``U -> R U R^T`` under a site-symmetry rotation ``R``; the site-allowed U is the fixed space of the stabiliser, - given by the Reynolds projector on the 6-dim symmetric-tensor space. A - component ``e_j`` with ``P e_j == e_j`` is FREE, ``== 0`` is FIXED, else - COUPLED (e.g. cubic ``m-3m`` -> ``u11=u22=u33`` coupled, off-diagonals FIXED). + given by the Reynolds projector on the 6-dim symmetric-tensor space, + classified by :func:`_classify` (e.g. cubic ``m-3m`` -> ``u11=u22=u33`` + coupled, off-diagonals FIXED). """ x = np.asarray(xyz, dtype=float) if x.shape != (3,): raise ValueError("xyz must be a 3-vector") ops = _expanded_ops(resolve_space_group(space_group)) stab = [R for (R, t) in ops if np.all(np.abs(_wrap_symmetric(R @ x + t - x)) < _POS_TOL)] + comps = _classify(_adp_projector(stab)) + return AdpDof(components=tuple(comps), stabilizer_order=len(stab)) - projector = np.zeros((6, 6)) - for R in stab: - for j in range(6): - basis = np.zeros(6) - basis[j] = 1.0 - projector[:, j] += _vec_from_sym(R @ _sym_from_vec(basis) @ R.T) - projector /= len(stab) - comps = [] - for j in range(6): - col = projector[:, j] - unit = np.zeros(6) - unit[j] = 1.0 - if np.linalg.norm(col - unit) < _MAT_TOL: - comps.append("FREE") - elif np.linalg.norm(col) < _MAT_TOL: - comps.append("FIXED") - else: - comps.append("COUPLED") - return AdpDof(components=tuple(comps), stabilizer_order=len(stab)) +# --- (d) core site validation (KI-03; A35, A69, A73) ------------------------ + + +@dataclass(frozen=True) +class SiteAnalysis: + """One atomic site, analyzed under the core schema rules. + + Attributes: + stated: the coordinates as given. + canonical: the coordinates every gateway uses -- equal to ``stated`` for + a general position; on a special position, symmetry-fixed axes are + exact (see ``exact``) and coupled axes satisfy their relation. + exact: per axis, the exact rational value of a symmetry-fixed + coordinate (``None`` for a free or coupled axis). + axes: ``"FREE"`` / ``"FIXED"`` / ``"COUPLED"`` per axis. + adp: the same classification for ``U11, U22, U33, U12, U13, U23``. + multiplicity: site multiplicity in the conventional cell. + stabilizer_order: number of operations fixing the site. + """ + + stated: tuple[float, float, float] + canonical: tuple[float, float, float] + exact: tuple[Fraction | None, Fraction | None, Fraction | None] + axes: tuple[str, str, str] + adp: tuple[str, str, str, str, str, str] + multiplicity: int + stabilizer_order: int + + @property + def adjusted(self) -> bool: + """True when ``canonical`` differs from ``stated`` beyond float noise.""" + return any(abs(c - s) > ADJUSTMENT_REPORT_TOL for c, s in zip(self.canonical, self.stated)) + + +def _fmt_xyz(xyz) -> str: + return "(" + ", ".join(f"{v:.6g}" for v in xyz) + ")" + + +def _fmt_exact(values, exact) -> str: + return "(" + ", ".join(str(e) if e is not None else f"{v:.6g}" for v, e in zip(values, exact)) + ")" + + +def _barycenter(x: np.ndarray, ops) -> np.ndarray: + """Mean of the stabilizer images of ``x``, each unwrapped next to ``x``. + + The barycenter of an orbit under a finite group is fixed by every element, + so this is the nearest point fixed by all of ``ops``. + """ + return x + np.mean([_wrap_symmetric(R @ x + t - x) for R, t in ops], axis=0) + + +def _axes(stab_rots) -> list[str]: + return _classify(sum(stab_rots) / len(stab_rots)) + + +def analyze_site(space_group: str, xyz) -> SiteAnalysis: + """Validate one site under the core schema rules and return its :class:`SiteAnalysis`. + + For every operation (centering expanded), the image distance ``d`` is + computed. ``d < SPECIAL_POSITION_TOL`` puts the operation in the stabilizer. + Any ``SPECIAL_POSITION_TOL <= d < AMBIGUOUS_BAND`` raises + :class:`SymmetryError`: the site is near a special position without being on + it (or is stated with too few decimals). The message names the special + position and its multiplicity. + + ``space_group`` must name its setting explicitly (two-origin and + rhombohedral groups, A62). + """ + x = np.asarray(xyz, dtype=float) + if x.shape != (3,) or not np.all(np.isfinite(x)): + raise SymmetryError("xyz must be a finite 3-vector") + ops = _expanded_ops(resolve_space_group(space_group, explicit_setting=True)) + dist = [float(np.max(np.abs(_wrap_symmetric(R @ x + t - x)))) for R, t in ops] + + ambiguous = [d for d in dist if SPECIAL_POSITION_TOL <= d < AMBIGUOUS_BAND] + if ambiguous: + near = [op for op, d in zip(ops, dist) if d < AMBIGUOUS_BAND] + target = _barycenter(x, near) + axes = _axes([R for R, _t in near]) + exact = [Fraction(float(v)).limit_denominator(_MAX_DENOMINATOR) if a == "FIXED" else None + for v, a in zip(target, axes)] + raise SymmetryError( + f"position {_fmt_xyz(x)} is {max(ambiguous):.2g} from the special position " + f"{_fmt_exact(target, exact)} (multiplicity {len(ops) // len(near)}) in " + f"{space_group!r} without being on it: state the special-position " + f"coordinates to at least 6 decimals, or move the atom at least " + f"{AMBIGUOUS_BAND:g} (fractional) off it" + ) + + stab = [op for op, d in zip(ops, dist) if d < SPECIAL_POSITION_TOL] + if not stab: # pragma: no cover - identity is always in the group + raise SymmetryError("empty stabilizer (should be impossible)") + axes = _axes([R for R, _t in stab]) + + canonical = _barycenter(x, stab) + exact: list[Fraction | None] = [] + for j in range(3): + if axes[j] != "FIXED": + exact.append(None) + continue + frac = Fraction(float(canonical[j])).limit_denominator(_MAX_DENOMINATOR) + if abs(float(frac) - canonical[j]) > 1e-9: # pragma: no cover - guards the 1/24 premise + raise SymmetryError( + f"fixed coordinate {canonical[j]!r} of {_fmt_xyz(x)} in {space_group!r} is not a " + f"fraction with denominator <= {_MAX_DENOMINATOR}" + ) + exact.append(frac) + canonical[j] = float(frac) + + # Consistency: the canonical point is fixed exactly by the whole stabilizer, + # and multiplicity x stabilizer order = group order. + residual = max(float(np.max(np.abs(_wrap_symmetric(R @ canonical + t - canonical)))) + for R, t in stab) + if residual > 1e-9 or len(ops) % len(stab): # pragma: no cover - internal invariant + raise SymmetryError( + f"inconsistent site analysis for {_fmt_xyz(x)} in {space_group!r} " + f"(residual {residual:.2g}, |G|={len(ops)}, |stabilizer|={len(stab)})" + ) + + return SiteAnalysis( + stated=(float(x[0]), float(x[1]), float(x[2])), + canonical=(float(canonical[0]), float(canonical[1]), float(canonical[2])), + exact=(exact[0], exact[1], exact[2]), + axes=(axes[0], axes[1], axes[2]), + adp=tuple(_classify(_adp_projector([R for R, _t in stab]))), + multiplicity=len(ops) // len(stab), + stabilizer_order=len(stab), + ) diff --git a/tests/test_symmetry_characterization.py b/tests/test_symmetry_characterization.py new file mode 100644 index 0000000..dc91bb7 --- /dev/null +++ b/tests/test_symmetry_characterization.py @@ -0,0 +1,177 @@ +"""Characterization: core site analysis vs GSAS-II, all 230 space groups (re/03 T5, A69). + +For every space group (two-origin groups in origin choice 2, rhombohedral groups +on hexagonal axes: the settings GSAS-II uses), many special and general +positions are analyzed by ``powderline.symmetry.analyze_site`` and by GSAS-II's +own ``SytSym`` / ``GetCSxinel`` / ``GetCSuinel``. They must agree on: + +- multiplicity; +- per-axis coordinate DOF (FIXED / FREE / COUPLED); +- per-component Uij DOF. + +The legacy ``site_dof`` / ``adp_dof`` (used by the 0.26.0 TOPAS writer) are held +to the same reference. GSAS-II is read only; nothing in it is changed. Skipped +where GSAS-II is not installed. A disagreement must be escalated, not +tolerated (A35). +""" + +from __future__ import annotations + +import json +import random +from collections import Counter +from pathlib import Path + +import numpy as np +import pytest + +G2spc = pytest.importorskip("GSASII.GSASIIspc") +gemmi = pytest.importorskip("gemmi") + +from powderline.exceptions import SymmetryError # noqa: E402 +from powderline.symmetry import _expanded_ops, adp_dof, analyze_site, site_dof # noqa: E402 + +EXAMPLES = Path(__file__).resolve().parents[1] / "examples" +_POINTS_PER_PATTERN = 2 # per space group: 12 patterns x this many draws + + +def _gemmi_group(number: int): + sg = gemmi.find_spacegroup_by_number(number) + if sg.ext == "1": # two-origin group: GSAS-II uses origin choice 2 + sg = gemmi.find_spacegroup_by_name(sg.hm + ":2") + return sg # rhombohedral groups default to ':H' in gemmi, as in GSAS-II + + +def _same_mod1(p, q, tol=1e-6) -> bool: + return bool(np.all(np.abs(((p - q) + 0.5) % 1.0 - 0.5) < tol)) + + +def _orbit(ops, x): + pts = [] + for R, t in ops: + y = (R @ x + t) % 1.0 + if not any(_same_mod1(y, p, 1e-8) for p in pts): + pts.append(y) + return pts + + +def _gsas_symbol(sg): + """A GSAS-II symbol for the same group *and setting*: the general-position orbits must match.""" + x = np.array([0.1234, 0.2345, 0.3456]) + ref = _orbit(_expanded_ops(sg), x) + parts = sg.hm.split() + candidates = [sg.hm, G2spc.StandardizeSpcName(sg.short_name())] + if len(parts) == 4 and parts[1] == "1" and parts[3] == "1": # 'P 1 21/c 1' -> 'P 21/c' + candidates.append(f"{parts[0]} {parts[2]}") + for cand in candidates: + err, sgdata = G2spc.SpcGroup(cand) + if err: + continue + theirs = [np.array(e[0]) % 1.0 for e in G2spc.GenAtom(x, sgdata, All=False)] + if len(theirs) == len(ref) and all(any(_same_mod1(p, q) for q in theirs) for p in ref): + return cand, sgdata + return None, None + + +def _gsas_classes(codes) -> tuple: + """GSAS-II constraint codes -> FIXED (0) / FREE (own group) / COUPLED (shared group).""" + groups = Counter(c for c in codes if c != 0) + return tuple("FIXED" if c == 0 else ("FREE" if groups[c] == 1 else "COUPLED") for c in codes) + + +def _positions(rng): + """Grid points (multiples of 1/24) in patterns that hit special positions, incl. coupled ones.""" + g = lambda: rng.randrange(24) / 24 # noqa: E731 + pts = [] + for _ in range(_POINTS_PER_PATTERN): + a, b, c = g(), g(), g() + pts += [(a, b, c), (a, a, c), (a, -a, c), (a, 2 * a, c), (2 * a, a, c), (a, a, a), + (a, a + 0.5, c), (a, a + 0.25, c), (a, c, c), (a, c, -c), (a, -a + 0.5, c), + (a, b, b + 0.25)] + return sorted({tuple(round(v % 1.0, 12) for v in p) for p in pts}) + + +@pytest.mark.parametrize("number", range(1, 231)) +def test_site_analysis_matches_gsasii(number): + sg = _gemmi_group(number) + name = sg.xhm() + symbol, sgdata = _gsas_symbol(sg) + assert symbol is not None, f"no GSAS-II symbol reproduces {name!r}" + + rng = random.Random(number) + disagreements = [] + for x in _positions(rng): + site = analyze_site(name, x) # exact grid points never fall in the ambiguous band + sitesym, mult = G2spc.SytSym(list(x), sgdata)[0:2] + ours = {"multiplicity": site.multiplicity, "legacy multiplicity": site_dof(name, x).orbit_size} + theirs = {"multiplicity": mult, "legacy multiplicity": mult} + try: + xyz = _gsas_classes(G2spc.GetCSxinel(sitesym)[0]) + uij = _gsas_classes(G2spc.GetCSuinel(sitesym)[0]) + except KeyError: + # GSAS-II could not name this site symmetry ('sp'), so it has no + # constraint table entry (seen once over all 230 groups: F432 24e). + # Multiplicity is still compared. + pass + else: + ours.update({"xyz": site.axes, "uij": site.adp, + "legacy xyz": site_dof(name, x).axes, + "legacy uij": adp_dof(name, x).components}) + theirs.update({"xyz": xyz, "uij": uij, "legacy xyz": xyz, "legacy uij": uij}) + for key in ours: + if tuple(np.atleast_1d(ours[key])) != tuple(np.atleast_1d(theirs[key])): + disagreements.append((x, sitesym, key, ours[key], theirs[key])) + assert not disagreements, f"{name} (GSAS-II {symbol!r}): {disagreements[:5]}" + + +@pytest.mark.parametrize("space_group, exact, rounded", [ + ("P 63/m m c", (1 / 3, 2 / 3, 0.25), (0.333333, 0.666667, 0.25)), + ("P 63/m m c", (1 / 6, 1 / 3, 0.25), (0.166667, 0.333333, 0.25)), + ("F d -3 m:2", (0.125, 0.125, 0.125), (0.125, 0.125, 0.125)), + ("R -3 m:H", (0.5, 0.0, 0.0), (0.5, 0.0, 0.0)), + ("F m -3 m", (0.0, 0.0, 0.0), (-1e-9, 1e-9, 0.0)), +]) +def test_canonical_coordinates_are_read_identically_by_gsasii(space_group, exact, rounded): + """6-decimal input is canonicalized; GSAS-II gets the same site from the canonical values. + + The last case is GSAS-II's cell-edge defect (it misreads values just below an + integer): the canonical exact 0 avoids it. + """ + site = analyze_site(space_group, rounded) + sg = gemmi.find_spacegroup_by_name(space_group) + _symbol, sgdata = _gsas_symbol(sg) + assert G2spc.SytSym(list(site.canonical), sgdata)[1] == site.multiplicity + assert G2spc.SytSym(list(exact), sgdata)[1] == site.multiplicity + exact_site = analyze_site(space_group, exact) + assert np.allclose(site.canonical, exact_site.canonical, atol=1e-12) + + +@pytest.mark.parametrize("space_group, xyz", [ + ("P 63/m m c", (0.3333, 0.6667, 0.25)), + ("P 63/m m c", (0.33333, 0.66667, 0.25)), + ("P 63/m m c", (0.333, 0.667, 0.25)), + ("F m -3 m", (1e-5, 0.0, 0.0)), + ("F d -3 m:2", (0.12501, 0.125, 0.125)), +]) +def test_ambiguous_band_is_rejected(space_group, xyz): + with pytest.raises(SymmetryError, match="without being on it"): + analyze_site(space_group, xyz) + + +def test_committed_examples_agree_with_gsasii(): + """Every atom of every committed example: same multiplicity from core and GSAS-II.""" + checked = 0 + for path in sorted(EXAMPLES.glob("*/input.json")): + if path.parent.name == "example_template": + continue + phases = (json.loads(path.read_text(encoding="utf-8")).get("payload") or {}).get("phases") or {} + for phase in phases.values(): + structure = phase["structure"] + sg = gemmi.find_spacegroup_by_name(structure["space_group"]) + _symbol, sgdata = _gsas_symbol(sg) + for atom in structure["atoms"].values(): + xyz = (atom["x"], atom["y"], atom["z"]) + site = analyze_site(sg.xhm(), xyz) + assert site.multiplicity == G2spc.SytSym(list(xyz), sgdata)[1] + checked += 1 + assert checked >= 20 From e3e1a774d7cc991cfa3d428ef501e1fcd611faac Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:29:05 -0400 Subject: [PATCH 024/259] feat(core): cell and Uij symmetry checks; least-change canonicalization (A77, A78) - check_cell(space_group, cell): the metric tensor must be invariant under every group rotation; compared with the group-averaged cell within CELL_TOL = 1e-9 (float noise only). Errors name each parameter and its symmetric value. Covers all crystal systems incl. monoclinic unique axes and rhombohedral :R. - check_uij(space_group, xyz, uij): U must be invariant under the site stabilizer (R U R^T, the GSAS-II convention). Within UIJ_TOL = 1e-6 A^2 the symmetric values are returned with adjusted=True; beyond that, SymmetryError. - Canonical coordinates and symmetric Uij use the least-change (orthogonal) projection onto the symmetric subspace, anchored at the stabilizer barycenter. The Reynolds average alone is oblique on hexagonal/trigonal axes and moved free components (e.g. U11 on 6h). Changes <= 1e-12 snap back to the stated value; SiteAnalysis gains `adp`. - tests/test_symmetry_core.py (core-only, no GSAS-II); the characterization canonicalization tests now assert exact values (the previous np.allclose silently allowed rtol=1e-5) and the coupled least-change result. Co-Authored-By: Claude Opus 5.5 --- src/powderline/symmetry.py | 110 ++++++++++- tests/test_symmetry_characterization.py | 39 ++-- tests/test_symmetry_core.py | 236 ++++++++++++++++++++++++ 3 files changed, 368 insertions(+), 17 deletions(-) create mode 100644 tests/test_symmetry_core.py diff --git a/src/powderline/symmetry.py b/src/powderline/symmetry.py index 0523e8a..6c15acf 100644 --- a/src/powderline/symmetry.py +++ b/src/powderline/symmetry.py @@ -364,7 +364,8 @@ class SiteAnalysis: stated: the coordinates as given. canonical: the coordinates every gateway uses -- equal to ``stated`` for a general position; on a special position, symmetry-fixed axes are - exact (see ``exact``) and coupled axes satisfy their relation. + exact (see ``exact``) and coupled axes satisfy their relation (to + floating-point precision), by the least change from ``stated``. exact: per axis, the exact rational value of a symmetry-fixed coordinate (``None`` for a free or coupled axis). axes: ``"FREE"`` / ``"FIXED"`` / ``"COUPLED"`` per axis. @@ -408,6 +409,19 @@ def _axes(stab_rots) -> list[str]: return _classify(sum(stab_rots) / len(stab_rots)) +def _orthogonal_projector(reynolds: np.ndarray) -> np.ndarray: + """Orthogonal projector onto the image of a (possibly oblique) Reynolds projector. + + The Reynolds average ``mean(R)`` projects onto the symmetric subspace, but not + orthogonally when the rotations are not orthogonal (hexagonal/trigonal axes). + The orthogonal projector gives the *least change* onto the same subspace, so + a free component stays as stated and only inconsistent ones move (A73, A78). + """ + u, sv, _vt = np.linalg.svd(reynolds) + basis = u[:, sv > 0.5] # a projector's singular values are ~1 on its image, 0 off it + return basis @ basis.T + + def analyze_site(space_group: str, xyz) -> SiteAnalysis: """Validate one site under the core schema rules and return its :class:`SiteAnalysis`. @@ -447,7 +461,11 @@ def analyze_site(space_group: str, xyz) -> SiteAnalysis: raise SymmetryError("empty stabilizer (should be impossible)") axes = _axes([R for R, _t in stab]) - canonical = _barycenter(x, stab) + # Least change onto the stabilizer's fixed set: anchor at a fixed point (the + # barycenter), then project the offset orthogonally onto the allowed directions. + anchor = _barycenter(x, stab) + canonical = anchor + _orthogonal_projector(sum(R for R, _t in stab) / len(stab)) @ (x - anchor) + canonical = np.where(np.abs(canonical - x) <= ADJUSTMENT_REPORT_TOL, x, canonical) # drop float noise exact: list[Fraction | None] = [] for j in range(3): if axes[j] != "FIXED": @@ -481,3 +499,91 @@ def analyze_site(space_group: str, xyz) -> SiteAnalysis: multiplicity=len(ops) // len(stab), stabilizer_order=len(stab), ) + + +# --- (e) cell and Uij consistency with symmetry (A76-A78) ------------------- + +#: Cell parameters must equal their symmetric values up to floating-point noise +#: (relative on lengths, degrees on angles): no adjustment, only an error (A77). +CELL_TOL = 1e-9 +#: Uij within this of their site-symmetric values (Angstrom^2) are set to those +#: values and reported; beyond it is an error (A78). Allows for values printed +#: to ~6 decimals breaking relations such as U12 = U22/2. +UIJ_TOL = 1e-6 + +_CELL_NAMES = ("a", "b", "c", "alpha", "beta", "gamma") + + +def _metric(cell) -> np.ndarray: + a, b, c, al, be, ga = cell + ca, cb, cg = (np.cos(np.radians(v)) for v in (al, be, ga)) + return np.array([[a * a, a * b * cg, a * c * cb], + [a * b * cg, b * b, b * c * ca], + [a * c * cb, b * c * ca, c * c]]) + + +def _cell_from_metric(g: np.ndarray) -> tuple[float, ...]: + a, b, c = np.sqrt(np.diag(g)) + al = np.degrees(np.arccos(np.clip(g[1, 2] / (b * c), -1.0, 1.0))) + be = np.degrees(np.arccos(np.clip(g[0, 2] / (a * c), -1.0, 1.0))) + ga = np.degrees(np.arccos(np.clip(g[0, 1] / (a * b), -1.0, 1.0))) + return tuple(float(v) for v in (a, b, c, al, be, ga)) + + +def check_cell(space_group: str, cell) -> tuple[float, ...]: + """Raise :class:`SymmetryError` unless ``cell`` (a, b, c, alpha, beta, gamma) fits the group. + + The cell's metric tensor must be invariant under every rotation of the + space group (``R^T G R = G``). The check compares the stated cell with the + cell of the group-averaged metric, within :data:`CELL_TOL`. Returns the + symmetric cell. Covers every crystal system, including monoclinic unique + axes and the rhombohedral ``:R`` setting. + """ + rots = [R for R, _t in _expanded_ops(resolve_space_group(space_group, explicit_setting=True))] + stated = tuple(float(v) for v in cell) + g = _metric(stated) + symmetric = _cell_from_metric(sum(R.T @ g @ R for R in rots) / len(rots)) + bad = [] + for name, v, s in zip(_CELL_NAMES, stated, symmetric): + off = abs(v - s) / s if name in ("a", "b", "c") else abs(v - s) + if off > CELL_TOL: + bad.append(f"{name} = {v:g} (symmetric value {s:.10g})") + if bad: + system = resolve_space_group(space_group, explicit_setting=True).crystal_system_str() + raise SymmetryError( + f"unit cell is inconsistent with {space_group!r} ({system}): " + "; ".join(bad) + + ". Symmetry-equivalent lengths must be equal and symmetry-fixed angles exact " + "(e.g. 90 or 120 degrees)" + ) + return symmetric + + +_UIJ_NAMES = ("U11", "U22", "U33", "U12", "U13", "U23") + + +def check_uij(space_group: str, xyz, uij) -> tuple[tuple[float, ...], bool]: + """Fit the anisotropic ADPs ``uij`` (U11, U22, U33, U12, U13, U23) to the site symmetry. + + ``U`` must be invariant under the site's stabilizer (``R U R^T = U``, the + convention GSAS-II uses). The site-symmetric tensor is the least-change + (orthogonal) projection of ``uij`` onto the invariant tensors. Components further than :data:`UIJ_TOL` from it raise + :class:`SymmetryError`; otherwise the symmetric values are returned, with a + flag saying whether any component changed (by more than 1e-12). + """ + site = analyze_site(space_group, xyz) + ops = _expanded_ops(resolve_space_group(space_group, explicit_setting=True)) + x = np.asarray(site.canonical) + stab = [R for R, t in ops if np.max(np.abs(_wrap_symmetric(R @ x + t - x))) < SPECIAL_POSITION_TOL] + stated = np.asarray(uij, dtype=float) + symmetric = _orthogonal_projector(_adp_projector(stab)) @ stated + symmetric = np.where(np.abs(symmetric - stated) <= ADJUSTMENT_REPORT_TOL, stated, symmetric) + bad = [f"{n} = {v:g} (site-symmetric value {s:.6g})" + for n, v, s in zip(_UIJ_NAMES, stated, symmetric) if abs(v - s) > UIJ_TOL] + if bad: + raise SymmetryError( + f"anisotropic ADPs break the site symmetry at {_fmt_xyz(x)} in {space_group!r}: " + + "; ".join(bad) + ) + if not np.any(np.abs(symmetric - stated) > ADJUSTMENT_REPORT_TOL): + return tuple(float(v) for v in stated), False + return tuple(float(v) for v in symmetric), True diff --git a/tests/test_symmetry_characterization.py b/tests/test_symmetry_characterization.py index dc91bb7..185b1b7 100644 --- a/tests/test_symmetry_characterization.py +++ b/tests/test_symmetry_characterization.py @@ -124,26 +124,35 @@ def test_site_analysis_matches_gsasii(number): assert not disagreements, f"{name} (GSAS-II {symbol!r}): {disagreements[:5]}" -@pytest.mark.parametrize("space_group, exact, rounded", [ - ("P 63/m m c", (1 / 3, 2 / 3, 0.25), (0.333333, 0.666667, 0.25)), - ("P 63/m m c", (1 / 6, 1 / 3, 0.25), (0.166667, 0.333333, 0.25)), +@pytest.mark.parametrize("space_group, rounded, expected", [ + # fully fixed sites: canonical == the exact special position + ("P 63/m m c", (0.333333, 0.666667, 0.25), (1 / 3, 2 / 3, 0.25)), ("F d -3 m:2", (0.125, 0.125, 0.125), (0.125, 0.125, 0.125)), ("R -3 m:H", (0.5, 0.0, 0.0), (0.5, 0.0, 0.0)), - ("F m -3 m", (0.0, 0.0, 0.0), (-1e-9, 1e-9, 0.0)), + # GSAS-II's cell-edge defect (misreads values just below an integer): the + # canonical exact 0 avoids it + ("F m -3 m", (-1e-9, 1e-9, 0.0), (0.0, 0.0, 0.0)), + # free axis kept as stated, fixed axes exact + ("P 63/m m c", (0.333333, 0.666667, 0.06), (1 / 3, 2 / 3, 0.06)), ]) -def test_canonical_coordinates_are_read_identically_by_gsasii(space_group, exact, rounded): - """6-decimal input is canonicalized; GSAS-II gets the same site from the canonical values. - - The last case is GSAS-II's cell-edge defect (it misreads values just below an - integer): the canonical exact 0 avoids it. - """ +def test_canonical_coordinates(space_group, rounded, expected): + """6-decimal input is canonicalized exactly; GSAS-II reads the same site from it.""" site = analyze_site(space_group, rounded) - sg = gemmi.find_spacegroup_by_name(space_group) - _symbol, sgdata = _gsas_symbol(sg) + assert site.canonical == expected + _symbol, sgdata = _gsas_symbol(gemmi.find_spacegroup_by_name(space_group)) assert G2spc.SytSym(list(site.canonical), sgdata)[1] == site.multiplicity - assert G2spc.SytSym(list(exact), sgdata)[1] == site.multiplicity - exact_site = analyze_site(space_group, exact) - assert np.allclose(site.canonical, exact_site.canonical, atol=1e-12) + + +def test_coupled_coordinates_canonicalized_by_least_change(): + """6h (x, 2x, 1/4): the relation is restored with the smallest change; z is exact.""" + site = analyze_site("P 63/m m c", (0.166667, 0.333333, 0.25)) + x, y, z = site.canonical + assert site.axes == ("COUPLED", "COUPLED", "FIXED") and site.adjusted + assert z == 0.25 and abs(y - 2 * x) < 1e-15 + # orthogonal projection onto (t, 2t): t = (x + 2y) / 5 + assert abs(x - (0.166667 + 2 * 0.333333) / 5) < 1e-15 + _symbol, sgdata = _gsas_symbol(gemmi.find_spacegroup_by_name("P 63/m m c")) + assert G2spc.SytSym(list(site.canonical), sgdata)[1] == site.multiplicity == 6 @pytest.mark.parametrize("space_group, xyz", [ diff --git a/tests/test_symmetry_core.py b/tests/test_symmetry_core.py new file mode 100644 index 0000000..3ebf199 --- /dev/null +++ b/tests/test_symmetry_core.py @@ -0,0 +1,236 @@ +"""Tests for powderline.symmetry core validation functions (check_cell, check_uij, analyze_site). + +Core-only: no GSAS-II needed; must run in a core-only environment. +""" +import pytest + +from powderline.exceptions import SymmetryError +from powderline.symmetry import check_cell, check_uij, analyze_site, SiteAnalysis +from fractions import Fraction + + +# --- check_cell ------------------------------------------------------------- + + +def test_check_cell_cubic_valid_returned(): + """check_cell: cubic P m -3 m (a=b=c, 90/90/90) returns symmetric cell.""" + sg = "P m -3 m" + cell = (4.15692, 4.15692, 4.15692, 90.0, 90.0, 90.0) + symmetric = check_cell(sg, cell) + assert len(symmetric) == 6 + assert abs(symmetric[0] - cell[0]) < 1e-12 + + +def test_check_cell_cubic_a_perturbed_rejected(): + """check_cell: cubic with b != a by 1e-6 relative rejected.""" + sg = "P m -3 m" + a = 4.15692 + cell = (a, a * (1 + 1e-6), a, 90.0, 90.0, 90.0) + with pytest.raises(SymmetryError, match="inconsistent"): + check_cell(sg, cell) + + +def test_check_cell_cubic_gamma_perturbed_rejected(): + """check_cell: cubic with gamma != 90 by 1e-6 degree rejected.""" + sg = "P m -3 m" + cell = (4.0, 4.0, 4.0, 90.0, 90.0, 90.0 + 1e-6) + with pytest.raises(SymmetryError, match="inconsistent"): + check_cell(sg, cell) + + +def test_check_cell_cubic_tiny_perturbation_accepted(): + """check_cell: cubic with perturbation below CELL_TOL (1e-12 relative) accepted.""" + sg = "P m -3 m" + a = 4.0 + cell = (a, a * (1 + 1e-13), a, 90.0, 90.0, 90.0) + symmetric = check_cell(sg, cell) + assert symmetric is not None + + +def test_check_cell_tetragonal_valid_returned(): + """check_cell: tetragonal I 41/a m d:2 (a=b, c, 90/90/90) returns symmetric cell.""" + sg = "I 41/a m d:2" + cell = (5.0, 5.0, 7.0, 90.0, 90.0, 90.0) + symmetric = check_cell(sg, cell) + assert abs(symmetric[0] - symmetric[1]) < 1e-12 + assert abs(symmetric[2] - 7.0) < 1e-12 + + +def test_check_cell_tetragonal_a_neq_b_rejected(): + """check_cell: tetragonal with a != b by 1e-6 relative rejected.""" + sg = "I 41/a m d:2" + cell = (5.0, 5.0 * (1 + 1e-6), 7.0, 90.0, 90.0, 90.0) + with pytest.raises(SymmetryError, match="inconsistent"): + check_cell(sg, cell) + + +def test_check_cell_hexagonal_valid_returned(): + """check_cell: hexagonal P 63/m m c (a=b, c, 90/90/120) returns symmetric cell.""" + sg = "P 63/m m c" + cell = (3.2, 3.2, 5.2, 90.0, 90.0, 120.0) + symmetric = check_cell(sg, cell) + assert abs(symmetric[0] - symmetric[1]) < 1e-12 + assert abs(symmetric[5] - 120.0) < 1e-12 + + +def test_check_cell_hexagonal_gamma_neq_120_rejected(): + """check_cell: hexagonal with gamma != 120 by 1e-6 degree rejected.""" + sg = "P 63/m m c" + cell = (3.2, 3.2, 5.2, 90.0, 90.0, 120.0 + 1e-6) + with pytest.raises(SymmetryError, match="inconsistent"): + check_cell(sg, cell) + + +def test_check_cell_monoclinic_valid_returned(): + """check_cell: monoclinic C 1 2/m 1 (a!=b!=c, 90/beta/90) returns symmetric cell.""" + sg = "C 1 2/m 1" + cell = (5.0, 6.0, 7.0, 90.0, 104.3, 90.0) + symmetric = check_cell(sg, cell) + assert abs(symmetric[4] - 104.3) < 1e-9 + + +def test_check_cell_monoclinic_alpha_neq_90_rejected(): + """check_cell: monoclinic with alpha != 90 by 1e-6 degree rejected.""" + sg = "C 1 2/m 1" + cell = (5.0, 6.0, 7.0, 90.0 + 1e-6, 104.3, 90.0) + with pytest.raises(SymmetryError, match="inconsistent"): + check_cell(sg, cell) + + +def test_check_cell_triclinic_valid_returned(): + """check_cell: triclinic P 1 (all free) returns cell unchanged.""" + sg = "P 1" + cell = (5.0, 6.0, 7.0, 80.0, 85.0, 95.0) + symmetric = check_cell(sg, cell) + for i in range(6): + assert abs(symmetric[i] - cell[i]) < 1e-12 + + +def test_check_cell_rhombohedral_r_setting_valid_returned(): + """check_cell: rhombohedral R -3 m:R (a=b=c, alpha=beta=gamma!=90) returns symmetric cell.""" + sg = "R -3 m:R" + alpha = 60.0 + cell = (5.0, 5.0, 5.0, alpha, alpha, alpha) + symmetric = check_cell(sg, cell) + assert abs(symmetric[0] - symmetric[1]) < 1e-12 + assert abs(symmetric[1] - symmetric[2]) < 1e-12 + assert abs(symmetric[3] - symmetric[4]) < 1e-12 + assert abs(symmetric[4] - symmetric[5]) < 1e-12 + + +def test_check_cell_rhombohedral_r_setting_angle_perturbed_rejected(): + """check_cell: rhombohedral R -3 m:R with alpha != beta by 1e-6 degree rejected.""" + sg = "R -3 m:R" + cell = (5.0, 5.0, 5.0, 60.0, 60.0 + 1e-6, 60.0) + with pytest.raises(SymmetryError, match="inconsistent"): + check_cell(sg, cell) + + +# --- check_uij -------------------------------------------------------------- + + +def test_check_uij_identity_unchanged(): + """check_uij: conforming tensor returned unchanged, adjusted=False.""" + sg = "P m -3 m" + xyz = (0.0, 0.0, 0.0) + # Cubic m-3m: U11=U22=U33, off-diag 0 + uij = (0.01, 0.01, 0.01, 0.0, 0.0, 0.0) + symmetric, adjusted = check_uij(sg, xyz, uij) + assert adjusted is False + for i in range(6): + assert abs(symmetric[i] - uij[i]) < 1e-15 + + +def test_check_uij_adjusted_within_tol(): + """check_uij: tensor within UIJ_TOL adjusted, adjusted=True.""" + sg = "P 63/m m c" + xyz = (0.2, 0.4, 0.25) + # Site 6h: U11 free, U22 free, U33 free, U12 = U22/2, U13=U23=0 + # State U12 slightly off from U22/2 by < UIJ_TOL + uij = (0.012, 0.024, 0.02, 0.012 + 5e-7, 0.0, 0.0) + symmetric, adjusted = check_uij(sg, xyz, uij) + assert adjusted is True + # Check U12 became exactly U22/2 + assert abs(symmetric[3] - symmetric[1] / 2) < 1e-15 + + +def test_check_uij_beyond_tol_raises(): + """check_uij: tensor beyond UIJ_TOL raises SymmetryError.""" + sg = "P m -3 m" + xyz = (0.0, 0.0, 0.0) + # Cubic m-3m: U11=U22=U33; state U11 != U22 by > UIJ_TOL + uij = (0.01, 0.02, 0.01, 0.0, 0.0, 0.0) + with pytest.raises(SymmetryError, match="break the site symmetry"): + check_uij(sg, xyz, uij) + + +def test_check_uij_general_position_unchanged(): + """check_uij: general position in P 1 accepts any tensor unchanged.""" + sg = "P 1" + xyz = (0.123, 0.456, 0.789) + uij = (0.01, 0.02, 0.03, 0.005, 0.007, 0.009) + symmetric, adjusted = check_uij(sg, xyz, uij) + assert adjusted is False + for i in range(6): + assert abs(symmetric[i] - uij[i]) < 1e-15 + + +# --- analyze_site ----------------------------------------------------------- + + +def test_analyze_site_general_position_multiplicity(): + """analyze_site: P m -3 m general position -> multiplicity 48 (number of operations).""" + sg = "P m -3 m" + xyz = (0.123, 0.456, 0.789) + site = analyze_site(sg, xyz) + assert site.multiplicity == 48 + + +def test_analyze_site_adjusted_false_for_exact(): + """analyze_site: exact input -> adjusted=False.""" + sg = "P m -3 m" + xyz = (0.0, 0.0, 0.0) + site = analyze_site(sg, xyz) + assert site.adjusted is False + + +def test_analyze_site_exact_fractions(): + """analyze_site: fixed coordinates in `exact` as Fraction(1, 3) etc.""" + sg = "P 63/m m c" + xyz = (0.333333, 0.666667, 0.25) + site = analyze_site(sg, xyz) + # Check exact contains Fraction(1, 3), Fraction(2, 3), Fraction(1, 4) + assert site.exact[0] == Fraction(1, 3) + assert site.exact[1] == Fraction(2, 3) + assert site.exact[2] == Fraction(1, 4) + + +def test_analyze_site_explicit_setting_required(): + """analyze_site: 'F d -3 m' without :1/:2 raises SymmetryError.""" + xyz = (0.125, 0.125, 0.125) + with pytest.raises(SymmetryError, match="two origin choices"): + analyze_site("F d -3 m", xyz) + + +def test_analyze_site_non_finite_raises(): + """analyze_site: non-finite xyz raises SymmetryError.""" + sg = "P 1" + xyz = (float("nan"), 0.0, 0.0) + with pytest.raises(SymmetryError, match="must be a finite 3-vector"): + analyze_site(sg, xyz) + + +def test_analyze_site_cubic_origin_multiplicity_1(): + """analyze_site: P m -3 m origin (0,0,0) -> multiplicity 1.""" + sg = "P m -3 m" + xyz = (0.0, 0.0, 0.0) + site = analyze_site(sg, xyz) + assert site.multiplicity == 1 + + +def test_analyze_site_hexagonal_6h_multiplicity_6(): + """analyze_site: P 63/m m c (0.2,0.4,0.25) -> multiplicity 6 (site 6h).""" + sg = "P 63/m m c" + xyz = (0.2, 0.4, 0.25) + site = analyze_site(sg, xyz) + assert site.multiplicity == 6 From d39f254ffce6c68189634e0bc8ff892f2d88feeb Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:28:48 -0400 Subject: [PATCH 025/259] feat(core): schema_core phase structure: UnitCell, Atom, PhaseStructure (A35, A62-A63, A69, A73-A78) PhaseStructure validates the structure once, in core: - explicit space-group setting (A62); - cell lengths > 0, angles in (0, 180), no volume (A75), cell consistent with the group (A77); - exact bare element symbols (A63); - occupancy 0..1 (A76); - ADP 'Uiso' with Uiso or 'Uaniso' with all six Uij, Uij consistent with the site symmetry, adjusted within 1e-6 A^2 (A78); - per-atom analyze_site: ambiguous band = error, stated Multiplicity cross-checked (A69), special-position coordinates replaced by their exact canonical values (A73). Every adjustment becomes a StructuredWarning (special_position_adjusted / adp_symmetry_adjusted, field_path relative to the structure), available from warnings(). The site analyses are available from site(label). All atom problems are reported together in one error. Co-Authored-By: Claude Opus 5.5 --- src/powderline/schema_core.py | 187 +++++++++++++++- tests/test_schema_core.py | 407 ++++++++++++++++++++++++++++++++++ 2 files changed, 593 insertions(+), 1 deletion(-) diff --git a/src/powderline/schema_core.py b/src/powderline/schema_core.py index 567d3cf..76e1e0e 100644 --- a/src/powderline/schema_core.py +++ b/src/powderline/schema_core.py @@ -21,7 +21,7 @@ import json import math -from typing import Any, Optional +from typing import Any, Literal, Optional import gemmi import numpy as np @@ -31,12 +31,16 @@ BaseModel, ConfigDict, Field, + PrivateAttr, StrictBool, field_validator, model_serializer, model_validator, ) +from powderline.exceptions import StructuredWarning, SymmetryError +from powderline.symmetry import analyze_site, check_cell, check_uij, resolve_space_group + # --- versions (A40, A65) --------------------------------------------------- #: The core schema version new recipes are written against. @@ -458,6 +462,187 @@ def validate_coefficients_length(cls, v, info): return v +# --- phase structure (A32, A35, A62, A63, A69, A73) ------------------------- + + +class UnitCell(BaseModel): + """Cell constants (values, not refinables). No ``volume``: every engine + derives it from a..gamma (A74).""" + + model_config = _STRICT + + a: float = Field(json_schema_extra=_unit(UNIT_ANGSTROM)) + b: float = Field(json_schema_extra=_unit(UNIT_ANGSTROM)) + c: float = Field(json_schema_extra=_unit(UNIT_ANGSTROM)) + alpha: float = Field(json_schema_extra=_unit(UNIT_DEGREE)) + beta: float = Field(json_schema_extra=_unit(UNIT_DEGREE)) + gamma: float = Field(json_schema_extra=_unit(UNIT_DEGREE)) + + @field_validator("a", "b", "c") + @classmethod + def _length(cls, v, info): + if not (math.isfinite(v) and v > 0): + raise ValueError(f"cell length {info.field_name} must be positive, got {v}") + return v + + @field_validator("alpha", "beta", "gamma") + @classmethod + def _angle(cls, v, info): + if not (math.isfinite(v) and 0 < v < 180): + raise ValueError(f"cell angle {info.field_name} must be between 0 and 180 degrees, got {v}") + return v + + +_UANISO_KEYS = ("U11", "U22", "U33", "U12", "U13", "U23") + + +class Atom(BaseModel): + """One atom of a phase structure (values, not refinables). + + Coordinates are fractional JSON numbers. A special position is declared by + stating it to at least 6 decimals. The validated phase holds canonical + (exact) coordinates and reports every adjustment (A73). ``Multiplicity`` is + optional and, when stated, must match the derived value (A69 T3). + ``occupancy`` is 0 to 1 inclusive, even where an engine would accept more + (A76). ``Uaniso`` must respect the site symmetry: within 1e-6 A^2 it is set + to the symmetric values and reported, beyond that it is an error (A78). + """ + + model_config = _STRICT + + element: str = Field(description="Bare element symbol, exactly as in the periodic table (e.g. 'Fe')") + x: float = Field(description="Fractional x coordinate") + y: float = Field(description="Fractional y coordinate") + z: float = Field(description="Fractional z coordinate") + occupancy: float = Field(default=1.0, ge=0.0, le=1.0, description="Site occupancy, 0 to 1 inclusive (A76)") + Multiplicity: Optional[int] = Field(default=None, description="Site multiplicity; cross-checked when stated") + ADP: Literal["Uiso", "Uaniso"] = Field(description="Displacement-parameter type") + Uiso: Optional[float] = Field(default=None, json_schema_extra=_unit(UNIT_ANGSTROM2)) + Uaniso: Optional[dict[Literal["U11", "U22", "U33", "U12", "U13", "U23"], float]] = Field( + default=None, json_schema_extra=_unit(UNIT_ANGSTROM2), + description="All six of U11, U22, U33, U12, U13, U23") + + @field_validator("element") + @classmethod + def _element(cls, v: str) -> str: + return check_element_symbol(v) + + @field_validator("x", "y", "z", "occupancy", "Uiso") + @classmethod + def _finite(cls, v, info): + return _finite(info.field_name, v) + + @field_validator("Uaniso") + @classmethod + def _uaniso_finite(cls, v): + if v is not None: + for k, u in v.items(): + _finite(k, u) + return v + + @model_validator(mode="after") + def _adp_block(self) -> "Atom": + if self.ADP == "Uiso": + if self.Uiso is None: + raise ValueError("ADP 'Uiso' requires a Uiso value") + if self.Uaniso is not None: + raise ValueError("ADP 'Uiso' must not also give Uaniso") + else: + if self.Uaniso is None or set(self.Uaniso) != set(_UANISO_KEYS): + raise ValueError(f"ADP 'Uaniso' requires all of {', '.join(_UANISO_KEYS)}") + if self.Uiso is not None: + raise ValueError("ADP 'Uaniso' must not also give Uiso") + return self + + +class PhaseStructure(BaseModel): + """A phase's crystal structure: space group, cell, atoms (core-owned, A35). + + Validation derives each atom's site (multiplicity, DOF) from the space group + (:func:`powderline.symmetry.analyze_site`). It rejects ambiguous positions + and stated multiplicities that don't match. It replaces stated coordinates + with the canonical ones, so every engine receives the same exact structure. + Each adjustment is reported by :meth:`warnings` (A73). The unit cell must + fit the space group exactly (A77), and anisotropic ADPs the site symmetry + (A78). + """ + + model_config = _STRICT + + phase_name: str = Field(min_length=1) + space_group: str = Field(description="Hermann-Mauguin symbol with an explicit setting " + "for two-origin (':1'/':2') and rhombohedral (':H'/':R') groups") + unit_cell: UnitCell + atoms: dict[str, Atom] = Field(min_length=1, description="Atoms keyed by unique label") + + _sites: dict = PrivateAttr(default_factory=dict) + _warnings: list = PrivateAttr(default_factory=list) + + @field_validator("space_group") + @classmethod + def _space_group(cls, v: str) -> str: + resolve_space_group(v, explicit_setting=True) # SymmetryError is a ValueError + return v + + @model_validator(mode="after") + def _sites_check(self) -> "PhaseStructure": + problems: list[str] = [] + cell = self.unit_cell + try: + check_cell(self.space_group, (cell.a, cell.b, cell.c, cell.alpha, cell.beta, cell.gamma)) + except SymmetryError as exc: + problems.append(str(exc)) + for label, atom in self.atoms.items(): + try: + site = analyze_site(self.space_group, (atom.x, atom.y, atom.z)) + except SymmetryError as exc: + problems.append(f"atom {label!r}: {exc}") + continue + if atom.Multiplicity is not None and atom.Multiplicity != site.multiplicity: + problems.append( + f"atom {label!r}: stated Multiplicity {atom.Multiplicity}, derived " + f"{site.multiplicity} ({self.space_group!r}, site {site.stated})" + ) + continue + if atom.Uaniso is not None: + stated_u = tuple(atom.Uaniso[k] for k in _UANISO_KEYS) + try: + symmetric_u, u_adjusted = check_uij(self.space_group, site.canonical, stated_u) + except SymmetryError as exc: + problems.append(f"atom {label!r}: {exc}") + continue + if u_adjusted: + atom.Uaniso = dict(zip(_UANISO_KEYS, symmetric_u)) + self._warnings.append(StructuredWarning( + code="adp_symmetry_adjusted", + message=(f"atom {label!r}: Uaniso {dict(zip(_UANISO_KEYS, stated_u))} adjusted to " + f"the site-symmetric values {atom.Uaniso}"), + field_path=f"atoms.{label}.Uaniso", + )) + self._sites[label] = site + if site.adjusted: + atom.x, atom.y, atom.z = site.canonical + self._warnings.append(StructuredWarning( + code="special_position_adjusted", + message=(f"atom {label!r}: coordinates {site.stated} are on a special position " + f"(multiplicity {site.multiplicity}); using the exact values " + f"{site.canonical}"), + field_path=f"atoms.{label}", + )) + if problems: + raise ValueError("; ".join(problems)) + return self + + def site(self, label: str): + """The :class:`~powderline.symmetry.SiteAnalysis` of atom ``label``.""" + return self._sites[label] + + def warnings(self) -> list: + """Structured warnings raised while validating this structure (paths relative to it).""" + return list(self._warnings) + + + # --- top-level recipe frame (A1, A18, A21, A40) ------------------------------ diff --git a/tests/test_schema_core.py b/tests/test_schema_core.py index dfec521..bd49812 100644 --- a/tests/test_schema_core.py +++ b/tests/test_schema_core.py @@ -901,3 +901,410 @@ def test_charged_types_rejected_not_stripped(symbol): def test_unknown_element_rejected(symbol): with pytest.raises(ValueError, match="not a known element symbol"): check_element_symbol(symbol) + + +# --- phase structure --- + +import pytest # noqa: E402 +from fractions import Fraction # noqa: E402 +from pydantic import ValidationError # noqa: E402 + +from powderline.schema_core import UnitCell, Atom, PhaseStructure # noqa: E402 +from powderline.exceptions import SymmetryError # noqa: E402 + + +def _valid_pmm_lab6_phase_dict(): + """Helper: valid P m -3 m LaB6-like phase (cubic a=4.15692, La at origin, B at 0.5,0.5,0.2021).""" + return { + "phase_name": "LaB6", + "space_group": "P m -3 m", + "unit_cell": { + "a": 4.15692, + "b": 4.15692, + "c": 4.15692, + "alpha": 90.0, + "beta": 90.0, + "gamma": 90.0, + }, + "atoms": { + "La1": { + "element": "La", + "x": 0.0, + "y": 0.0, + "z": 0.0, + "occupancy": 1.0, + "ADP": "Uiso", + "Uiso": 0.005, + }, + "B1": { + "element": "B", + "x": 0.5, + "y": 0.5, + "z": 0.2021, + "occupancy": 1.0, + "ADP": "Uiso", + "Uiso": 0.006, + }, + }, + } + + +def test_phase_structure_valid_validates(): + """Valid phase validates with no warnings.""" + phase = PhaseStructure.model_validate(_valid_pmm_lab6_phase_dict()) + assert phase.warnings() == [] + + +def test_phase_structure_site_multiplicity(): + """Site multiplicity: La (origin) -> 1, B (0.5,0.5,0.2021) -> 6 in P m -3 m.""" + phase = PhaseStructure.model_validate(_valid_pmm_lab6_phase_dict()) + assert phase.site("La1").multiplicity == 1 + assert phase.site("B1").multiplicity == 6 + + +def test_unit_cell_length_zero_rejected(): + """UnitCell: a=0 rejected.""" + with pytest.raises(ValidationError, match="must be positive"): + UnitCell(a=0.0, b=4.0, c=4.0, alpha=90, beta=90, gamma=90) + + +def test_unit_cell_length_negative_rejected(): + """UnitCell: b=-1 rejected.""" + with pytest.raises(ValidationError, match="must be positive"): + UnitCell(a=4.0, b=-1.0, c=4.0, alpha=90, beta=90, gamma=90) + + +def test_unit_cell_length_non_finite_rejected(): + """UnitCell: c=nan rejected.""" + with pytest.raises(ValidationError, match="must be positive"): + UnitCell(a=4.0, b=4.0, c=float("nan"), alpha=90, beta=90, gamma=90) + + +def test_unit_cell_angle_zero_rejected(): + """UnitCell: alpha=0 rejected.""" + with pytest.raises(ValidationError, match="must be between 0 and 180"): + UnitCell(a=4.0, b=4.0, c=4.0, alpha=0.0, beta=90, gamma=90) + + +def test_unit_cell_angle_180_rejected(): + """UnitCell: beta=180 rejected.""" + with pytest.raises(ValidationError, match="must be between 0 and 180"): + UnitCell(a=4.0, b=4.0, c=4.0, alpha=90, beta=180.0, gamma=90) + + +def test_unit_cell_angle_above_180_rejected(): + """UnitCell: gamma=181 rejected.""" + with pytest.raises(ValidationError, match="must be between 0 and 180"): + UnitCell(a=4.0, b=4.0, c=4.0, alpha=90, beta=90, gamma=181.0) + + +def test_unit_cell_angle_non_finite_rejected(): + """UnitCell: alpha=inf rejected.""" + with pytest.raises(ValidationError, match="must be between 0 and 180"): + UnitCell(a=4.0, b=4.0, c=4.0, alpha=float("inf"), beta=90, gamma=90) + + +def test_unit_cell_extra_key_rejected(): + """UnitCell: 'volume' key rejected (extra='forbid').""" + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + UnitCell(a=4.0, b=4.0, c=4.0, alpha=90, beta=90, gamma=90, volume=64.0) + + +def test_atom_element_uppercase_rejected_with_suggestion(): + """Atom: 'FE' -> message suggests 'Fe'.""" + with pytest.raises(ValidationError, match="write the element symbol as 'Fe'"): + Atom(element="FE", x=0.0, y=0.0, z=0.0, ADP="Uiso", Uiso=0.01) + + +def test_atom_element_charged_rejected(): + """Atom: 'Fe3+' rejected as charged.""" + with pytest.raises(ValidationError, match="charged scattering types are not supported"): + Atom(element="Fe3+", x=0.0, y=0.0, z=0.0, ADP="Uiso", Uiso=0.01) + + +def test_atom_occupancy_zero_accepted(): + """Atom: occupancy=0 accepted.""" + atom = Atom(element="Fe", x=0.0, y=0.0, z=0.0, occupancy=0.0, ADP="Uiso", Uiso=0.01) + assert atom.occupancy == 0.0 + + +def test_atom_occupancy_one_accepted(): + """Atom: occupancy=1 accepted.""" + atom = Atom(element="Fe", x=0.0, y=0.0, z=0.0, occupancy=1.0, ADP="Uiso", Uiso=0.01) + assert atom.occupancy == 1.0 + + +def test_atom_occupancy_negative_rejected(): + """Atom: occupancy=-0.01 rejected.""" + with pytest.raises(ValidationError, match="greater than or equal to 0"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, occupancy=-0.01, ADP="Uiso", Uiso=0.01) + + +def test_atom_occupancy_above_one_rejected(): + """Atom: occupancy=1.01 rejected.""" + with pytest.raises(ValidationError, match="less than or equal to 1"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, occupancy=1.01, ADP="Uiso", Uiso=0.01) + + +def test_atom_adp_uiso_without_value_rejected(): + """Atom: ADP='Uiso' without Uiso rejected.""" + with pytest.raises(ValidationError, match="requires a Uiso value"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, ADP="Uiso") + + +def test_atom_adp_uiso_with_uaniso_rejected(): + """Atom: ADP='Uiso' with Uaniso also given rejected.""" + with pytest.raises(ValidationError, match="must not also give Uaniso"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, ADP="Uiso", Uiso=0.01, + Uaniso={"U11": 0.01, "U22": 0.01, "U33": 0.01, "U12": 0, "U13": 0, "U23": 0}) + + +def test_atom_adp_uaniso_missing_component_rejected(): + """Atom: ADP='Uaniso' missing U23 rejected.""" + with pytest.raises(ValidationError, match="requires all of U11"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, ADP="Uaniso", + Uaniso={"U11": 0.01, "U22": 0.01, "U33": 0.01, "U12": 0, "U13": 0}) + + +def test_atom_adp_uaniso_unknown_key_rejected(): + """Atom: ADP='Uaniso' with U14 rejected.""" + with pytest.raises(ValidationError, match="Input should be"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, ADP="Uaniso", + Uaniso={"U11": 0.01, "U22": 0.01, "U33": 0.01, "U12": 0, "U13": 0, "U23": 0, "U14": 0}) + + +def test_atom_adp_uaniso_with_uiso_rejected(): + """Atom: ADP='Uaniso' with Uiso also given rejected.""" + with pytest.raises(ValidationError, match="must not also give Uiso"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, ADP="Uaniso", Uiso=0.01, + Uaniso={"U11": 0.01, "U22": 0.01, "U33": 0.01, "U12": 0, "U13": 0, "U23": 0}) + + +def test_atom_adp_wrong_value_rejected(): + """Atom: ADP='Uaniso' but only Uiso given rejected.""" + with pytest.raises(ValidationError, match="requires all of U11"): + Atom(element="Fe", x=0.0, y=0.0, z=0.0, ADP="Uaniso", Uiso=0.01) + + +def test_atom_xyz_non_finite_rejected(): + """Atom: x=nan rejected.""" + with pytest.raises(ValidationError, match="must be finite"): + Atom(element="Fe", x=float("nan"), y=0.0, z=0.0, ADP="Uiso", Uiso=0.01) + + +def test_phase_structure_space_group_no_origin_rejected(): + """PhaseStructure: 'F d -3 m' (no :1/:2) rejected.""" + d = _valid_pmm_lab6_phase_dict() + d["space_group"] = "F d -3 m" + with pytest.raises(ValidationError, match="two origin choices"): + PhaseStructure.model_validate(d) + + +def test_phase_structure_space_group_no_rhombohedral_setting_rejected(): + """PhaseStructure: 'R -3 m' (no :H/:R) rejected.""" + d = _valid_pmm_lab6_phase_dict() + d["space_group"] = "R -3 m" + with pytest.raises(ValidationError, match="rhombohedral"): + PhaseStructure.model_validate(d) + + +def test_phase_structure_space_group_fd3m_origin2_accepted(): + """PhaseStructure: 'F d -3 m:2' (cubic) accepted.""" + d = _valid_pmm_lab6_phase_dict() + d["space_group"] = "F d -3 m:2" + # Adjust cell to cubic (already is in the helper, but be explicit) + d["unit_cell"] = {"a": 8.0, "b": 8.0, "c": 8.0, "alpha": 90, "beta": 90, "gamma": 90} + # Put an atom at a general position to avoid special-position complications + d["atoms"] = { + "A1": {"element": "O", "x": 0.125, "y": 0.125, "z": 0.125, "ADP": "Uiso", "Uiso": 0.01} + } + phase = PhaseStructure.model_validate(d) + assert phase.space_group == "F d -3 m:2" + + +def test_phase_structure_space_group_r3m_hexagonal_accepted(): + """PhaseStructure: 'R -3 m:H' (hexagonal a=b, gamma=120) accepted.""" + d = { + "phase_name": "test", + "space_group": "R -3 m:H", + "unit_cell": {"a": 3.2, "b": 3.2, "c": 5.0, "alpha": 90, "beta": 90, "gamma": 120}, + "atoms": { + "A1": {"element": "O", "x": 0.2, "y": 0.4, "z": 0.1, "ADP": "Uiso", "Uiso": 0.01} + }, + } + phase = PhaseStructure.model_validate(d) + assert phase.space_group == "R -3 m:H" + + +def test_phase_structure_special_position_adjusted(): + """PhaseStructure: P 63/m m c atom at (0.333333,0.666667,0.25) adjusted to 1/3,2/3,1/4.""" + d = { + "phase_name": "test", + "space_group": "P 63/m m c", + "unit_cell": {"a": 3.2, "b": 3.2, "c": 5.2, "alpha": 90, "beta": 90, "gamma": 120}, + "atoms": { + "A1": {"element": "O", "x": 0.333333, "y": 0.666667, "z": 0.25, "ADP": "Uiso", "Uiso": 0.01} + }, + } + phase = PhaseStructure.model_validate(d) + # Check coordinates are exact fractions + assert abs(phase.atoms["A1"].x - 1/3) < 1e-15 + assert abs(phase.atoms["A1"].y - 2/3) < 1e-15 + # Check warning + warnings = phase.warnings() + assert len(warnings) == 1 + assert warnings[0]["code"] == "special_position_adjusted" + assert "A1" in warnings[0]["message"] + assert warnings[0]["field_path"] == "atoms.A1" + + +def test_phase_structure_special_position_ambiguous_rejected(): + """PhaseStructure: atom at (0.3333,0.6667,0.25) in P 63/m m c rejected (ambiguous).""" + d = { + "phase_name": "test", + "space_group": "P 63/m m c", + "unit_cell": {"a": 3.2, "b": 3.2, "c": 5.2, "alpha": 90, "beta": 90, "gamma": 120}, + "atoms": { + "A1": {"element": "O", "x": 0.3333, "y": 0.6667, "z": 0.25, "ADP": "Uiso", "Uiso": 0.01} + }, + } + with pytest.raises(ValidationError, match="without being on it") as exc_info: + PhaseStructure.model_validate(d) + # Check that the atom label appears in the error + assert "A1" in str(exc_info.value) + + +def test_phase_structure_multiplicity_match_accepted(): + """PhaseStructure: stated Multiplicity equal to derived accepted.""" + d = _valid_pmm_lab6_phase_dict() + d["atoms"]["La1"]["Multiplicity"] = 1 + d["atoms"]["B1"]["Multiplicity"] = 6 + phase = PhaseStructure.model_validate(d) + assert phase.site("La1").multiplicity == 1 + assert phase.site("B1").multiplicity == 6 + + +def test_phase_structure_multiplicity_mismatch_rejected(): + """PhaseStructure: stated Multiplicity != derived rejected.""" + d = _valid_pmm_lab6_phase_dict() + d["atoms"]["B1"]["Multiplicity"] = 12 # should be 6 + with pytest.raises(ValidationError) as exc_info: + PhaseStructure.model_validate(d) + msg = str(exc_info.value) + assert "stated Multiplicity" in msg + assert "derived" in msg + + +def test_phase_structure_cell_cubic_b_neq_a_rejected(): + """PhaseStructure: cubic with b != a rejected.""" + d = _valid_pmm_lab6_phase_dict() + d["unit_cell"]["b"] = 4.2 + with pytest.raises(ValidationError) as exc_info: + PhaseStructure.model_validate(d) + msg = str(exc_info.value) + assert "b" in msg.lower() + assert "inconsistent" in msg.lower() + + +def test_phase_structure_cell_cubic_gamma_91_rejected(): + """PhaseStructure: cubic with gamma=91 rejected.""" + d = _valid_pmm_lab6_phase_dict() + d["unit_cell"]["gamma"] = 91.0 + with pytest.raises(ValidationError, match="inconsistent"): + PhaseStructure.model_validate(d) + + +def test_phase_structure_cell_hexagonal_gamma_90_rejected(): + """PhaseStructure: hexagonal with gamma=90 rejected.""" + d = { + "phase_name": "test", + "space_group": "P 63/m m c", + "unit_cell": {"a": 3.2, "b": 3.2, "c": 5.2, "alpha": 90, "beta": 90, "gamma": 90}, + "atoms": { + "A1": {"element": "O", "x": 0.2, "y": 0.4, "z": 0.1, "ADP": "Uiso", "Uiso": 0.01} + }, + } + with pytest.raises(ValidationError, match="inconsistent"): + PhaseStructure.model_validate(d) + + +def test_phase_structure_cell_monoclinic_accepted(): + """PhaseStructure: valid monoclinic C 1 2/m 1 with beta=104.3 accepted.""" + d = { + "phase_name": "test", + "space_group": "C 1 2/m 1", + "unit_cell": {"a": 5.0, "b": 6.0, "c": 7.0, "alpha": 90, "beta": 104.3, "gamma": 90}, + "atoms": { + "A1": {"element": "O", "x": 0.2, "y": 0.0, "z": 0.1, "ADP": "Uiso", "Uiso": 0.01} + }, + } + phase = PhaseStructure.model_validate(d) + assert phase.space_group == "C 1 2/m 1" + + +def test_phase_structure_uaniso_cubic_m3m_isotropic_accepted(): + """PhaseStructure: La at (0,0,0) in P m -3 m with isotropic Uaniso (U11=U22=U33, off-diag 0) accepted.""" + d = _valid_pmm_lab6_phase_dict() + d["atoms"]["La1"]["ADP"] = "Uaniso" + d["atoms"]["La1"]["Uaniso"] = {"U11": 0.01, "U22": 0.01, "U33": 0.01, "U12": 0, "U13": 0, "U23": 0} + del d["atoms"]["La1"]["Uiso"] + phase = PhaseStructure.model_validate(d) + assert phase.warnings() == [] + + +def test_phase_structure_uaniso_cubic_m3m_anisotropic_rejected(): + """PhaseStructure: La at (0,0,0) in P m -3 m with U11!=U22 rejected (breaks symmetry).""" + d = _valid_pmm_lab6_phase_dict() + d["atoms"]["La1"]["ADP"] = "Uaniso" + d["atoms"]["La1"]["Uaniso"] = {"U11": 0.01, "U22": 0.02, "U33": 0.01, "U12": 0, "U13": 0, "U23": 0} + del d["atoms"]["La1"]["Uiso"] + with pytest.raises(ValidationError, match="break the site symmetry"): + PhaseStructure.model_validate(d) + + +def test_phase_structure_uaniso_hexagonal_6h_adjusted(): + """PhaseStructure: P 63/m m c, site 6h, Uaniso with U11=U22/2 adjusted and reported.""" + d = { + "phase_name": "test", + "space_group": "P 63/m m c", + "unit_cell": {"a": 3.2, "b": 3.2, "c": 5.2, "alpha": 90, "beta": 90, "gamma": 120}, + "atoms": { + "A1": { + "element": "O", + "x": 0.2, + "y": 0.4, + "z": 0.25, + "ADP": "Uaniso", + "Uaniso": { + "U11": 0.012, + "U22": 0.012347, + "U33": 0.02, + "U12": 0.006174, + "U13": 0.0, + "U23": 0.0, + }, + } + }, + } + phase = PhaseStructure.model_validate(d) + # Check U11 stayed + assert abs(phase.atoms["A1"].Uaniso["U11"] - 0.012) < 1e-15 + # Check U12 became U22/2 + u22 = phase.atoms["A1"].Uaniso["U22"] + u12 = phase.atoms["A1"].Uaniso["U12"] + assert abs(u12 - u22 / 2) < 1e-15 + # Check warning + warnings = phase.warnings() + assert any(w["code"] == "adp_symmetry_adjusted" for w in warnings) + + +def test_phase_structure_multiple_atom_problems_all_reported(): + """PhaseStructure: two atoms with wrong Multiplicity -> both labels appear in one error.""" + d = _valid_pmm_lab6_phase_dict() + d["atoms"]["La1"]["Multiplicity"] = 2 + d["atoms"]["B1"]["Multiplicity"] = 12 + with pytest.raises(ValidationError) as exc_info: + PhaseStructure.model_validate(d) + msg = str(exc_info.value) + assert "La1" in msg + assert "B1" in msg From 69a40f85a0a036601eca13d85a1eb34151cb564f Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:28:48 -0400 Subject: [PATCH 026/259] docs(SCHEMA_HISTORY): core 1.0.0 phase-structure rules for recipe builders Co-Authored-By: Claude Opus 5.5 --- docs/SCHEMA_HISTORY.md | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/docs/SCHEMA_HISTORY.md b/docs/SCHEMA_HISTORY.md index 449da94..f0f4173 100644 --- a/docs/SCHEMA_HISTORY.md +++ b/docs/SCHEMA_HISTORY.md @@ -40,8 +40,37 @@ engine schemas adopt it in re/04–06. - **Units** are fixed per field in the schema, never written in a recipe. - **Accepted core versions** (this release): `==1.0.0`. -Phase structure and symmetry validation (space-group setting, element symbols, -special positions) are documented here when they land. +- **Phase structure** (`PhaseStructure`): `phase_name`, `space_group`, + `unit_cell`, `atoms` (keyed by label). Structural interpretation is checked + once, in core, so every engine gets the same structure: + - **Space group**: a Hermann–Mauguin symbol. Two-origin groups need an explicit + `:1`/`:2` and rhombohedral groups `:H`/`:R` (e.g. `"F d -3 m:2"`, + `"R -3 m:H"`). Individual engines may accept fewer settings. + - **Unit cell**: `a`, `b`, `c` (Å, > 0), `alpha`, `beta`, `gamma` (degrees, + 0–180). No `volume` (every engine derives it). The cell must fit the + space group **exactly** (to floating-point precision): e.g. cubic + `a = b = c` and all angles 90°. A mismatch is an error naming each + parameter and its symmetric value. (GSAS-II alone would silently apply the + symmetry only when the cell is refined.) + - **Elements**: a bare element symbol spelled exactly (`"Fe"`, not `"FE"`). + Charged scattering types (`"Fe3+"`) are not supported yet and are rejected, + never reduced to the neutral atom. + - **Occupancy**: 0 to 1 inclusive, even where an engine would accept more. + - **Special positions**: an atom whose symmetry images lie within 5e-6 + (fractional) of itself is on a special position, so write special + coordinates with **at least 6 decimals** (e.g. `0.333333`). An atom 5e-6 to + 2e-3 from a special position is an **error** (`0.33`, `0.3333`, `0.33333`): + state it to ≥ 6 decimals or move it off. Accepted special positions are + replaced by their **exact** coordinates (fixed coordinates become the exact + fraction; coupled ones satisfy their relation, by the smallest change). Each + adjustment is reported as a structured warning, and these exact values are + what every engine receives. + - **Multiplicity**: optional; when stated it must equal the multiplicity + derived from the space group. + - **ADPs**: `ADP` is `"Uiso"` (with `Uiso`, Ų) or `"Uaniso"` (with all of + `U11 U22 U33 U12 U13 U23`, Ų). Anisotropic ADPs must respect the site + symmetry: within 1e-6 Ų they are set to the symmetric values and reported; + beyond that it is an error. ## gsasii engine schema From 8f7991fa01bceefc5bdc68bb19a010167129f92b Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Tue, 6 Oct 2026 14:46:51 -0400 Subject: [PATCH 027/259] fix(core): PhaseStructure reports every structural problem at its own location (A70) Review of PR #3 (S2, F1, N2): - All of an atom's problems are reported: a wrong Multiplicity no longer skips that atom's Uaniso check. - Each problem is a separate pydantic error at its field: unit_cell, atoms.