From 1cdd263d022650240fff6005760bf21013f2c70f Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:18:21 -0400 Subject: [PATCH 1/6] docs: add recipe-building guide and supported-features page PowderLine deliberately ships no recipe builder. Document why, what a recipe contains, where to start (template, nine examples, Materials Project), how to validate, and what validation does not catch. Add a helper page with a small I/O module (CIF, .instprm, pattern -> recipe sections) and an LLM prompt template, adapted from the v0.1.0 tester bundle and updated for the current code. Both are explicitly non-authoritative guidance. Add a per-engine supported-features page listing what is not yet supported, and link both pages from the README and Quickstart. Assisted-by: claude-code:claude-opus-5-5 --- README.md | 8 + docs/building-recipes.md | 225 +++++++++++++++ docs/capabilities.md | 100 +++++++ docs/index.rst | 2 + docs/quickstart.md | 2 + docs/recipe-helpers.md | 582 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 919 insertions(+) create mode 100644 docs/building-recipes.md create mode 100644 docs/capabilities.md create mode 100644 docs/recipe-helpers.md diff --git a/README.md b/README.md index ed83665..e6fcb34 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,10 @@ Results are written next to the recipe in `examples/example_LaB6/output/`: > `examples/example_template/` is a fill-in-the-blanks skeleton, not a runnable > recipe — copy it to start your own. +**Bringing your own CIF, instrument, and data files?** PowderLine has no +built-in recipe builder; see [Building Recipes](docs/building-recipes.md) for +starting points, validation, and helper code you can adapt. + ## 3. Ways to use PowderLine **Command line** — run or validate a recipe: @@ -191,6 +195,10 @@ request access). - **[Quickstart](docs/quickstart.md)** — clone → install → run → read the output. - **[Getting Started](docs/getting-started.rst)** — full recipe structure, output files, and the Python API. +- **[Building Recipes](docs/building-recipes.md)** — writing and validating your + own recipes, with helper code and an LLM prompt template. +- **[Supported Features](docs/capabilities.md)** — what a recipe can describe, + per engine, and what is not yet supported. - **[Troubleshooting](docs/TROUBLESHOOTING.md)** — common errors and fixes. - **[Schema History](docs/SCHEMA_HISTORY.md)** — recipe-schema changelog (current: **0.26.0**) and migration guidance. diff --git a/docs/building-recipes.md b/docs/building-recipes.md new file mode 100644 index 0000000..441ba32 --- /dev/null +++ b/docs/building-recipes.md @@ -0,0 +1,225 @@ +# Building Recipes + +A PowderLine recipe is a single, self-contained JSON (or YAML) document that +describes one refinement: the diffraction data, the instrument, the phases, and +which parameters to refine. PowderLine reads no other files — the data arrays, +instrument parameters, and crystal structures are all embedded in the recipe. + +```{toctree} +:hidden: + +recipe-helpers +``` + +## Why PowderLine has no recipe builder + +PowderLine deliberately does **not** ship a recipe builder. Recipes are +constructed in many different ways — from GUIs, from scripts, through +interfaces to databases such as Materials Project, or with an LLM assistant — +and any one built-in builder would make choices (defaults, file formats, what +to refine first) that restrict the others. PowderLine instead defines the +recipe format precisely and checks it strictly, and gives you: + +- a [blank template](#starting-points) and nine worked examples to copy; +- a [Materials Project builder](#from-materials-project) for simulated patterns; +- [validation](#validating-a-recipe) that names the missing or malformed field; +- [helper code and an LLM prompt template](recipe-helpers.md) for turning a CIF, + a GSAS-II `.instprm` file, and a diffraction pattern into a recipe. These are + guidance to adapt, not an authoritative builder. + +What a recipe can express — and what it cannot yet — is summarized in +[Supported Features](capabilities.md). + +## What a recipe contains + +Every recipe has three top-level keys: + +| Key | Value | +|---|---| +| `schema_name` | `"GSASII_Rietveld"` (structure-based refinement) or `"GSASII_SPF"` (single-peak fitting, no structure) | +| `schema_version` | `"0.26.0"` — must match the installed PowderLine exactly | +| `payload` | Everything else, in the sections below | + +The `payload` sections: + +| Section | Required | Holds | +|---|---|---| +| `xrd_data` | always | `tth` (2θ, degrees, strictly increasing), `Itth` (intensity), `Itth_weights` (1/σ²), optional `filename` | +| `refinement_controls` | always | `refinement_cycles` (default 5; `1` means simulation mode), and for SPF `single_peak_fitting_mode` | +| `instrument` | Rietveld and SPF | `description`, `initialization` (GSAS-II instrument parameters: exactly two dicts, the second `{}`), optional `parameterization` (what to refine) | +| `phases` | Rietveld only (forbidden for SPF) | One entry per phase, keyed by phase name: `structure` (starting model) and `parameterization` (what to refine) | +| `single_peaks` | SPF only | Parallel lists of peak positions, intensities, and widths | +| `background` | optional | `chebyshev` polynomial and/or `single_peaks` (background peaks) | +| `fit_range` | optional | `[min_2theta, max_2theta]` in degrees | + +### Refinable parameters + +Every refinable value is a four-element list: + +```json +[4.15682, true, null, null] +``` + +The elements are `[value, refine_flag, min, max]`: + +- **`value`** — the starting value. `null` keeps the value already set in the + `structure` or `initialization` block or, where nothing is set there, the + engine's default. +- **`refine_flag`** — `true` refines the parameter; `false` (or leaving the + parameter out of `parameterization` entirely) holds it fixed. +- **`min` / `max`** — accepted by the schema, but ignored by the GSAS-II and + TOPAS engines; only easydiffraction uses them, as fit bounds. Leave them + `null` unless you need them. + +Symmetry-linked parameters refine as a group: for a cubic cell, flagging any of +`a`, `b`, `c` refines all three together, and the same holds for coordinates +tied by site symmetry. Flags on symmetry-fixed parameters (e.g. cubic angles) +have no effect. See [Schema History](SCHEMA_HISTORY.md) for the full 0.26.0 +refine-flag semantics. + +### Units + +PowderLine uses GSAS-II conventions throughout: + +| Quantity | Unit | +|---|---| +| 2θ, `fit_range`, peak positions, instrument `Zero` | degrees | +| Wavelength (`Lam`), cell lengths | Å | +| Cell angles | degrees | +| Instrument `U`, `V`, `W` | centidegrees² | +| Instrument `X`, `Y`, `Z` | centidegrees | +| Isotropic crystallite size | µm | +| Isotropic strain | microstrain (Δd/d × 10⁻⁶) | +| `Uiso`, `U11`…`U23` | Ų | +| Data weights | 1/σ² | + +For the complete list of fields, see the `powderline.schema` models in the +[API Reference](api.rst). + +## Starting points + +### Copy the template or an example + +`examples/example_template/` is a fill-in-the-blanks skeleton covering every +section of a Rietveld recipe. It is not runnable as-is: `pixi run kicker` refuses +any recipe whose path contains `template`, so rename the directory when you +copy it. + +The nine worked examples are complete recipes with real data, each with a +`DESCRIPTION.md` and (except `example_LaB6_easydiff`) committed reference +output: + +| Example | Type | What it shows | +|---|---|---| +| `example_LaB6` | Rietveld | Instrument calibration on a LaB6 standard: phase scale, Chebyshev background, one background peak, and instrument profile U–Z | +| `example_LaB6_simulation` | Rietveld (simulation) | Calculating a pattern with every flag off and `refinement_cycles: 1` | +| `example_LaB6_singlepeakfit` | SPF | Fitting individual peaks without a crystal structure | +| `example_LaB6_easydiff` | Rietveld | The LaB6 recipe adapted to the easydiffraction engine: no background peak, `Z` fixed, lattice parameter refined | +| `example_DRX_33` | Rietveld | Two phases (cubic and monoclinic): scales, lattice parameters, isotropic size and strain with Lorentzian/Gaussian mixing, background | +| `example_DRX_33_atomrefine` | Rietveld | Adds atom coordinates, occupancies, and Uiso | +| `example_DRX_33_anisoADP` | Rietveld | Anisotropic displacement parameters (U11–U23) | +| `example_DRX_33_strainonly` | Rietveld | The same data with strain-only peak broadening | +| `example_DRX_33_simulation` | Rietveld (simulation) | A two-phase calculated pattern | + +The usual workflow is to copy the example closest to your case and replace its +data, structure, and flags. + +### From Materials Project + +`pixi run mp-simulate` fetches a structure from Materials Project, builds a +simulation recipe for it, and calculates the pattern. Add `--keep-recipe` to +keep the generated recipe JSON as a starting point; to refine against your +own data, replace its `xrd_data` and instrument and turn on the flags you need +(see [Simulating Patterns from Materials Project](mp-simulation.md)). From +Python, `SimulationRecipeBuilder().build_recipe_from_mp_structure(...)` (in +`powderline.simulation_builder`) builds the same recipe from the structure +returned by `MPInterface(api_key=...).get_structure(material_id)` (in +`powderline.mp_interface`). + +### From your own files + +To build a recipe from a CIF, a GSAS-II `.instprm` file, and a data file, see +[Recipe Helper Code and LLM Prompt](recipe-helpers.md). + +### YAML recipes + +`powderline.load_recipe_asset(path)` and `pixi run kicker` also read recipes +written in YAML (`.yaml`, `.yml`, or `.txt`), which can be easier to write by +hand. The structure is identical. + +## Validating a recipe + +Validate before you run. Each check reports the location of the problem: + +```bash +pixi run kicker --validate-only my_recipe.json # schema + simulation-mode checks +pixi run topas-kicker --validate-only my_recipe.json # can the recipe be translated to TOPAS? +``` + +From Python: + +```python +import powderline + +powderline.validate(recipe) # schema + simulation-mode checks + +# Also check that a specific engine can translate the recipe, without running it: +powderline.run(recipe, "output", engine="easydiffraction", validate_only=True) +``` + +`powderline.validate` raises `pydantic.ValidationError` for schema problems, +`ValueError` for a simulation-mode recipe with a refine flag set, and +`NotImplementedError` for a peak-broadening model that is not implemented yet. +A `ValidationError` lists each problem with its path in the recipe, for +example: + +```text +2 validation errors for RecipeModel +payload.xrd_data + Value error, XRD 'tth' must be strictly increasing; tth[5]=0.6584157943757244 <= tth[4]=0.6621325357184655. Sort/deduplicate the pattern upstream. +payload.phases.LaB6.parameterization.unit_cell.a.3 + Field required [type=missing, input_value=[4.15682, True, None], input_type=list] +``` + +Here the data arrays are out of order, and the `a` parameter has three +elements instead of four. + +If your tool cannot install GSAS-II, validate against the schema alone with +`powderline.schema.RecipeModel.model_validate(recipe)` (see the schema-only +track in [Using PowderLine in Other Projects](integration-guide.md)). This runs +the same schema checks as `powderline.validate`, without the simulation-mode +check. + +### What validation does not catch + +Passing validation means the recipe is well-formed, not that it describes the +model you intended. Keep the following in mind: + +- **Unknown keys are ignored, not rejected.** A misspelled section + (`"backgound"`) or a feature PowderLine does not have + (`"preferred_orientation"`) passes validation and is silently skipped. Check + key names against the examples or the schema reference. +- **Some errors appear only at run time.** Validation accepts these, and the + run then fails — not always with a clear message: + - an `initialization` dict with no `Type` entry; + - an `instrument.parameterization` block without both `broadening` and + `corrections` (each may contain only `null` entries); + - an atom with `ADP: "Uaniso"` but no `Uaniso` values; + - a phase key that differs from its `structure.phase_name`; + - an unknown key under `instrument.parameterization.broadening` or + `corrections`; + - a two-wavelength (Kα₁/Kα₂, `Lam1`/`Lam2`) instrument. +- **Simulation-mode checks are incomplete.** A flagged `polarization`, or + flagged SPF `single_peaks`, is not caught when `refinement_cycles` is 1. +- **Unset size and strain fall back to engine defaults, and the engines + differ.** GSAS-II uses 1 µm and 1000 microstrain; TOPAS uses 10 µm and 0. + Set `peak_broadening` explicitly if you compare engines. +- **Symmetry is your responsibility.** A fixed cell that breaks its space + group's symmetry (for example, a cubic phase with `a ≠ b`) is used as given + ([KI-01](known_issues.md)). For space groups with two origin choices, + GSAS-II assumes origin choice 2, and PowderLine cannot check that your + coordinates match ([KI-07](known_issues.md)). +- **Engines support different features.** A recipe valid for GSAS-II may be + rejected by easydiffraction or only partly translated by TOPAS; run + `validate_only=True` with the engine you plan to use, and see + [Supported Features](capabilities.md). diff --git a/docs/capabilities.md b/docs/capabilities.md new file mode 100644 index 0000000..337a057 --- /dev/null +++ b/docs/capabilities.md @@ -0,0 +1,100 @@ +# Supported Features + +This page summarizes what a PowderLine recipe can describe and which engines +can run it, and lists common refinement features that are **not yet +supported**. It reflects **PowderLine 0.1.2 / recipe schema 0.26.0**; check +[Schema History](SCHEMA_HISTORY.md) for changes in later versions. For how to +write the corresponding recipe fields, see [Building Recipes](building-recipes.md). + +## Supported + +✓ = supported (refinable where applicable). "Fixed only" = the value is used +but cannot be refined; flagging it for refinement is rejected with an error. +"Ignored" = the engine runs the recipe without this feature. + +### Workflows and data + +| Feature | GSAS-II (default) | TOPAS v7 | easydiffraction | +|---|---|---|---| +| Rietveld refinement (`GSASII_Rietveld`) | ✓ | ✓ | ✓ | +| Single-peak fitting (`GSASII_SPF`) | ✓ | ✓, except `use_instrument_profile: true` | Not supported | +| Simulation mode (`refinement_cycles: 1`, no flags) | ✓ | ✓ (relative intensities only) | ✓ | +| Multiple phases | ✓ | ✓ | ✓ | +| Constant-wavelength X-ray data on a 2θ axis, single wavelength | ✓ | ✓ | ✓ | +| Data weights (`Itth_weights`), `fit_range` | ✓ | ✓ | ✓ | + +The TOPAS engine also requires a Rietveld recipe to include an +`instrument.parameterization` block (it may be empty). + +### Instrument + +| Parameter | GSAS-II | TOPAS v7 | easydiffraction | +|---|---|---|---| +| Wavelength | ✓ | ✓ | ✓ | +| Profile `U`, `V`, `W`, `X`, `Y` | ✓ | ✓ | ✓ | +| Profile `Z` | ✓ | ✓ | Fixed `Z` ignored; refining rejected | +| Zero shift | ✓ | Ignored (not refined, no warning) | ✓, but see note below | +| Axial divergence (`SH/L`) | ✓ | Ignored (no axial model) | Fixed only | +| Polarization | ✓ | Fixed `LP_Factor(90)`; refine flag ignored | Fixed only | + +**Note on zero shift with easydiffraction:** the easydiffraction engine +currently converts the zero shift as if it were in centidegrees, but GSAS-II +(and the recipe) give it in degrees. A nonzero starting zero shift is +therefore passed to easydiffraction 100× too small, and a refined value is +reported 100× too large. Check zero-shift results from this engine against +GSAS-II. + +### Background + +| Feature | GSAS-II | TOPAS v7 | easydiffraction | +|---|---|---|---| +| Chebyshev polynomial | ✓ | ✓ | ✓ | +| Background peaks (`background.single_peaks`) | ✓ | ✓ | Ignored; refining positions or intensities is rejected | + +### Phases + +| Parameter | GSAS-II | TOPAS v7 | easydiffraction | +|---|---|---|---| +| Phase scale | ✓ | ✓ | ✓ | +| Unit cell, with symmetry-linked parameters refined together | ✓ | ✓ | ✓ | +| Atom coordinates, occupancies, Uiso | ✓ | ✓ | Fixed only | +| Anisotropic displacement (`U11`…`U23`) | ✓ | ✓ | Fixed values ignored; refining rejected | +| Isotropic crystallite size and microstrain, with Lorentzian/Gaussian mixing (`LG_eta`) | ✓ | ✓ | Ignored, with a warning (also when flagged) | + +Intensity is scaled through each phase's `scale`; the histogram scale is +fixed at 1. + +**Peak fitting alongside a structure.** A Rietveld recipe can fit individual +peaks together with the structural model through background peaks +(`background.single_peaks`) — for example, an impurity or unindexed peak. +`examples/example_LaB6` refines one background peak this way. + +## Not yet supported + +The following are not yet supported by any engine. Unless noted, a recipe +cannot express them; unknown keys are ignored rather than rejected, so +adding a field for one of these features will not make it take effect. + +- **Pawley and Le Bail fitting** (whole-pattern fitting with unconstrained + reflection intensities). For structure-free fitting, use single-peak fitting + (`GSASII_SPF`). +- **Anisotropic peak broadening:** uniaxial or ellipsoidal crystallite size, + and uniaxial or generalized (Stephens) microstrain. The schema names these + models, but validation raises `NotImplementedError` if you select one. +- **Sample corrections:** preferred orientation, absorption, sample + displacement, extinction, and surface roughness. +- **User-defined constraints, restraints, and rigid bodies** (for example, + tying two sites' occupancies together, or restraining bond lengths). + Symmetry constraints are applied automatically. +- **Parameter limits.** The `min`/`max` entries are ignored by GSAS-II and + TOPAS; only easydiffraction uses them, as fit bounds. +- **Kα₁/Kα₂ doublets** and other multi-wavelength sources. +- **Other radiation and geometries:** neutron, time-of-flight, and + energy-dispersive data. Data on a Q or d-spacing axis must be converted to 2θ + before it goes in the recipe. +- **More than one pattern per recipe:** joint refinement of several + histograms, and sequential refinement that carries results into the next + recipe ([KI-04](known_issues.md)). +- **Choice of minimization algorithm.** `refinement_controls.refinement_algorithm` + is reserved and currently unused. +- **Magnetic structures.** diff --git a/docs/index.rst b/docs/index.rst index 92b7853..b2b1e82 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -19,6 +19,8 @@ fresh clone to a finished refinement, on Linux or Windows. quickstart getting-started + building-recipes + capabilities integration-guide mp-simulation TROUBLESHOOTING diff --git a/docs/quickstart.md b/docs/quickstart.md index f3ab4f9..609f147 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -73,6 +73,8 @@ This is the fastest way to confirm your own recipe is valid before a full run. - Copy an example directory (e.g. `examples/example_LaB6/`) and edit its `input.json` — replace the `xrd_data`, structure, and refinement flags with your own. `examples/example_template/` is a blank skeleton to start from. +- Starting from your own CIF, instrument, and data files? See + [Building Recipes](building-recipes.md). - Send results elsewhere with `--output DIR`. - See more detail in each example's `DESCRIPTION.md`. diff --git a/docs/recipe-helpers.md b/docs/recipe-helpers.md new file mode 100644 index 0000000..6c42205 --- /dev/null +++ b/docs/recipe-helpers.md @@ -0,0 +1,582 @@ +# Recipe Helper Code and LLM Prompt + +This page holds two **helpers** for building recipes from your own files: a +small Python module that reads a CIF, a GSAS-II `.instprm` file, and a +diffraction pattern into recipe-shaped dicts, and a prompt template you can +hand to an LLM coding assistant to drive that module. + +> **These are guidance, not an authoritative recipe builder.** PowderLine does +> not ship a recipe builder (see [Building Recipes](building-recipes.md) for +> why). The code below is not part of the `powderline` package, is not covered +> by its tests, and makes choices — default values, which flags start on — +> that may not suit your data. Read it, adapt it, and check every recipe it +> produces. A recipe that passes validation can still describe the wrong model. + +## The I/O helper module + +Copy the code block below into a file named `io_helpers.py` next to your data +(or anywhere on your `PYTHONPATH`). It needs only `numpy` and `gemmi`, both of +which are installed with PowderLine, so it runs inside PowderLine's pixi +environment (`pixi shell` from your PowderLine clone) or any environment where +PowderLine is installed. + +| Function | Reads / builds | Recipe section | +|---|---|---| +| `read_cif(path, phase_name=None)` | a CIF → `(structure, warnings)` | `phases..structure` | +| `phase_block(structure)` | the structure plus a parameterization with every flag `False` | `phases` | +| `merge_phases(*blocks)` | several phases, rejecting duplicate names | `phases` | +| `read_instprm(path)` | a GSAS-II `.instprm` file → flat dict | — | +| `instrument_block(flat, description, refine_profile=False)` | the instrument section | `instrument` | +| `read_pattern(path, x_unit="2theta", wavelength=None)` | a 2- or 3-column pattern → `(xrd_data, warnings)` | `xrd_data` | +| `assemble_recipe(...)` | the full `{schema_name, schema_version, payload}` | — | +| `save_recipe(recipe, path)` | JSON file for `pixi run kicker` | — | + +A minimal Rietveld recipe: + +```python +import io_helpers as io +import powderline + +structure, cif_warnings = io.read_cif("LaB6.cif", phase_name="LaB6") +phases = io.phase_block(structure) # every refine flag starts False +instrument = io.instrument_block(io.read_instprm("my_beamline.instprm"), + "my beamline", refine_profile=True) +xrd_data, data_warnings = io.read_pattern("LaB6.xye") +for w in cif_warnings + data_warnings: + print("WARNING:", w) + +# Choose what to refine +p = phases["LaB6"]["parameterization"] +p["scale"][1] = True +p["unit_cell"]["a"][1] = True + +recipe = io.assemble_recipe( + xrd_data=xrd_data, + instrument=instrument, + phases=phases, + background={"chebyshev": {"num_coefficients": 6, + "coefficients": [10, 5, 1, 0, 0, 0], + "refine_flag": True}}, + fit_range=[1.0, 15.0], +) +powderline.validate(recipe) +io.save_recipe(recipe, "recipe.json") # then: pixi run kicker recipe.json +``` + +For a multi-phase recipe, read each CIF with its own `phase_name` and combine +the blocks with `io.merge_phases(...)`. For single-peak fitting, simulation +mode, and engine-specific limits, see the `assemble_recipe` docstring and +[Supported Features](capabilities.md). + +```python +"""io_helpers.py -- example code for turning a CIF, a GSAS-II .instprm file, and a +diffraction pattern into a PowderLine recipe. + +This module is NOT part of PowderLine and is not an authoritative recipe builder. +It is guidance: copy it, read it, and adapt it to your data. It was written +against recipe schema 0.26.0 (PowderLine 0.1.2); check the PowderLine docs if +your version differs. + +Requirements: numpy and gemmi (both installed with PowderLine). PowderLine +itself is only needed for the final ``powderline.validate`` / ``powderline.run``. + +Every builder function returns plain dicts in the recipe's shape and sets every +refine flag to False -- you decide what to refine. Readers return +``(result, warnings)``: print the warnings and check them. Problems that would +silently produce a wrong model (no space group, an unknown element, an atom +without coordinates) raise ``ValueError`` instead of being defaulted. +""" + +from __future__ import annotations + +import json +import math +import re +from pathlib import Path + +import gemmi +import numpy as np + +SCHEMA_VERSION = "0.26.0" # must equal PowderLine's EXPECTED_SCHEMA_VERSION exactly + +DEFAULT_SIZE_UM = 10.0 # isotropic crystallite size, microns (GSAS-II convention) +DEFAULT_MICROSTRAIN = 0.0 # isotropic microstrain (x 10^-6) +EIGHT_PI_SQ = 8.0 * math.pi**2 # B = 8 pi^2 U +U_KEYS = ("U11", "U22", "U33", "U12", "U13", "U23") + + +def _fixed(value): + """A recipe leaf ``[value, refine_flag, min, max]``, held fixed.""" + return [value, False, None, None] + + +def _phase_key(name: str) -> str: + """Recipe phase names: whitespace runs become underscores.""" + return re.sub(r"\s+", "_", name.strip()) + + +# -- CIF -> phase --------------------------------------------------------------- + + +def _values(block, tag): + """Values of a CIF tag (looped or single) as raw strings, or None if absent.""" + col = block.find_values(tag) + return [col[i] for i in range(len(col))] if len(col) else None + + +def _number(raw): + """CIF number with its s.u. stripped ("1.234(5)" -> 1.234); None for '?' / '.'.""" + if raw is None: + return None + value = gemmi.cif.as_number(raw) + return None if math.isnan(value) else value + + +def _element(raw): + """Element symbol from a type symbol or label ("O2-" -> "O", "La1" -> "La"), or None.""" + text = gemmi.cif.as_string(raw).strip() + for size in (2, 1): + symbol = text[:size] + if re.fullmatch(r"[A-Z][a-z]?", symbol) and gemmi.Element(symbol).name != "X": + return symbol + return None + + +def read_cif(path, phase_name=None): + """Read the first CIF data block that has a cell and atom sites. + + Returns ``(structure, warnings)``, where ``structure`` is the recipe's + ``phases..structure`` block:: + + {"phase_name", "space_group", "unit_cell": {a, b, c, alpha, beta, gamma, volume}, + "atoms": {label: {element, x, y, z, occupancy, ADP, Uiso [, Uaniso]}}} + + Raises ``ValueError`` for a missing/unknown space group, an incomplete cell, + missing coordinates, or an element that cannot be identified. Missing + occupancies (-> 1.0) and missing Uiso/Biso (-> 0.0) are defaulted, with a + warning. B values are converted to U (U = B / 8 pi^2). Ionic type symbols + ("O2-") are reduced to the neutral element. ``Multiplicity`` is not written; + PowderLine derives it from the space group. + """ + raw = Path(path).read_bytes() + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + text = raw.decode("latin-1") # many real CIFs are latin-1 / cp1252 + doc = gemmi.cif.read_string(text) + block = next( + (b for b in doc if b.find_value("_cell_length_a") and len(b.find_values("_atom_site_fract_x"))), + None, + ) + if block is None: + raise ValueError(f"{path}: no data block with both a unit cell and atom sites") + warnings = [] + + # Phase name + name = phase_name + if not name: + for tag in ("_pd_phase_name", "_chemical_name_common", "_chemical_formula_sum"): + value = block.find_value(tag) + if value and gemmi.cif.as_string(value).strip() not in ("", "?", "."): + name = gemmi.cif.as_string(value) + break + if not name: + raise ValueError(f"{path}: CIF has no phase name; pass phase_name=...") + name = _phase_key(name) + + # Space group: the symbol as written, checked with gemmi; else the IT number + symbol = None + for tag in ("_space_group_name_H-M_alt", "_symmetry_space_group_name_H-M"): + value = block.find_value(tag) + if value and gemmi.cif.as_string(value).strip() not in ("", "?", "."): + symbol = gemmi.cif.as_string(value).strip() + break + if symbol: + sg = gemmi.find_spacegroup_by_name(symbol) + if sg is None: + raise ValueError(f"{path}: space group symbol {symbol!r} not recognized") + else: + number = None + for tag in ("_space_group_IT_number", "_symmetry_Int_Tables_number"): + number = _number(block.find_value(tag)) or number + if not number: + raise ValueError(f"{path}: no space group symbol or number; refusing to guess") + sg = gemmi.find_spacegroup_by_number(int(number)) + symbol = sg.hm + warnings.append(f"space group taken from IT number {int(number)} as {symbol!r}; check the setting") + if sg.ext in ("1", "2"): + warnings.append( + f"space group {symbol!r} has two origin choices: GSAS-II assumes origin choice 2 and " + "the TOPAS engine needs it written out (e.g. 'F d -3 m:2'); check that the CIF " + "coordinates use origin choice 2" + ) + elif sg.ext in ("H", "R"): + warnings.append( + f"rhombohedral space group {symbol!r}: use hexagonal axes (gamma = 120); " + "the TOPAS engine rejects rhombohedral axes" + ) + + # Unit cell + cell = {k: _number(block.find_value(f"_cell_{t}")) + for k, t in (("a", "length_a"), ("b", "length_b"), ("c", "length_c"), + ("alpha", "angle_alpha"), ("beta", "angle_beta"), ("gamma", "angle_gamma"))} + if None in cell.values(): + raise ValueError(f"{path}: incomplete unit cell {cell}") + cell["volume"] = gemmi.UnitCell(*cell.values()).volume + + # Atom sites + labels = _values(block, "_atom_site_label") + xyz = [_values(block, f"_atom_site_fract_{c}") for c in "xyz"] + types = _values(block, "_atom_site_type_symbol") + occs = _values(block, "_atom_site_occupancy") + uisos = _values(block, "_atom_site_U_iso_or_equiv") + bisos = _values(block, "_atom_site_B_iso_or_equiv") + + # Anisotropic Uij (or Bij, converted), keyed by label + aniso = {} + aniso_labels = _values(block, "_atom_site_aniso_label") or [] + for prefix, factor in (("U", 1.0), ("B", 1.0 / EIGHT_PI_SQ)): + cols = {k: _values(block, f"_atom_site_aniso_{prefix}_{k[1:]}") for k in U_KEYS} + if all(cols.values()): + for i, lbl in enumerate(aniso_labels): + aniso[gemmi.cif.as_string(lbl)] = {k: _number(cols[k][i]) * factor for k in U_KEYS} + break + + atoms = {} + for i, raw_label in enumerate(labels): + label = gemmi.cif.as_string(raw_label) + coords = [_number(col[i]) for col in xyz] + if None in coords: + raise ValueError(f"{path}: atom {label!r} has missing coordinates") + element = _element(types[i]) if types else None + element = element or _element(label) + if element is None: + raise ValueError(f"{path}: cannot determine the element of atom {label!r}") + if types and gemmi.cif.as_string(types[i]).strip() != element: + warnings.append(f"atom {label!r}: type {gemmi.cif.as_string(types[i])!r} used as neutral {element!r}") + + occ = _number(occs[i]) if occs else None + if occ is None: + occ = 1.0 + warnings.append(f"atom {label!r}: no occupancy, set to 1.0") + uiso = _number(uisos[i]) if uisos else None + if uiso is None and bisos: + biso = _number(bisos[i]) + uiso = None if biso is None else biso / EIGHT_PI_SQ + if uiso is None: + uiso = 0.0 + warnings.append(f"atom {label!r}: no Uiso/Biso, set to 0.0") + + atom = {"element": element, "x": coords[0], "y": coords[1], "z": coords[2], + "occupancy": occ, "ADP": "Uiso", "Uiso": uiso} + if label in aniso and None not in aniso[label].values(): + atom["ADP"] = "Uaniso" + atom["Uaniso"] = aniso[label] + atoms[label] = atom + + structure = {"phase_name": name, "space_group": symbol, "unit_cell": cell, "atoms": atoms} + return structure, warnings + + +def phase_block(structure): + """Wrap a ``structure`` (from :func:`read_cif`) as ``{name: {structure, parameterization}}``. + + The parameterization repeats every refinable value as ``[value, False, None, None]``: + phase scale, cell, per-atom x/y/z/occupancy/Uiso (or the six Uaniso terms), + and explicit isotropic size/strain broadening. Size and strain are written out + because leaving them unset lets each engine apply its own, different defaults. + """ + name = structure["phase_name"] + cell = {k: _fixed(structure["unit_cell"][k]) for k in ("a", "b", "c", "alpha", "beta", "gamma")} + atoms = {} + for label, atom in structure["atoms"].items(): + entry = {k: _fixed(atom[k]) for k in ("x", "y", "z", "occupancy")} + entry["ADP"] = atom["ADP"] + if atom["ADP"] == "Uaniso": + entry["Uaniso"] = {k: _fixed(v) for k, v in atom["Uaniso"].items()} + else: + entry["Uiso"] = _fixed(atom["Uiso"]) + atoms[label] = entry + parameterization = { + "scale": _fixed(1.0), + "unit_cell": cell, + "atoms": atoms, + "peak_broadening": { + "size_broadening": {"model": "isotropic", "isotropic_size": _fixed(DEFAULT_SIZE_UM), + "LG_eta": _fixed(1.0)}, + "strain_broadening": {"model": "isotropic", "isotropic_strain": _fixed(DEFAULT_MICROSTRAIN), + "LG_eta": _fixed(1.0)}, + }, + } + return {name: {"structure": structure, "parameterization": parameterization}} + + +def merge_phases(*blocks): + """Combine :func:`phase_block` outputs; raises on a duplicate phase name.""" + merged = {} + for block in blocks: + for name, phase in block.items(): + if name in merged: + raise ValueError(f"duplicate phase name {name!r}; pass a distinct phase_name to read_cif") + merged[name] = phase + return merged + + +# -- .instprm -> instrument ------------------------------------------------------ + + +def read_instprm(path): + """Read a GSAS-II ``.instprm`` file (``key:value`` lines) into a flat dict.""" + flat = {} + for line in Path(path).read_text().splitlines(): + line = line.strip() + if not line or line.startswith("#") or ":" not in line: + continue + key, value = (s.strip() for s in line.split(":", 1)) + try: + flat[key] = float(value) + except ValueError: + flat[key] = value + return flat + + +def instrument_block(flat, description, refine_profile=False): + """Build ``payload.instrument`` from a flat ``.instprm`` dict. + + ``initialization`` holds every key as ``[value, value, False]`` (always emit + the three-element form: the TOPAS and easydiffraction engines read the + second element). ``parameterization`` holds the refinable terms; a ``None`` + value keeps the ``initialization`` value. ``refine_profile=True`` flags U, V, + W, X and Y (not Z, which easydiffraction cannot refine). Zero shift and axial + divergence are left unset (fixed); set e.g. + ``corrections["zero_shift"] = [None, True, None, None]`` to refine one. + + Raises ``ValueError`` for a two-wavelength (Ka1/Ka2) file or a missing + ``Type`` / ``Lam``: PowderLine supports single-wavelength data only. + """ + if "Lam1" in flat or "Lam2" in flat: + raise ValueError("two-wavelength (Lam1/Lam2) instrument files are not supported; use a single Lam") + for key in ("Type", "Lam"): + if key not in flat: + raise ValueError(f".instprm has no {key!r} entry") + init = {k: [v, v, False] for k, v in flat.items()} + if "Bank" in init: + init["Bank"] = [int(flat["Bank"]), int(flat["Bank"]), False] + parameterization = { + "wavelength": _fixed(flat["Lam"]), + "broadening": {k: [None, refine_profile and k != "Z", None, None] for k in "UVWXYZ"}, + "corrections": {"zero_shift": None, "axial_divergence": None}, + } + if "Polariz." in flat: + parameterization["polarization"] = _fixed(flat["Polariz."]) + return {"description": description, "initialization": [init, {}], "parameterization": parameterization} + + +# -- pattern -> xrd_data --------------------------------------------------------- + + +def read_pattern(path, x_unit="2theta", wavelength=None): + """Read a 2- or 3-column text pattern (.xy, .xye, .chi, .csv, .dat, .txt). + + Columns: x, intensity, and optionally the intensity's standard uncertainty + (esd). Leading lines that are not at least two numbers (titles, column names, + a point count) are skipped; ``#`` lines are ignored anywhere. Columns may be + separated by whitespace, commas, or semicolons. + + ``x_unit`` is ``"2theta"`` (degrees), ``"q"`` (1/Angstrom) or ``"d"`` + (Angstrom); Q and d need ``wavelength`` (Angstrom) and are converted to 2theta. + Points are sorted by 2theta; repeated 2theta values raise. + + Weights (1/sigma^2): 3 columns -> 1/esd^2 (an esd <= 0 raises); 2 columns -> + 1/max(I, 1), i.e. counting statistics with a floor for I <= 1 (warned). + Intensities are never changed and no point is dropped. + + Returns ``(xrd_data, warnings)`` with ``xrd_data = {"tth", "Itth", + "Itth_weights", "filename"}``. + """ + rows, started = [], False + for n, line in enumerate(Path(path).read_text(errors="replace").splitlines(), 1): + line = line.strip() + if not line or line.startswith("#"): + continue + tokens = [t for t in re.split(r"[\s,;]+", line) if t] + try: + values = [float(t) for t in tokens] + except ValueError: + values = [] + if len(values) >= 2: + rows.append(values[:3]) + started = True + elif started: + raise ValueError(f"{path}:{n}: cannot parse data line {line!r}") + if not rows or len({len(r) for r in rows}) != 1: + raise ValueError(f"{path}: expected rows of 2 or 3 numbers in every data line") + data = np.array(rows, dtype=float) + x, intensity = data[:, 0], data[:, 1] + warnings = [] + + if x_unit == "2theta": + tth = x + if tth.max() < 5.0: + warnings.append(f"x runs {tth.min():.3g}..{tth.max():.3g}; check that it is 2theta, not Q or d") + elif x_unit in ("q", "d"): + if wavelength is None: + raise ValueError(f"x_unit={x_unit!r} needs wavelength= (Angstrom)") + sin_theta = x * wavelength / (4 * math.pi) if x_unit == "q" else wavelength / (2 * x) + if np.any(np.abs(sin_theta) > 1): + raise ValueError(f"some {x_unit} values are unreachable at wavelength {wavelength} A") + tth = np.degrees(2 * np.arcsin(sin_theta)) + else: + raise ValueError(f"x_unit must be '2theta', 'q' or 'd', not {x_unit!r}") + + if data.shape[1] == 3: + esd = data[:, 2] + if np.any(~(esd > 0)): + raise ValueError(f"{path}: {np.count_nonzero(~(esd > 0))} esd values are <= 0 or not finite") + weights = 1.0 / esd**2 + else: + weights = 1.0 / np.maximum(intensity, 1.0) + n_low = int(np.count_nonzero(intensity <= 1.0)) + if n_low: + warnings.append( + f"{n_low} points have I <= 1 and get weight 1 (2-column data assumes counts; " + "supply a third esd column for background-subtracted or rescaled data)" + ) + + order = np.argsort(tth, kind="stable") + tth, intensity, weights = tth[order], intensity[order], weights[order] + if np.any(np.diff(tth) <= 0): + raise ValueError(f"{path}: repeated 2theta values") + xrd_data = {"tth": tth.tolist(), "Itth": intensity.tolist(), + "Itth_weights": weights.tolist(), "filename": Path(path).name} + return xrd_data, warnings + + +# -- recipe --------------------------------------------------------------------- + + +def assemble_recipe(*, schema_name="GSASII_Rietveld", xrd_data, instrument, phases=None, + background=None, single_peaks=None, refinement_controls=None, fit_range=None): + """Put the sections together as ``{schema_name, schema_version, payload}``. + + ``refinement_controls`` defaults to ``{"refinement_cycles": 5}``. + ``refinement_cycles: 1`` is simulation mode: no refine flag may be true. + ``GSASII_Rietveld`` needs ``phases``; ``GSASII_SPF`` needs ``single_peaks``, + no ``phases``, and ``refinement_controls["single_peak_fitting_mode"]``. + ``fit_range`` is ``[min_2theta, max_2theta]`` in degrees (either may be None). + """ + payload = {"xrd_data": xrd_data, "instrument": instrument, + "refinement_controls": refinement_controls or {"refinement_cycles": 5}} + for key, value in (("phases", phases), ("background", background), + ("single_peaks", single_peaks), ("fit_range", fit_range)): + if value is not None: + payload[key] = value + return {"schema_name": schema_name, "schema_version": SCHEMA_VERSION, "payload": payload} + + +def save_recipe(recipe, path): + """Write the recipe as JSON (what ``pixi run kicker `` reads).""" + Path(path).write_text(json.dumps(recipe, indent=2)) + return Path(path) +``` + +## LLM prompt template + +If you use an LLM coding assistant, the prompt below asks it to build and +validate a recipe with the module above. Save the module as `io_helpers.py` +first, fill in the bracketed values, and paste everything inside the block. +Review the script the assistant writes and the flags it sets — you are still +responsible for the refinement model. + +````text +You are helping me build a PowderLine refinement recipe from my own data files +and validate it. PowderLine (https://nsls2.github.io/PowderLine/) reads a +single self-contained JSON recipe (schema 0.26.0) with the diffraction data, +instrument parameters, and crystal structure all embedded; it does not read +CIF, .instprm, or data files itself. + +Use the helper module io_helpers.py (in my working directory) for all file +reading and recipe assembly. Read its docstrings first. Call its functions; do +not rewrite the parsing or invent recipe keys beyond the ones it produces and +the background block shown below. Treat +io_helpers.py as guidance, not as an authority: if it disagrees with +powderline.validate or the PowderLine docs, tell me. + +My files: +- CIF (one per phase): [PATH TO .cif] (phase name: [NAME]) +- Instrument parameters (GSAS-II .instprm): [PATH TO .instprm] +- Diffraction pattern: [PATH TO DATA FILE] +- The pattern's x-axis is: [2theta (degrees) | q (1/Angstrom) | d (Angstrom)] +- What I want to learn / refine: [e.g. lattice parameter and crystallite size] +- Engine I will run: [gsasii (default) | topas | easydiffraction] + +What to do: +1. Write a Python script that imports io_helpers as io and powderline, and: + - structure, cif_warnings = io.read_cif(cif_path, phase_name=...). Print + every warning. If read_cif raises (no space group, unknown element, missing + coordinates), stop and ask me; do not patch in a default. + - phases = io.phase_block(structure); for several CIFs use + io.merge_phases(io.phase_block(s1), io.phase_block(s2), ...) with a + distinct phase_name for each. + - instrument = io.instrument_block(io.read_instprm(path), "", + refine_profile=...). + - xrd_data, data_warnings = io.read_pattern(path, x_unit=..., wavelength=...). + Pass wavelength (the .instprm Lam) when x is q or d. Print every warning, + especially "check that it is 2theta, not Q or d". + - A Chebyshev background is written directly (its refine flag is a single + boolean, not a 4-element list): + background={"chebyshev": {"num_coefficients": 6, + "coefficients": [10, 5, 1, 0, 0, 0], + "refine_flag": True}} + - recipe = io.assemble_recipe(...); io.save_recipe(recipe, "recipe.json"). +2. Decide what to refine and set only those refine flags (the second element + of a [value, refine_flag, min, max] leaf) to True; everything starts False, + and absent or False means held fixed. Ask me if unsure. A sensible first + Rietveld pass: the phase scale, a Chebyshev background (4-6 coefficients), + the lattice parameters allowed by the symmetry, and the instrument profile + (refine_profile=True). If my instrument parameters come from a separate + calibrant fit, keep the profile fixed instead; sample size/strain (which + start at 10 microns and 0, i.e. almost no broadening) can then be refined. + Do not refine sample broadening on the calibrant itself. Leave atom + coordinates, occupancies, and displacement parameters fixed unless I ask. +3. Set fit_range=[min_2theta, max_2theta] in degrees of 2theta (Q and d data + have already been converted; xrd_data["tth"] holds the 2theta values). Do + not truncate the data arrays yourself. +4. Call powderline.validate(recipe) (it returns the parsed recipe; don't print + it, as it contains the whole pattern), then + powderline.run(recipe, "output", engine="", validate_only=True). + Fix anything rejected. Do not run the refinement unless I ask; when I do, + it is powderline.run(recipe, "output", engine=...) or, from the shell, + pixi run kicker recipe.json. + +Rules (schema 0.26.0): +- schema_version must be exactly "0.26.0". +- Every refinable value is a 4-element list [value, refine_flag, min, max]; + value null keeps the starting value. min/max are ignored by GSAS-II and + TOPAS but used as bounds by easydiffraction; leave them null unless I ask. +- Symmetry-linked parameters (cubic a=b=c, special-position coordinates) + refine together if any one of them is flagged. +- Only single-wavelength, constant-wavelength X-ray data (Type PXC) on a 2theta + axis is supported. Ka1/Ka2 doublets are not; io.instrument_block raises. +- Peak broadening: only the isotropic size (microns) and strain (microstrain) + models exist. Keep explicit values; unset values fall back to engine + defaults that differ between engines. +- The background single-peaks block uses pv_gaussian_sigma (sigma); the + GSASII_SPF single_peaks block uses pv_gaussian_sigma_sq (sigma squared). + Misspelled or misplaced keys are silently ignored, not rejected, so + double-check key names against the docs. +- Simulation mode is refinement_cycles = 1, with every refine flag False. +- GSASII_Rietveld needs phases; GSASII_SPF needs single_peaks, no phases, and + refinement_controls.single_peak_fitting_mode = {"use_instrument_profile": ...}. +- Engine limits: easydiffraction cannot refine atom parameters, Z, polarization, + axial divergence, or background peaks, and does not model size/strain or SPF; + TOPAS does not translate zero shift, axial divergence, or polarization + refinement. validate_only=True catches what that engine rejects outright, + but not everything: features an engine ignores (e.g. size/strain in + easydiffraction) pass with only a warning in the run output, and some + recipe errors appear only at run time. Tell me about any such limits. + +When you are done, report: phase name(s), space group(s) and atom counts; the +instrument Type and Lam; the number of points and the 2theta range; every +warning printed; which flags you set True and why; and the validation results. +```` From 192050a609678fd7fac191e53b20bd4b520afbc5 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:18:25 -0400 Subject: [PATCH 2/6] docs: ask users to cite the refinement engine too Add GSAS-II (and its scripting interface), TOPAS, and easydiffraction references to the README citation section, a new Citing page in the Sphinx docs, and the references list in CITATION.cff. Assisted-by: claude-code:claude-opus-5-5 --- CITATION.cff | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 32 +++++++++++++++++++++++++++ docs/citing.md | 51 +++++++++++++++++++++++++++++++++++++++++++ docs/index.rst | 1 + 4 files changed, 143 insertions(+) create mode 100644 docs/citing.md diff --git a/CITATION.cff b/CITATION.cff index 4a5d897..cc4de8c 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -42,3 +42,62 @@ preferred-citation: - type: doi value: "10.48550/arXiv.2608.17009" description: "arXiv preprint" +# Refinement engines PowderLine drives. Please cite the engine you used in +# addition to PowderLine (see the "Citation" section of README.md). +references: + - type: article + title: "GSAS-II: the genesis of a modern open-source all purpose crystallography software package" + authors: + - family-names: "Toby" + given-names: "Brian H." + - family-names: "Von Dreele" + given-names: "Robert B." + journal: "Journal of Applied Crystallography" + volume: 46 + start: 544 + end: 549 + year: 2013 + doi: "10.1107/S0021889813003531" + - type: article + title: "A scripting interface for GSAS-II" + authors: + - family-names: "O'Donnell" + given-names: "Jackson H." + - family-names: "Von Dreele" + given-names: "Robert B." + - family-names: "Chan" + given-names: "Maria K. Y." + - family-names: "Toby" + given-names: "Brian H." + journal: "Journal of Applied Crystallography" + volume: 51 + start: 1244 + end: 1250 + year: 2018 + doi: "10.1107/S1600576718008075" + - type: article + title: "TOPAS and TOPAS-Academic: an optimization program integrating computer algebra and crystallographic objects written in C++" + authors: + - family-names: "Coelho" + given-names: "Alan A." + journal: "Journal of Applied Crystallography" + volume: 51 + start: 210 + end: 218 + year: 2018 + doi: "10.1107/S1600576718000183" + - type: software + title: "easydiffraction" + version: "0.20.1" + authors: + - family-names: "Sazonov" + given-names: "Andrew" + - family-names: "Lindgren" + given-names: "Eric" + - family-names: "Rozyczko" + given-names: "Piotr" + - family-names: "Seth" + given-names: "Mridul" + year: 2026 + doi: "10.5281/zenodo.21999827" + repository-code: "https://github.com/easyscience/diffraction-lib" diff --git a/README.md b/README.md index e6fcb34..f8d19cc 100644 --- a/README.md +++ b/README.md @@ -220,6 +220,38 @@ If you use PowderLine in your research, please cite the preprint: Machine-readable metadata is in [`CITATION.cff`](CITATION.cff). +### Cite the refinement engine too + +PowderLine drives an underlying refinement engine. If you use PowderLine in +your work, please cite the engine you used in addition to PowderLine: + +- **GSAS-II** (default engine): + > B. H. Toby and R. B. Von Dreele. *GSAS-II: the genesis of a modern + > open-source all purpose crystallography software package.* J. Appl. Cryst. + > **46**, 544–549 (2013). + > [doi:10.1107/S0021889813003531](https://doi.org/10.1107/S0021889813003531) + + PowderLine drives GSAS-II through its scripting interface, so please also cite: + > J. H. O'Donnell, R. B. Von Dreele, M. K. Y. Chan, and B. H. Toby. *A + > scripting interface for GSAS-II.* J. Appl. Cryst. **51**, 1244–1250 (2018). + > [doi:10.1107/S1600576718008075](https://doi.org/10.1107/S1600576718008075) +- **TOPAS** (`engine="topas"`): + > A. A. Coelho. *TOPAS and TOPAS-Academic: an optimization program + > integrating computer algebra and crystallographic objects written in C++.* + > J. Appl. Cryst. **51**, 210–218 (2018). + > [doi:10.1107/S1600576718000183](https://doi.org/10.1107/S1600576718000183) +- **easydiffraction** (`engine="easydiffraction"`): the easydiffraction + project asks you to cite the specific version you used, through its + [Zenodo archive](https://doi.org/10.5281/zenodo.16806521) (all versions). + PowderLine's `easydiff` environment currently installs version 0.20.1: + > A. Sazonov, E. Lindgren, P. Rozyczko, and M. Seth. *easydiffraction + > 0.20.1.* Zenodo (2026). + > [doi:10.5281/zenodo.21999827](https://doi.org/10.5281/zenodo.21999827) + +If you simulate patterns from Materials Project data (`pixi run mp-simulate`), +please also cite Materials Project — see +[Simulating Patterns from Materials Project](docs/mp-simulation.md#citation). + ## License BSD 3-Clause — see [LICENSE](LICENSE). diff --git a/docs/citing.md b/docs/citing.md new file mode 100644 index 0000000..559e445 --- /dev/null +++ b/docs/citing.md @@ -0,0 +1,51 @@ +# Citing PowderLine + +If you use PowderLine in your research, please cite the preprint: + +> A. A. Corrao, J. A. Perez, J. D. Langhout, M. M. Butala, T. A. Caswell, and +> D. Olds. *PowderLine: a programmatic powder diffraction analysis application.* +> arXiv:2608.17009 (2026). +> [doi:10.48550/arXiv.2608.17009](https://doi.org/10.48550/arXiv.2608.17009) + +Machine-readable metadata is in +[`CITATION.cff`](https://github.com/NSLS2/PowderLine/blob/main/CITATION.cff). + +## Cite the refinement engine too + +PowderLine drives an underlying refinement engine. If you use PowderLine in +your work, please cite the engine you used in addition to PowderLine. + +**GSAS-II** (default engine): + +> B. H. Toby and R. B. Von Dreele. *GSAS-II: the genesis of a modern +> open-source all purpose crystallography software package.* J. Appl. Cryst. +> **46**, 544–549 (2013). +> [doi:10.1107/S0021889813003531](https://doi.org/10.1107/S0021889813003531) + +PowderLine drives GSAS-II through its scripting interface, so please also cite: + +> J. H. O'Donnell, R. B. Von Dreele, M. K. Y. Chan, and B. H. Toby. *A +> scripting interface for GSAS-II.* J. Appl. Cryst. **51**, 1244–1250 (2018). +> [doi:10.1107/S1600576718008075](https://doi.org/10.1107/S1600576718008075) + +**TOPAS** (`engine="topas"`): + +> A. A. Coelho. *TOPAS and TOPAS-Academic: an optimization program integrating +> computer algebra and crystallographic objects written in C++.* J. Appl. +> Cryst. **51**, 210–218 (2018). +> [doi:10.1107/S1600576718000183](https://doi.org/10.1107/S1600576718000183) + +**easydiffraction** (`engine="easydiffraction"`): the easydiffraction project +asks you to cite the specific version you used, through its +[Zenodo archive](https://doi.org/10.5281/zenodo.16806521) (all versions). +PowderLine's `easydiff` environment currently installs version 0.20.1: + +> A. Sazonov, E. Lindgren, P. Rozyczko, and M. Seth. *easydiffraction 0.20.1.* +> Zenodo (2026). +> [doi:10.5281/zenodo.21999827](https://doi.org/10.5281/zenodo.21999827) + +## Materials Project + +If you simulate patterns from Materials Project data (`pixi run mp-simulate`), +please also cite Materials Project — see +[Simulating Patterns from Materials Project](mp-simulation.md#citation). diff --git a/docs/index.rst b/docs/index.rst index b2b1e82..bbd7431 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -26,6 +26,7 @@ fresh clone to a finished refinement, on Linux or Windows. TROUBLESHOOTING SCHEMA_HISTORY api + citing .. toctree:: :maxdepth: 1 From 9173dc70fe1c20e2bd9e77dafc5a41b96ac596db Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:18:28 -0400 Subject: [PATCH 3/6] docs: note that ESD means standard uncertainty Keep the engines' 'esd' wording and column names, but note that the quantity is a standard uncertainty (IUCr 1995; NIST TN 1297). Assisted-by: claude-code:claude-opus-5-5 --- docs/getting-started.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/getting-started.rst b/docs/getting-started.rst index a2b932d..7bb7b51 100644 --- a/docs/getting-started.rst +++ b/docs/getting-started.rst @@ -156,6 +156,18 @@ Output Files After refinement, PowderLine generates standardized outputs with fixed filenames (Schema 0.26.0): +.. note:: + + **ESD and standard uncertainty.** PowderLine labels uncertainties ``esd`` + (estimated standard deviation) to match the terminology of the refinement + engines it drives. The quantity reported is what is now called the + *standard uncertainty* (s.u.): the IUCr recommends "standard uncertainty" + in place of "estimated standard deviation" (Schwarzenbach et al., `Acta + Cryst. A51, 565 (1995) `_), in + line with `NIST Technical Note 1297 + `_ (Taylor & Kuyatt, + 1994). + **GSAS-II files:** - ``dummy.gpx`` - GSAS-II project file (reopenable in GUI) From 21d2a92bb5c5e5d946d1958082681a9bd4327d4d Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:18:33 -0400 Subject: [PATCH 4/6] docs: fix recipe snippet, API availability, sim esd - Getting Started: the example recipe had an empty instrument block and no corrections block, so it validated but failed at run time; it now runs. Point to the Building Recipes guide. - Integration guide: validate() and load_recipe_asset() are exported only when GSAS-II is installed, so they are not on the schema-only track. - Simulation unit-cell reports have an empty esd column, not 0.0. Assisted-by: claude-code:claude-opus-5-5 --- docs/DEVELOPMENT.md | 2 +- docs/getting-started.rst | 33 +++++++++++++++++++++++++------ docs/integration-guide.md | 11 +++++++++-- examples/CONTRIBUTING_EXAMPLES.md | 2 +- 4 files changed, 38 insertions(+), 10 deletions(-) diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index d5bdf4c..5556e37 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -114,7 +114,7 @@ In addition to the comprehensive `refined_parameters.csv`, each phase generates - `value`: Refined unit cell parameter - `esd`: Estimated standard deviation -**Note on simulations**: Simulation mode (all `refine_flag=false`) does not generate `refined_parameters.csv` since no parameters are refined. Unit cell reports still generated with `esd=0.0`. +**Note on simulations**: Simulation mode (all `refine_flag=false`) does not generate `refined_parameters.csv` since no parameters are refined. Unit cell reports are still generated, with an empty `esd` column (read as `NaN`). ### Schema Evolution diff --git a/docs/getting-started.rst b/docs/getting-started.rst index 7bb7b51..96ce28d 100644 --- a/docs/getting-started.rst +++ b/docs/getting-started.rst @@ -98,15 +98,32 @@ All examples use schema 0.26.0 file-less payloads with embedded data. "instrument": { "description": "28-ID-2", "initialization": [ - {}, + { + "Type": ["PXC", "PXC", false], + "Bank": [1, 1, false], + "Lam": [0.45236, 0.45236, false], + "Zero": [0.0, 0.0, false], + "Polariz.": [0.99, 0.99, false], + "U": [2.0, 2.0, false], + "V": [-2.0, -2.0, false], + "W": [5.0, 5.0, false], + "X": [0.0, 0.0, false], + "Y": [0.0, 0.0, false], + "Z": [0.0, 0.0, false], + "SH/L": [0.002, 0.002, false] + }, {} ], "parameterization": { "wavelength": [0.45236, false, null, null], "broadening": { - "U": [0.01, true, null, null], - "V": [-0.005, true, null, null], - "W": [0.002, true, null, null] + "U": [null, true, null, null], + "V": [null, true, null, null], + "W": [null, true, null, null] + }, + "corrections": { + "zero_shift": null, + "axial_divergence": null } } }, @@ -143,13 +160,17 @@ All examples use schema 0.26.0 file-less payloads with embedded data. } }, "refinement_controls": { - "refinement_cycles": 5 } } } -See ``examples/`` directory for complete working examples. +``initialization`` holds the GSAS-II instrument parameters (the contents of a +``.instprm`` file) as ``[value, value, refine_flag]`` lists; ``parameterization`` +lists what to refine, with ``null`` values meaning "start from the +``initialization`` value". See ``examples/`` for complete working recipes, and +:doc:`building-recipes` for every section, how to validate a recipe, and how to +build one from your own CIF, instrument, and data files. Output Files ------------ diff --git a/docs/integration-guide.md b/docs/integration-guide.md index 4d75626..570833e 100644 --- a/docs/integration-guide.md +++ b/docs/integration-guide.md @@ -104,11 +104,18 @@ The imports a consuming project will use: | Import | Purpose | Track | |---|---|---| | `from powderline.schema import RecipeModel` | Validate recipe dicts with Pydantic | Both | -| `powderline.validate()` | Validate a recipe dict (returns a `RecipeModel`); raises on invalid input | Both | -| `powderline.load_recipe_asset()` | Load a recipe from a `.json`/`.yaml`/`.txt` file into a dict | Both | +| `powderline.validate()` | Validate a recipe dict (returns a `RecipeModel`); raises on invalid input. Adds the simulation-mode check to the schema validation | Full only | +| `powderline.load_recipe_asset()` | Load a recipe from a `.json`/`.yaml`/`.txt` file into a dict | Full only | | `powderline.run()` | Primary programmatic entry point (validates + runs + returns DataFrames). Pass `validate_only=True` to validate without refining | Full only | | `from powderline.gsas_client import GSASClient` | Run via the persistent GSAS-II server | Full only | +`powderline.validate()` and `powderline.load_recipe_asset()` are exported only +when GSAS-II is installed, so they are not available on the schema-only track. +There, validate with `RecipeModel.model_validate()` (below) and load JSON or +YAML yourself. `RecipeModel.model_validate()` runs the same schema checks but +not the simulation-mode check (no refine flag may be `true` when +`refinement_cycles` is 1). + ### Schema validation ```python diff --git a/examples/CONTRIBUTING_EXAMPLES.md b/examples/CONTRIBUTING_EXAMPLES.md index d297fd5..1bc2c76 100644 --- a/examples/CONTRIBUTING_EXAMPLES.md +++ b/examples/CONTRIBUTING_EXAMPLES.md @@ -111,7 +111,7 @@ PowderLine generates fixed output filenames: - `single_peaks_report.txt` - Peak fit results (position, width, intensity per peak) - `peak_convergence_diagnostics.txt` - Convergence warnings for aphysical parameters -**Note:** Simulation mode (all `refine_flag=false`) does not generate `refined_parameters.csv` since no parameters are refined. Unit cell reports still generated with `esd=0.0`. +**Note:** Simulation mode (all `refine_flag=false`) does not generate `refined_parameters.csv` since no parameters are refined. Unit cell reports are still generated, with an empty `esd` column (read as `NaN`). **`DESCRIPTION.md`**: Explains the scientific purpose, input parameters, expected behavior, and any known issues for this specific refinement. Just fill in the template sections. From a3129b46d4b79b2995ef9a41052da4e780e32b7e Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:55:07 -0400 Subject: [PATCH 5/6] docs: address review comments on recipe pages - Helper module: keep missing anisotropic CIF components as None (fall back to Uiso with a warning) instead of raising TypeError; reject infinite esd values, which would otherwise become zero weights. - Scope symmetry-linked refinement to GSAS-II; note that TOPAS only groups cell lengths and refines flagged symmetry-fixed parameters with a warning. - Microstrain is (delta d / d) x 10^6. - Materials Project recipes start in simulation mode; raise refinement_cycles before refining. Assisted-by: claude-code:claude-opus-5-5 --- docs/building-recipes.md | 26 +++++++++++++++++--------- docs/capabilities.md | 15 +++++++++++---- docs/recipe-helpers.md | 26 ++++++++++++++++++-------- 3 files changed, 46 insertions(+), 21 deletions(-) diff --git a/docs/building-recipes.md b/docs/building-recipes.md index 441ba32..b24eb29 100644 --- a/docs/building-recipes.md +++ b/docs/building-recipes.md @@ -71,11 +71,17 @@ The elements are `[value, refine_flag, min, max]`: TOPAS engines; only easydiffraction uses them, as fit bounds. Leave them `null` unless you need them. -Symmetry-linked parameters refine as a group: for a cubic cell, flagging any of -`a`, `b`, `c` refines all three together, and the same holds for coordinates -tied by site symmetry. Flags on symmetry-fixed parameters (e.g. cubic angles) -have no effect. See [Schema History](SCHEMA_HISTORY.md) for the full 0.26.0 -refine-flag semantics. +In GSAS-II, symmetry-linked parameters refine as a group: for a cubic cell, +flagging any of `a`, `b`, `c` refines all three together, and the same holds +for coordinates and anisotropic displacement components tied by site symmetry. +Flags on symmetry-fixed parameters (e.g. cubic angles) have no effect. The +other engines differ: easydiffraction groups cell parameters the same way (and +does not refine atom parameters), but TOPAS only groups cell lengths. TOPAS +refines a flagged symmetry-fixed angle, site-restricted coordinate, or +displacement component as given, with a warning rather than a constraint, so +flag only the parameters the symmetry allows to vary. See +[Schema History](SCHEMA_HISTORY.md) for the full 0.26.0 refine-flag semantics +(GSAS-II). ### Units @@ -89,7 +95,7 @@ PowderLine uses GSAS-II conventions throughout: | Instrument `U`, `V`, `W` | centidegrees² | | Instrument `X`, `Y`, `Z` | centidegrees | | Isotropic crystallite size | µm | -| Isotropic strain | microstrain (Δd/d × 10⁻⁶) | +| Isotropic strain | microstrain: (Δd/d) × 10⁶, so 1000 means Δd/d = 0.001 | | `Uiso`, `U11`…`U23` | Ų | | Data weights | 1/σ² | @@ -128,9 +134,11 @@ data, structure, and flags. `pixi run mp-simulate` fetches a structure from Materials Project, builds a simulation recipe for it, and calculates the pattern. Add `--keep-recipe` to -keep the generated recipe JSON as a starting point; to refine against your -own data, replace its `xrd_data` and instrument and turn on the flags you need -(see [Simulating Patterns from Materials Project](mp-simulation.md)). From +keep the generated recipe JSON as a starting point. The generated recipe is +in simulation mode, so to refine against your own data, replace its +`xrd_data` and instrument, set `payload.refinement_controls.refinement_cycles` +to a value greater than 1 (e.g. 5), and turn on the flags you need (see +[Simulating Patterns from Materials Project](mp-simulation.md)). From Python, `SimulationRecipeBuilder().build_recipe_from_mp_structure(...)` (in `powderline.simulation_builder`) builds the same recipe from the structure returned by `MPInterface(api_key=...).get_structure(material_id)` (in diff --git a/docs/capabilities.md b/docs/capabilities.md index 337a057..530de8b 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -56,14 +56,20 @@ GSAS-II. | Parameter | GSAS-II | TOPAS v7 | easydiffraction | |---|---|---|---| | Phase scale | ✓ | ✓ | ✓ | -| Unit cell, with symmetry-linked parameters refined together | ✓ | ✓ | ✓ | -| Atom coordinates, occupancies, Uiso | ✓ | ✓ | Fixed only | -| Anisotropic displacement (`U11`…`U23`) | ✓ | ✓ | Fixed values ignored; refining rejected | +| Unit cell, with symmetry-linked parameters refined together | ✓ | ✓, but see note below | ✓ | +| Atom coordinates, occupancies, Uiso | ✓ | ✓, but see note below | Fixed only | +| Anisotropic displacement (`U11`…`U23`) | ✓ | ✓, but see note below | Fixed values ignored; refining rejected | | Isotropic crystallite size and microstrain, with Lorentzian/Gaussian mixing (`LG_eta`) | ✓ | ✓ | Ignored, with a warning (also when flagged) | Intensity is scaled through each phase's `scale`; the histogram scale is fixed at 1. +**Note on symmetry with TOPAS:** GSAS-II refines symmetry-linked parameters +together and ignores flags on symmetry-fixed ones. TOPAS only groups +symmetry-linked cell lengths. A flagged symmetry-fixed cell angle, +site-restricted coordinate, or anisotropic displacement component is refined +as given, with a warning rather than a constraint. + **Peak fitting alongside a structure.** A Rietveld recipe can fit individual peaks together with the structural model through background peaks (`background.single_peaks`) — for example, an impurity or unindexed peak. @@ -85,7 +91,8 @@ adding a field for one of these features will not make it take effect. displacement, extinction, and surface roughness. - **User-defined constraints, restraints, and rigid bodies** (for example, tying two sites' occupancies together, or restraining bond lengths). - Symmetry constraints are applied automatically. + Symmetry constraints are applied automatically by GSAS-II (see the note on + TOPAS above). - **Parameter limits.** The `min`/`max` entries are ignored by GSAS-II and TOPAS; only easydiffraction uses them, as fit bounds. - **Kα₁/Kα₂ doublets** and other multi-wavelength sources. diff --git a/docs/recipe-helpers.md b/docs/recipe-helpers.md index 6c42205..cd646f3 100644 --- a/docs/recipe-helpers.md +++ b/docs/recipe-helpers.md @@ -100,7 +100,7 @@ import numpy as np SCHEMA_VERSION = "0.26.0" # must equal PowderLine's EXPECTED_SCHEMA_VERSION exactly DEFAULT_SIZE_UM = 10.0 # isotropic crystallite size, microns (GSAS-II convention) -DEFAULT_MICROSTRAIN = 0.0 # isotropic microstrain (x 10^-6) +DEFAULT_MICROSTRAIN = 0.0 # isotropic microstrain, (delta d / d) x 10^6 EIGHT_PI_SQ = 8.0 * math.pi**2 # B = 8 pi^2 U U_KEYS = ("U11", "U22", "U33", "U12", "U13", "U23") @@ -239,7 +239,10 @@ def read_cif(path, phase_name=None): cols = {k: _values(block, f"_atom_site_aniso_{prefix}_{k[1:]}") for k in U_KEYS} if all(cols.values()): for i, lbl in enumerate(aniso_labels): - aniso[gemmi.cif.as_string(lbl)] = {k: _number(cols[k][i]) * factor for k in U_KEYS} + values = {k: _number(cols[k][i]) for k in U_KEYS} + aniso[gemmi.cif.as_string(lbl)] = { + k: None if value is None else value * factor for k, value in values.items() + } break atoms = {} @@ -272,6 +275,8 @@ def read_cif(path, phase_name=None): if label in aniso and None not in aniso[label].values(): atom["ADP"] = "Uaniso" atom["Uaniso"] = aniso[label] + elif label in aniso: + warnings.append(f"atom {label!r}: incomplete anisotropic ADPs, using Uiso instead") atoms[label] = atom structure = {"phase_name": name, "space_group": symbol, "unit_cell": cell, "atoms": atoms} @@ -431,8 +436,9 @@ def read_pattern(path, x_unit="2theta", wavelength=None): if data.shape[1] == 3: esd = data[:, 2] - if np.any(~(esd > 0)): - raise ValueError(f"{path}: {np.count_nonzero(~(esd > 0))} esd values are <= 0 or not finite") + invalid_esd = ~np.isfinite(esd) | (esd <= 0) + if np.any(invalid_esd): + raise ValueError(f"{path}: {np.count_nonzero(invalid_esd)} esd values are <= 0 or not finite") weights = 1.0 / esd**2 else: weights = 1.0 / np.maximum(intensity, 1.0) @@ -554,12 +560,16 @@ Rules (schema 0.26.0): - Every refinable value is a 4-element list [value, refine_flag, min, max]; value null keeps the starting value. min/max are ignored by GSAS-II and TOPAS but used as bounds by easydiffraction; leave them null unless I ask. -- Symmetry-linked parameters (cubic a=b=c, special-position coordinates) - refine together if any one of them is flagged. +- In GSAS-II, symmetry-linked parameters (cubic a=b=c, special-position + coordinates, anisotropic displacement components) refine together if any one + of them is flagged, and flags on symmetry-fixed parameters have no effect. + TOPAS does not enforce this beyond grouping cell lengths: it refines a + flagged symmetry-fixed angle or site-restricted coordinate/ADP on its own, + with only a warning. Only flag parameters the symmetry allows to vary. - Only single-wavelength, constant-wavelength X-ray data (Type PXC) on a 2theta axis is supported. Ka1/Ka2 doublets are not; io.instrument_block raises. -- Peak broadening: only the isotropic size (microns) and strain (microstrain) - models exist. Keep explicit values; unset values fall back to engine +- Peak broadening: only the isotropic size (microns) and strain (microstrain, + (delta d / d) x 10^6, so 1000 means 0.1%) models exist. Keep explicit values; unset values fall back to engine defaults that differ between engines. - The background single-peaks block uses pv_gaussian_sigma (sigma); the GSASII_SPF single_peaks block uses pv_gaussian_sigma_sq (sigma squared). From 9b4f02615a66377ceeba6dd83042258e6fbfb9e8 Mon Sep 17 00:00:00 2001 From: acorrao <95718914+AdamCorrao@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:06:59 -0400 Subject: [PATCH 6/6] docs: fix element, instprm parsing in helpers; scope kicker - Read two-letter element symbols case-insensitively (FE1 -> Fe, not F) and warn when the element is taken from the atom label. - Split .instprm lines on ';' as GSAS-II does. - Note that pixi run kicker runs GSAS-II only; topas-kicker runs TOPAS. Assisted-by: claude-code:claude-opus-5-5 --- docs/recipe-helpers.md | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/docs/recipe-helpers.md b/docs/recipe-helpers.md index cd646f3..4e943ba 100644 --- a/docs/recipe-helpers.md +++ b/docs/recipe-helpers.md @@ -133,10 +133,14 @@ def _number(raw): def _element(raw): - """Element symbol from a type symbol or label ("O2-" -> "O", "La1" -> "La"), or None.""" + """Element symbol from a type symbol or label, or None. + + Case-insensitive, two-letter symbols first: "O2-" -> "O", "La1" -> "La", + "FE1" -> "Fe", "CL1" -> "Cl". + """ text = gemmi.cif.as_string(raw).strip() for size in (2, 1): - symbol = text[:size] + symbol = text[:size].capitalize() if re.fullmatch(r"[A-Z][a-z]?", symbol) and gemmi.Element(symbol).name != "X": return symbol return None @@ -252,10 +256,13 @@ def read_cif(path, phase_name=None): if None in coords: raise ValueError(f"{path}: atom {label!r} has missing coordinates") element = _element(types[i]) if types else None - element = element or _element(label) + if element is None: + element = _element(label) + if element is not None: + warnings.append(f"atom {label!r}: no usable type symbol, element {element!r} taken from the label") if element is None: raise ValueError(f"{path}: cannot determine the element of atom {label!r}") - if types and gemmi.cif.as_string(types[i]).strip() != element: + if types and gemmi.cif.as_string(types[i]).strip().lower() not in (element.lower(), ""): warnings.append(f"atom {label!r}: type {gemmi.cif.as_string(types[i])!r} used as neutral {element!r}") occ = _number(occs[i]) if occs else None @@ -331,17 +338,24 @@ def merge_phases(*blocks): def read_instprm(path): - """Read a GSAS-II ``.instprm`` file (``key:value`` lines) into a flat dict.""" + """Read a single-bank GSAS-II ``.instprm`` file into a flat dict. + + Each line holds one or more ``key:value`` pairs separated by ``;``, as in + GSAS-II's own reader. For a multi-bank file, extract one bank first. + """ flat = {} for line in Path(path).read_text().splitlines(): line = line.strip() - if not line or line.startswith("#") or ":" not in line: + if not line or line.startswith("#"): continue - key, value = (s.strip() for s in line.split(":", 1)) - try: - flat[key] = float(value) - except ValueError: - flat[key] = value + for pair in line.split(";"): + if ":" not in pair: + continue + key, value = (s.strip() for s in pair.split(":", 1)) + try: + flat[key] = float(value) + except ValueError: + flat[key] = value return flat @@ -552,8 +566,9 @@ What to do: it, as it contains the whole pattern), then powderline.run(recipe, "output", engine="", validate_only=True). Fix anything rejected. Do not run the refinement unless I ask; when I do, - it is powderline.run(recipe, "output", engine=...) or, from the shell, - pixi run kicker recipe.json. + it is powderline.run(recipe, "output", engine=...). From the shell, + pixi run kicker recipe.json runs GSAS-II only and pixi run topas-kicker + recipe.json runs TOPAS; easydiffraction has no shell command. Rules (schema 0.26.0): - schema_version must be exactly "0.26.0".