diff --git a/docs/deferred_defects.md b/docs/deferred_defects.md index 3ef555e4..597d2bd7 100644 --- a/docs/deferred_defects.md +++ b/docs/deferred_defects.md @@ -211,3 +211,8 @@ without renumbering. `TextureFittingModel.from_json(filename)` with one argument; it needs `(filename, fit_range_table)`, so the menu action raises `TypeError` out of a Qt slot (`texture_fitting_viewer.py:1186`, `texture_fitting_crtl.py:225`). Found while moving `from_json` onto the checked peak-range reader (#1147). +- **DD-37**, 2026-11-25: the texture window's pole figures (`PoleFigureCalculator.rotate_project_q`) take + χ = 0 as φ along Q (He's convention). On the HB-2B cradle the φ axis is vertical at χ = 0 and lies along Q at + χ = 90° (ω = θ), checked with the cradle camera. For HB-2B data the poles then match `pyrs.pole_figures` + only with χ → 90° − χ and the axes relabeled ([ground_truths.md](ground_truths.md), "Path-length-corrected + pole figures"). Recorded, not changed: the fix is a production change that needs the maintainers' decision. diff --git a/docs/ground_truths.md b/docs/ground_truths.md index 4ee48895..3c263b19 100644 --- a/docs/ground_truths.md +++ b/docs/ground_truths.md @@ -3371,6 +3371,74 @@ Found while testing; all four are fixed, see the next section ([deferred_defects longer returns a stale result. Tests: `tests/unit/pyrs/core/test_polefigurecalculator.py`. Each new test fails without its fix. + +## Path-length-corrected pole figures: conventions and approved parameters (2026-11-25) + +`pyrs.pole_figures` corrects HB-2B pole figures for the beam path through the sample. The sample shape is a +closed STL mesh. The core is a port of an earlier HB-2B pole-figure script, called "the reference script" in +the core docstrings and "PF" in the tests. The integration tests in +`tests/integration/test_pole_figures_parity.py` check the port against its outputs for a slab measured on HB-2B +(`tests/data/pole_figures/reference/`). + +**Frames and angles.** +- The sample frame is the STL frame, with axes vx, vy and vz. `gauge_center_mm` is the rotation point. +- In the cradle frame, eₓ is the vertical φ axis at χ = 0. The incident beam is `ki = (0, s·cos ω, −sin ω)` + and the diffracted beam is `kf = (0, s·cos(2θ−ω), sin(2θ−ω))`. `s` is ±1 and sets the side the beam comes + from. +- The sample turns as `R(χ, φ) = R_y(χ) · R_x(φ) · M0`. `M0` is the mount matrix, the identity by default. + The pole is `h = Rᵀ q̂`. +- With ω = θ, the φ axis is perpendicular to Q at χ = 0 and lies along Q at χ = 90°. At χ = 90° every φ + measures the same pole. The owner (HB-2B instrument scientist) checked this against the cradle camera. + +**Relation to `PoleFigureCalculator` (#411).** The two give the same pole once χ and the axes are mapped: +- χ_PyRS = 90° − χ_HB-2B. +- PyRS (x, y, normal) = (vy, vz, −vx). PyRS's "sample normal" is the φ axis. + +Checked at 2θ/ω = 90/45, 105/52.5, 57/28.5, 90/40 and 105/60, over χ 0–90° and φ 0–345°. The largest +difference is 2e-8. So `rotate_project_q` puts φ along Q at χ = 0 (He's convention), and the HB-2B cradle +puts it along Q at χ = 90°. See DD-37 for what this means for the texture window. + +**Attenuation.** +- μ = Σ nᵢ (σ_s,i + σ_a,i · λ / 1.798 Å). σ_s is the bound scattering cross section (coherent + incoherent) + and σ_a the 2200 m/s absorption cross section, from Sears (1992). +- σ_s is taken as constant. This is the free-atom approximation, with no Bragg edges and no wavelength + dependence of the scattering. +- The unit tests check μ for Fe, Ni and Al by hand from the published cross sections. For example, Fe at + 1.54 Å gives 0.1173 /mm. +- The intensity factor is F = V · ⟨inside · exp(−μ(L_in + L_out))⟩, averaged over Monte Carlo points in + the gauge parallelepiped. The correction is F(0,0)/F. + +**Empirical parameters, approved by the owner (2026-11-25).** Each is a named constant or a function +argument with a default, and the user can change the ones that matter. They come from the reference script +unless marked new. + +| Parameter | Value | Effect | +|---|---|---| +| Correction cutoff | 3.0 | points with a larger correction are ignored | +| Central half width | ±5° of the arm 2θ | which peaks are used | +| Integration window | ±1.5 FWHM | net counts above a straight background | +| Edge margin | peak at least 0.5° inside the detector | which peaks are used | +| `find_peak` | search ±1.0°, background 1.2–3.0°, centroid ±1.2° | peak position and FWHM | +| Background band | half width + 0.3° to + 2.5° | background level | +| Pseudo-Voigt fit (`method="fit"`) | span half + 2.5°, center ±1°, FWHM 0.3–3×, η 0–1 | fitted rate | +| Live sub-run | last sub-run of 1000 s or more dropped | sub-runs used | +| Short sub-run | under 10 % of the median count time dropped | sub-runs used | +| χ, φ rounding | 0.01° | ≤ 0.005° | +| Monte Carlo | 40,000 points (runs), 20,000 (prediction), seed 3 | noise only | +| Allowed 2θ (new) | 50–120° | reflections offered | +| Extinct reflection (new) | \|F\|² < 1e-6 · Σ\|b\|² | reflection list | +| Free φ at χ 90 (new, option, off) | φ axis within 0.1° of Q, ties within 1 %, lowest φ wins | planned φ | +| Equal spacing (new, option, off) | ring step = divisor of 360 nearest φ_step / cos χ | grid | +| Combine scale (option, default none) | median(reference) / median(run) | merged runs | + +Some checks only flag a run and do not change results. They flag a weak peak below net/σ = 5, an FWHM +under 2 bins and overlapping peaks. They also flag a density outside 0.5–25 g/cm³, a mesh size outside +1–1000 mm, and ω or the arm moving more than 0.01° during a run. + +Tests: unit in `tests/unit/pyrs/pole_figures/`, integration in `tests/integration/test_pole_figures_*.py`. +A 13-sub-run subset of one reduced run (`tests/data/pole_figures/hb2b/`) runs in CI. The full-run tests skip +unless `HIDRA_PF_TEST_DATA` points to the folder that holds the full reduced runs HB2B_6494 to HB2B_6497. + ## Calibration drivers in the package; one shared ring calibration for the unit tier (2026-11-18, #1101) **Drivers moved into the package** (user decision): `scripts/pyrs_pixel_calibration.py` and diff --git a/pixi.lock b/pixi.lock index 761eff89..7af734f1 100644 --- a/pixi.lock +++ b/pixi.lock @@ -68,6 +68,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.18-h7cc23a3_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/frozenlist-1.8.0-py313h7259b1b_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gdk-pixbuf-2.44.8-h68053f1_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/gemmi-0.7.5-py313hbaa079c_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gl2ps-1.4.3-h8658303_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glew-2.2.0-h3abd4de_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glib-tools-2.90.1-h876c321_3.conda @@ -195,6 +196,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/libsndfile-1.2.2-hbc6d301_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsodium-1.0.22-hebe6cf0_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsolv-0.7.41-h72ddc62_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libspatialindex-2.1.0-hee9eb32_2.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.54.1-h13e7031_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libssh2-1.11.1-h6154650_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-16.2.0-h934c35e_7.conda @@ -545,6 +547,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/rich-15.0.0-pyhcf101f3_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/rich-rst-2.2.0-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/roman-numerals-4.1.0-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/rtree-1.4.1-pyh11ca60a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/scooby-0.12.1-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/secretstorage-3.5.0-pyhc9edb4d_3.conda - conda: https://conda.anaconda.org/conda-forge/noarch/seekpath-2.2.2-pyh5ded981_0.conda @@ -577,6 +580,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/toolz-1.2.0-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/tqdm-4.70.1-pyhfa0c392_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/traitlets-5.16.1-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/trimesh-5.2.2-pyh7b2049a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/trove-classifiers-2026.9.21.13-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/truststore-0.10.5-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/twine-7.0.0-pyhcf101f3_0.conda @@ -667,6 +671,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.18-h7cc23a3_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/frozenlist-1.8.0-py313h7259b1b_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gdk-pixbuf-2.44.8-h68053f1_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/gemmi-0.7.5-py313hbaa079c_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gl2ps-1.4.3-h8658303_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glew-2.2.0-h3abd4de_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glib-tools-2.90.1-h876c321_3.conda @@ -794,6 +799,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/libsndfile-1.2.2-hbc6d301_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsodium-1.0.22-hebe6cf0_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsolv-0.7.41-h72ddc62_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libspatialindex-2.1.0-hee9eb32_2.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.54.1-h13e7031_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libssh2-1.11.1-h6154650_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-16.2.0-h934c35e_7.conda @@ -1129,6 +1135,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/rich-15.0.0-pyhcf101f3_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/rich-rst-2.2.0-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/roman-numerals-4.1.0-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/rtree-1.4.1-pyh11ca60a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/scooby-0.12.1-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/secretstorage-3.5.0-pyhc9edb4d_3.conda - conda: https://conda.anaconda.org/conda-forge/noarch/seekpath-2.2.2-pyh5ded981_0.conda @@ -1159,6 +1166,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/toolz-1.2.0-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/tqdm-4.70.1-pyhfa0c392_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/traitlets-5.16.1-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/trimesh-5.2.2-pyh7b2049a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/trove-classifiers-2026.9.21.13-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/truststore-0.10.5-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/twine-7.0.0-pyhcf101f3_0.conda @@ -1245,6 +1253,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.18-h7cc23a3_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/frozenlist-1.8.0-py313h7259b1b_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gdk-pixbuf-2.44.8-h68053f1_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/gemmi-0.7.5-py313hbaa079c_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gl2ps-1.4.2-h36e74d4_2.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glew-2.3.0-h71661d4_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glib-tools-2.90.1-h876c321_3.conda @@ -1371,6 +1380,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/libsndfile-1.2.2-hbc6d301_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsodium-1.0.22-hebe6cf0_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsolv-0.7.41-h72ddc62_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libspatialindex-2.1.0-hee9eb32_2.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.54.1-h13e7031_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libssh2-1.11.1-h6154650_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-16.2.0-h934c35e_7.conda @@ -1705,6 +1715,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/rich-15.0.0-pyhcf101f3_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/rich-rst-2.2.0-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/roman-numerals-4.1.0-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/rtree-1.4.1-pyh11ca60a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/scooby-0.12.1-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/secretstorage-3.5.0-pyhc9edb4d_3.conda - conda: https://conda.anaconda.org/conda-forge/noarch/seekpath-2.2.2-pyh5ded981_0.conda @@ -1735,6 +1746,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/toolz-1.2.0-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/tqdm-4.70.1-pyhfa0c392_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/traitlets-5.16.1-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/trimesh-5.2.2-pyh7b2049a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/trove-classifiers-2026.9.21.13-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/truststore-0.10.5-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/twine-7.0.0-pyhcf101f3_0.conda @@ -1821,6 +1833,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/fribidi-1.0.18-h7cc23a3_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/frozenlist-1.8.0-py313h7259b1b_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gdk-pixbuf-2.44.8-h68053f1_2.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/gemmi-0.7.5-py313hbaa079c_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/gl2ps-1.4.2-h36e74d4_2.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glew-2.3.0-h71661d4_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/glib-tools-2.90.1-h876c321_3.conda @@ -1947,6 +1960,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/linux-64/libsndfile-1.2.2-hbc6d301_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsodium-1.0.22-hebe6cf0_3.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsolv-0.7.41-h72ddc62_0.conda + - conda: https://conda.anaconda.org/conda-forge/linux-64/libspatialindex-2.1.0-hee9eb32_2.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.54.1-h13e7031_0.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libssh2-1.11.1-h6154650_1.conda - conda: https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-16.2.0-h934c35e_7.conda @@ -2281,6 +2295,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/rich-15.0.0-pyhcf101f3_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/rich-rst-2.2.0-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/roman-numerals-4.1.0-pyhd8ed1ab_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/rtree-1.4.1-pyh11ca60a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/scooby-0.12.1-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/secretstorage-3.5.0-pyhc9edb4d_3.conda - conda: https://conda.anaconda.org/conda-forge/noarch/seekpath-2.2.2-pyh5ded981_0.conda @@ -2311,6 +2326,7 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/toolz-1.2.0-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/tqdm-4.70.1-pyhfa0c392_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/traitlets-5.16.1-pyhcf101f3_0.conda + - conda: https://conda.anaconda.org/conda-forge/noarch/trimesh-5.2.2-pyh7b2049a_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/trove-classifiers-2026.9.21.13-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/truststore-0.10.5-pyh5ded981_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/twine-7.0.0-pyhcf101f3_0.conda @@ -3219,6 +3235,25 @@ packages: - gdk-pixbuf >=2.44.8,<3.0a0 size: 581961 timestamp: 1788490424411 +- conda: https://conda.anaconda.org/conda-forge/linux-64/gemmi-0.7.5-py313hbaa079c_0.conda + sha256: 10ac77aa3cd42b193d003bdc7f64c1d32dba8e4ecefc18d9f78cab94a0237984 + md5: 895c5a768147a9d479351bf75b641bf9 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc >=14 + - libstdcxx >=14 + - python >=3.13,<3.14.0a0 + - python_abi 3.13.* *_cp313 + - zlib-ng >=2.3.3,<2.4.0a0 + license: MPL-2.0 + license_family: OTHER + purls: + - pkg:pypi/gemmi?source=hash-mapping + run_exports: + weak: + - gemmi >=0.7.5,<0.7.6.0a0 + size: 4326665 + timestamp: 1772446412986 - conda: https://conda.anaconda.org/conda-forge/linux-64/gl2ps-1.4.2-h36e74d4_2.conda sha256: e28a214c71590a09f75f1aaccf5795bbcfb99b00c2d6ef55d34320b4f47485bd md5: 787c780ff43f9f79d78d01e476b81a7c @@ -5480,6 +5515,21 @@ packages: - libsolv >=0.7.41,<0.8.0a0 size: 530491 timestamp: 1793004545403 +- conda: https://conda.anaconda.org/conda-forge/linux-64/libspatialindex-2.1.0-hee9eb32_2.conda + sha256: 8c903e353cb7191168c907405e798d60e63576811c9a46c8fdf48d278ed909bc + md5: 32fc7241da2d00a9471e3a4fc6370e85 + depends: + - libstdcxx >=15 + - libgcc >=15 + - __glibc >=2.17,<3.0.a0 + license: MIT + license_family: MIT + purls: [] + run_exports: + weak: + - libspatialindex >=2.1.0,<2.1.1.0a0 + size: 451278 + timestamp: 1789740039745 - conda: https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.54.1-h13e7031_0.conda sha256: 07b3c98282022f05781122d073f84e944bfb4299946e8457ece3ce6c384ff78e md5: 8f15f0ec9b69344df5c3bb5cce1751a1 @@ -11322,6 +11372,19 @@ packages: run_exports: {} size: 13814 timestamp: 1766003022813 +- conda: https://conda.anaconda.org/conda-forge/noarch/rtree-1.4.1-pyh11ca60a_0.conda + sha256: 461ddd1d84c180bb682560b50d538e9e264ee5cc78cab5eb2a0f21cc24815bed + md5: 73f0eccab422ca6a96d904a805d68fa3 + depends: + - libspatialindex + - python >=3.9 + license: MIT + license_family: MIT + purls: + - pkg:pypi/rtree?source=hash-mapping + run_exports: {} + size: 41185 + timestamp: 1755128422366 - conda: https://conda.anaconda.org/conda-forge/noarch/scooby-0.12.1-pyhd8ed1ab_0.conda sha256: 1771c8e40dcaec8192501473a351b1f98715e151d0bac36e445e8146a5dd721d md5: cdf6f9bbeda2031b42f6ca56c4ccc1e0 @@ -11808,6 +11871,41 @@ packages: run_exports: {} size: 116935 timestamp: 1785761789772 +- conda: https://conda.anaconda.org/conda-forge/noarch/trimesh-5.2.2-pyh7b2049a_0.conda + sha256: 74da035e0e59e1772cdba28df121cb0a60407e0794f053af3f6521b6ae04e6ad + md5: a96f0a3123706c0581d272017cf1a64f + depends: + - numpy + - python >=3.11 + constrains: + - chardet + - colorlog + - jsonschema + - lxml + - mapbox_earcut + - meshio + - msgpack-python + - networkx + - pillow + - psutil + - pycollada + - pyglet + - requests + - rtree + - scikit-image + - scipy + - setuptools + - shapely + - svg.path + - sympy + - xxhash + license: MIT + license_family: MIT + purls: + - pkg:pypi/trimesh?source=hash-mapping + run_exports: {} + size: 615867 + timestamp: 1795320811506 - conda: https://conda.anaconda.org/conda-forge/noarch/trove-classifiers-2026.9.21.13-pyh5ded981_0.conda sha256: 43cde9446d690a198ab5b35801d08e2926afe7202495aaa3df98702cb4a19f9a md5: ca71e34cacec0f00b1c7c312fbc884b7 diff --git a/pyproject.toml b/pyproject.toml index ff2d89f6..d9507769 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -88,6 +88,7 @@ pandas = "*" types-six = "*" nexusformat = ">=1.0.8,<2" pydantic = ">=2.7.3,<3" +gemmi = ">=0.6,<0.8" # pyrs.pole_figures: CIF files and structure factors h5glance = ">=0.9,<0.10" py-rattler = "==0.24.0" neutrons_standard = "*" @@ -111,6 +112,7 @@ pandas = "*" types-six = "*" nexusformat = ">=1.0.8,<2" pydantic = ">=2.7.3,<3" +gemmi = ">=0.6,<0.8" # pyrs.pole_figures: CIF files and structure factors neutrons_standard = "*" @@ -124,6 +126,8 @@ pytest-cov = "*" pytest-timeout = "*" pytest-xdist = "*" mypy = "*" +trimesh = ">=4" # pyrs.pole_figures tests: cross-check the STL path lengths +rtree = ">=1" # trimesh ray tests without embree need the R-tree [tool.pixi.feature.package.dependencies] anaconda-client = "*" @@ -171,6 +175,7 @@ pandas = "*" types-six = "*" nexusformat = ">=1.0.8,<2" pydantic = ">=2.7.3,<3" +gemmi = ">=0.6,<0.8" # pyrs.pole_figures: CIF files and structure factors # ------------------------------- # # QA Environment Feature # @@ -188,6 +193,7 @@ pandas = "*" types-six = "*" nexusformat = ">=1.0.8,<2" pydantic = ">=2.7.3,<3" +gemmi = ">=0.6,<0.8" # pyrs.pole_figures: CIF files and structure factors py-rattler = "==0.24.0" # ------------------------------- # @@ -205,6 +211,7 @@ pandas = "*" types-six = "*" nexusformat = ">=1.0.8,<2" pydantic = ">=2.7.3,<3" +gemmi = ">=0.6,<0.8" # pyrs.pole_figures: CIF files and structure factors [tool.pixi.package] name = "pyrs" diff --git a/pyrs/pole_figures/__init__.py b/pyrs/pole_figures/__init__.py new file mode 100644 index 00000000..8c1a8a5b --- /dev/null +++ b/pyrs/pole_figures/__init__.py @@ -0,0 +1,6 @@ +"""Path-length-corrected pole figures for HIDRA (HB-2B, HFIR). + +Ported from the HIDRA_PathLength_PoleFigs project. ``core`` is pure numpy/scipy/h5py (no Qt): the sample model +(STL), the stage geometry, the gauge-volume Monte Carlo, predicted corrections, peak intensities of reduced runs, +corrected pole figures and table scans. +""" diff --git a/pyrs/pole_figures/core/__init__.py b/pyrs/pole_figures/core/__init__.py new file mode 100644 index 00000000..b6891cf2 --- /dev/null +++ b/pyrs/pole_figures/core/__init__.py @@ -0,0 +1,21 @@ +""" +Physics core: pure numpy/scipy/h5py/gemmi, no GUI or plotting imports. + +The "reference script" in the docstrings is the original HB-2B pole-figure script (``pole_figures.py``) this code +was ported from and is tested against. "As the reference script" means the numerics are unchanged from it. The +parity tests compare with its outputs. + +Frames and units: the sample frame is the STL frame with the virtual axes vx, vy, vz (mm). The cradle (instrument) +frame is described in :mod:`.geometry`. Angles are in degrees, wavelengths in Å, mu in 1/mm and rates in counts/s. + +Typical workflow: + +1. Load the sample (:mod:`.stl_mesh`) and the phase (:mod:`.phase`), and set the mount (:mod:`.geometry`). +2. Predict the corrections with no data (:mod:`.prediction`) and plan table scans (:mod:`.table_scan`). +3. Read the runs (:mod:`.runs`) and build the corrected pole figures (:mod:`.polefig`, :mod:`.combine`). + +Example: + >>> from pyrs.pole_figures.core.geometry import Mount, MountConventions + >>> Mount(MountConventions(), omega=45.0, tth=90.0).pole(0.0, 0.0) + array([0., 0., 1.]) +""" diff --git a/pyrs/pole_figures/core/combine.py b/pyrs/pole_figures/core/combine.py new file mode 100644 index 00000000..dcd2e808 --- /dev/null +++ b/pyrs/pole_figures/core/combine.py @@ -0,0 +1,152 @@ +""" +Combine runs that measured the same pole figure (``combine_runs`` of the reference script). + +A pole figure split over several reduced files (a scan stopped and restarted, or measured in parts) is merged into +one pole figure per hkl: every point keeps its own pole vector, rate and correction. Scale "none" (default) keeps the +rates as they are, which is right for parts of one scan. Scale "median" multiplies each run by +median(reference) / median(run) of the corrected rates of the points that are kept. That assumes the runs differ only +by a constant efficiency (for example different detector regions, such as eta slices). + +Typical workflow: + +1. Analyze each run with ``polefig.analyze_run``. +2. Merge the pole figures that share an hkl with :func:`combine_by_hkl` (or two or more chosen ones with + :func:`combine`). + +Example: + >>> results = [pf for run in runs for pf in analyze_run(run, ...)] # doctest: +SKIP + >>> merged = combine_by_hkl(results, scale="median") # doctest: +SKIP +""" + +import typing +from collections.abc import Sequence +from dataclasses import fields +from typing import Literal + +import numpy as np + +from .correction import concatenate +from .geometry import MountConventions +from .polefig import PolePeak + +Scale = Literal["none", "median"] +#: parts whose omega differs by more than this are refused (the log median is used, so a restarted scan agrees to +#: well within it) +OMEGA_TOL_DEG = 0.01 + + +def _kept_corrected(r: PolePeak) -> np.ndarray: + return np.where(r.ignored | ~np.isfinite(r.correction), np.nan, r.rate * r.correction) + + +def combine(parts: Sequence[PolePeak], *, scale: Scale = "none", reference: str) -> PolePeak: + """ + Merge pole figures of the same hkl into one. + + Every point keeps its own pole vector, rate, sigma and correction. The first part gives the mount used to draw + cells (so omega and the chi offset), the wavelength and the beams. 2theta and FWHM are the means of the parts. + + Args: + parts: Two or more pole figures of one hkl, analyzed with the same cutoff, mu, method, wavelength and mount + conventions (chi offset included), and omega within ``OMEGA_TOL_DEG``. + scale: "none" keeps the rates (default). "median" scales each part's rate and sigma by + median(reference) / median(part) of the kept corrected rates. + reference: Run name of the part the others are scaled to. It must be one of the parts. + + Returns: + The combined pole figure, run named "+...", with ``source_runs`` and a note on the scaling. + + Raises: + ValueError: If scale is unknown, there are fewer than two parts, the parts have different hkl, cutoff, mu, + method, wavelength, mount conventions or omega, reference is not one of the parts, or (scale "median") a + part has no kept point with a positive corrected rate. + """ + if scale not in typing.get_args(Scale): + raise ValueError(f"scale must be one of {', '.join(typing.get_args(Scale))}, got {scale!r}") + if len(parts) < 2: + raise ValueError(f"combining needs at least two pole figures, got {len(parts)}") + hkls = {r.hkl for r in parts} + if len(hkls) != 1: + raise ValueError(f"cannot combine different reflections: {', '.join(sorted(hkls))}") + if reference not in {r.run for r in parts}: + names = ", ".join(r.run for r in parts) + raise ValueError(f"reference run {reference} is not one of the runs combined ({names})") + ref = next(r for r in parts if r.run == reference) + for name in ("cutoff", "mu", "method", "wavelength_A"): + values = {getattr(r, name) for r in parts} + if len(values) > 1: + raise ValueError(f"cannot combine runs analyzed with different {name}: {', '.join(map(str, values))}") + check_same_mount(parts) + if scale == "median": + medians = {r.run: float(np.nanmedian(_kept_corrected(r))) if np.isfinite(_kept_corrected(r)).any() + else float("nan") for r in parts} # fmt: skip + bad = [run for run, m in medians.items() if not (np.isfinite(m) and m > 0)] + if bad: + raise ValueError(f"cannot scale by median: run {', '.join(bad)} has no kept points with a positive " + "corrected rate") # fmt: skip + fac = [medians[ref.run] / medians[r.run] for r in parts] + else: + fac = [1.0] * len(parts) + first = parts[0] + + def cat(name: str) -> np.ndarray: + return np.concatenate([np.asarray(getattr(r, name), float) for r in parts]) + + runs = tuple(r.run for r in parts) + how = (f"scaled by median: {', '.join(f'{r.run} x{f:.3f}' for r, f in zip(parts, fac, strict=True))}" + if scale == "median" else "no scaling between runs") # fmt: skip + return PolePeak( + run="+".join(runs), hkl=first.hkl, title=" | ".join(dict.fromkeys(r.title for r in parts)), + two_theta=float(np.mean([r.two_theta for r in parts])), fwhm=float(np.mean([r.fwhm for r in parts])), + wavelength_A=first.wavelength_A, beams=first.beams, mount=first.mount, + chi=cat("chi"), phi=cat("phi"), count_s=cat("count_s"), + rate=np.concatenate([r.rate * f for r, f in zip(parts, fac, strict=True)]), + sigma=np.concatenate([r.sigma * f for r, f in zip(parts, fac, strict=True)]), + gauge=concatenate([r.gauge for r in parts]), cutoff=first.cutoff, mu=first.mu, method=first.method, + live=any(r.live for r in parts), h=np.vstack([r.poles() for r in parts]), source_runs=runs, + notes=f"combined from runs {', '.join(runs)}, {how}", + ) # fmt: skip + + +def check_same_mount(parts: Sequence[PolePeak], *, omega_tol_deg: float = OMEGA_TOL_DEG) -> None: + """ + Check that pole figures were measured on the same mount, so one mount describes the combined pole figure. + + Args: + parts: The pole figures. + omega_tol_deg: Largest allowed spread of omega (deg, default: ``OMEGA_TOL_DEG``). + + Raises: + ValueError: If the parts differ in a mount convention (the chi offset included) or in omega by more than + omega_tol_deg. The message names the field and the runs' values. + """ + for f in fields(MountConventions): + values = {r.run: getattr(r.mount.conv, f.name) for r in parts} + if len(set(values.values())) > 1: + shown = ", ".join(f"run {run}: {v!r}" for run, v in values.items()) + raise ValueError(f"cannot combine runs measured with different mount conventions: {f.name} ({shown})") + omegas = {r.run: r.omega for r in parts} + if max(omegas.values()) - min(omegas.values()) > omega_tol_deg: + shown = ", ".join(f"run {run}: {w:g}" for run, w in omegas.items()) + raise ValueError(f"cannot combine runs measured at different omega (more than {omega_tol_deg:g} deg apart): " + f"{shown}") # fmt: skip + + +def combine_by_hkl(results: Sequence[PolePeak], *, scale: Scale = "none") -> list[PolePeak]: + """ + One pole figure per hkl: runs sharing an hkl are merged, single runs are kept. + + Args: + results: Pole figures of any hkl. + scale: "none" (default) or "median", as in :func:`combine`. The first run of each hkl is the reference. + + Returns: + One pole figure per hkl, in order of first appearance. + + Raises: + ValueError: If the runs of one hkl cannot be combined (see :func:`combine`). + """ + groups: dict[str, list[PolePeak]] = {} + for r in results: + groups.setdefault(r.hkl, []).append(r) + return [combine(g, scale=scale, reference=g[0].run) if len(g) > 1 else g[0] for g in groups.values()] diff --git a/pyrs/pole_figures/core/correction.py b/pyrs/pole_figures/core/correction.py new file mode 100644 index 00000000..e0c1c684 --- /dev/null +++ b/pyrs/pole_figures/core/correction.py @@ -0,0 +1,200 @@ +""" +The path-length correction step shared by predictions and measured runs: the gauge Monte Carlo at every orientation. + +The gauge points are drawn once for the mount and beams (``gauge.gauge_points``). F is computed at every cradle chi, +phi and at chi 0, phi 0, the orientation every correction is relative to. The correction is F(0, 0) / F, inf where F +is 0 (the gauge misses the sample). Points whose correction is above the cutoff are ignored by the callers. + +Typical workflow: + +1. Set the beam and slit sizes with :class:`Beams`. +2. Call :func:`gauge_corrections` with the mount, the orientations, the sample mesh and mu. +3. Use the :class:`GaugeCorrections` fields by name, or :meth:`GaugeCorrections.take` to keep some orientations. + +Example: + >>> Beams(incident_width=2.0, incident_height=2.0, diffracted_width=2.0) + Beams(incident_width=2.0, incident_height=2.0, diffracted_width=2.0) + >>> g = gauge_corrections(m, beams=Beams(), chi=chi, phi=phi, mesh=mesh, center=(0.0, 0.0, 0.0), mu=0.1, + ... n_points=DEFAULT_MC_POINTS, progress=no_count_progress, workers="auto") # doctest: +SKIP + >>> g.correction[0] # doctest: +SKIP + 1.0 +""" + +from collections.abc import Sequence +from dataclasses import dataclass + +import numpy as np +import numpy.typing as npt + +from .gauge import gauge_points, intensity_factor +from .geometry import Mount +from .parallel import Workers, intensity_factors +from .stl_mesh import SampleMesh +from .types import CountProgress, FloatArray + +DEFAULT_CUTOFF = 3.0 # points with a correction above this are ignored, as the reference script + + +@dataclass(frozen=True, kw_only=True) +class Beams: + """ + Beam and slit sizes (mm). + + Attributes: + incident_width: Incident beam width in the scattering plane (default: 4). HB-2B logs it as ISR:X:Gap. + incident_height: Incident beam height, vertical (default: 4). HB-2B logs it as ISR:Y:Gap. + diffracted_width: Receiving slit width (default: 3). + + Raises: + ValueError: If a size is not positive and finite (a NaN slit log would make every point ignored). + """ + + incident_width: float = 4.0 + incident_height: float = 4.0 + diffracted_width: float = 3.0 + + def __post_init__(self) -> None: + """Refuse sizes that are not positive and finite (a NaN slit log would make every point ignored).""" + for name in ("incident_width", "incident_height", "diffracted_width"): + v = getattr(self, name) + if not (np.isfinite(v) and v > 0): + raise ValueError(f"{name.replace('_', ' ')} must be a positive size in mm, not {v}") + + +def check_reference(f_ref: float, center: npt.ArrayLike) -> None: + """ + Check that the gauge sees sample at chi 0, phi 0, the orientation every correction is relative to. + + F(0, 0) of 0 (or NaN) would make every correction 0, which looks like a perfect prediction. + + Args: + f_ref: F at chi 0, phi 0 (mm3). + center: Gauge center in the sample frame (mm), for the message. + + Raises: + ValueError: If f_ref is not positive and finite. + """ + if not (np.isfinite(f_ref) and f_ref > 0): + c = ", ".join(f"{float(x):g}" for x in np.asarray(center, float).ravel()) + raise ValueError(f"the gauge volume at ({c}) mm holds no sample at chi 0, phi 0 (F(0,0) = {f_ref}). " + "Move the gauge center inside the sample.") # fmt: skip + + +@dataclass(frozen=True, kw_only=True) +class GaugeCorrections: + """ + Gauge Monte Carlo results at each orientation (one entry per orientation in every array). + + Attributes: + F: Attenuation-weighted sample volume in the gauge (mm3). + F_ref: F at chi 0, phi 0 (mm3). + volume_in_sample: Sample volume in the gauge (mm3). + mean_path: Mean path in + out (mm), NaN where the gauge misses the sample. + vy_offset: Intensity-weighted vy centroid of the gauge (mm), NaN where the gauge misses the sample. + vy_rms: Intensity-weighted vy spread of the gauge (mm), NaN where the gauge misses the sample. + correction: F_ref / F, inf where F is 0. + """ + + F: FloatArray + F_ref: float + volume_in_sample: FloatArray + mean_path: FloatArray + vy_offset: FloatArray + vy_rms: FloatArray + correction: FloatArray + + def take(self, index: npt.ArrayLike | slice) -> "GaugeCorrections": + """ + The results at some orientations. + + Args: + index: Indices, a boolean mask or a slice of the orientations. + + Returns: + The selected results, with the same ``F_ref``. + """ + i = index if isinstance(index, slice) else np.asarray(index) + return GaugeCorrections(F=self.F[i], F_ref=self.F_ref, volume_in_sample=self.volume_in_sample[i], + mean_path=self.mean_path[i], vy_offset=self.vy_offset[i], vy_rms=self.vy_rms[i], + correction=self.correction[i]) # fmt: skip + + +def concatenate(parts: Sequence[GaugeCorrections]) -> GaugeCorrections: + """ + The results of several pole figures one after another (for a combined pole figure). + + Each part's correction stays relative to its own F(0, 0). ``F_ref`` of the result is the first part's, kept as a + record. + + Args: + parts: One or more results. + + Returns: + The results joined in order. + + Raises: + ValueError: If there are no parts. + """ + if not parts: + raise ValueError(f"nothing to concatenate: give at least one result, got {list(parts)!r}") + + def cat(name: str) -> FloatArray: + return np.concatenate([np.asarray(getattr(g, name), float) for g in parts]) + + return GaugeCorrections(F=cat("F"), F_ref=parts[0].F_ref, volume_in_sample=cat("volume_in_sample"), + mean_path=cat("mean_path"), vy_offset=cat("vy_offset"), vy_rms=cat("vy_rms"), + correction=cat("correction")) # fmt: skip + + +def gauge_corrections( + m: Mount, + *, + beams: Beams, + chi: npt.ArrayLike, + phi: npt.ArrayLike, + mesh: SampleMesh, + center: npt.ArrayLike, + mu: float, + n_points: int, + progress: CountProgress, + workers: Workers, +) -> GaugeCorrections: + """ + Gauge Monte Carlo at each cradle chi, phi, and the correction F(0, 0) / F. + + Args: + m: Beams and rotation conventions for the plane's omega and 2theta. + beams: Beam and slit sizes (mm). + chi: Cradle chi per orientation (deg). + phi: Phi per orientation (deg), same length as chi. + mesh: Sample in its own frame (mm). + center: Gauge center in the sample frame (mm). + mu: Linear attenuation coefficient (1/mm). + n_points: Monte Carlo gauge points (``gauge.DEFAULT_MC_POINTS`` for runs, ``gauge.PREDICTION_MC_POINTS`` for + predictions). + progress: ``progress(n_done)`` as orientations finish (``types.no_count_progress`` for none). + workers: Number of processes, or "auto" to choose from the job size (``parallel.n_workers``). + + Returns: + The results at every orientation, in the order of chi and phi. + + Raises: + ValueError: If the gauge holds no sample at chi 0, phi 0, or workers is neither "auto" nor a positive whole + number. + """ + pts, vol = gauge_points(m, incident_width=beams.incident_width, incident_height=beams.incident_height, + diffracted_width=beams.diffracted_width, n_points=n_points) # fmt: skip + f_ref = intensity_factor(m, chi=0.0, phi=0.0, points=pts, volume=vol, mesh=mesh, center=center, mu=mu).F + check_reference(f_ref, center) + rows = intensity_factors(m, chi=chi, phi=phi, points=pts, volume=vol, mesh=mesh, center=center, mu=mu, + progress=progress, workers=workers) # fmt: skip + + def column(name: str) -> FloatArray: + return np.array([getattr(r, name) for r in rows], float) + + F = column("F") + with np.errstate(divide="ignore", invalid="ignore"): + corr = np.where(F > 0, f_ref / np.where(F > 0, F, 1), np.inf) + return GaugeCorrections(F=F, F_ref=float(f_ref), volume_in_sample=column("volume_in_sample"), + mean_path=column("mean_path"), vy_offset=column("vy_offset"), vy_rms=column("vy_rms"), + correction=corr) # fmt: skip diff --git a/pyrs/pole_figures/core/gauge.py b/pyrs/pole_figures/core/gauge.py new file mode 100644 index 00000000..dccc9a8a --- /dev/null +++ b/pyrs/pole_figures/core/gauge.py @@ -0,0 +1,208 @@ +""" +Gauge volume Monte Carlo and the attenuation-weighted intensity factor F. + +Ported from the reference script (``gauge_points``, ``set_slit_offset``, ``intensity_factor``, ``beam_value``) +with the same numerics. + +The gauge is the incident beam (width x height) crossed with the diffracted-slit band (width), sampled by uniform +Monte Carlo points in the cradle frame. For each point inside the sample, the path in (along -ki) and out (along kf) +is traced through the mesh. F = vol * mean(inside * exp(-mu (L_in + L_out))) holds both the attenuation and the gauge +volume inside the sample. The correction is F(0, 0) / F. + +Typical workflow: + +1. Build a :class:`~.geometry.Mount` for the plane's omega and 2theta. +2. Optionally shift the diffracted band with :func:`set_slit_offset`. +3. Draw the gauge points once with :func:`gauge_points`. +4. Call :func:`intensity_factor` at each cradle chi, phi (or ``parallel.intensity_factors`` for many). + +Example: + >>> mesh = SampleMesh.from_stl("sample.stl") # doctest: +SKIP + >>> m = Mount(MountConventions(), omega=45.0, tth=90.0) + >>> pts, vol = gauge_points(m, incident_width=2.0, incident_height=2.0, diffracted_width=2.0, n_points=40_000) + >>> f = intensity_factor(m, chi=30.0, phi=90.0, points=pts, volume=vol, mesh=mesh, + ... center=(0.0, 0.0, 0.0), mu=0.1) # doctest: +SKIP + >>> ref = intensity_factor(m, chi=0.0, phi=0.0, points=pts, volume=vol, mesh=mesh, + ... center=(0.0, 0.0, 0.0), mu=0.1) # doctest: +SKIP + >>> correction = ref.F / f.F # doctest: +SKIP +""" + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any, Final + +import numpy as np +import numpy.typing as npt + +from .geometry import Mount, MountConventions +from .stl_mesh import SampleMesh +from .types import FloatArray + +MC_SEED = 3 +DEFAULT_MC_POINTS = 40_000 # Monte Carlo gauge points per orientation for a measured run, as the reference script +#: the prediction uses half of them, as the reference script does +PREDICTION_MC_POINTS = DEFAULT_MC_POINTS // 2 +#: a beam size given as this prefix and a log name is the median of that run log (``beam_value``) +LOG_PREFIX: Final = "log:" + + +def gauge_points( + m: Mount, + *, + incident_width: float, + incident_height: float, + diffracted_width: float, + n_points: int, + seed: int = MC_SEED, +) -> tuple[FloatArray, float]: + """ + Uniform points in the incident beam x diffracted band (cradle frame, mm, about the gauge center). + + The gauge is the parallelepiped bounded by the incident beam (width across ki, height along e_x) and the + diffracted band (width across kf). The points are uniform in it. + + Args: + m: Beams for this omega and 2theta. ``m.band_offset`` shifts the diffracted band (see ``set_slit_offset``). + incident_width: Incident beam width in the scattering plane (mm). + incident_height: Incident beam height along e_x (mm). + diffracted_width: Diffracted (receiving) slit width (mm). + n_points: Number of points. + seed: Random seed (default: ``MC_SEED`` = 3, as the reference script). + + Returns: + The points, shape (n_points, 3), in the cradle frame relative to the gauge center (mm), and the gauge volume + (mm3). + """ + ex = np.array([1.0, 0, 0]) + ni = np.cross(ex, m.ki) + nf = np.cross(ex, m.kf) + A = np.vstack([ni / np.linalg.norm(ni), nf / np.linalg.norm(nf), ex]) + wi, hi, wd = incident_width, incident_height, diffracted_width + rng = np.random.default_rng(seed) + s = rng.uniform(-0.5, 0.5, (n_points, 3)) * [wi, wd, hi] + if m.band_offset: + s[:, 1] += m.band_offset # off-center peak: the band passes through the slit center, not the gauge center + return np.linalg.solve(A, s.T).T, float(wi * wd * hi / abs(np.linalg.det(A))) + + +def set_slit_offset(m: Mount, *, conv: MountConventions, omega: float, arm_tth: float, slit_mm: float) -> Mount: + """ + Shift the diffracted band for a peak away from the arm angle. + + A peak away from the arm angle is seen through the receiving slit along its own diffracted direction, so its band + is centered on the line through the slit center (``slit_mm`` along the arm direction from the rotation point). + + Args: + m: Mount of the peak (its kf is the peak's diffracted direction). Changed in place. + conv: Mount conventions (beam side). + omega: Omega (deg). + arm_tth: Detector arm 2theta (deg). + slit_mm: Distance from the rotation point to the receiving slit (mm). 0 leaves ``m`` unchanged. + + Returns: + ``m``, with ``band_offset`` (mm, along e_x x kf) set by ``Mount.set_band_offset``. + """ + if not slit_mm: + return m + w, ta = np.radians(omega), np.radians(arm_tth) + k_arm = np.array([0.0, conv.sb * np.cos(ta - w), np.sin(ta - w)]) + nf = np.cross([1.0, 0, 0], m.kf) + m.set_band_offset(float(np.dot(nf / np.linalg.norm(nf), slit_mm * k_arm))) + return m + + +@dataclass(frozen=True, kw_only=True) +class IntensityFactor: + """ + Result of ``intensity_factor`` for one orientation. + + Attributes: + F: Attenuation-weighted sample volume in the gauge (mm3). + volume_in_sample: Sample volume in the gauge (mm3). + mean_path: Mean path in + out over the sample part of the gauge (mm). NaN when the gauge misses the sample. + vy_offset: Intensity-weighted centroid along the sample vy axis, relative to the gauge center (mm). NaN when + the gauge misses the sample. + vy_rms: Intensity-weighted rms spread along the sample vy axis about that centroid (mm). NaN when the gauge + misses the sample. + """ + + F: float + volume_in_sample: float + mean_path: float + vy_offset: float + vy_rms: float + + +def intensity_factor( + m: Mount, + *, + chi: float, + phi: float, + points: FloatArray, + volume: float, + mesh: SampleMesh, + center: npt.ArrayLike, + mu: float, +) -> IntensityFactor: + """ + F and the path statistics for one orientation. + + The gauge points are rotated into the sample frame (``R^T p + center``). From each point inside the mesh the path + in is traced along -ki and the path out along kf, and the point is weighted by ``exp(-mu (L_in + L_out))``. + + Args: + m: Beams and rotation conventions. + chi: Cradle chi (deg). + phi: Phi (deg). + points: Gauge points from ``gauge_points`` (cradle frame, mm). + volume: Gauge volume from ``gauge_points`` (mm3). + mesh: Sample in its own frame (mm). + center: Gauge center = rotation point in the sample frame (vx, vy, vz in mm). + mu: Linear attenuation coefficient (1/mm). + + Returns: + F, the sample volume in the gauge, the mean path and the vy centroid and spread. All zero or NaN when no + gauge point is inside the sample. + """ + pts, vol = points, volume + c = np.asarray(center, float) + R = m.R(chi, phi) + p = pts @ R + c # rows: R^T p + ki, kf = R.T @ m.ki, R.T @ m.kf + wind, L_in = mesh.trace(p, -ki) + inside = wind > 0.5 + if not inside.any(): + return IntensityFactor(F=0.0, volume_in_sample=0.0, mean_path=np.nan, vy_offset=np.nan, vy_rms=np.nan) + L = L_in[inside] + mesh.trace(p[inside], kf)[1] + w = np.exp(-mu * L) + n = len(p) + vy = p[inside, 1] - c[1] + cy = float((w * vy).sum() / w.sum()) + sy = float(np.sqrt((w * (vy - cy) ** 2).sum() / w.sum())) + return IntensityFactor(F=float(vol * w.sum() / n), volume_in_sample=float(vol * inside.sum() / n), + mean_path=float(L.mean()), vy_offset=cy, vy_rms=sy) # fmt: skip + + +def beam_value(spec: float | str, logs: Mapping[str, Any]) -> float: + """ + A beam size from a config value: a number, or ``LOG_PREFIX + ""`` for the median of a run log. + + Args: + spec: A size (mm) or ``"log:"``, e.g. ``"log:ISR:X:Gap"``. + logs: Run logs by name. + + Returns: + The size (mm). + + Raises: + ValueError: If spec is text that is neither a number nor ``"log:"``, or names a log not in ``logs``. + """ + if isinstance(spec, str) and spec.startswith(LOG_PREFIX): + name = spec.removeprefix(LOG_PREFIX) + if name not in logs: + raise ValueError(f"beam size {spec!r} names a log the run does not have ({name!r})") + return float(np.median(logs[name])) + try: + return float(spec) + except ValueError as exc: + raise ValueError(f"beam size must be a number (mm) or {LOG_PREFIX}, got {spec!r}") from exc diff --git a/pyrs/pole_figures/core/geometry.py b/pyrs/pole_figures/core/geometry.py new file mode 100644 index 00000000..77b07d00 --- /dev/null +++ b/pyrs/pole_figures/core/geometry.py @@ -0,0 +1,339 @@ +""" +HB-2B Eulerian-cradle geometry: mount conventions, beams, rotation and poles. + +Ported from the reference script (``rot``, ``Mount``). Its global ``CHI_OFF`` is the explicit ``chi_offset_deg`` +here. The pole-figure projection is in :mod:`.projection`. + +Frames: the sample frame is the STL frame, with the virtual axes vx, vy, vz (mm). The cradle (instrument) frame at +chi 0, phi 0 has e_x vertical (the phi axis), e_z along Q at omega = theta, and e_y = e_z x e_x. All angles are in +degrees. + +- incident ``ki = (0, sb cos w, -sin w)``, diffracted ``kf = (0, sb cos(2t - w), sin(2t - w))`` +- sample to cradle: ``R(chi, phi) = rot(e_y, s_chi chi) @ rot(e_x, s_phi phi) @ M0`` (``rotation.rot``) +- pole in the sample frame: ``h = R^T q`` + +Typical workflow: + +1. Describe how the sample sits on the cradle with :class:`MountConventions`. +2. Build a :class:`Mount` for one omega and 2theta. +3. Get the pole of each cradle chi, phi with :meth:`Mount.pole` or :meth:`Mount.poles`. +4. Place the poles on a pole figure with ``projection.project``. + +Example: + >>> m = Mount(MountConventions(), omega=45.0, tth=90.0) + >>> m.pole(0.0, 0.0) + array([0., 0., 1.]) +""" + +import difflib +import typing +from dataclasses import dataclass, fields, replace +from typing import Any, Literal, NamedTuple + +import numpy as np +import numpy.typing as npt + +from .rotation import SampleAxis, axis_name, axis_vector, check_rotation, nearest_rotation, rot +from .types import FloatArray + +PhiSense = Literal["clockwise_from_above", "counterclockwise_from_above"] +IncidentFrom = Literal["+vy", "-vy"] + + +class AxesAtZero(NamedTuple): + """ + Sample axis nearest each instrument direction at chi 0, phi 0 (see ``MountConventions.axes_at_zero``). + + Attributes: + up: Along e_x, the phi axis (up). + across: Along e_y, the chi axis. + q: Along e_z, Q at omega = theta. + """ + + up: str + across: str + q: str + + +@dataclass(frozen=True, kw_only=True) +class MountConventions: + """ + How the sample sits on the cradle (the ``conventions`` block of a reference-script config). + + At chi 0, phi 0 the cradle axes are e_x (up, the phi axis), e_y (horizontal, across the beams) and e_z (Q at + omega = theta). phi turns about e_x, chi about e_y, and chi 90 puts the phi axis along Q. By default +vx is + up, +vy along e_y and +vz along Q. ``up_axis`` and ``q_axis`` mount the sample another way, e.g. a cylinder + turned about its long axis vz by phi: up_axis "+vz". A full ``sample_to_instrument`` matrix replaces both for a + tilted mount. + + Attributes: + phi_sense: Sense of +phi seen from above (check with the top camera): "clockwise_from_above" (default) + or "counterclockwise_from_above". + vx_up: +vx points up at chi 0 (default: True). If False, vx and vy are reversed (legacy key, applied after + up_axis and q_axis, or after sample_to_instrument). + chi_tilts_up_axis_toward_Q: Sense of chi: +chi tilts the upward phi axis toward Q (default: True). + incident_from: Side the incident beam comes from at chi 0, phi 0, "+vy" or "-vy" (default: "-vy"). + chi_offset_deg: Cradle chi = logged chi + chi_offset_deg, for a goniometer whose chi zero is not the cradle + one (deg, default: 0). + eta_up_sign: Sense of eta for eta-sliced runs, +1 or -1 (default: +1). + up_axis: Sample axis along the phi axis (up) at chi 0 (default: "+vx"). + q_axis: Sample axis along Q (e_z) at chi 0, phi 0, at right angles to up_axis (default: "+vz"). The third + axis (along e_y) follows from the right-hand rule. + sample_to_instrument: The 3 x 3 sample-to-instrument matrix M0, 9 values row by row, or None to build M0 + from up_axis and q_axis (default: None). + + Raises: + ValueError: If a value is not one of its allowed options, up_axis and q_axis are not at right angles, or + sample_to_instrument is not a rotation. + + Example: + >>> MountConventions(up_axis="+vz", q_axis="+vx").axes_at_zero() + AxesAtZero(up='+vz', across='-vy', q='+vx') + """ + + phi_sense: PhiSense = "clockwise_from_above" + vx_up: bool = True + chi_tilts_up_axis_toward_Q: bool = True # noqa: N815 (config key name) + incident_from: IncidentFrom = "-vy" + chi_offset_deg: float = 0.0 + eta_up_sign: float = 1.0 + up_axis: SampleAxis = "+vx" + q_axis: SampleAxis = "+vz" + sample_to_instrument: tuple[float, ...] | None = None + + def __post_init__(self) -> None: + """Check every value and that the mount is a rotation (raises ValueError).""" + allowed = {"phi_sense": typing.get_args(PhiSense), "incident_from": typing.get_args(IncidentFrom), + "up_axis": typing.get_args(SampleAxis), "q_axis": typing.get_args(SampleAxis)} # fmt: skip + for name, values in allowed.items(): + if getattr(self, name) not in values: + raise ValueError(f"{name} must be one of {', '.join(values)}, not {getattr(self, name)!r}") + for name in ("vx_up", "chi_tilts_up_axis_toward_Q"): + if not isinstance(getattr(self, name), (bool, np.bool_)): + raise ValueError(f"{name} must be true or false, not {getattr(self, name)!r}") + if self.eta_up_sign not in (1, -1): + raise ValueError(f"eta_up_sign must be +1 or -1, not {self.eta_up_sign!r}") + if not np.isfinite(self.chi_offset_deg): + raise ValueError(f"chi_offset_deg must be a number, not {self.chi_offset_deg!r}") + if abs(float(axis_vector(self.up_axis) @ axis_vector(self.q_axis))) > 0.5: + raise ValueError(f"the up axis ({self.up_axis}) and the axis along Q ({self.q_axis}) must be different " + "sample axes (at right angles)") # fmt: skip + if self.sample_to_instrument is not None: + check_rotation(np.reshape(self.sample_to_instrument, (3, 3))) + + @classmethod + def from_dict(cls, d: dict[str, Any]) -> "MountConventions": + """ + Build from a ``conventions`` dict (the reference script's config block). + + Args: + d: Field name -> value. Keys starting with ``_`` are notes and are ignored. Missing keys take the + defaults. + + Returns: + The mount conventions. + + Raises: + ValueError: If a key is unknown (a misspelled key would otherwise give the default mount; the message + suggests the closest name) or a value is not allowed. + """ + names = {f.name for f in fields(cls)} + unknown = [k for k in d if k not in names and not k.startswith("_")] + if unknown: + hints = [f"{k} (did you mean {m[0]}?)" if (m := difflib.get_close_matches(k, names, 1)) else k + for k in unknown] # fmt: skip + raise ValueError(f"unknown mount convention key: {', '.join(hints)}") + return cls(**{k: v for k, v in d.items() if k in names}) + + @property + def s_phi(self) -> float: + """Sign applied to phi in ``R``: -1 for clockwise from above, +1 for counterclockwise.""" + return -1.0 if self.phi_sense == "clockwise_from_above" else 1.0 + + @property + def s_chi(self) -> float: + """Sign applied to chi in ``R``: -1 when +chi tilts the up axis toward Q, else +1.""" + return -1.0 if self.chi_tilts_up_axis_toward_Q else 1.0 + + @property + def sb(self) -> float: + """Beam side sign ``sb`` in ki and kf: -1 when the incident beam comes from +vy, else +1.""" + return -1.0 if self.incident_from == "+vy" else 1.0 + + @property + def M0(self) -> FloatArray: # noqa: N802 (matches the physics notation) + """ + Sample-to-instrument (cradle) rotation at chi 0, phi 0: instrument vector = M0 @ sample vector. + + Rows are e_x (up, phi axis), e_y (across) and e_z (Q) in sample coordinates. Identity for the default mount. + A given ``sample_to_instrument`` matrix is used as it is (made exactly orthonormal), otherwise it is built from + ``up_axis`` and ``q_axis``. ``vx_up`` = False is applied on top. + """ + if self.sample_to_instrument is not None: + m = nearest_rotation(np.reshape(self.sample_to_instrument, (3, 3))) + else: + u, w = axis_vector(self.up_axis), axis_vector(self.q_axis) + m = np.vstack([u, np.cross(w, u), w]) + return m if self.vx_up else np.diag([-1.0, -1.0, 1.0]) @ m + + def axes_at_zero(self) -> "AxesAtZero": + """ + Sample axis nearest each instrument direction at chi 0, phi 0. + + Returns: + The signed sample axes (such as '+vx') along e_x (up), e_y (across) and e_z (Q). A leading '~' marks an + axis more than 1 deg from that direction (a tilted mount). + """ + names = [axis_name(row) if np.abs(row).max() > np.cos(np.radians(1.0)) else "~" + axis_name(row) + for row in self.M0] # fmt: skip + return AxesAtZero(up=names[0], across=names[1], q=names[2]) + + def cradle_chi(self, logged_chi: float | FloatArray) -> float | FloatArray: + """ + Cradle chi used in the geometry from the logged chi: logged chi + ``chi_offset_deg``. + + Args: + logged_chi: Chi from the run logs or goniometer (deg). + + Returns: + Cradle chi (deg), same shape as the input. + """ + return logged_chi + self.chi_offset_deg + + def logged_chi(self, cradle_chi: float | FloatArray) -> float | FloatArray: + """ + Logged chi (run file, goniometer) from the cradle chi: cradle chi - ``chi_offset_deg``. + + Args: + cradle_chi: Cradle chi used in the geometry (deg). + + Returns: + Logged chi (deg), same shape as the input. + """ + return cradle_chi - self.chi_offset_deg + + def mirrored(self) -> "MountConventions": + """Same mount with the beams on the other side (for a background check with mirrored beams).""" + other: IncidentFrom = "-vy" if self.incident_from == "+vy" else "+vy" + return replace(self, incident_from=other) + + +class Mount: + """ + Beams and sample orientation for one omega and 2theta. + + The beam vectors are unit vectors in the cradle frame at chi 0, phi 0. + + Args: + conv: Mount conventions. + omega: Omega (deg). + tth: Scattering angle 2theta (deg). + eta_deg: Eta slice: kf turned out of the scattering plane toward +e_x by eta (deg, default: 0 for the full + detector). + + Attributes: + conv: The mount conventions. + omega: Omega (deg). + tth: 2theta (deg). + eta: Eta slice (deg). + ki: Incident beam direction (cradle frame). + kf: Diffracted beam direction (cradle frame). + q: Unit scattering vector ``(kf - ki) / |kf - ki|`` (cradle frame). + s_phi: Sign applied to phi (from ``conv``). + s_chi: Sign applied to chi (from ``conv``). + M0: Sample-to-cradle rotation at chi 0, phi 0 (from ``conv``). + band_offset: Shift of the diffracted band center along e_x x kf (mm), set by :meth:`set_band_offset`. + + Example: + >>> m = Mount(MountConventions(), omega=45.0, tth=90.0) + >>> m.q + array([0., 0., 1.]) + """ + + def __init__(self, conv: MountConventions, *, omega: float, tth: float, eta_deg: float = 0.0) -> None: + self.conv = conv + self.omega, self.tth = float(omega), float(tth) + self.s_phi, self.s_chi, self.M0 = conv.s_phi, conv.s_chi, conv.M0 + sb = conv.sb + w, t2 = np.radians(omega), np.radians(tth) + self.ki: FloatArray = np.array([0.0, sb * np.cos(w), -np.sin(w)]) + self.kf: FloatArray = np.array([0.0, sb * np.cos(t2 - w), np.sin(t2 - w)]) + self.eta = float(eta_deg) + if self.eta: + # kf on the Debye cone, turned out of the scattering plane toward +e_x (up) by eta, so + # kf . e_x = sin 2theta sin eta as for the pyRS pixel eta. + e = np.radians(self.eta) * conv.eta_up_sign + uh = (self.kf - np.cos(t2) * self.ki) / np.sin(t2) + self.kf = np.cos(t2) * self.ki + np.sin(t2) * (np.cos(e) * uh + np.sin(e) * np.array([1.0, 0.0, 0.0])) + q = self.kf - self.ki + self.q: FloatArray = q / np.linalg.norm(q) + self.band_offset = 0.0 # mm along e_x x kf; see set_band_offset + + def set_band_offset(self, offset_mm: float) -> None: + """ + Shift the diffracted band off the gauge center (``gauge.set_slit_offset`` computes the shift). + + Args: + offset_mm: Shift of the band center along e_x x kf (mm). 0 centers the band on the gauge. + """ + self.band_offset = float(offset_mm) + + def R(self, chi: float, phi: float) -> FloatArray: # noqa: N802 (physics notation) + """ + Sample-to-cradle rotation: ``rot(e_y, s_chi chi) @ rot(e_x, s_phi phi) @ M0``. + + Args: + chi: Cradle chi (deg). + phi: Phi (deg). + + Returns: + The 3 x 3 matrix: cradle vector = R @ sample vector. + """ + return rot([0, 1, 0], self.s_chi * chi) @ rot([1, 0, 0], self.s_phi * phi) @ self.M0 + + def pole(self, chi: float, phi: float) -> FloatArray: + """ + Unit scattering vector (the pole) in the sample frame: ``R(chi, phi)^T q``. + + Args: + chi: Cradle chi (deg). + phi: Phi (deg). + + Returns: + The pole (vx, vy, vz components). + """ + return self.R(chi, phi).T @ self.q + + def poles(self, chi: npt.ArrayLike, phi: npt.ArrayLike) -> FloatArray: + """ + :meth:`pole` for arrays of cradle chi and phi, vectorized. + + Same rotations as ``R`` written out: h = M0^T Rx(s_phi phi)^T Ry(s_chi chi)^T q. + + Args: + chi: Cradle chi (deg), any shape (flattened). + phi: Phi (deg), same size as chi. + + Returns: + Poles in the sample frame, shape (n, 3). + """ + c = np.radians(self.s_chi * np.asarray(chi, float).ravel()) + p = np.radians(self.s_phi * np.asarray(phi, float).ravel()) + qx, qy, qz = self.q + cc, sc = np.cos(c), np.sin(c) + ax, ay, az = cc * qx - sc * qz, np.full_like(c, qy), sc * qx + cc * qz # Ry(chi)^T q + cp, sp = np.cos(p), np.sin(p) + v = np.c_[ax, cp * ay + sp * az, -sp * ay + cp * az] # Rx(phi)^T + return np.asarray(v @ self.M0) # M0^T applied to row vectors + + def phi_axis(self, chi: float) -> FloatArray: + """ + Phi axis in the cradle frame at a cradle chi (e_x at chi 0). + + Args: + chi: Cradle chi (deg). + + Returns: + Unit vector of the phi axis. + """ + return rot([0, 1, 0], self.s_chi * chi) @ np.array([1.0, 0.0, 0.0]) diff --git a/pyrs/pole_figures/core/grid.py b/pyrs/pole_figures/core/grid.py new file mode 100644 index 00000000..87ba4f6f --- /dev/null +++ b/pyrs/pole_figures/core/grid.py @@ -0,0 +1,148 @@ +""" +The chi/phi grid of a predicted pole figure and the solid-angle weight of each point. + +The reference script's grid is chi 0 to below 90 in 10 deg rings, phi 0 to below 360 in 5 deg steps, plus one point +at chi 90. With equal spacing the high-chi rings take coarser phi steps, so the points stay about as far apart on the +sphere as at chi 0. + +Example: + >>> Grid().describe() + '10 x 5 deg' + >>> len(Grid().points()[0]) + 649 +""" + +from dataclasses import KW_ONLY, dataclass + +import numpy as np + +from .types import FloatArray + +#: whole-degree phi steps that divide 360, for the equal-spacing grid (motor positions stay round numbers) +PHI_DIVISORS = tuple(d for d in range(1, 361) if 360 % d == 0) + + +@dataclass(frozen=True) +class Grid: + """ + chi/phi grid: chi 0 to below 90 in ``chi_step``, phi 0 to below 360 in ``phi_step``, plus one point at chi 90. + + ``equal_spacing`` (off by default, the reference grid): a chi ring is a circle on the sphere whose size goes as + cos(chi), so the same phi step crowds the points as chi grows. With equal spacing each ring takes the whole-degree + divisor of 360 nearest to ``phi_step / cos(chi)`` in log ratio (never finer than ``phi_step``), which keeps the + spacing on the sphere close to the chi 0 spacing. 10 x 5 deg: 454 points instead of 649. + + Attributes: + chi_step: Step between chi rings (deg, default: 10). + phi_step: Step along each ring, and on every ring unless equal_spacing (deg, default: 5). + equal_spacing: Coarser phi steps on the high-chi rings (default: False). + + Example: + >>> Grid(equal_spacing=True).ring_phi_step(60.0) + 10.0 + """ + + chi_step: float = 10.0 + phi_step: float = 5.0 + _: KW_ONLY + equal_spacing: bool = False + + def rings(self) -> FloatArray: + """ + The chi of each ring below 90. + + Returns: + Ring chi values (deg), from 0 in ``chi_step``. + """ + return np.arange(0, 90, self.chi_step).astype(float) + + def ring_phi_step(self, chi: float) -> float: + """ + The phi step on the ring at ``chi``. + + Args: + chi: Ring chi (deg). + + Returns: + The phi step (deg): ``phi_step``, or with equal spacing a coarser whole-degree divisor of 360. + """ + ideal = self.phi_step / max(float(np.cos(np.radians(chi))), 1e-9) + if not self.equal_spacing or ideal <= self.phi_step * (1 + 1e-9): + return float(self.phi_step) + coarser = [d for d in PHI_DIVISORS if d >= self.phi_step] + if not coarser: + return float(self.phi_step) + return float(min(coarser, key=lambda d: abs(np.log(d / ideal)))) + + def points(self) -> tuple[FloatArray, FloatArray]: + """ + Cradle chi and phi of every grid point, in order (ring by ring, phi increasing, chi 90 last). + + Returns: + Chi and phi (deg). + """ + chi_parts, phi_parts = [], [] + for c in self.rings(): + phis = np.arange(0, 360, self.ring_phi_step(float(c))) + chi_parts.append(np.full(len(phis), c)) + phi_parts.append(phis) + chi = np.r_[np.concatenate(chi_parts), 90.0] + phi = np.r_[np.concatenate(phi_parts), 0.0] + return chi.astype(float), phi.astype(float) + + def weights(self, chi: FloatArray) -> FloatArray: + """ + Solid-angle weight of each grid point (see :func:`solid_angle_weights`). + + Args: + chi: Chi of each grid point (deg). + + Returns: + Weights in units of a chi_step x phi_step cell. + """ + c = np.asarray(chi, float) + steps = np.array([self.ring_phi_step(float(x)) if x < 90 - 1e-6 else self.phi_step for x in c]) + return solid_angle_weights(c, chi_step=self.chi_step, phi_step=self.phi_step, ring_steps=steps) + + def describe(self) -> str: + """ + Short text for captions. + + Returns: + E.g. '10 x 5 deg', or with equal spacing the range of phi steps from chi 0 to the last ring. + """ + if not self.equal_spacing: + return f"{self.chi_step:g} x {self.phi_step:g} deg" + last = float(self.rings().max()) + return (f"{self.chi_step:g} deg chi, equal spacing (phi {self.phi_step:g} deg at chi 0 to " + f"{self.ring_phi_step(last):g} deg at chi {last:g})") # fmt: skip + + +#: the reference script's grid, 10 x 5 deg (Grid is frozen, so one shared default is safe) +DEFAULT_GRID = Grid() + + +def solid_angle_weights(chi: FloatArray, *, chi_step: float, phi_step: float, + ring_steps: FloatArray | None = None) -> FloatArray: # fmt: skip + """ + Solid-angle weight of each grid point: cos chi, half at chi 0, and the chi 90 cap shared by its points. + + Args: + chi: Chi of each point (deg). + chi_step: Ring step (deg). Points within chi_step / 2 of chi 90 share the polar cap. + phi_step: Phi step (deg). + ring_steps: The phi step of each point's ring, which scales a point whose ring is stepped more coarsely than + ``phi_step``. None is the uniform grid (default). + + Returns: + Weights in units of a chi_step x phi_step cell. + """ + w = np.cos(np.radians(chi)) * np.where(np.abs(chi) < 0.05, 0.5, 1.0) + if ring_steps is not None: + w = w * np.asarray(ring_steps, float) / phi_step + cap = chi > 90 - chi_step / 2 - 1e-6 + w[cap] = ( + 2 * np.pi * (1 - np.cos(np.radians(chi_step / 2))) / (np.radians(phi_step) * np.radians(chi_step)) + / max(int(cap.sum()), 1) + ) # fmt: skip + return np.asarray(w, float) diff --git a/pyrs/pole_figures/core/hb2b.py b/pyrs/pole_figures/core/hb2b.py new file mode 100644 index 00000000..d7206a14 --- /dev/null +++ b/pyrs/pole_figures/core/hb2b.py @@ -0,0 +1,38 @@ +""" +HB-2B (HIDRA, HFIR) instrument constants used by the pole-figure core. + +They are the monochromator wavelengths, the 2theta range for pole figures and the table-scan process-variable (PV) +names. + +Example: + >>> two_theta_allowed(104.0), two_theta_allowed(130.0) + (True, False) +""" + +from pyrs.core.monosetting import MonoSetting + +#: HB-2B monochromator setting -> nominal wavelength (Å), from PyRS's +#: ``pyrs.core.monosetting.MonoSetting`` (every name, so Si511 is listed with the same wavelength as Si333). Calibrated +#: values per run come from the data files. +HB2B_WAVELENGTHS: dict[str, float] = {name: float(m.value) for name, m in MonoSetting.__members__.items()} + +# 2theta range allowed for pole-figure reflections on HB-2B. Outside it the peak is not used. +TWO_THETA_MIN, TWO_THETA_MAX = 50.0, 120.0 + + +def two_theta_allowed(two_theta: float) -> bool: + """ + True when a reflection's 2theta is inside the allowed HB-2B range (inclusive). + + Args: + two_theta: 2theta of the reflection (deg). + + Returns: + Whether ``TWO_THETA_MIN <= two_theta <= TWO_THETA_MAX``. + """ + return TWO_THETA_MIN <= two_theta <= TWO_THETA_MAX + + +#: table-scan columns that set the run title and the phase label (EPICS process variables) +RUN_TITLE_PV = "HB2B:SMS:RunInfo:RunTitle" +PHASE_PV = "HB2B:CS:hklPhase" diff --git a/pyrs/pole_figures/core/neutron_xs.py b/pyrs/pole_figures/core/neutron_xs.py new file mode 100644 index 00000000..dae2fa95 --- /dev/null +++ b/pyrs/pole_figures/core/neutron_xs.py @@ -0,0 +1,215 @@ +""" +Neutron attenuation of a mixture from the packaged cross-section table, and compositions as text. + +- Attenuation: Beer-Lambert for a mixture, mu = sum of n_i (sigma_scatt + sigma_abs(lambda)) over the elements, + with the absorption cross section scaled linearly with wavelength from the 1.798 A reference. +- Neutron data: natural-abundance coherent scattering lengths and cross sections from the NIST table (Sears, + Neutron News 3 (1992) 26), packaged as ``data/isotope_xs_db.csv``. Elements without data there are refused. + +Typical workflow: + +1. Read a composition typed as text with :func:`parse_composition` (or build the dict). +2. Get the attenuation with :func:`mu_per_mm`. + +Example: + >>> round(mu_per_mm({"Fe": 100.0}, 7.874, 1.54), 4) + 0.1173 + >>> parse_composition("Ni:52.5, Cr:19") + {'Ni': 52.5, 'Cr': 19.0} +""" + +import csv +import math +from collections.abc import Mapping +from dataclasses import dataclass +from functools import cache +from importlib import resources + +import gemmi +import numpy as np + +#: the package's data folder, found from this module's own package (core -> the package root) +DATA_PACKAGE = __name__.rsplit(".", 2)[0] + ".data" + +_LAMBDA_REF_A = 1.798 # 2200 m/s neutron +AVOGADRO = 6.02214076e23 # 1/mol + + +@dataclass(frozen=True) +class ElementXS: + """ + Natural-abundance neutron data for one element (NIST, Sears 1992). NaN where the table has no value. + + Attributes: + b_coh_fm: Coherent scattering length (fm), complex for absorbing elements. + scatt_xs_b: Total scattering cross section (barn). + abs_xs_b: Absorption cross section at 1.798 Å (barn). + """ + + b_coh_fm: complex + scatt_xs_b: float + abs_xs_b: float + + +def _num(s: str) -> float: + """A number from the table, NaN when it has none (so a missing value is never used as 0).""" + try: + return float(s) + except ValueError: + return math.nan + + +def _cnum(s: str) -> complex: + try: + return complex(s.strip().replace("i", "j")) + except ValueError: + return complex(math.nan, math.nan) + + +def _known(value: complex | float) -> bool: + return bool(np.isfinite(value)) + + +@cache +def scattering_table() -> dict[str, ElementXS]: + """ + Natural elements from the packaged isotope table (cached). + + Returns: + Element symbol -> neutron data, for the rows whose symbol is purely alphabetic (no isotope number). + """ + text = resources.files(DATA_PACKAGE).joinpath("isotope_xs_db.csv").read_text(encoding="utf-8") + out: dict[str, ElementXS] = {} + for row in csv.DictReader(text.splitlines()): + sym = row["Isotope"].strip() + if sym.isalpha(): + out[sym] = ElementXS(_cnum(row["coh_b_fm"]), _num(row["scatt_xs_b"]), _num(row["abs_xs_b"])) + return out + + +def atomic_mass(symbol: str) -> float: + """ + Standard atomic weight. + + Args: + symbol: Element symbol. + + Returns: + The atomic weight (g/mol). + + Raises: + ValueError: If gemmi does not know the element. + """ + w = float(gemmi.Element(symbol).weight) + if w <= 0: + raise ValueError(f"unknown element '{symbol}'") + return w + + +def _check_elements(composition: Mapping[str, float]) -> None: + table = scattering_table() + for el, wt in composition.items(): + if wt < 0: + raise ValueError(f"weight percent for {el} is negative ({wt})") + if el not in table: + raise ValueError(f"element '{el}' is not in the neutron cross-section table") + if not (_known(table[el].scatt_xs_b) and _known(table[el].abs_xs_b)): + raise ValueError(f"no neutron cross sections for element '{el}' in the table, so mu cannot be computed") + if sum(composition.values()) <= 0: + raise ValueError(f"the composition has no weight, got {composition!r}") + + +def mu_per_mm(composition: Mapping[str, float], density_g_cm3: float, wavelength_A: float) -> float: + """ + Linear attenuation coefficient of a mixture: scattering plus wavelength-scaled absorption. + + Args: + composition: Element symbol -> weight percent (normalized internally). + density_g_cm3: Bulk density (g/cm3). + wavelength_A: Neutron wavelength (Å). + + Returns: + mu (1/mm). + + Raises: + ValueError: If the density or wavelength is not positive, a weight is negative, the weights sum to zero, or + an element has no cross sections in the table. + + Example: + >>> round(mu_per_mm({"Fe": 100.0}, 7.874, 1.54), 4) + 0.1173 + """ + if density_g_cm3 <= 0 or wavelength_A <= 0: + raise ValueError(f"density and wavelength must be positive, got density {density_g_cm3!r} g/cm3 and " + f"wavelength {wavelength_A!r} A") # fmt: skip + _check_elements(composition) + table = scattering_table() + total = sum(composition.values()) + sigma_cm = 0.0 + for el, wt in composition.items(): + xs = table[el] + sigma_tot = xs.scatt_xs_b + xs.abs_xs_b * (wavelength_A / _LAMBDA_REF_A) + sigma_cm += density_g_cm3 * (wt / total) * AVOGADRO / atomic_mass(el) * sigma_tot * 1e-24 + return sigma_cm * 0.1 + + +def atomic_fractions(composition: Mapping[str, float]) -> dict[str, float]: + """ + Weight percent to atomic fraction. + + Args: + composition: Element symbol -> weight percent (any total). + + Returns: + Element symbol -> atomic fraction (summing to 1). + """ + n = {el: wt / atomic_mass(el) for el, wt in composition.items()} + s = sum(n.values()) + return {el: v / s for el, v in n.items()} + + +def parse_composition(text: str) -> dict[str, float]: + """ + Read a composition typed as text. + + Args: + text: ``Element:weight_percent`` pairs split by commas, e.g. ``"Ni:52.5, Cr:19, Fe:18.5"``. Symbols are + title-cased and repeated elements are added up. + + Returns: + Element symbol -> weight percent, e.g. ``{"Ni": 52.5, "Cr": 19.0, "Fe": 18.5}``. + + Raises: + ValueError: If a pair has no colon or no number, the composition is empty, or an element is not usable (see + :func:`mu_per_mm`). + """ + out: dict[str, float] = {} + for token in text.split(","): + token = token.strip() + if not token: + continue + if ":" not in token: + raise ValueError(f"'{token}': expected Element:weight_percent, e.g. Fe:97.0") + el, wt = token.split(":", 1) + sym = el.strip().title() + try: + out[sym] = out.get(sym, 0.0) + float(wt) + except ValueError as exc: + raise ValueError(f"'{wt.strip()}' is not a number (element {sym})") from exc + if not out: + raise ValueError(f"the composition is empty, got {text!r}") + _check_elements(out) + return out + + +def format_composition(composition: Mapping[str, float]) -> str: + """ + Write a composition as text that :func:`parse_composition` reads back. + + Args: + composition: Element symbol -> weight percent. + + Returns: + E.g. ``"Ni:52.5, Cr:19, Fe:18.5"``. + """ + return ", ".join(f"{el}:{wt:g}" for el, wt in composition.items()) diff --git a/pyrs/pole_figures/core/parallel.py b/pyrs/pole_figures/core/parallel.py new file mode 100644 index 00000000..e33669ff --- /dev/null +++ b/pyrs/pole_figures/core/parallel.py @@ -0,0 +1,251 @@ +""" +Worker processes for independent pieces of work, such as the Monte Carlo orientations. + +Each orientation's intensity factor is computed exactly as in the serial loop, so the results are identical. Small +jobs stay serial: starting the processes costs a few seconds. No Qt here; a GUI calls this from a worker thread. + +Typical workflow: + +1. :func:`intensity_factors` picks the number of processes with :func:`n_workers` (or the ``HIDRA_PF_WORKERS`` + environment variable). +2. :func:`run_chunks` starts spawned workers at low priority and hands back each chunk's result as it finishes. + +Example: + >>> n_workers(1e6) + 1 + >>> rows = intensity_factors(m, chi=chi, phi=phi, points=pts, volume=vol, mesh=mesh, + ... center=(0.0, 0.0, 0.0), mu=0.1) # doctest: +SKIP +""" + +import ctypes +import multiprocessing +import os +import pickle +import sys +import threading +import warnings +from collections.abc import Callable, Iterator, Sequence +from concurrent.futures import ProcessPoolExecutor, as_completed +from contextlib import contextmanager +from typing import Any, Literal + +import numpy as np +import numpy.typing as npt + +from .gauge import IntensityFactor, intensity_factor +from .geometry import Mount +from .stl_mesh import SampleMesh +from .types import CountProgress, FloatArray, no_count_progress + +MAX_WORKERS = 6 # gentle on a desktop or a shared analysis node; HIDRA_PF_WORKERS overrides (1 = serial) +#: orientations x Monte Carlo points x triangles below this run serially (about 8 s of tracing on a desktop) +MIN_PARALLEL_WORK = 3e9 + +_ONE_THREAD = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS") +_STATE: dict[str, Any] = {} +#: worker_start changes process-wide state (environment, __main__): one job at a time may do so +_START_LOCK = threading.Lock() + + +def usable_cpus() -> int: + """Cores this process may run on (CPU affinity or cgroup limits on a shared node), else all cores.""" + if hasattr(os, "process_cpu_count"): # Python 3.13+ + return os.process_cpu_count() or 1 + if hasattr(os, "sched_getaffinity"): + return len(os.sched_getaffinity(0)) or 1 + return os.cpu_count() or 1 + + +Workers = int | Literal["auto"] + + +def n_workers(work: float, *, requested: Workers = "auto", min_work: float = MIN_PARALLEL_WORK) -> int: + """ + Processes to use for a job of the given size. + + Args: + work: Size of the job: orientations x Monte Carlo points x triangles. + requested: A positive whole number to use as it is, or "auto" (default): the HIDRA_PF_WORKERS environment + variable (a positive whole number), else 1 below ``min_work``, else up to MAX_WORKERS and at most half + the cores this process may use (the workers run at low priority). + min_work: Jobs smaller than this run serially (default: ``MIN_PARALLEL_WORK``). + + Returns: + The number of processes, 1 for serial. + + Raises: + ValueError: If requested is neither "auto" nor a positive whole number. + """ + if requested != "auto": + if isinstance(requested, bool) or not isinstance(requested, int) or requested < 1: + raise ValueError(f"workers must be a positive whole number or 'auto', got {requested!r}") + return requested + env = os.environ.get("HIDRA_PF_WORKERS", "").strip() + if env: + if env.isascii() and env.isdigit() and int(env) > 0: # isdigit alone accepts "²", which int() refuses + return int(env) + warnings.warn(f"HIDRA_PF_WORKERS={env!r} is not a positive whole number; choosing automatically", + stacklevel=2) # fmt: skip + if work < min_work: + return 1 + return max(1, min(MAX_WORKERS, usable_cpus() // 2)) + + +def lower_priority() -> None: + """Run this process below normal priority, so interactive work on the machine comes first.""" + if sys.platform == "win32": + below_normal = 0x00004000 + # a failed call returns 0 and leaves normal priority: the results are the same, only less polite + ctypes.windll.kernel32.SetPriorityClass(ctypes.windll.kernel32.GetCurrentProcess(), below_normal) + return + try: + os.nice(10) + except OSError: # not permitted here (e.g. a restricted container): normal priority gives the same results + pass + + +@contextmanager +def worker_start() -> Iterator[None]: + """ + Settings for starting worker processes (they inherit them): no main-module import, one numpy thread each. + + A spawned process imports the parent's main module (by its spec or file). For a GUI that is the whole Qt app, + loaded in every worker before it can start, one after another, so the main module is hidden meanwhile. Each + worker's numpy is limited to one thread: a dozen workers each starting a thread per core slow each other down. + The changes are process-wide, so only one job at a time makes them (a lock), and they are always undone. + """ + with _START_LOCK: + with _hidden_main(): + yield + + +@contextmanager +def _hidden_main() -> Iterator[None]: + old_env = {k: os.environ.get(k) for k in _ONE_THREAD} + os.environ.update(dict.fromkeys(_ONE_THREAD, "1")) + main = sys.modules.get("__main__") + saved: dict[str, Any] = {} + if main is not None: + saved = {k: main.__dict__[k] for k in ("__spec__", "__file__") if k in main.__dict__} + main.__dict__["__spec__"] = None + main.__dict__.pop("__file__", None) + try: + yield + finally: + if main is not None: + main.__dict__.pop("__spec__", None) + main.__dict__.update(saved) + for k, v in old_env.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + + +def run_chunks(chunks: Sequence[Any], *, init: Callable[[bytes], None], task: Callable[[Any], Any], payload: bytes, + workers: int, on_done: Callable[[Any, Any], None]) -> None: # fmt: skip + """ + Run ``task(chunk)`` for every chunk in spawned worker processes. + + Args: + chunks: The pieces of work, each picklable. + init: Called once in each worker with ``payload`` (module-level, so it pickles). + task: Called in a worker for each chunk (module-level, so it pickles). + payload: Pickled data every worker needs (sent once per worker, not per chunk). + workers: Number of processes. + on_done: ``on_done(chunk, result)``, called in this process as chunks finish, in completion order. If it + raises (e.g. the user cancelled), the remaining chunks are dropped and the exception is passed on. + """ + ctx = multiprocessing.get_context("spawn") + with ProcessPoolExecutor(max_workers=workers, mp_context=ctx, initializer=init, initargs=(payload,)) as pool: + with worker_start(): # processes start as tasks are submitted + futures = {pool.submit(task, c): c for c in chunks} + try: + for fut in as_completed(futures): + on_done(futures[fut], fut.result()) + except BaseException: + pool.shutdown(wait=False, cancel_futures=True) + raise + + +def _init_if(payload: bytes) -> None: + lower_priority() + _STATE["if"] = pickle.loads(payload) + + +def _run_if(chunk: list[tuple[int, float, float]]) -> list[tuple[int, IntensityFactor]]: + m, pts, vol, mesh, center, mu = _STATE["if"] + return [(k, intensity_factor(m, chi=c, phi=f, points=pts, volume=vol, mesh=mesh, center=center, mu=mu)) + for k, c, f in chunk] # fmt: skip + + +def intensity_factors( + m: Mount, + *, + chi: npt.ArrayLike, + phi: npt.ArrayLike, + points: FloatArray, + volume: float, + mesh: SampleMesh, + center: npt.ArrayLike, + mu: float, + progress: CountProgress = no_count_progress, + workers: Workers = "auto", +) -> list[IntensityFactor]: + """ + ``gauge.intensity_factor`` at every (chi, phi), in order; in parallel processes when the job is large. + + Args: + m: Beams and rotation conventions. + chi: Cradle chi of each orientation (deg). + phi: Phi of each orientation (deg), same length as chi. + points: Gauge points from ``gauge.gauge_points`` (cradle frame, mm). + volume: Gauge volume (mm3). + mesh: Sample in its own frame (mm). + center: Gauge center in the sample frame (mm). + mu: Linear attenuation coefficient (1/mm). + progress: ``progress(n_done)``, called as orientations finish. It may raise to stop the job. + workers: Number of processes, or "auto" (default) to choose from the job size (:func:`n_workers`). + + Returns: + One result per orientation, in the order of chi and phi. + + Raises: + ValueError: If workers is neither "auto" nor a positive whole number. + RuntimeError: If an orientation returned no result. + """ + pts, vol = points, volume + chi = np.asarray(chi, float).ravel() + phi = np.asarray(phi, float).ravel() + n = len(chi) + w = n_workers(float(n) * len(pts) * mesh.ntri, requested=workers) + out: list[IntensityFactor | None] = [None] * n + if w <= 1 or n < 2 * w: + for k in range(n): + out[k] = intensity_factor(m, chi=float(chi[k]), phi=float(phi[k]), points=pts, volume=vol, mesh=mesh, + center=center, mu=mu) # fmt: skip + progress(k + 1) + return _complete(out) + jobs = [(k, float(chi[k]), float(phi[k])) for k in range(n)] + size = max(1, min(40, n // (6 * w))) + chunks = [jobs[j : j + size] for j in range(0, n, size)] + done = 0 + + def on_done(_chunk: Any, result: list[tuple[int, IntensityFactor]]) -> None: + nonlocal done + for k, r in result: + out[k] = r + done += len(result) + progress(done) + + payload = pickle.dumps((m, pts, vol, mesh, np.asarray(center, float), mu)) + run_chunks(chunks, init=_init_if, task=_run_if, payload=payload, workers=w, on_done=on_done) + return _complete(out) + + +def _complete(out: list[IntensityFactor | None]) -> list[IntensityFactor]: + """The results in order. Raises if any orientation has none (a shorter list would misalign chi and phi).""" + missing = sum(r is None for r in out) + if missing: + raise RuntimeError(f"{missing} of {len(out)} orientations returned no result") + return [r for r in out if r is not None] diff --git a/pyrs/pole_figures/core/peaks.py b/pyrs/pole_figures/core/peaks.py new file mode 100644 index 00000000..8e734c1e --- /dev/null +++ b/pyrs/pole_figures/core/peaks.py @@ -0,0 +1,290 @@ +""" +Peak intensity per sub-run: window integration or a pseudo-Voigt fit, ported from the reference script. + +``peak_list``, ``find_peak``, ``integrate`` and ``fit_peak`` keep its numerics. + +Intensity = net counts in a fixed 2theta window (+- 1.5 FWHM of the summed peak) above a straight background from +both sides, or (option) the area of a pseudo-Voigt plus linear background fit. Rates are per second of count time. +All 2theta values and widths are in degrees. + +Typical workflow: + +1. List the reflections on the detector with :func:`peak_list`. +2. Find each central peak's center and FWHM on the spectrum summed over sub-runs with :func:`find_peak`. +3. Measure each sub-run with :func:`integrate` (or :func:`fit_peak`) and flag doubtful peaks with + :func:`peak_quality`. :func:`measure_peaks` does all three for every central peak of a run. + +Example: + >>> peaks = peak_list(x, arm=90.0, candidates=[("111", 70.1), ("200", 82.3)]) # doctest: +SKIP + >>> center, fwhm = find_peak(x, y.sum(axis=0), peaks[0].two_theta) # doctest: +SKIP + >>> net, sigma = integrate(x, y[0], center=center, half_width=WINDOW_FWHM * fwhm) # doctest: +SKIP +""" + +import typing +from collections.abc import Iterable +from dataclasses import dataclass, field +from typing import Literal + +import numpy as np +from scipy.optimize import curve_fit + +from .runs import RunData +from .types import FloatArray + +CENTRAL_HALF_WIDTH_DEG = 5.0 # only peaks this close to the arm 2theta are used (edge pixels see another volume) +WINDOW_FWHM = 1.5 # integration half-window in FWHM of the summed peak +WEAK_PEAK_SIGMA = 5.0 # a summed peak below this net/sigma is flagged as weak (it is still used) +MIN_FWHM_BINS = 2 # a summed-peak FWHM narrower than this many bins is flagged +Method = Literal["window", "fit"] + + +@dataclass(frozen=True) +class PeakCandidate: + """ + A reflection on the detector. + + Attributes: + hkl: hkl label, e.g. "111". + two_theta: Expected 2theta at the run's wavelength (deg). + central: Within ``central_hw`` of the arm 2theta, so it is used for a pole figure. + """ + + hkl: str + two_theta: float + central: bool + + +def peak_list(x: FloatArray, *, arm: float, candidates: Iterable[tuple[str, float]], + central_hw: float = CENTRAL_HALF_WIDTH_DEG) -> list[PeakCandidate]: # fmt: skip + """ + Reflections whose expected 2theta is on the detector (0.5 deg inside its edges), flagged central or not. + + Args: + x: 2theta of the spectrum bins (deg). + arm: Detector arm 2theta (deg). + candidates: (hkl label, expected 2theta) pairs at the run's wavelength. Non-finite 2theta are skipped. + central_hw: A reflection within this of the arm is central (deg, default: 5). + + Returns: + The reflections on the detector, in the order given. + """ + out = [] + for hkl, tt in candidates: + if np.isfinite(tt) and x.min() + 0.5 < tt < x.max() - 0.5: + out.append(PeakCandidate(hkl, float(tt), abs(tt - arm) <= central_hw)) + return out + + +def find_peak(x: FloatArray, ysum: FloatArray, guess: float) -> tuple[float, float]: + """ + Center and FWHM of the summed peak near ``guess``. + + The highest bin within 1 deg of the guess starts the search. A straight background fitted 1.2 to 3 deg from it + is subtracted. The center is the centroid of the positive net counts within 1.2 deg, and the FWHM is the span of + the bins above half the net maximum. + + Args: + x: 2theta of the bins (deg). + ysum: Counts summed over sub-runs. + guess: Expected 2theta (deg). + + Returns: + The center and the FWHM (deg). + + Raises: + ValueError: If there are no net counts above the background near the guess. + """ + near = np.abs(x - guess) < 1.0 + c0 = x[near][np.argmax(ysum[near])] + bgm = (np.abs(x - c0) > 1.2) & (np.abs(x - c0) < 3.0) + net = ysum - np.polyval(np.polyfit(x[bgm], ysum[bgm], 1), x) + near = np.abs(x - c0) < 1.2 + w = np.clip(net[near], 0, None) + if not w.sum() > 0: + raise ValueError(f"no peak above the background near 2theta {guess:.2f} deg") + c = float((x[near] * w).sum() / w.sum()) + above = x[near][net[near] > net[near].max() / 2] + return c, float(above.max() - above.min()) + + +def integrate(x: FloatArray, y: FloatArray, *, center: float, half_width: float) -> tuple[float, float]: + """ + Net counts in a 2theta window above a straight background, and its sigma. + + The background line is fitted to the bins from half_width + 0.3 to half_width + 2.5 deg on both sides. The sigma + holds the Poisson error of the net counts and of the background under the window. + + Args: + x: 2theta of the bins (deg). + y: Counts per bin. + center: Window center (deg). + half_width: Window half-width (deg): bins with ``|x - center| <= half_width`` are summed. + + Returns: + The net counts and their sigma (counts). + """ + c, half = center, half_width + bgm = (np.abs(x - c) > half + 0.3) & (np.abs(x - c) < half + 2.5) + s = np.abs(x - c) <= half + coef = np.polyfit(x[bgm], y[bgm], 1) + bg = np.polyval(coef, x[s]).sum() + net = float(y[s].sum() - bg) + bgv = float(s.sum() ** 2 / bgm.sum() * np.mean(y[bgm]) + bg) + return net, float(np.sqrt(max(net, 0) + bgv)) + + +def _pv(t: FloatArray, a: float, x0: float, f: float, eta: float, b0: float, b1: float, c: float) -> FloatArray: + g = np.exp(-4 * np.log(2) * ((t - x0) / f) ** 2) * 2 * np.sqrt(np.log(2) / np.pi) / f + lo = 2 / (np.pi * f) / (1 + 4 * ((t - x0) / f) ** 2) + return np.asarray(a * (eta * lo + (1 - eta) * g) + b0 + b1 * (t - c)) + + +def fit_peak(x: FloatArray, y: FloatArray, *, center: float, fwhm: float, half_width: float) -> tuple[float, float]: + """ + Peak area from a pseudo-Voigt plus linear background fit, with Poisson weights. + + The fit range is ``|x - center| < half_width + 2.5`` deg. The center is bounded to center +- 1 deg, the FWHM to + 0.3 to 3 times ``fwhm`` and the Lorentzian fraction to 0 to 1. + + Args: + x: 2theta of the bins (deg). + y: Counts per bin. Non-finite bins are left out. + center: Center of the summed peak (deg). + fwhm: FWHM of the summed peak (deg). + half_width: Integration half-width (deg). + + Returns: + The area and its sigma in counts (area over the bin width), or (nan, nan) when the fit fails. + """ + c, fw, half = center, fwhm, half_width + s = np.abs(x - c) < half + 2.5 + t, v = x[s], y[s] + ok = np.isfinite(v) + t, v = t[ok], v[ok] + bw = float(np.median(np.diff(t))) + edge = np.abs(t - c) > half + 0.3 + b0 = float(np.median(v[edge])) if edge.any() else float(np.min(v)) + a0 = max(float((v[~edge] - b0).sum()) * bw, 1.0) + p0 = [a0, c, fw, 0.5, b0, 0.0] + lb = [-np.inf, c - 1.0, 0.3 * fw, 0.0, -np.inf, -np.inf] + ub = [np.inf, c + 1.0, 3.0 * fw, 1.0, np.inf, np.inf] + try: + + def model(tt: FloatArray, a: float, x0: float, f: float, eta: float, b0_: float, b1: float) -> FloatArray: + return _pv(tt, a, x0, f, eta, b0_, b1, c) + + p, cov = curve_fit(model, t, v, p0=p0, sigma=np.sqrt(np.maximum(v, 1.0)), absolute_sigma=False, + bounds=(lb, ub), maxfev=20000) # fmt: skip + return float(p[0] / bw), float(np.sqrt(cov[0, 0]) / bw) + except (RuntimeError, ValueError, np.linalg.LinAlgError): # the fit did not converge: NaN, so the point is ignored + return np.nan, np.nan + + +def peak_quality(x: FloatArray, ysum: FloatArray, *, center: float, fwhm: float, hkl: str, + others: Iterable[PeakCandidate] = ()) -> list[str]: # fmt: skip + """ + Warnings about the summed peak (the values are still used): weak, too narrow, or overlapping another. + + The pole figure then says why it may be unreliable, instead of looking like any other. + + Args: + x: 2theta of the bins (deg). + ysum: Counts summed over sub-runs. + center: Center of the summed peak (deg). + fwhm: FWHM of the summed peak (deg). + hkl: hkl label of the peak. + others: The other central reflections. One within 1.5 FWHM (or 1.5 bins) of the center overlaps. + + Returns: + Warning texts, empty when the peak looks fine. + """ + c, fw = center, fwhm + notes = [] + net, sig = integrate(x, ysum, center=c, half_width=WINDOW_FWHM * fw) + if not (sig > 0 and net / sig >= WEAK_PEAK_SIGMA): + notes.append(f"weak peak: summed net/sigma {net / sig if sig > 0 else 0:.1f} (below {WEAK_PEAK_SIGMA:g})") + bin_w = float(np.median(np.diff(x))) if len(x) > 1 else 0.0 + if bin_w > 0 and fw < MIN_FWHM_BINS * bin_w: + notes.append(f"peak FWHM {fw:.3f} deg is under {MIN_FWHM_BINS} bins") + close = [o.hkl for o in others if abs(o.two_theta - c) < WINDOW_FWHM * max(fw, bin_w)] + if close: + notes.append(f"{{{hkl}}} overlaps {', '.join('{' + h + '}' for h in close)} on the detector") + return notes + + +def find_peaks(run: RunData, candidates: Iterable[tuple[str, float]], *, + central_hw: float = CENTRAL_HALF_WIDTH_DEG) -> list[PeakCandidate]: # fmt: skip + """ + Reflections on this run's detector (central and edge). + + Args: + run: The run. + candidates: (hkl label, expected 2theta) pairs at the run's wavelength. + central_hw: A reflection within this of the arm is central (deg, default: 5). + + Returns: + The reflections on the detector (see ``peaks.peak_list``). + """ + return peak_list(run.x, arm=run.arm_two_theta, candidates=candidates, central_hw=central_hw) + + +@dataclass(frozen=True, kw_only=True) +class PeakIntensity: + """ + A central peak of one run. + + Attributes: + hkl: hkl label. + two_theta: Center of the summed peak (deg). + fwhm: FWHM of the summed peak (deg). + rate: Raw net rate per sub-run (counts/s). NaN where the fit failed. + sigma: Sigma of the rate (counts/s). + notes: Warnings about the peak (see ``peaks.peak_quality``) or the fit. + """ + + hkl: str + two_theta: float + fwhm: float + rate: FloatArray + sigma: FloatArray + notes: list[str] = field(default_factory=list) + + +def measure_peaks(run: RunData, candidates: Iterable[tuple[str, float]], *, central_hw: float = CENTRAL_HALF_WIDTH_DEG, + method: Method = "window") -> list[PeakIntensity]: # fmt: skip + """ + Net rate and sigma per sub-run for each central peak. + + Args: + run: The run. + candidates: (hkl label, expected 2theta) pairs at the run's wavelength. + central_hw: Peaks within this of the arm are used (deg, default: 5). + method: "window" integration (default) or pseudo-Voigt "fit". + + Returns: + One entry per central peak. + + Raises: + ValueError: If method is unknown, or a central peak has no counts above the background. + """ + if method not in typing.get_args(Method): + raise ValueError(f"method must be one of {', '.join(typing.get_args(Method))}, got {method!r}") + x, y, t = run.x, run.y, run.count_s + ysum = y.sum(axis=0) + out = [] + central = [pk for pk in find_peaks(run, candidates, central_hw=central_hw) if pk.central] + for pk in central: + c, fw = find_peak(x, ysum, pk.two_theta) + half = WINDOW_FWHM * fw + if method == "fit": + net = np.array([fit_peak(x, y[i], center=c, fwhm=fw, half_width=half) for i in range(len(t))]) + else: + net = np.array([integrate(x, y[i], center=c, half_width=half) for i in range(len(t))]) + notes = peak_quality(x, ysum, center=c, fwhm=fw, hkl=pk.hkl, others=[q for q in central if q is not pk]) + failed = int((~np.isfinite(net[:, 0])).sum()) + if failed: + notes.append(f"the fit failed in {failed} of {len(t)} sub-runs (those points are ignored)") + out.append( + PeakIntensity(hkl=pk.hkl, two_theta=c, fwhm=fw, rate=net[:, 0] / t, sigma=net[:, 1] / t, notes=notes) + ) + return out diff --git a/pyrs/pole_figures/core/phase.py b/pyrs/pole_figures/core/phase.py new file mode 100644 index 00000000..095c3afd --- /dev/null +++ b/pyrs/pole_figures/core/phase.py @@ -0,0 +1,350 @@ +""" +Crystal phases: presets, CIF import, allowed reflections and 2theta at a wavelength. + +- Allowed reflections: every hkl that is not systematically absent in the space group and whose neutron structure + factor (coherent scattering lengths, all sites in the cell) is not zero. Symmetry-equivalent hkl are grouped into + one family with its multiplicity (Friedel pairs included). +- Attenuation of a phase: :meth:`Phase.mu_per_mm`, from its composition and density (``neutron_xs.mu_per_mm``). + +Typical workflow: + +1. Take a preset with :func:`presets`, read a CIF with :meth:`Phase.from_cif`, or build a :class:`Phase`. +2. List the reflections at the wavelength with :meth:`Phase.reflections` and keep those inside the HB-2B 2theta range + (``hb2b.two_theta_allowed``). +3. Get the attenuation with :meth:`Phase.mu_per_mm`. + +Example: + >>> fe = Phase(name="Fe", space_group="Im-3m", cell=(2.8665, 2.8665, 2.8665, 90.0, 90.0, 90.0), + ... sites=(Site(element="Fe", x=0.0, y=0.0, z=0.0),), composition={"Fe": 100.0}, density_g_cm3=7.874) + >>> [r.label for r in fe.reflections(1.54)][:3] + ['110', '200', '211'] + >>> round(fe.two_theta((2, 1, 1), 1.54), 2) + 82.29 + >>> round(fe.mu_per_mm(1.54), 4) + 0.1173 +""" + +import json +import warnings +from collections.abc import Mapping +from dataclasses import dataclass, fields +from functools import cache +from importlib import resources +from pathlib import Path +from types import MappingProxyType +from typing import Any + +import gemmi +import numpy as np + +from .neutron_xs import AVOGADRO, DATA_PACKAGE, atomic_fractions, atomic_mass, mu_per_mm, scattering_table +from .reflections import Reflection, ScatteringSite, bragg_two_theta, hkl_search_limit, reflection_families + +AVERAGE = "avg" # site element meaning "the composition-weighted average atom" (alloys on one site) + + +@dataclass(frozen=True, kw_only=True) +class Site: + """ + Atom site of the asymmetric unit. + + Attributes: + element: Element symbol, or ``"avg"`` for the composition-average atom (alloys on one site). + x: Fractional coordinate along a. + y: Fractional coordinate along b. + z: Fractional coordinate along c. + occupancy: Site occupancy (default: 1). + """ + + element: str + x: float + y: float + z: float + occupancy: float = 1.0 + + +@dataclass(frozen=True, kw_only=True) +class Phase: + """ + A crystal phase with its composition and density (for attenuation). + + Attributes: + name: Display name. + space_group: Hermann-Mauguin symbol (any form gemmi accepts, e.g. ``"Fm-3m"`` or ``"P 63/m m c"``). + cell: a, b, c (Å), alpha, beta, gamma (deg). + sites: Asymmetric-unit sites. + composition: Element -> weight percent, kept as a read-only mapping (a copy of the one given). + density_g_cm3: Bulk density (g/cm3). + source: Where the data came from (default: ""). + + Raises: + ValueError: If the cell is not six finite numbers with positive lengths and angles between 0 and 180 deg, + the composition is empty or the density is not positive. + + Example: + >>> al = Phase(name="Al", space_group="Fm-3m", cell=(4.0495, 4.0495, 4.0495, 90.0, 90.0, 90.0), + ... sites=(Site(element="Al", x=0.0, y=0.0, z=0.0),), composition={"Al": 100.0}, density_g_cm3=2.70) + >>> [r.label for r in al.reflections(1.54)][:3] + ['111', '200', '220'] + """ + + name: str + space_group: str + cell: tuple[float, float, float, float, float, float] + sites: tuple[Site, ...] + composition: Mapping[str, float] + density_g_cm3: float + source: str = "" + + def __post_init__(self) -> None: + """Refuse a bad cell, or a phase without a composition or a positive density (attenuation needs both).""" + cell = np.asarray(self.cell, float).reshape(-1) + if cell.size != 6 or not np.isfinite(cell).all(): + raise ValueError(f"{self.name}: the cell must be six finite numbers (a, b, c, alpha, beta, gamma), " + f"got {self.cell!r}") # fmt: skip + if not (cell[:3] > 0).all(): + raise ValueError(f"{self.name}: the cell lengths must be positive (A), got {tuple(self.cell[:3])}") + if not ((cell[3:] > 0) & (cell[3:] < 180)).all(): + raise ValueError(f"{self.name}: the cell angles must be between 0 and 180 deg, got {tuple(self.cell[3:])}") + if not self.composition: + raise ValueError(f"{self.name}: the composition is empty, got {self.composition!r}") + object.__setattr__(self, "composition", MappingProxyType(dict(self.composition))) + if not (np.isfinite(self.density_g_cm3) and self.density_g_cm3 > 0): + raise ValueError(f"{self.name}: the density must be positive (g/cm3), got {self.density_g_cm3!r}") + + @classmethod + def from_dict(cls, d: dict[str, Any]) -> "Phase": + """ + Build from a dict such as a preset JSON file. + + Args: + d: Keys name, space_group, cell, composition and density_g_cm3, and optionally sites (a list of + :class:`Site` fields, default one composition-average atom at the origin) and source. A cell of one + value is a cubic a. + + Returns: + The phase. + + Raises: + ValueError: If a required key is missing, the cell does not have 1 or 6 values, a site has an unknown or + missing key, the cell is invalid, the composition is empty or the density is not positive. + """ + name = d.get("name", "?") + missing = [k for k in ("name", "space_group", "cell", "composition", "density_g_cm3") if k not in d] + if missing: + raise ValueError(f"phase {name!r} lacks {', '.join(missing)}") + cell = list(d["cell"]) + if len(cell) not in (1, 6): + raise ValueError(f"phase {name!r}: the cell must have 1 value (cubic a) or 6, got {len(cell)}: {cell!r}") + if len(cell) == 1: + cell = [cell[0]] * 3 + [90.0] * 3 + site_dicts = d.get("sites", [{"element": AVERAGE, "x": 0, "y": 0, "z": 0}]) + known = {f.name for f in fields(Site)} + required = known - {"occupancy"} + for s in site_dicts: + unknown, absent = sorted(set(s) - known), sorted(required - set(s)) + if unknown or absent: + raise ValueError( + f"phase {name!r}: a site takes element, x, y, z and optionally occupancy, got {s!r} " + f"(unknown: {', '.join(unknown) or 'none'}, missing: {', '.join(absent) or 'none'})" + ) + return cls( + name=d["name"], + space_group=d["space_group"], + cell=tuple(float(c) for c in cell), # type: ignore[arg-type] + sites=tuple(Site(**s) for s in site_dicts), + composition={k: float(v) for k, v in d["composition"].items()}, + density_g_cm3=float(d["density_g_cm3"]), + source=d.get("source", ""), + ) + + @classmethod + def from_cif(cls, path: str | Path) -> "Phase": + """ + Read a small-molecule or inorganic CIF. Composition and density come from the cell contents. + + A density outside 0.5 to 25 g/cm3 gives a warning (check the cell and the occupancies). + + Args: + path: The CIF file. + + Returns: + The phase, with the space group in its CIF setting (extended H-M symbol). + + Raises: + ValueError: If the file cannot be read or parsed as a CIF, holds more than one data block, has no space + group gemmi recognizes, no unit cell, no atom sites, or atoms whose occupancies are all zero. The + message names the file. + """ + try: + doc = gemmi.cif.read(str(path)).sole_block() + st = gemmi.read_small_structure(str(path)) + except (RuntimeError, ValueError) as exc: # gemmi reports parse errors and several blocks as RuntimeError + raise ValueError(f"{path}: cannot read the CIF: {exc}") from exc + # the space group with its setting (origin choice, hexagonal or rhombohedral axes) from the CIF's own + # setting code, Hall symbol or symmetry operators: the plain H-M name alone picks the default setting + sg = st.spacegroup + if sg is None: + raise ValueError(f"{path}: no space group that gemmi recognizes in the CIF ({st.spacegroup_hm!r})") + if not all(doc.find_value(f"_cell_length_{k}") for k in "abc"): + raise ValueError(f"{path}: the CIF has no unit cell (_cell_length_a, b, c)") + sites = tuple( + Site( + element=s.element.name, + x=float(s.fract.x), + y=float(s.fract.y), + z=float(s.fract.z), + occupancy=float(s.occ), + ) + for s in st.sites + ) + if not sites: + raise ValueError(f"{path}: no atom sites in the CIF") + c = st.cell + cell = (c.a, c.b, c.c, c.alpha, c.beta, c.gamma) + mass: dict[str, float] = {} + for s in st.get_all_unit_cell_sites(): + el = s.element.name + mass[el] = mass.get(el, 0.0) + float(s.occ) * atomic_mass(el) + total = sum(mass.values()) + if not total > 0: + raise ValueError(f"{path}: the atom occupancies in the CIF are all zero, so it has no composition") + density = total / AVOGADRO / (c.volume * 1e-24) + if not 0.5 <= density <= 25.0: + warnings.warn(f"{path}: the cell contents give a density of {density:.3g} g/cm3, outside 0.5 to 25. " + "Check the cell and the occupancies.", stacklevel=2) # fmt: skip + name = st.name or Path(path).stem + return cls( + name=name, + space_group=sg.xhm(), + cell=cell, + sites=sites, + composition={el: 100 * m / total for el, m in mass.items()}, + density_g_cm3=density, + source=f"CIF {Path(path).name}", + ) + + def unit_cell(self) -> gemmi.UnitCell: + """The cell as a gemmi unit cell.""" + return gemmi.UnitCell(*self.cell) + + def spacegroup(self) -> gemmi.SpaceGroup: + """ + The space group as a gemmi space group. + + Raises: + ValueError: If gemmi does not know the symbol. + """ + sg = gemmi.find_spacegroup_by_name(self.space_group) + if sg is None: + raise ValueError(f"unknown space group '{self.space_group}'") + return sg + + def d_spacing(self, hkl: tuple[int, int, int]) -> float: + """ + d-spacing of a reflection. + + Args: + hkl: Miller indices. + + Returns: + d (Å). + """ + return float(self.unit_cell().calculate_d(list(hkl))) + + def two_theta(self, hkl: tuple[int, int, int], wavelength_A: float) -> float: + """ + Bragg angle 2theta of a reflection. + + Args: + hkl: Miller indices. + wavelength_A: Neutron wavelength (Å). + + Returns: + 2theta (deg), NaN when the reflection is beyond 2theta = 180. + """ + return bragg_two_theta(self.unit_cell(), hkl, wavelength_A) + + def _site_b(self) -> list[ScatteringSite]: + """(b, occupancy, all positions in the cell) per site.""" + table = scattering_table() + b_avg = 0j + if any(s.element == AVERAGE for s in self.sites): + if not self.composition: + raise ValueError("an 'avg' site needs a composition") + b_avg = sum(table[el].b_coh_fm * x for el, x in atomic_fractions(self.composition).items()) + ops = self.spacegroup().operations() + out = [] + for s in self.sites: + b = b_avg if s.element == AVERAGE else table[gemmi.Element(s.element).name].b_coh_fm + if not np.isfinite(b): + raise ValueError(f"no coherent scattering length for element '{s.element}' in the neutron table") + pos: list[list[float]] = [] + for op in ops: + p = np.mod(op.apply_to_xyz([s.x, s.y, s.z]), 1.0) + if not any(np.allclose(np.mod(p - q + 0.5, 1.0) - 0.5, 0, atol=1e-4) for q in pos): + pos.append(list(p)) + out.append((b, s.occupancy, pos)) + return out + + def reflections(self, wavelength_A: float, *, two_theta_max: float = 179.0) -> list[Reflection]: + """ + Allowed reflection families up to ``two_theta_max``, in order of decreasing d. + + A family is listed when it is not systematically absent and its neutron structure factor is above 1e-6 of + the strongest possible. + + Args: + wavelength_A: Neutron wavelength (Å). + two_theta_max: Largest 2theta to list (deg, default: 179). + + Returns: + The reflection families. + + Raises: + ValueError: If the wavelength is not positive, the space group is unknown, a site element has no + coherent scattering length, no site scatters, or the hkl search would go beyond + ``reflections.MAX_HKL_INDEX`` (a very large cell or a very short d-spacing limit). + """ + dmin, n = hkl_search_limit(name=self.name, cell_lengths=self.cell[:3], wavelength_A=wavelength_A, + two_theta_max=two_theta_max) # fmt: skip + ops = self.spacegroup().operations() + return reflection_families(name=self.name, cell=self.unit_cell(), ops=ops, sites=self._site_b(), dmin=dmin, + n=n, wavelength_A=wavelength_A) # fmt: skip + + def mu_per_mm(self, wavelength_A: float) -> float: + """ + Linear attenuation coefficient of the phase (see the module function :func:`mu_per_mm`). + + Args: + wavelength_A: Neutron wavelength (Å). + + Returns: + mu (1/mm). + + Raises: + ValueError: If the wavelength is not positive or an element has no cross sections. + """ + return mu_per_mm(self.composition, self.density_g_cm3, wavelength_A) + + +def presets() -> Mapping[str, Phase]: + """ + Packaged preset phases (``data/materials/*.json``, read once). + + Returns: + Phase name -> phase, in file-name order, read-only (the phases are frozen too), so a caller cannot change + the presets every other caller sees. + """ + return MappingProxyType(_read_presets()) + + +@cache +def _read_presets() -> dict[str, Phase]: + root = resources.files(DATA_PACKAGE).joinpath("materials") + out = {} + for f in sorted(root.iterdir(), key=lambda p: p.name): + if f.name.endswith(".json"): + p = Phase.from_dict(json.loads(f.read_text(encoding="utf-8"))) + out[p.name] = p + return out diff --git a/pyrs/pole_figures/core/polefig.py b/pyrs/pole_figures/core/polefig.py new file mode 100644 index 00000000..9d49b808 --- /dev/null +++ b/pyrs/pole_figures/core/polefig.py @@ -0,0 +1,253 @@ +""" +Measured pole figures: per run and per central peak, the raw rate, the path-length correction and the ignored points. + +Ported from the main loop of the reference script. For each run the peaks near the detector center are found on the +summed spectrum, and each sub-run's net rate is the window (or fit) intensity per second. The gauge Monte Carlo +(incident slits from the run's logs, receiving slit from the user) is traced through the sample at every measured chi, +phi. The correction is F(0, 0) / F and points above the cutoff are ignored. Measured data need not match a prediction: +any chi, phi set, count times and number of sub-runs work. + +Typical workflow: + +1. Read the run with ``runs.read_run``. +2. Call :func:`analyze_run` with the phase's reflections, the sample mesh and the mount. It measures the peaks + with ``peaks.measure_peaks``. +3. Use each :class:`PolePeak`: ``corrected`` and ``ignored`` for plots and CSVs, :meth:`PolePeak.with_cutoff` to try + another cutoff without a new Monte Carlo. + +Example: + >>> run = read_run("HB2B_1234.h5") # doctest: +SKIP + >>> lam = run.wavelength_A # doctest: +SKIP + >>> refl = [(r.label, r.two_theta) for r in phase.reflections(lam)] # doctest: +SKIP + >>> pfs = analyze_run(run, refl, mesh=mesh, center=(0.0, 0.0, 0.0), conv=MountConventions(), + ... receiving_slit_mm=2.0, mu=phase.mu_per_mm(lam)) # doctest: +SKIP + >>> [pf.label for pf in pfs] # doctest: +SKIP + ['1234 {311}'] +""" + +from collections.abc import Iterable +from dataclasses import dataclass, replace + +import numpy as np +import numpy.typing as npt + +from .correction import DEFAULT_CUTOFF, Beams, GaugeCorrections, gauge_corrections +from .gauge import DEFAULT_MC_POINTS +from .geometry import Mount, MountConventions +from .parallel import Workers +from .peaks import CENTRAL_HALF_WIDTH_DEG, Method, measure_peaks +from .runs import RunData +from .stl_mesh import SampleMesh +from .types import BoolArray, FloatArray, Progress, no_progress, part_progress + + +@dataclass(kw_only=True) +class PolePeak: + """ + One measured pole figure: a run and one of its central peaks. + + chi is the cradle chi (logged chi + offset), rounded to 0.01 deg. phi is in 0 to 360. ``h`` holds the pole + vector (sample frame) of every point: ``analyze_run`` fills it from the mount, and a combined pole figure keeps + each part's own poles. Per-point arrays all have one entry per sub-run. Omega and the chi offset are those of + ``mount`` (``combine.combine`` refuses parts that differ in either), so they are not stored twice. + + Attributes: + run: Run number ("+" when combined). + hkl: hkl label. + title: Run title. + two_theta: Fitted center of the summed peak (deg). + fwhm: FWHM of the summed peak (deg). + wavelength_A: Wavelength (Å). + beams: Incident beam and receiving slit sizes (mm). + mount: Beams and rotation used for the Monte Carlo (and to draw cells). Its omega is the median of the log. + chi: Cradle chi per point (deg). + phi: Phi per point, 0 to 360 (deg). + count_s: Count time per point (s). + rate: Raw net rate per point (counts/s). + sigma: Sigma of the rate (counts/s). + gauge: Gauge Monte Carlo per point: F, F_ref, sample volume, mean path, vy centroid and spread, correction. + cutoff: Points with a correction above this are ignored. + mu: Linear attenuation coefficient (1/mm). + method: "window" or "fit". + h: Pole vectors in the sample frame, shape (n, 3). + live: The file was reduced while the run was still counting. + source_runs: Runs merged into this pole figure (combined only). + notes: Warnings about the peak or the fit. + + Raises: + ValueError: If ``h`` does not have one (vx, vy, vz) row per point, or ``gauge`` not one entry per point. + """ + + run: str + hkl: str + title: str + two_theta: float + fwhm: float + wavelength_A: float + beams: Beams + mount: Mount + chi: FloatArray + phi: FloatArray + count_s: FloatArray + rate: FloatArray + sigma: FloatArray + gauge: GaugeCorrections + cutoff: float + mu: float + method: Method + h: FloatArray # pole vectors (n, 3), sample frame + live: bool = False + source_runs: tuple[str, ...] = () # runs merged into this pole figure (combined only) + notes: str = "" + + def __post_init__(self) -> None: + """Refuse pole vectors or gauge results that do not match the points (one per chi, phi): ValueError.""" + if np.shape(self.h) != (len(self.chi), 3): + raise ValueError( + f"h must hold one pole vector per point, shape ({len(self.chi)}, 3), got {np.shape(self.h)}" + ) + if len(self.gauge.correction) != len(self.chi): + raise ValueError(f"gauge must hold one result per point ({len(self.chi)}), got " + f"{len(self.gauge.correction)}") # fmt: skip + + @property + def omega(self) -> float: + """Omega of the mount (deg): the median of the run's omega log.""" + return self.mount.omega + + @property + def chi_offset_deg(self) -> float: + """Cradle chi = logged chi + this offset (deg), from the mount conventions.""" + return self.mount.conv.chi_offset_deg + + @property + def correction(self) -> FloatArray: + """Path-length correction F_ref / F per point, inf where F is 0 (``gauge.correction``).""" + return self.gauge.correction + + @property + def n_points(self) -> int: + """Number of points.""" + return len(self.chi) + + @property + def label(self) -> str: + """Run and hkl, e.g. '1234 {311}'.""" + return f"{self.run} {{{self.hkl}}}" + + @property + def ignored(self) -> BoolArray: + """Points whose correction is above the cutoff (or infinite), or whose rate is not finite (a failed fit).""" + return np.asarray(~(self.correction <= self.cutoff) | ~np.isfinite(self.rate), bool) + + @property + def corrected(self) -> FloatArray: + """Corrected rate, rate x correction (counts/s), NaN where the correction is not finite.""" + return np.where(np.isfinite(self.correction), self.rate * self.correction, np.nan) + + @property + def corrected_sigma(self) -> FloatArray: + """Sigma of the corrected rate, sigma x correction (counts/s), NaN where the correction is not finite.""" + return np.where(np.isfinite(self.correction), self.sigma * self.correction, np.nan) + + def poles(self) -> FloatArray: + """Pole vectors in the sample frame, shape (n, 3).""" + return self.h + + def with_cutoff(self, cutoff: float) -> "PolePeak": + """ + Same result with another cutoff (no new Monte Carlo). + + Args: + cutoff: The new cutoff. + + Returns: + A copy with the new cutoff, so ``ignored`` changes. + """ + return replace(self, cutoff=float(cutoff)) + + +def cradle_angles(run: RunData, conv: MountConventions) -> tuple[FloatArray, FloatArray]: + """ + Cradle chi and phi of each sub-run, rounded to 0.01 deg. + + Args: + run: The run. + conv: Mount conventions. Cradle chi = logged chi + ``conv.chi_offset_deg``. + + Returns: + Cradle chi and phi (wrapped to 0 to 360), both rounded to 0.01 deg. + """ + chi = np.round(np.asarray(conv.cradle_chi(run.chi), float), 2) if conv.chi_offset_deg else np.round(run.chi, 2) + phi = np.round(np.mod(run.phi, 360), 2) + return chi.astype(float), phi.astype(float) + + +def analyze_run( + run: RunData, + candidates: Iterable[tuple[str, float]], + *, + mesh: SampleMesh, + center: npt.ArrayLike, + conv: MountConventions, + receiving_slit_mm: float, + mu: float, + cutoff: float = DEFAULT_CUTOFF, + n_points: int = DEFAULT_MC_POINTS, + central_hw: float = CENTRAL_HALF_WIDTH_DEG, + method: Method = "window", + progress: Progress = no_progress, + allow_open_mesh: bool = False, + workers: Workers = "auto", +) -> list[PolePeak]: + """ + Raw rates, corrections and ignored points for every central peak of one run. + + Args: + run: From ``read_run``. + candidates: (hkl label, expected 2theta) pairs at the run's wavelength (from the phase). + mesh: Sample model in the sample frame (mm). + center: Gauge center in the sample frame (mm). + conv: Mount conventions. + receiving_slit_mm: Diffracted (receiving) slit width (mm). Not in the file. The incident slits come from the + run's logs. + mu: Linear attenuation coefficient at the run's wavelength (1/mm). + cutoff: Points with a correction above this are ignored (default: 3). + n_points: Monte Carlo gauge points (default: 40,000). + central_hw: Use peaks within this many degrees of the arm 2theta (default: 5). + method: "window" integration (default) or pseudo-Voigt "fit". + progress: ``progress(fraction, message)`` within this run. The default ignores progress. + allow_open_mesh: Trace a mesh that is not closed or not consistently wound (default: False, which raises + ValueError). + workers: Number of processes, or "auto" (default) to choose from the job size (``parallel.n_workers``). + + Returns: + One pole figure per central peak, empty when the run has none. + + Raises: + ValueError: If the mesh is open or inconsistently wound (unless allowed), method is unknown, a central peak + has no counts above the background, the slit sizes are not positive, or the gauge holds no sample at + chi 0, phi 0. + """ + if not allow_open_mesh: + mesh.check() + peaks = measure_peaks(run, candidates, central_hw=central_hw, method=method) + if not peaks: + return [] + beams = Beams(incident_width=run.incident_width, incident_height=run.incident_height, + diffracted_width=float(receiving_slit_mm)) # fmt: skip + chi, phi = cradle_angles(run, conv) + out = [] + for k, pk in enumerate(peaks): + m = Mount(conv, omega=run.omega_median, tth=pk.two_theta) + tick = part_progress(progress, part=k, parts=len(peaks), n=len(chi), label=f"run {run.run} {{{pk.hkl}}}", + unit="points") # fmt: skip + g = gauge_corrections(m, beams=beams, chi=chi, phi=phi, mesh=mesh, center=center, mu=mu, n_points=n_points, + progress=tick, workers=workers) # fmt: skip + out.append(PolePeak( + run=run.run, hkl=pk.hkl, title=run.title, two_theta=pk.two_theta, fwhm=pk.fwhm, + wavelength_A=run.wavelength_A, beams=beams, mount=m, chi=chi, phi=phi, count_s=run.count_s, + rate=pk.rate, sigma=pk.sigma, gauge=g, cutoff=float(cutoff), mu=float(mu), method=method, live=run.live, + notes="; ".join(pk.notes), h=np.array([m.pole(c, f) for c, f in zip(chi, phi, strict=True)]), + )) # fmt: skip + return out diff --git a/pyrs/pole_figures/core/prediction.py b/pyrs/pole_figures/core/prediction.py new file mode 100644 index 00000000..7ed297fa --- /dev/null +++ b/pyrs/pole_figures/core/prediction.py @@ -0,0 +1,332 @@ +""" +Predicted beam path and correction pole figures from the sample model alone (no data). + +Ported from ``predicted_corrections`` of the reference script. Each plane is measured at its own 2theta and omega +on a chi/phi grid. For each grid point the gauge Monte Carlo gives F, and the correction is F(0, 0) / F. Points whose +correction is above the cutoff are flagged as ignored. + +The reference script takes the beam sizes and the wavelength from the first run. Here they are inputs, so the +prediction works before any data exist. + +Free phi: where the phi axis lies along Q (chi 90 with omega = theta), every phi measures the same pole. With +``best_phi`` on, such points are evaluated over a phi sweep and the phi with the shortest mean path is kept +(paths within 1 % tie and the lowest phi wins, so symmetric shapes always give the same choice), so +the table scan measures that pole where the beams travel least through the sample. The reference script keeps phi 0 +there, so the option is off by default (parity). + +Typical workflow: + +1. Choose the planes (hkl, 2theta, omega), e.g. with :meth:`Plane.symmetric`. +2. Set the beam and slit sizes (``correction.Beams``) and the grid (``grid.Grid``). +3. Call :func:`predict` with the sample mesh, gauge center, mount conventions and mu. +4. Plot each :class:`PlanePrediction` or plan its table scan (``table_scan.plan_scan``). + +Example: + >>> pred = predict(mesh, center=(0.0, 0.0, 0.0), conv=MountConventions(), + ... planes=[Plane.symmetric("311", 104.0)], beams=Beams(), mu=0.1) # doctest: +SKIP + >>> pred.planes[0].sphere_fraction_ignored # doctest: +SKIP + 0.12 +""" + +from collections.abc import Sequence +from dataclasses import dataclass, field + +import numpy as np +import numpy.typing as npt + +from .correction import DEFAULT_CUTOFF, Beams, GaugeCorrections, gauge_corrections +from .gauge import PREDICTION_MC_POINTS +from .geometry import Mount, MountConventions +from .grid import DEFAULT_GRID, Grid +from .parallel import Workers +from .stl_mesh import SampleMesh +from .types import BoolArray, CountProgress, FloatArray, Progress, no_count_progress, no_progress, part_progress + + +@dataclass(frozen=True) +class Plane: + """ + One planned pole figure. + + Attributes: + hkl: hkl label. + two_theta: 2theta of the reflection (deg). + omega: Omega (deg). + + Example: + >>> Plane.symmetric("311", 104.0) + Plane(hkl='311', two_theta=104.0, omega=52.0) + """ + + hkl: str + two_theta: float + omega: float + + @classmethod + def symmetric(cls, hkl: str, two_theta: float) -> "Plane": + """ + Plane with omega = theta, which puts Q along vz at chi 0, phi 0 (for the default mount). + + Args: + hkl: hkl label. + two_theta: 2theta of the reflection (deg). + + Returns: + The plane with omega = two_theta / 2. + """ + return cls(hkl, float(two_theta), float(two_theta) / 2) + + +@dataclass(kw_only=True) +class PlanePrediction: + """ + Prediction for one plane on the grid. + + Attributes: + plane: hkl, 2theta and omega. + mount: Beams and rotation for the plane. + chi: Cradle chi per point (deg). + phi: Phi per point (deg). + gauge: Gauge Monte Carlo per point: F, F(0, 0), sample volume, mean path (NaN where the gauge misses the + sample), vy centroid and spread, correction F(0, 0) / F (inf where F is 0). + ignored: correction > cutoff. + sphere_fraction_ignored: Solid-angle-weighted fraction of the grid that is ignored. + phi_chosen: True where phi was free (phi axis along Q) and set to the phi with the shortest path. + phi_sweeps: For those points: index -> (phi values tried, mean path at each), for reporting. + """ + + plane: Plane + mount: Mount + chi: FloatArray + phi: FloatArray + gauge: GaugeCorrections + ignored: BoolArray + sphere_fraction_ignored: float + phi_chosen: BoolArray + phi_sweeps: dict[int, tuple[FloatArray, FloatArray]] = field(default_factory=dict) + + @property + def hkl(self) -> str: + """Hkl label of the plane.""" + return self.plane.hkl + + @property + def correction(self) -> FloatArray: + """Path-length correction F(0, 0) / F per point, inf where F is 0 (``gauge.correction``).""" + return self.gauge.correction + + def poles(self) -> FloatArray: + """Pole vectors in the sample frame, shape (n, 3).""" + return np.array([self.mount.pole(c, f) for c, f in zip(self.chi, self.phi, strict=True)]) + + +@dataclass(kw_only=True) +class Prediction: + """ + Predictions for all planes plus the inputs that made them. + + Attributes: + planes: One prediction per plane. + center: Gauge center in the sample frame (mm). + beams: Beam and slit sizes (mm). + mu: Linear attenuation coefficient (1/mm). + cutoff: Points with a correction above this are ignored. + grid: The chi/phi grid. + n_points: Monte Carlo points per orientation. + """ + + planes: list[PlanePrediction] + center: FloatArray + beams: Beams + mu: float + cutoff: float + grid: Grid + n_points: int + + +FREE_PHI_TOL_DEG = 0.1 # phi axis within this of Q counts as along Q (omega and 2theta are rounded to 0.01 deg) +TIE_REL = 0.01 # paths within 1 % of the shortest are a tie (Monte Carlo noise); the lowest phi wins + + +def phi_is_free(m: Mount, chi: float, *, tol_deg: float = FREE_PHI_TOL_DEG) -> bool: + """ + True when the phi axis at cradle chi lies along Q, so phi does not change the pole. + + Args: + m: Beams and rotation conventions. + chi: Cradle chi (deg). + tol_deg: Largest angle between the phi axis and +-Q (deg, default: 0.1). + + Returns: + Whether phi is free at this chi. + """ + return bool(abs(float(m.phi_axis(chi) @ m.q)) >= np.cos(np.radians(tol_deg))) + + +def shortest_path_index(paths: FloatArray, *, rel: float = TIE_REL) -> int: + """ + Index of the shortest path. Paths within rel of the shortest tie, and the first (lowest phi) wins. + + Args: + paths: Mean path at each trial phi (mm), NaN where the gauge misses the sample. At least one must be finite. + rel: Relative tie tolerance (default: 0.01, Monte Carlo noise). + + Returns: + The index of the chosen path. + + Example: + >>> shortest_path_index(np.array([10.05, 10.0, 12.0])) + 0 + """ + best = float(np.nanmin(paths)) + return int(np.flatnonzero(np.nan_to_num(paths, nan=np.inf) <= best * (1 + rel))[0]) + + +def predict_plane( + mesh: SampleMesh, + *, + center: npt.ArrayLike, + conv: MountConventions, + plane: Plane, + beams: Beams, + mu: float, + chi: FloatArray, + phi: FloatArray, + weights: FloatArray, + cutoff: float = DEFAULT_CUTOFF, + n_points: int = PREDICTION_MC_POINTS, + progress: CountProgress = no_count_progress, + best_phi: bool = False, + best_phi_step: float, + workers: Workers = "auto", +) -> PlanePrediction: + """ + Correction for one plane at the given cradle chi, phi points. + + Args: + mesh: Sample model in the sample frame (mm). Not checked for closure here (``predict`` does that). + center: Gauge center in the sample frame (mm). + conv: Mount conventions. + plane: hkl, 2theta and omega. + beams: Beam and slit sizes (mm). + mu: Linear attenuation coefficient (1/mm). + chi: Cradle chi per point (deg). + phi: Phi per point (deg). + weights: Solid-angle weight per point, for ``sphere_fraction_ignored``. + cutoff: Points with a correction above this are ignored (default: 3). + n_points: Monte Carlo points per orientation (default: 20,000, half the 40,000 used for runs). + progress: ``progress(n_done)`` in points of the grid (a phi sweep counts as its one point). + best_phi: Where phi is free (phi axis along Q), try phi 0 to 360 in ``best_phi_step`` and keep the phi with + the shortest mean path (default: False, which keeps the given phi). + best_phi_step: Step of that sweep (deg). Required so the sweep step is always stated (``predict`` passes the + grid's phi step). + workers: Number of processes, or "auto" (default) to choose from the job size (``parallel.n_workers``). + + Returns: + The prediction for the plane. + + Raises: + ValueError: If best_phi is on and best_phi_step is not a positive step, or the gauge holds no sample at + chi 0, phi 0. + """ + if best_phi and not (np.isfinite(best_phi_step) and best_phi_step > 0): + raise ValueError(f"best_phi_step must be a positive step in degrees, got {best_phi_step!r}") + m = Mount(conv, omega=plane.omega, tth=plane.two_theta) + chi = np.asarray(chi, float) + phi = np.array(phi, float) + # every orientation to compute: the point itself, or where phi is free the phi sweep and then the given phi + spans: list[tuple[int, FloatArray | None]] = [] # (first orientation, trial phis) per point + all_chi: list[float] = [] + all_phi: list[float] = [] + for c, f in zip(chi, phi, strict=True): + trial = np.arange(0.0, 360.0, float(best_phi_step)) if best_phi and phi_is_free(m, float(c)) else None + ph = [*trial, f] if trial is not None else [f] + spans.append((len(all_chi), trial)) + all_chi += [float(c)] * len(ph) + all_phi += [float(x) for x in ph] + n_all = len(all_chi) + + def tick(done: int) -> None: # progress counts grid points, not the orientations of a phi sweep + progress(int(done * len(chi) / max(n_all, 1))) + + g = gauge_corrections(m, beams=beams, chi=all_chi, phi=all_phi, mesh=mesh, center=center, mu=mu, + n_points=n_points, progress=tick, workers=workers) # fmt: skip + rows = np.array([first for first, _ in spans], int) + chosen = np.zeros(len(chi), bool) + sweeps: dict[int, tuple[FloatArray, FloatArray]] = {} + for i, (first, trial) in enumerate(spans): + if trial is None: + continue + paths = g.mean_path[first : first + len(trial)].copy() + if np.isfinite(paths).any(): + best = shortest_path_index(paths) + phi[i], chosen[i], rows[i] = trial[best], True, first + best + sweeps[i] = (trial, paths) + else: # the gauge misses the sample at every phi: keep the given phi + rows[i] = first + len(trial) + q = g.take(rows) + ign = q.correction > cutoff + frac = float((weights * ign).sum() / weights.sum()) + return PlanePrediction(plane=plane, mount=m, chi=chi, phi=phi, gauge=q, ignored=ign, sphere_fraction_ignored=frac, + phi_chosen=chosen, phi_sweeps=sweeps) # fmt: skip + + +def predict( + mesh: SampleMesh, + *, + center: npt.ArrayLike, + conv: MountConventions, + planes: Sequence[Plane], + beams: Beams, + mu: float, + grid: Grid = DEFAULT_GRID, + cutoff: float = DEFAULT_CUTOFF, + n_points: int = PREDICTION_MC_POINTS, + progress: Progress = no_progress, + best_phi: bool = False, + allow_open_mesh: bool = False, + workers: Workers = "auto", +) -> Prediction: + """ + Predicted path and correction for each plane on a chi/phi grid. + + Args: + mesh: Sample model in the sample frame (mm). + center: Gauge center in the sample frame (mm). + conv: Mount conventions. + planes: hkl, 2theta and omega of each planned pole figure. + beams: Beam and slit sizes (mm). + mu: Linear attenuation coefficient (1/mm). + grid: chi/phi grid (default: 10 x 5 deg). + cutoff: Points with correction above this are ignored (default: 3). + n_points: Monte Carlo points per orientation (default: 20,000, half the 40,000 used for runs). + progress: ``progress(fraction, message)``. The default ignores progress. + best_phi: Where phi is free (phi axis along Q), use the phi with the shortest mean path, tried in the grid's + phi step (default: False, which keeps phi 0 there). + allow_open_mesh: Trace a mesh that is not closed or not consistently wound (default: False, which raises + ValueError because its path lengths can be wrong). + workers: Number of processes, or "auto" (default) to choose from the job size (``parallel.n_workers``). + + Returns: + The predictions and the inputs that made them. + + Raises: + ValueError: If the mesh is open or inconsistently wound (unless allowed), there are no planes, or the gauge + holds no sample at chi 0, phi 0. + """ + if not allow_open_mesh: + mesh.check() + if not planes: + raise ValueError(f"no planes to predict: select at least one reflection, got {list(planes)!r}") + chi, phi = grid.points() + w = grid.weights(chi) + out = [] + for k, pl in enumerate(planes): + tick = part_progress( + progress, part=k, parts=len(planes), n=len(chi), label=f"{{{pl.hkl}}}", unit="orientations" + ) + out.append(predict_plane(mesh, center=center, conv=conv, plane=pl, beams=beams, mu=mu, chi=chi, phi=phi, + weights=w, cutoff=cutoff, n_points=n_points, progress=tick, best_phi=best_phi, + best_phi_step=grid.phi_step, workers=workers)) # fmt: skip + return Prediction(planes=out, center=np.asarray(center, float), beams=beams, mu=float(mu), cutoff=float(cutoff), + grid=grid, n_points=int(n_points)) # fmt: skip diff --git a/pyrs/pole_figures/core/projection.py b/pyrs/pole_figures/core/projection.py new file mode 100644 index 00000000..22abbbdf --- /dev/null +++ b/pyrs/pole_figures/core/projection.py @@ -0,0 +1,114 @@ +""" +Equal-area (Schmidt) projection of sample-frame poles, and the pole-figure views. + +Ported from the reference script (``project``). Its global ``VIEW`` is the explicit ``view`` argument here. + +Views ("pf_view_from" in a reference-script config): "+vz" is seen from +vz with +vx right and +vy up (default), +"-vz" mirrors it as the 2D maps do (vx to the left), and "+vx" is seen down the phi axis with +vy right and +vz up. + +Typical workflow: + +1. Get the poles of a pole figure (``geometry.Mount.poles``). +2. Place them on the pole figure with :func:`project`. + +Example: + >>> project(np.array([0.0, 0.0, 1.0])) + array([[0., 0.]]) +""" + +import typing +from typing import Literal + +import numpy as np +import numpy.typing as npt + +from .types import FloatArray + +ViewFrom = Literal["+vz", "-vz", "+vx"] + +# Display frame for "pf_view_from": "+vx": (vy, vz, vx), vx toward the viewer. +_VIEW_PLUS_VX = np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]) + + +def check_view(view: str) -> None: + """ + Check that ``view`` is one of the pole-figure views (``ViewFrom``). + + Args: + view: "+vz", "-vz" or "+vx". + + Raises: + ValueError: If view is anything else. + """ + allowed = typing.get_args(ViewFrom) + if view not in allowed: + raise ValueError(f"view must be one of {', '.join(allowed)}, got {view!r}") + + +def to_view(h: npt.ArrayLike, *, view: ViewFrom = "+vz") -> FloatArray: + """ + Sample-frame vectors in the display frame (x right, y up, z toward the viewer). + + Args: + h: Sample-frame vectors, shape (..., 3). + view: "+vz", "-vz" or "+vx" (default: "+vz"). Only "+vx" changes the frame: (vy, vz, vx). The "-vz" mirror + is applied in :func:`project`. + + Returns: + The vectors in the display frame, same shape. + + Raises: + ValueError: If view is not one of the pole-figure views. + """ + check_view(view) + h = np.asarray(h, float) + return h @ _VIEW_PLUS_VX.T if view == "+vx" else h + + +def from_view(d: npt.ArrayLike, *, view: ViewFrom = "+vz") -> FloatArray: + """ + Display-frame vectors back to the sample frame (inverse of :func:`to_view`). + + Args: + d: Display-frame vectors, shape (..., 3). + view: "+vz", "-vz" or "+vx" (default: "+vz"). + + Returns: + The vectors in the sample frame, same shape. + + Raises: + ValueError: If view is not one of the pole-figure views. + """ + check_view(view) + d = np.asarray(d, float) + return d @ _VIEW_PLUS_VX if view == "+vx" else d + + +def project(h: npt.ArrayLike, *, view: ViewFrom = "+vz", fold: bool = True) -> FloatArray: + """ + Equal-area (Schmidt) projection of sample-frame unit vectors. + + Args: + h: Sample-frame unit vectors, shape (3,) or (n, 3). + view: "+vz": seen from +vz, +vx right, +vy up (default). "-vz": as the 2D maps (vx to the left). "+vx": seen + down the phi axis, +vy right, +vz up. + fold: Replace poles on the far hemisphere with their antipodes (default: True). + + Returns: + Projected points, shape (n, 2), radius 1 at the equator. + + Raises: + ValueError: If view is not one of the pole-figure views. + """ + check_view(view) + sgn = -1.0 if view == "-vz" else 1.0 + h = np.atleast_2d(np.asarray(h, float)) + h = to_view(h, view=view) + if fold: + h = np.where(sgn * h[:, 2:3] < -1e-9, -h, h) + alpha = np.arccos(np.clip(sgn * h[:, 2], -1, 1)) + r = np.sqrt(2) * np.sin(alpha / 2) + xy = np.c_[sgn * h[:, 0], h[:, 1]] + n = np.linalg.norm(xy, axis=1) + n[n < 1e-12] = 1 + return np.asarray(xy / n[:, None] * r[:, None]) diff --git a/pyrs/pole_figures/core/protocols.py b/pyrs/pole_figures/core/protocols.py new file mode 100644 index 00000000..34dc4990 --- /dev/null +++ b/pyrs/pole_figures/core/protocols.py @@ -0,0 +1,57 @@ +""" +What plots and the GUI need from a pole figure, predicted or measured. + +``prediction.PlanePrediction`` and ``polefig.PolePeak`` both have these members. +Code that only draws or animates the points takes a :class:`PoleFigureLike`, so it works with either kind without +checking which it got. + +Example: + >>> def n_ignored(q: PoleFigureLike) -> int: + ... return int(q.ignored.sum()) +""" + +from typing import Protocol + +from .correction import GaugeCorrections +from .geometry import Mount +from .types import BoolArray, FloatArray + + +class PoleFigureLike(Protocol): + """ + Points of one pole figure with their path-length correction. + + Attributes: + hkl: hkl label. + mount: Beams and rotation used for the Monte Carlo (and to draw cells). + chi: Cradle chi per point (deg). + phi: Phi per point (deg). + gauge: Gauge Monte Carlo per point. + correction: F(0, 0) / F per point, inf where F is 0. + ignored: Points left out (correction above the cutoff, or no usable value). + """ + + @property + def hkl(self) -> str: ... # noqa: D102 (documented in the class docstring) + + @property + def mount(self) -> Mount: ... # noqa: D102 + + @property + def chi(self) -> FloatArray: ... # noqa: D102 + + @property + def phi(self) -> FloatArray: ... # noqa: D102 + + @property + def gauge(self) -> GaugeCorrections: ... # noqa: D102 + + @property + def correction(self) -> FloatArray: ... # noqa: D102 + + @property + def ignored(self) -> BoolArray: ... # noqa: D102 + + def poles(self) -> FloatArray: + """Pole vectors in the sample frame, shape (n, 3).""" + ... diff --git a/pyrs/pole_figures/core/reflections.py b/pyrs/pole_figures/core/reflections.py new file mode 100644 index 00000000..3a9b2853 --- /dev/null +++ b/pyrs/pole_figures/core/reflections.py @@ -0,0 +1,163 @@ +""" +Allowed reflection families of a crystal: the hkl search, the neutron structure factor and the Bragg angle. + +A family is listed when it is not systematically absent in the space group and its neutron structure factor (coherent +scattering lengths, all sites in the cell) is above 1e-6 of the strongest possible. Symmetry-equivalent hkl are +grouped into one family with its multiplicity (Friedel pairs included). ``phase.Phase.reflections`` is the usual way +in. + +Example: + >>> hkl_label((3, 1, 1)), hkl_label((1, -1, 0)) + ('311', '1 -1 0') + >>> round(bragg_two_theta(gemmi.UnitCell(3.6, 3.6, 3.6, 90, 90, 90), (1, 1, 1), 1.54), 3) + 43.489 +""" + +from collections.abc import Sequence +from dataclasses import dataclass + +import gemmi +import numpy as np + +#: the hkl search runs over -n..n in h, k and l with n = max(a, b, c) / d_min + 1. Above this n the search (n^3 +#: Python iterations) takes minutes, so it is refused: lower two_theta_max or check the cell. +MAX_HKL_INDEX = 60 +#: (coherent scattering length b (fm), occupancy, fractional positions of the site in the cell) of one site +ScatteringSite = tuple[complex, float, list[list[float]]] + + +@dataclass(frozen=True, kw_only=True) +class Reflection: + """ + One family of symmetry-equivalent reflections. + + Attributes: + hkl: Representative indices (fewest negative indices, then the largest h, k, l). + d_A: d-spacing (Å). + two_theta: 2theta at the wavelength used (deg), NaN beyond 180. + multiplicity: Number of equivalent hkl, Friedel pairs included. + f2: Neutron structure factor squared, ``|F|^2`` per cell (fm^2). + """ + + hkl: tuple[int, int, int] + d_A: float + two_theta: float + multiplicity: int + f2: float # |F|^2 per cell, fm^2 + + @property + def label(self) -> str: + """The hkl label (see :func:`hkl_label`).""" + return hkl_label(self.hkl) + + +def hkl_label(hkl: tuple[int, int, int]) -> str: + """ + Miller indices as a label. + + Args: + hkl: Miller indices. + + Returns: + Compact ``"311"`` when every index is a single non-negative digit, else ``"1 -1 0"``. + """ + if all(0 <= i <= 9 for i in hkl): + return "".join(str(i) for i in hkl) + return " ".join(str(i) for i in hkl) + + +def bragg_two_theta(cell: gemmi.UnitCell, hkl: tuple[int, int, int], wavelength_A: float) -> float: + """ + Bragg angle 2theta of a reflection. + + Args: + cell: The unit cell. + hkl: Miller indices. + wavelength_A: Neutron wavelength (Å). + + Returns: + 2theta (deg), NaN when the reflection is beyond 2theta = 180. + """ + s = wavelength_A / (2 * float(cell.calculate_d(list(hkl)))) + return float(2 * np.degrees(np.arcsin(s))) if s < 1 else float("nan") + + +def hkl_search_limit(*, name: str, cell_lengths: Sequence[float], wavelength_A: float, + two_theta_max: float) -> tuple[float, int]: # fmt: skip + """ + Smallest d-spacing to list and the largest hkl index the search needs. + + Args: + name: Phase name, for the messages. + cell_lengths: a, b, c (Å). + wavelength_A: Neutron wavelength (Å). + two_theta_max: Largest 2theta to list (deg). + + Returns: + d_min (Å) and n: the search runs over -n..n in h, k and l. + + Raises: + ValueError: If the wavelength is not positive, or n is above ``MAX_HKL_INDEX``. + """ + if not (np.isfinite(wavelength_A) and wavelength_A > 0): + raise ValueError(f"{name}: the wavelength must be positive (A), got {wavelength_A!r}") + dmin = wavelength_A / (2 * np.sin(np.radians(two_theta_max / 2))) + n = int(np.ceil(max(cell_lengths) / dmin)) + 1 + if n > MAX_HKL_INDEX: + raise ValueError(f"{name}: listing reflections down to d {dmin:.3g} A in a cell of " + f"{max(cell_lengths):g} A needs hkl up to {n}, more than {MAX_HKL_INDEX}. Lower " + "two_theta_max or check the cell.") # fmt: skip + return float(dmin), n + + +def reflection_families(*, name: str, cell: gemmi.UnitCell, ops: gemmi.GroupOps, sites: Sequence[ScatteringSite], + dmin: float, n: int, wavelength_A: float) -> list[Reflection]: # fmt: skip + """ + Allowed reflection families with d >= dmin, in order of decreasing d. + + Args: + name: Phase name, for the messages. + cell: The unit cell. + ops: The space group's operations. + sites: Every site with its scattering length, occupancy and positions in the cell. + dmin: Smallest d-spacing to list (Å). + n: Largest hkl index searched (from :func:`hkl_search_limit`). + wavelength_A: Neutron wavelength (Å), for each family's 2theta. + + Returns: + The reflection families. + + Raises: + ValueError: If no site scatters. + """ + rots = list(ops.sym_ops) + b_sum = sum(abs(b) * occ * len(p) for b, occ, p in sites) + if not b_sum > 0: + raise ValueError(f"{name}: the sites scatter nothing (all coherent scattering lengths are 0)") + seen: set[tuple[int, int, int]] = set() + out: list[Reflection] = [] + for h in range(-n, n + 1): + for k in range(-n, n + 1): + for l in range(-n, n + 1): # noqa: E741 + hkl = (h, k, l) + if hkl == (0, 0, 0) or hkl in seen: + continue + d = float(cell.calculate_d([h, k, l])) + if d < dmin - 1e-9: + continue + eq = {tuple(op.apply_to_hkl([h, k, l])) for op in rots} + eq |= {(-a, -b, -c) for a, b, c in eq} + seen |= eq # type: ignore[arg-type] + if ops.is_systematically_absent([h, k, l]): + continue + hv = np.array(hkl, float) + F = sum(b * occ * np.exp(2j * np.pi * (np.asarray(ps) @ hv)).sum() for b, occ, ps in sites) + f2 = float(abs(F) ** 2) + if f2 < 1e-6 * b_sum**2: + continue + v = min(eq, key=lambda v: (sum(i < 0 for i in v), -v[0], -v[1], -v[2])) + rep = (v[0], v[1], v[2]) + out.append(Reflection(hkl=rep, d_A=d, two_theta=bragg_two_theta(cell, rep, wavelength_A), + multiplicity=len(eq), f2=f2)) # fmt: skip + out.sort(key=lambda r: (-r.d_A, r.hkl)) + return out diff --git a/pyrs/pole_figures/core/rotation.py b/pyrs/pole_figures/core/rotation.py new file mode 100644 index 00000000..cc5d0e8b --- /dev/null +++ b/pyrs/pole_figures/core/rotation.py @@ -0,0 +1,120 @@ +""" +Rotation helpers of the stage geometry: signed sample axes, rotation matrices and checks that a matrix is a rotation. + +Ported from the reference script (``rot``). The signed sample axes ("+vx", "-vz", ...) name how a sample sits on the +cradle (``geometry.MountConventions``). + +Example: + >>> axis_vector("-vz") + array([ 0., 0., -1.]) + >>> axis_name([0.0, -0.9, 0.1]) + '-vy' + >>> np.round(rot([0, 0, 1], 90.0) @ [1.0, 0.0, 0.0], 12) + 0.0 + array([0., 1., 0.]) +""" + +from typing import Literal + +import numpy as np +import numpy.typing as npt + +from .types import FloatArray + +SampleAxis = Literal["+vx", "-vx", "+vy", "-vy", "+vz", "-vz"] +SAMPLE_AXES: tuple[SampleAxis, ...] = ("+vx", "-vx", "+vy", "-vy", "+vz", "-vz") + + +def axis_vector(a: str) -> FloatArray: + """ + Unit vector of a signed sample axis: '+vx' -> (1, 0, 0), '-vz' -> (0, 0, -1). + + Args: + a: One of ``SAMPLE_AXES``. + + Returns: + The unit vector in the sample frame. + + Raises: + ValueError: If ``a`` is not one of ``SAMPLE_AXES``. + """ + if a not in SAMPLE_AXES: + raise ValueError(f"sample axis must be one of {', '.join(SAMPLE_AXES)}, not {a!r}") + v = np.zeros(3) + v["xyz".index(a[2])] = 1.0 if a[0] == "+" else -1.0 + return v + + +def check_rotation(m: npt.ArrayLike, *, tol: float = 2e-3) -> None: + """ + Check that m is a proper rotation (orthonormal rows, determinant +1) within tol. + + Args: + m: A 3 x 3 sample-to-instrument matrix. + tol: Largest allowed element of ``|m m^T - I|`` (default: 2e-3, so values typed to 3 or 4 decimals pass). + + Raises: + ValueError: If m is not 3 x 3 finite numbers, its rows are not orthonormal within tol, or it is a reflection + (negative determinant). + """ + m = np.asarray(m, float) + if m.shape != (3, 3) or not np.all(np.isfinite(m)): + raise ValueError(f"the sample-to-instrument matrix must be 3 x 3 finite numbers, got {m.tolist()!r}") + err = float(np.abs(m @ m.T - np.eye(3)).max()) + if err > tol: + raise ValueError(f"the sample-to-instrument matrix is not a rotation: rows must be unit length and at right " + f"angles (off by {err:.3g})") # fmt: skip + det = float(np.linalg.det(m)) + if det < 0: + raise ValueError(f"the sample-to-instrument matrix is a reflection (determinant {det:.3g}): flip the sign of " + "one row") # fmt: skip + + +def nearest_rotation(m: npt.ArrayLike) -> FloatArray: + """ + The rotation closest to m (polar decomposition), so a matrix typed to 3 or 4 decimals is exactly orthonormal. + + A matrix that is already orthonormal (to 1e-12) is returned as it is, so the identity stays exact. + + Args: + m: A 3 x 3 matrix that is nearly a rotation. + + Returns: + The orthonormal 3 x 3 matrix ``U V^T`` from the singular value decomposition of m. + """ + m = np.asarray(m, float) + if np.abs(m @ m.T - np.eye(3)).max() < 1e-12: + return m.copy() + u, _, vt = np.linalg.svd(m) + return np.asarray(u @ vt) + + +def axis_name(v: npt.ArrayLike) -> str: + """ + Name of the sample axis nearest a vector: (0, -1, 0) -> '-vy'. + + Args: + v: A vector in the sample frame. Only its largest component counts. + + Returns: + The signed axis name, one of ``SAMPLE_AXES``. + """ + v = np.asarray(v, float) + i = int(np.argmax(np.abs(v))) + return ("+" if v[i] > 0 else "-") + "v" + "xyz"[i] + + +def rot(axis: npt.ArrayLike, deg: float) -> FloatArray: + """ + Rotation matrix about an axis (right hand, Rodrigues formula). + + Args: + axis: Rotation axis, any length. + deg: Rotation angle (deg). + + Returns: + The 3 x 3 rotation matrix. + """ + a = np.asarray(axis, float) / np.linalg.norm(axis) + t = np.radians(deg) + K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]]) + return np.eye(3) + np.sin(t) * K + (1 - np.cos(t)) * K @ K diff --git a/pyrs/pole_figures/core/runs.py b/pyrs/pole_figures/core/runs.py new file mode 100644 index 00000000..2c14203d --- /dev/null +++ b/pyrs/pole_figures/core/runs.py @@ -0,0 +1,318 @@ +""" +Read HB-2B reduced (pyRS) project files for pole figures. + +A reduced file ``HB2B_.h5`` holds, per sub-run, the motor logs (chi, phi, omega, 2theta), the count time, the +incident slit gaps (ISR:X/Y:Gap), and the reduced spectrum (counts against 2theta). Three kinds of sub-run are +skipped, and counted, so the run table can say so: + +* still counting: a file reduced while the run is measured ("live") has a placeholder duration in its last sub-run + (1000 s or more). Only the last sub-run can be live, so a real count of 1000 s or more elsewhere is kept. +* too short: under 10 % of the median count time (a final sub-run of a few ms after the scan returns home). +* invalid: a non-finite duration or motor log (chi, phi, omega, 2theta). + +chi, phi, omega and 2theta always come from the logs, never from the run title. The virtual sample axes vx, vy, vz +(the gauge position in the sample frame) are read when logged. They are NaN when the virtual frame was not set up. + +Typical workflow: + +1. Read each file with :func:`read_run`. +2. Show :meth:`RunData.describe` in the run table and pass the run to ``polefig.analyze_run``. + +Example: + >>> run_number("HB2B_1234.h5") + '1234' + >>> run = read_run("HB2B_1234.h5") # doctest: +SKIP + >>> run.describe() # doctest: +SKIP + 'run 1234: 649 sub-runs, lambda 1.5401 A, omega 56.00, arm 2theta 112.00, slits 2 x 2 mm' +""" + +import re +from dataclasses import dataclass +from pathlib import Path + +import h5py +import numpy as np + +from .types import FloatArray + +# Paths and log names in a reduced (pyRS) project file: the strings of pyrs.dataobjects.constants.HidraConstants. +LOGS_PATH = "raw data/logs" +REDUCED_MAIN_PATH = "reduced diffraction data/main" +REDUCED_2THETA_PATH = "reduced diffraction data/2theta" +WAVELENGTH_PATH = "instrument/monochromator setting/wave length" +DURATION_LOG = "sub-run duration" +SUB_RUNS_LOG = "sub-runs" +POSITION_KEYS = ("vx", "vy", "vz") # optional logs: the gauge position in the sample (STL) frame, mm + +LIVE_PLACEHOLDER_S = 1000.0 # a live file's last (counting) sub-run carries a placeholder duration at or above this +MOTOR_TOL_DEG = 0.01 # omega or the arm 2theta moving more than this during a run is reported +SHORT_FRACTION = 0.1 # sub-runs shorter than this fraction of the median count time are skipped +LOG_KEYS = ("chi", "phi", "omega", "2theta", DURATION_LOG, SUB_RUNS_LOG, "ISR:X:Gap", "ISR:Y:Gap") + + +@dataclass(kw_only=True) +class RunData: + """ + One reduced run, finished sub-runs only. + + Attributes: + run: Run number (from the file name ``HB2B_.h5``, else the file stem). + path: The file. + title: Run title from the logs ("" when absent). + wavelength_A: Wavelength from the file (Å). + chi: Logged (goniometer) chi per sub-run (deg). + phi: Logged phi per sub-run (deg). + omega: Logged omega per sub-run (deg). + two_theta_arm: Logged detector arm 2theta per sub-run (deg). + count_s: Count time per sub-run (s). + subruns: Sub-run numbers. + slit_x: Incident slit width per sub-run, ISR:X:Gap (mm). + slit_y: Incident slit height per sub-run, ISR:Y:Gap (mm). + x: 2theta of the reduced spectra (deg), only bins that are finite in every sub-run kept. + y: Counts per bin, shape (n_subruns, n_bins). + live_skipped: Sub-runs left out because they were still counting. + short_skipped: Sub-runs left out as too short. + invalid_skipped: Sub-runs left out for a non-finite duration or motor log. + position: Logged vx, vy, vz per sub-run (mm), shape (n_subruns, 3). NaN where not logged or not defined. + notes: Things the user should know about the run (omega or the arm moved during the run). + position_note: Why part of the position is missing (a log absent or of the wrong length, NaN sub-runs). + Empty when the position is fully logged or not logged at all. + """ + + run: str + path: Path + title: str + wavelength_A: float + chi: FloatArray + phi: FloatArray + omega: FloatArray + two_theta_arm: FloatArray + count_s: FloatArray + subruns: FloatArray + slit_x: FloatArray + slit_y: FloatArray + x: FloatArray + y: FloatArray + live_skipped: int + short_skipped: int + invalid_skipped: int + position: FloatArray + notes: list[str] + position_note: str + + def _logged_rows(self) -> FloatArray: + """Sub-runs with all of vx, vy, vz finite.""" + return self.position[np.isfinite(self.position).all(axis=1)] + + @property + def logged_position(self) -> FloatArray | None: + """ + Median vx, vy, vz (mm) over the sub-runs that logged all three. + + None means the run has no logged position: no sub-run logged all of vx, vy and vz (the virtual frame was not + set up, or a log is absent). That is a real state of a run, not a missing value, so callers check for it. + """ + rows = self._logged_rows() + if not len(rows): + return None + return np.asarray(np.median(rows, axis=0), dtype=float) + + @property + def position_spread(self) -> float: + """Largest range of the logged vx, vy or vz over the sub-runs (mm). 0 when not logged.""" + rows = self._logged_rows() + return float(np.ptp(rows, axis=0).max()) if len(rows) else 0.0 + + @property + def n_subruns(self) -> int: + """Number of sub-runs kept.""" + return len(self.count_s) + + @property + def omega_median(self) -> float: + """Omega used in the geometry: the median of the log (deg).""" + return float(np.median(self.omega)) + + @property + def arm_two_theta(self) -> float: + """Detector arm 2theta: the median of the log (deg).""" + return float(np.median(self.two_theta_arm)) + + @property + def incident_width(self) -> float: + """Incident beam width: the median of ISR:X:Gap (mm).""" + return float(np.median(self.slit_x)) + + @property + def incident_height(self) -> float: + """Incident beam height: the median of ISR:Y:Gap (mm).""" + return float(np.median(self.slit_y)) + + @property + def live(self) -> bool: + """True when the file was reduced while the run was still counting (its last sub-run was skipped).""" + return self.live_skipped > 0 + + def describe(self) -> str: + """One-line summary for the run table: sub-runs, skipped sub-runs, wavelength, omega, arm, slits, notes.""" + skipped = [] + if self.live_skipped: + skipped.append(f"{self.live_skipped} still counting") + if self.short_skipped: + skipped.append(f"{self.short_skipped} too short") + if self.invalid_skipped: + skipped.append(f"{self.invalid_skipped} with a non-finite duration or motor log") + extra = f" ({', '.join(skipped)} skipped)" if skipped else "" + notes = "".join(f". {n}" for n in self.notes) + return (f"run {self.run}: {self.n_subruns} sub-runs{extra}, lambda {self.wavelength_A:.4f} A, omega " + f"{self.omega_median:.2f}, arm 2theta {self.arm_two_theta:.2f}, slits {self.incident_width:g} x " + f"{self.incident_height:g} mm{notes}") # fmt: skip + + +def run_number(path: str | Path) -> str: + """ + Run number from a file name. + + Args: + path: The file, e.g. 'HB2B_1234.h5' (case is ignored). + + Returns: + The digits after 'HB2B_', e.g. '1234', or the file stem for other names. + """ + m = re.search(r"HB2B_(\d+)", Path(path).name, re.IGNORECASE) + return m.group(1) if m else Path(path).stem + + +def read_run(path: str | Path) -> RunData: + """ + Read a reduced HB-2B (pyRS) file, keeping only the finished sub-runs. + + Args: + path: The ``HB2B_.h5`` file. + + Returns: + The run, with the skipped sub-runs counted and notes on omega or the arm moving during the run. + + Raises: + ValueError: If the file cannot be read, is not a reduced HB-2B file, lacks a needed log, has logs or spectra + of different lengths or no sub-runs, has a wavelength outside 0.5 to 5 Å, or has no finished sub-runs. + """ + path = Path(path) + try: + with h5py.File(path, "r") as h: + needed = (LOGS_PATH, REDUCED_MAIN_PATH, REDUCED_2THETA_PATH, WAVELENGTH_PATH) + absent = [k for k in needed if k not in h] + if absent: + raise ValueError(f"{path.name} is not a reduced HB-2B (pyRS) file: no {', '.join(absent)}") + L = h[LOGS_PATH] + missing = [k for k in LOG_KEYS if k not in L] + if missing: + raise ValueError(f"{path.name} lacks the logs {', '.join(missing)}") + d = {k: np.asarray(L[k][()], float).reshape(-1) for k in LOG_KEYS} + x = np.asarray(h[REDUCED_2THETA_PATH][()], float) + y = np.asarray(h[REDUCED_MAIN_PATH][()], float) + n_log = _check_lengths(path, d, x=x, y=y) + pos, notes = _read_position(L, n_log) + title = _read_title(L) + lam = float(np.asarray(h[WAVELENGTH_PATH][()], float).reshape(-1)[0]) + except OSError as exc: + raise ValueError(f"cannot read {path.name}: {exc}") from exc + if not (np.isfinite(lam) and 0.5 <= lam <= 5.0): + raise ValueError(f"{path.name}: wavelength {lam} A is not a valid HB-2B wavelength (0.5 to 5 A)") + x = x[0] + t = d[DURATION_LOG] + valid = np.isfinite(t) & np.all([np.isfinite(d[k]) for k in ("chi", "phi", "omega", "2theta")], axis=0) + live = np.zeros(n_log, bool) + live[-1] = bool(valid[-1] and t[-1] >= LIVE_PLACEHOLDER_S) # only the last sub-run can still be counting + counted = valid & ~live + med = float(np.median(t[counted])) if counted.any() else 0.0 + short = counted & (t < SHORT_FRACTION * med) + done = counted & ~short + if not done.any(): + raise ValueError(f"{path.name} has no finished sub-runs") + ok = np.isfinite(y[done]).all(axis=0) # bins finite in every sub-run used + run_notes = [f"{name} moved by {np.ptp(d[k][done]):.3f} deg during the run (the median is used)" + for k, name in (("omega", "omega"), ("2theta", "the arm 2theta")) + if np.ptp(d[k][done]) > MOTOR_TOL_DEG] # fmt: skip + return RunData( + run=run_number(path), + path=path, + title=title, + wavelength_A=lam, + chi=d["chi"][done], + phi=d["phi"][done], + omega=d["omega"][done], + two_theta_arm=d["2theta"][done], + count_s=t[done], + subruns=d[SUB_RUNS_LOG][done], + slit_x=d["ISR:X:Gap"][done], + slit_y=d["ISR:Y:Gap"][done], + x=x[ok], + y=y[done][:, ok], + live_skipped=int(live.sum()), + short_skipped=int(short.sum()), + invalid_skipped=int((~valid).sum()), + notes=run_notes, + position=pos[done], + position_note=_position_note(pos[done], notes), + ) + + +def _check_lengths(path: Path, logs: dict[str, FloatArray], *, x: FloatArray, y: FloatArray) -> int: + """ + The number of sub-runs, checked to be the same in every needed log and in the spectra. + + Raises: + ValueError: If the spectra are not 2D (sub-run x bin), 2theta has no row of the spectra's width, the logs and + spectra have different lengths, or there are no sub-runs. The message names the file. + """ + if y.ndim != 2 or x.ndim != 2 or x.shape[0] < 1 or x.shape[1] != y.shape[1]: + raise ValueError(f"{path.name}: the reduced spectra must be (sub-run, bin) arrays with a 2theta row of the " + f"same width, got main {y.shape} and 2theta {x.shape}") # fmt: skip + lengths = {k: v.size for k, v in logs.items()} | {"reduced spectra": y.shape[0]} + if len(set(lengths.values())) != 1: + shown = ", ".join(f"{k} {n}" for k, n in lengths.items()) + raise ValueError(f"{path.name}: the logs and spectra must have one value per sub-run, got lengths {shown}") + n = y.shape[0] + if n == 0: + raise ValueError(f"{path.name} has no sub-runs") + return n + + +def _read_title(logs: h5py.Group) -> str: + """The run title from the logs: the first value, decoded as UTF-8 (bad bytes replaced), "" when absent.""" + if "run_title" not in logs: + return "" + v = np.asarray(logs["run_title"][()]).reshape(-1) + if not v.size: + return "" + first = v[0] + return first.decode("utf-8", errors="replace") if isinstance(first, bytes) else str(first) + + +def _read_position(logs: h5py.Group, n_log: int) -> tuple[FloatArray, list[str]]: + """vx, vy, vz per sub-run (NaN where absent) and notes on logs that are absent or of the wrong length.""" + pos = np.full((n_log, 3), np.nan) + absent, notes = [], [] + for j, k in enumerate(POSITION_KEYS): + if k not in logs: + absent.append(k) + continue + v = np.asarray(logs[k][()], float).reshape(-1) # (n,) or (n, 1) + if v.size != n_log: + notes.append(f"{k} log has {v.size} values for {n_log} sub-runs") + else: + pos[:, j] = v + if absent and len(absent) < len(POSITION_KEYS): + notes.append(f"{', '.join(absent)} not logged") + return pos, notes + + +def _position_note(pos: FloatArray, notes: list[str]) -> str: + """The notes, plus a count of sub-runs without a full position when some sub-runs have one.""" + full = np.isfinite(pos).all(axis=1) + if full.any() and not full.all(): + notes = [*notes, f"{int((~full).sum())} of {len(full)} sub-runs have no full vx, vy, vz"] + elif not full.any() and np.isfinite(pos).any() and not notes: + notes = [*notes, "no sub-run has all of vx, vy, vz"] + return "; ".join(notes) diff --git a/pyrs/pole_figures/core/stl_mesh.py b/pyrs/pole_figures/core/stl_mesh.py new file mode 100644 index 00000000..ff9bea2f --- /dev/null +++ b/pyrs/pole_figures/core/stl_mesh.py @@ -0,0 +1,360 @@ +""" +Closed triangle mesh of the sample and the ray tracer for beam path lengths. + +Ported from the reference script (``read_stl``, ``SampleMesh``) with no change to the numerics. The STL frame is the +sample frame (vx, vy, vz) and its units are read as mm. + +Typical workflow: + +1. Load the sample with :meth:`SampleMesh.from_stl` and show :meth:`SampleMesh.describe` and + :meth:`SampleMesh.warnings`. +2. :meth:`SampleMesh.check` before tracing (prediction and analysis do this unless told not to). +3. :meth:`SampleMesh.trace` gives the inside test and the path ahead of many points along one direction. + +Example: + >>> cube = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]], float) + >>> faces = [(0, 2, 1), (0, 3, 2), (4, 5, 6), (4, 6, 7), (0, 1, 5), (0, 5, 4), + ... (1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6), (3, 0, 4), (3, 4, 7)] + >>> mesh = SampleMesh(cube[faces], name="cube") + >>> mesh.closed, mesh.consistent, mesh.volume + (True, True, 1.0) + >>> wind, length = mesh.trace([[0.3, 0.6, 0.25]], [0.0, 0.0, 1.0]) + >>> wind, length + (array([1.]), array([0.75])) +""" + +from pathlib import Path + +import numpy as np +import numpy.typing as npt + +from .types import FloatArray + +GRID_FACTOR = 1.5 # grid cells per side = GRID_FACTOR * sqrt(triangles in the footprint); fastest over the fixtures + + +def read_stl(path: str | Path) -> FloatArray: + """ + Read the triangles of a binary or ASCII STL. + + A file whose size matches the binary layout (84 + 50 n bytes) is read as binary, any other as ASCII. + + Args: + path: STL file. + + Returns: + Triangle vertices in the file's frame and units, shape (n, 3, 3). + + Raises: + ValueError: If the file is neither a valid binary nor a valid ASCII STL. + """ + data = Path(path).read_bytes() + if len(data) >= 84: + n = int(np.frombuffer(data, " tuple[FloatArray, npt.NDArray[np.bool_]]: # fmt: skip + """ + Moller-Trumbore ray-triangle test for point-triangle pairs (one row per pair), all along one direction d. + + Args: + s: Ray start minus the triangle's first vertex, shape (k, 3). + e1: The triangle's first edge, shape (k, 3). + e2: The triangle's second edge, shape (k, 3). + h: ``d x e2`` per pair, shape (k, 3). + f: ``1 / (e1 . h)`` per pair, shape (k,). Triangles parallel to d (e1 . h near 0) must be left out before. + d: Ray direction, shape (3,). + + Returns: + The ray parameter t of the crossing (in units of ``|d|``) and whether the ray crosses the triangle ahead of + the start (t > 0), per pair. + """ + u = f * np.einsum("ij,ij->i", s, h) + q = np.cross(s, e1) + v = f * (q @ d) + t = f * np.einsum("ij,ij->i", q, e2) + return t, (u >= 0) & (v >= 0) & (u + v <= 1) & (t > 0) + + +class SampleMesh: + """ + Closed triangle mesh of the sample in the sample frame (vx, vy, vz in mm, the frame of the gauge center). + + Rays are traced with the Moller-Trumbore test against every triangle. For a ray ``p + t d`` (t > 0) each + crossing adds ``s = sign(n . d)`` (+1 leaving, -1 entering, n the outward normal). The sum of s is 1 for a point + inside a closed mesh and 0 outside. The sum of ``s t`` is the material path ahead of an inside point, re-entries + included, so concave shapes, holes and cavities are handled. + + Args: + triangles: Triangle vertices, shape (n, 3, 3) (mm). Inward winding is detected from the signed volume and + flipped. + name: Label used by :meth:`describe` (default: "mesh", usually the file name). + + Attributes: + v0: First vertex of each triangle. + e1: Edge from v0 to the second vertex (after any winding flip). + e2: Edge from v0 to the third vertex (after any winding flip). + n: Outward normal of each triangle (not unit length). + volume: Enclosed volume (mm3). + ntri: Number of triangles. + name: Label. + lo: Lower corner of the bounding box (mm). + hi: Upper corner of the bounding box (mm). + size: Bounding box size (mm). + closed: Every edge is shared by exactly two triangles. + consistent: Every triangle is wound the same way (each directed edge once, and its reverse once). + + Raises: + ValueError: If there are no triangles. + """ + + def __init__(self, triangles: npt.ArrayLike, *, name: str = "mesh") -> None: + T = np.asarray(triangles, float).reshape(-1, 3, 3) + if len(T) == 0: + raise ValueError(f"the mesh has no triangles, got an array of shape {np.shape(triangles)}") + if not np.isfinite(T).all(): + bad = int((~np.isfinite(T)).any(axis=(1, 2)).sum()) + raise ValueError(f"{name}: {bad} triangles have non-finite vertex coordinates (inf or nan)") + e1, e2 = T[:, 1] - T[:, 0], T[:, 2] - T[:, 0] + vol = float(np.einsum("ij,ij->", T[:, 0], np.cross(T[:, 1], T[:, 2])) / 6) + if vol < 0: # inward winding: flip every triangle + e1, e2, vol = e2, e1, -vol + self.v0: FloatArray = T[:, 0] + self.e1: FloatArray = e1 + self.e2: FloatArray = e2 + self.n: FloatArray = np.cross(e1, e2) + self.volume = vol + self.ntri = len(T) + self.name = name + P = T.reshape(-1, 3) + self.lo: FloatArray = P.min(axis=0) + self.hi: FloatArray = P.max(axis=0) + self.size: FloatArray = self.hi - self.lo + key = np.round(P, 6) + idx = np.unique(key, axis=0, return_inverse=True)[1].reshape(-1, 3) + directed = np.concatenate([idx[:, [0, 1]], idx[:, [1, 2]], idx[:, [2, 0]]]) + edges = np.sort(directed, axis=1) + self.closed = bool(np.all(np.unique(edges, axis=0, return_counts=True)[1] == 2)) + # consistent winding: every directed edge once, and its reverse once (a few flipped triangles pass the + # closed test but give wrong crossing signs, so wrong or even negative path lengths) + uniq = np.unique(directed, axis=0) + fwd = {tuple(e) for e in uniq.tolist()} + self.consistent = bool(len(uniq) == len(directed) and all((b, a) in fwd for a, b in fwd)) + + @classmethod + def from_stl(cls, path: str | Path) -> "SampleMesh": + """ + Load a mesh from an STL file. + + Args: + path: STL file, in mm in the sample frame. + + Returns: + The mesh, named after the file. + + Raises: + ValueError: If the file is not a valid STL or has no triangles. + """ + return cls(read_stl(path), name=Path(path).name) + + def triangles(self) -> FloatArray: + """Triangle vertices (n, 3, 3) with outward winding.""" + return np.stack([self.v0, self.v0 + self.e1, self.v0 + self.e2], axis=1) + + def trace( + self, points: npt.ArrayLike, d: npt.ArrayLike, *, chunk: int = 2_000_000 + ) -> tuple[FloatArray, FloatArray]: + """ + Trace rays from many points along one direction, with a 2D spatial index. + + Points and triangles are projected on the plane normal to d and binned on a grid. A ray from a point can only + cross triangles whose projection covers the point, so each point is tested only against the triangles that + overlap its grid cell. Each point-triangle pair is tested with :func:`moller_trumbore`, as in the reference + script's brute-force tracer (every point against every triangle), so the hits are the same; it is many times + faster on meshes with many triangles. + + Args: + points: Ray start points, shape (n, 3) (mm). + d: Ray direction, shape (3,). Any length: the path is in units of ``|d|``, so pass a unit vector for mm. + chunk: Point-triangle pairs per step of the crossing test (default: 2,000,000). The index of candidate + pairs is built in full first, so peak memory still grows with the number of pairs. + + Returns: + The sum of crossing signs per point (1 inside a closed mesh, 0 outside) and the material path ahead of + each point (meaningful for inside points). + """ + p = np.atleast_2d(np.asarray(points, float)) + d = np.asarray(d, float) + n_pts = len(p) + wind, length = np.zeros(n_pts), np.zeros(n_pts) + if n_pts == 0: + return wind, length + h = np.cross(d, self.e2) + a = np.einsum("ij,ij->i", self.e1, h) + b1 = np.cross(d, [1.0, 0, 0] if abs(d[0]) < 0.9 else [0, 1.0, 0]) + b1 /= np.linalg.norm(b1) + B = np.c_[b1, np.cross(d / np.linalg.norm(d), b1)] + pp = p @ B # (n, 2) + tv = np.stack([self.v0, self.v0 + self.e1, self.v0 + self.e2]) @ B # (3, m, 2) + tmin, tmax = tv.min(axis=0), tv.max(axis=0) + lo, hi = pp.min(axis=0), pp.max(axis=0) + tol = 1e-9 * (1 + np.abs(pp).max()) + use = (np.abs(a) > 1e-12) & np.all((tmax >= lo - tol) & (tmin <= hi + tol), axis=1) + tri = np.flatnonzero(use) + if len(tri) == 0: + return wind, length + # grid over the points' footprint: about one cell per triangle, at most 256 x 256 + g = int(np.clip(GRID_FACTOR * np.sqrt(len(tri)), 1, 256)) + span = np.maximum(hi - lo, 1e-9) + cell = span / g + + def cell_of(x: FloatArray) -> npt.NDArray[np.int64]: + return np.clip(np.floor((x - lo) / cell).astype(np.int64), 0, g - 1) + + pc = cell_of(pp) + pid = pc[:, 0] * g + pc[:, 1] + order = np.argsort(pid, kind="stable") + counts = np.bincount(pid, minlength=g * g) + starts = np.concatenate([[0], np.cumsum(counts)[:-1]]) + # cells covered by each triangle's projected bounding box (widened by tol so a touching edge counts) + c0, c1 = cell_of(tmin[tri] - tol), cell_of(tmax[tri] + tol) + nx, ny = c1[:, 0] - c0[:, 0] + 1, c1[:, 1] - c0[:, 1] + 1 + ncell = nx * ny + t_rep = np.repeat(np.arange(len(tri)), ncell) + k = np.arange(len(t_rep)) - np.repeat(np.cumsum(ncell) - ncell, ncell) # index within each triangle + cx = c0[t_rep, 0] + k // ny[t_rep] + cy = c0[t_rep, 1] + k % ny[t_rep] + tc_cell = cx * g + cy + keep = counts[tc_cell] > 0 + t_rep, tc_cell, cx, cy = t_rep[keep], tc_cell[keep], cx[keep], cy[keep] + # drop cells that the projected triangle misses (all four corners outside one edge): long thin triangles at + # a slant cover far fewer cells than their bounding box + tp = tv[:, tri[t_rep]] # (3, k, 2) projected vertices + x0, y0 = lo[0] + cx * cell[0] - tol, lo[1] + cy * cell[1] - tol + x1, y1 = x0 + cell[0] + 2 * tol, y0 + cell[1] + 2 * tol + area2 = (tp[1, :, 0] - tp[0, :, 0]) * (tp[2, :, 1] - tp[0, :, 1]) - (tp[1, :, 1] - tp[0, :, 1]) * ( + tp[2, :, 0] - tp[0, :, 0] + ) + orient = np.sign(area2) # +1 counterclockwise in the projection + inside_all = orient != 0 # an edge-on triangle (zero area) cannot be crossed: drop it + for e in range(3): + ax, ay = tp[e, :, 0], tp[e, :, 1] + bx, by = tp[(e + 1) % 3, :, 0], tp[(e + 1) % 3, :, 1] + ex, ey = bx - ax, by - ay + # signed side of each corner times the orientation: < 0 is outside this edge + out_all = np.ones(len(t_rep), bool) + for qx, qy in ((x0, y0), (x1, y0), (x0, y1), (x1, y1)): + out_all &= orient * (ex * (qy - ay) - ey * (qx - ax)) < -tol * (np.abs(ex) + np.abs(ey)) + inside_all &= ~out_all + t_rep, tc_cell = t_rep[inside_all], tc_cell[inside_all] + # point-triangle pairs: every point of the cell with every triangle over it + npair = counts[tc_cell] + pair_tri = np.repeat(t_rep, npair) + j = np.arange(len(pair_tri)) - np.repeat(np.cumsum(npair) - npair, npair) + pair_pt = order[np.repeat(starts[tc_cell], npair) + j] + ti = tri[pair_tri] + v0, e1, e2, hh = self.v0[ti], self.e1[ti], self.e2[ti], h[ti] + f = 1.0 / a[ti] + s_t = np.sign(self.n[ti] @ d) + for k0 in range(0, len(ti), max(1, chunk)): + sl = slice(k0, k0 + chunk) + t, hit = moller_trumbore(p[pair_pt[sl]] - v0[sl], e1=e1[sl], e2=e2[sl], h=hh[sl], f=f[sl], d=d) + idx = pair_pt[sl][hit] + wind += np.bincount(idx, weights=s_t[sl][hit], minlength=n_pts) + length += np.bincount(idx, weights=s_t[sl][hit] * t[hit], minlength=n_pts) + return wind, length + + def ray_segments(self, p: npt.ArrayLike, d: npt.ArrayLike) -> list[tuple[float, float]]: + """ + Material segments ahead of one point along d, from every crossing (for drawing beam paths). + + Args: + p: Start point, shape (3,) (mm). + d: Ray direction. The segment ends are in units of ``|d|``. + + Returns: + ``[(t0, t1), ...]``: each stretch of the ray inside the sample. A start point inside gives t0 = 0 first. + """ + d = np.asarray(d, float) + h = np.cross(d, self.e2) + a = np.einsum("ij,ij->i", self.e1, h) + use = np.abs(a) > 1e-12 + f = 1.0 / a[use] + s = np.asarray(p, float) - self.v0[use] + t, hit = moller_trumbore(s, e1=self.e1[use], e2=self.e2[use], h=h[use], f=f, d=d) + t, sg = t[hit], np.sign(self.n[use][hit] @ d) + order = np.argsort(t) + t, sg = t[order], sg[order] + w, start, segs = sg.sum(), 0.0, [] # winding at p: 1 inside, 0 outside + for ti, si in zip(t, sg, strict=True): + if w > 0.5 >= w - si: + segs.append((start, float(ti))) + elif w <= 0.5 < w - si: + start = float(ti) + w -= si + return segs + + def contains(self, p: npt.ArrayLike) -> npt.NDArray[np.bool_]: + """ + True for points inside the mesh (winding test along an oblique direction). + + Args: + p: Points, shape (n, 3) or (3,) (mm). + + Returns: + Inside flag per point. + """ + wind, _ = self.trace(p, np.array([0.5773502691896258, 0.5773502691896258, 0.5773502691896258])) + return wind > 0.5 + + def describe(self) -> str: + """One-line summary: triangles, closed, volume and bounds.""" + return ( + f"{self.name}: {self.ntri} triangles, {'closed' if self.closed else 'NOT closed'}, " + f"volume {self.volume:.2f} mm3, bounds vx {self.lo[0]:g} to {self.hi[0]:g}, vy {self.lo[1]:g} to " + f"{self.hi[1]:g}, vz {self.lo[2]:g} to {self.hi[2]:g} mm" + ) + + def warnings(self) -> list[str]: + """ + Problems the user should know about before trusting path lengths. + + Returns: + Messages for an open mesh, inconsistent winding, or a size below 1 or above 1000 (wrong units). + """ + out = [] + if not self.closed: + out.append( + "The STL is not closed (an edge is not shared by exactly two triangles), so inside tests and path " + "lengths can be wrong." + ) + elif not self.consistent: + out.append( + "The STL's triangles are not all wound the same way (some face inward), so inside tests and path " + "lengths can be wrong. Repair the normals in the CAD program." + ) + if self.size.max() < 1.0 or self.size.max() > 1000.0: + out.append(f"The STL is {self.size.max():g} across. Lengths are read as mm: check the units.") + return out + + def check(self) -> None: + """ + Check that the mesh gives correct path lengths. + + Raises: + ValueError: If the mesh is not closed or its winding is inconsistent. + """ + if not (self.closed and self.consistent): + raise ValueError(f"{self.name}: {self.warnings()[0]} Pass allow_open_mesh=True to use it anyway.") diff --git a/pyrs/pole_figures/core/table_scan.py b/pyrs/pole_figures/core/table_scan.py new file mode 100644 index 00000000..84b2408d --- /dev/null +++ b/pyrs/pole_figures/core/table_scan.py @@ -0,0 +1,196 @@ +""" +Pole-figure table scans from a prediction: keep only the useful chi, phi points and set each count time. + +One table scan per plane (one run per reflection). Points whose predicted correction is +above the cutoff are left out, so no time is spent where the beam path is too long. By default the count time of each +kept point scales with its correction (time = base x correction, whole seconds), so every kept point gets about the +same corrected statistics. A fixed time per point and a cap per point are options. + +Order: chi ring by ring, with phi going up on one ring and down on the next ("serpentine"), so the cradle never swings +phi back from 355 to 0 between rings. Left-out points are simply not visited. + +The points hold the logged (goniometer) chi. ``io.table_scan`` writes them in the HB-2B table-scan file layout. + +Typical workflow: + +1. Predict the correction on the planned grid (``prediction.predict``). +2. Plan each plane with :func:`plan_scan`. +3. Write the scans as spreadsheets with ``io.table_scan.write_table_scans``. + +Example: + >>> scan = plan_scan(prediction.planes[0], cutoff=3.0, base_s=30.0) # doctest: +SKIP + >>> scan.total_s # doctest: +SKIP + 18720 +""" + +import math +from dataclasses import dataclass + +import numpy as np + +from .prediction import Plane, PlanePrediction + + +@dataclass(frozen=True, kw_only=True) +class ScanPoint: + """ + One measurement of a table scan. + + Attributes: + chi: Logged (goniometer) chi (deg). + phi: Phi (deg). + correction: Predicted path-length correction F(0, 0) / F. + count_s: Count time (s). + """ + + chi: float + phi: float + correction: float + count_s: int + + +@dataclass(kw_only=True) +class PlaneScan: + """ + The table scan for one plane. + + Attributes: + plane: hkl, 2theta and omega. + points: Kept points in measurement order (chi rings, phi alternating up and down when serpentine). + n_grid: Number of grid points before the cutoff. + base_s: Count time at correction 1 (s). + cutoff: Points with a correction above this were left out. + serpentine: phi alternates direction from one chi ring to the next. + chi_offset_deg: Cradle chi = logged chi + offset (deg), the mount's offset used for the logged chi of the + points (a record: the points already hold the logged chi). + scaled: Count time = base x correction (True) or base for every point (False). + max_s: Cap on the count time per point (s, inf: no cap). + """ + + plane: Plane + points: list[ScanPoint] + n_grid: int + base_s: float + cutoff: float + serpentine: bool + chi_offset_deg: float + scaled: bool + max_s: float + + @property + def n_capped(self) -> int: + """Points whose time was cut by the cap.""" + return sum(1 for p in self.points if self.scaled and self.base_s * p.correction > self.max_s + 0.5) + + @property + def n_skipped(self) -> int: + """Grid points left out by the cutoff.""" + return self.n_grid - len(self.points) + + @property + def total_s(self) -> int: + """Total count time (s), without motor moves.""" + return int(sum(p.count_s for p in self.points)) + + +def count_time(correction: float, *, base_s: float, scaled: bool = True, max_s: float = math.inf) -> int: + """ + Count time for one point: base x correction (or base when not scaled), capped, whole seconds, at least 1. + + Args: + correction: Predicted correction of the point. + base_s: Count time at correction 1 (s). + scaled: Scale the time with the correction (default: True). + max_s: Cap on the count time (s, default: inf, no cap). + + Returns: + The count time (s), rounded to a whole second. + + Example: + >>> count_time(2.4, base_s=30.0, max_s=60.0) + 60 + """ + t = base_s * correction if scaled else base_s + t = min(t, max_s) + return max(1, int(round(t))) + + +def measurement_order(chi: np.ndarray, phi: np.ndarray, *, serpentine: bool = True) -> np.ndarray: + """ + Indices in measurement order: chi rings from low to high, phi up, then down on the next ring when serpentine. + + Only rings that have points count for the alternation, so left-out rings do not break it. + + Args: + chi: Chi of each point (deg). Values that round to the same 1e-6 deg are one ring. + phi: Phi of each point (deg). + serpentine: Alternate the phi direction from ring to ring (default: True). + + Returns: + Indices into chi and phi. + + Example: + >>> measurement_order(np.array([0.0, 0.0, 10.0, 10.0]), np.array([0.0, 90.0, 0.0, 90.0])) + array([0, 1, 3, 2]) + """ + rings = np.round(np.asarray(chi, float), 6) + out: list[int] = [] + up = True + for c in np.unique(rings): + idx = np.flatnonzero(rings == c) + idx = idx[np.argsort(np.asarray(phi, float)[idx], kind="stable")] + out.extend(idx if (up or not serpentine) else idx[::-1]) + up = not up + return np.asarray(out, int) + + +def plan_scan(q: PlanePrediction, *, cutoff: float, base_s: float, serpentine: bool = True, scaled: bool = True, + max_s: float = math.inf) -> PlaneScan: # fmt: skip + """ + Keep the points with correction <= cutoff, give each a count time, and put them in measurement order. + + Args: + q: Prediction for one plane on the planned chi/phi grid. Its mount's ``conv.chi_offset_deg`` turns the + predicted cradle chi into the logged chi that the table holds. + cutoff: Leave out points whose correction is above this (the hatched cells) or not finite. + base_s: Count time at correction 1 (s). + serpentine: Alternate the phi direction from ring to ring (default: True). False keeps phi increasing on + every ring. + scaled: Count time = base x correction (default: True). False gives every point the base time. + max_s: Cap on the count time per point (s, default: inf, no cap). + + Returns: + The table scan of the plane. + + Raises: + ValueError: If base_s is not positive or max_s is below 1 s. + """ + if base_s <= 0: + raise ValueError(f"the count time at correction 1 must be positive, got {base_s!r} s") + if not max_s >= 1: + raise ValueError(f"the cap on the count time must be at least 1 s, got {max_s!r} s") + keep = np.isfinite(q.correction) & (q.correction <= cutoff) + idx = np.flatnonzero(keep) + order = idx[measurement_order(q.chi[idx], q.phi[idx], serpentine=serpentine)] + conv = q.mount.conv + pts = [ScanPoint(chi=float(conv.logged_chi(q.chi[i])) + 0.0, phi=float(q.phi[i]), + correction=float(q.correction[i]), + count_s=count_time(float(q.correction[i]), base_s=base_s, scaled=scaled, max_s=max_s)) + for i in order] # fmt: skip + return PlaneScan(plane=q.plane, points=pts, n_grid=len(q.chi), base_s=float(base_s), cutoff=float(cutoff), + serpentine=serpentine, chi_offset_deg=float(conv.chi_offset_deg), scaled=scaled, + max_s=float(max_s)) # fmt: skip + + +def phi_travel(scan: PlaneScan) -> float: + """ + Total phi motion between consecutive points (a rough measure of move time). + + Args: + scan: The table scan. + + Returns: + Sum of the phi steps (deg), 0 for fewer than two points. + """ + phi = np.array([p.phi for p in scan.points]) + return float(np.abs(np.diff(phi)).sum()) if len(phi) > 1 else 0.0 diff --git a/pyrs/pole_figures/core/types.py b/pyrs/pole_figures/core/types.py new file mode 100644 index 00000000..5fdae982 --- /dev/null +++ b/pyrs/pole_figures/core/types.py @@ -0,0 +1,76 @@ +""" +Array and progress-callback types shared by the core modules, and the no-op callbacks. + +A long job reports progress through a plain callable, so the core stays free of Qt: ``Progress`` takes the fraction +done and a message, ``CountProgress`` takes the number of items done. The no-op callbacks are the defaults where no +progress is wanted. + +Typical workflow: + +1. A job takes ``progress: Progress = no_progress``. +2. Each of its parts counts items and reports them through :func:`part_progress`. + +Example: + >>> seen = [] + >>> tick = part_progress(lambda f, m: seen.append((f, m)), part=1, parts=2, n=20, label="{311}", unit="points") + >>> tick(10) + >>> seen + [(0.75, '{311}: 10 of 20 points')] +""" + +from collections.abc import Callable + +import numpy as np +import numpy.typing as npt + +FloatArray = npt.NDArray[np.float64] +BoolArray = npt.NDArray[np.bool_] +#: ``progress(fraction, message)``: fraction of the whole job done (0 to 1) and what is being done +Progress = Callable[[float, str], None] +#: ``progress(n_done)``: number of items finished so far +CountProgress = Callable[[int], None] + +PROGRESS_EVERY = 10 # report every this many items (and the last), so a fast loop does not flood the GUI + + +def no_progress(fraction: float, message: str) -> None: + """ + Progress callback that ignores every report (the default where no progress is wanted). + + Args: + fraction: Fraction of the job done, 0 to 1. + message: What is being done. + """ + + +def no_count_progress(done: int) -> None: + """ + Progress callback that ignores the count (the default where no progress is wanted). + + Args: + done: Number of items finished so far. + """ + + +def part_progress(progress: Progress, *, part: int, parts: int, n: int, label: str, unit: str) -> CountProgress: + """ + Count progress of one of ``parts`` equal parts of a job, passed on as the fraction of the whole job. + + Args: + progress: ``progress(fraction, message)`` of the whole job. + part: Index of this part, 0 to parts - 1. + parts: Number of parts in the job. + n: Number of items in this part. + label: Start of the message, e.g. "{311}". + unit: Name of the items, e.g. "points". + + Returns: + ``tick(done)``: reports every ``PROGRESS_EVERY`` items and the last one as + ``progress((part * n + done) / (parts * n), "