Skip to content

Add the ODF step with MTEX for Python (stage 4 of 4, stacked on #1167) - #1168

Open
jefrbunn wants to merge 17 commits into
neutrons:nextfrom
jefrbunn:feature/pole-figures-odf
Open

jefrbunn wants to merge 17 commits into
neutrons:nextfrom
jefrbunn:feature/pole-figures-odf

Conversation

@jefrbunn

Copy link
Copy Markdown

Summary

This PR adds the ODF step to the path-length-corrected pole figures: the MTEX tab of the pole-figure window. It fits the orientation distribution function (ODF) from the corrected pole figures with MTEX for Python (pymtex). It does not use or need MATLAB.

This is stage 4 of 4. It is stacked on #1167 (stage 3, the window), which is stacked on #1166 (stage 2, plots and file output) and #1165 (stage 1, the physics core). Please review those first. Until they merge, this PR also shows their commits.

Dependency: pymtex is optional and not distributed with PyRS

pymtex (PyPI package mtex, mtex-toolbox/pymtex) is GPL-2.0-only. As the maintainers answered on the license question, PyRS does not distribute it. It is installed separately on the analysis cluster and is a dependency of the ODF part only.

  • pyproject.toml: a new optional extra, [project.optional-dependencies] odf = ["mtex>=1.0,<2"].
  • A new pixi feature and environment, odf: the default features plus mtex from PyPI and finufft and numba from conda-forge. It is in the default solve group, so the packages it shares with default keep their versions. It has a test-odf task.
  • pymtex is not in the default, prod, dev or qa environments, and not in the conda package's run-dependencies.
  • Relocked with pixi 0.81.0 (CI's version). The lock only adds the odf environment and its new packages: mtex 1.0.0, finufft 2.5.1, fftw, numba 0.68.1 and llvmlite. pixi install --locked gives default and prod without mtex, finufft or numba.
  • The code imports mtex only inside the two functions that need it, with a comment on why (an optional dependency, and the first import takes seconds while numba compiles). Every module of pyrs.pole_figures and pyrs.interface.pole_figures imports without pymtex.

What is in this PR

  • pyrs.pole_figures.core.odf: reads the pole-figure CSVs and fits the ODF (de la Vallée Poussin kernel, halfwidth and resolution 5°, no specimen symmetry). It computes the RP errors, ODF maximum, texture index, entropy, color ranges and the grids for the plots. pymtex_installed() checks for pymtex without importing it.
  • pyrs.pole_figures.core.mtex: the ODF settings (MtexOptions), the Laue class from the space group, checks on the pole figures (two or more χ rings), and the output names.
  • pyrs.pole_figures.plots.odf: the ODF section, recalculated and measured pole figures, the eight-band pole figures and the inverse pole figures, drawn with matplotlib. The styles follow Peterson et al. (2021) and Plotkowski et al. (2021).
  • pyrs.pole_figures.io.odf: run_odf writes the pole-figure CSVs, runs the fit and writes the plots, the plot data (CSV with a README), the ODF on the Bunge grid and the summary. Every file goes through the safe write of Add pyrs.pole_figures plots and file output (stage 2 of 4, stacked on #1165) #1166.
  • pyrs.interface.pole_figures: odf_tab with the MTEX tab, its model and its presenter. The window from Add the path-length-corrected pole figure window (stage 3 of 4, stacked on #1166) #1167 already adds this tab when the module exists, so main_window does not change.

Without pymtex

The MTEX tab still opens. A note at the top says that MTEX for Python (pymtex) is not installed. It also says that pymtex is installed separately on the analysis cluster. Run MTEX stays off, and the readiness line names pymtex as missing. The other tabs work as before. Nothing crashes.

Parity with the stored MTEX 7.2.0 reference

The reference values were made once with MTEX 7.2.0 from the four reference pole figures of #1165. They are stored in tests/data/pole_figures/reference/slab_vx29.4vy19.75/mtex/ (874 kB, most of it the ODF on the 5° Bunge grid). MATLAB is named only as their origin. pymtex 1.0.0 gives:

  • RP errors equal to 3 decimals.
  • Texture index 1.1508 against 1.1475, entropy -0.067 against -0.064.
  • The ODF on the reference's 5° grid (24,624 points): rms difference 0.035 mrd, correlation 0.998.
  • ODF maximum 2.91 against 2.80 mrd. The maximum moves between 2.70 and 2.88 mrd with pymtex's iteration limits alone, and the reference value lies in that range.
  • The color ranges are equal.

docs/ground_truths.md has a new section with these numbers and the dependency decision.

Tests

  • Unit (no pymtex needed): tests/unit/pyrs/pole_figures/test_odf.py and test_mtex_options.py, 36 tests. They cover the CSV reading, grids, ranges and progress, and the behavior without pymtex.
  • Integration: test_pole_figures_odf_reference.py (7 tests: parity and the writers) and test_pole_figures_odf_settings.py (1 test). The 6 tests that use the fit skip without pymtex.
  • GUI (gui and integration markers): tests/ui/test_pole_figures_odf_tab.py, 8 tests. A fake ODF step runs the tab without pymtex. One test checks the note and the disabled button without pymtex. One test runs the real step and is skipped without pymtex.
  • Tests that need pymtex use pytest.importorskip("mtex"), so they skip cleanly where it is missing.

Local runs, default environment (no pymtex):

  • pre-commit and pixi run mypy pyrs scripts tests are clean.
  • The ODF tests: 45 passed, 7 skipped (the ones that need pymtex).
  • pixi run test-unit: 1908 passed, 13 xfailed. The pole-figure unit tests are 517 now.
  • Pole-figure integration tests: 253 passed, 6 skipped with HIDRA_PF_TEST_DATA set. 213 passed, 46 skipped without it.
  • pixi run test-gui: 173 passed, 3 skipped, 2 xfailed.

Local runs, odf environment (pymtex 1.0.0):

  • pixi run -e odf test-odf: 52 passed, none skipped.
  • Pole-figure unit tests 517 passed, integration tests 259 passed (with HIDRA_PF_TEST_DATA), GUI tests 108 passed.

The ODF tests also pass in the prod environment (55 passed, 7 skipped), and the ODF tab tests pass with qtpy on PySide6.

CI runs the default environment, so the parity tests skip there. A CI job in the odf environment would run them. That is not in this PR (see the question below).

Docs

docs/user/source/basics/basics.rst: a paragraph on the MTEX tab. It says the tab uses MTEX for Python, not MATLAB, and that pymtex is installed separately on the analysis cluster. In a PyRS checkout, pixi run -e odf pyrs starts PyRS with the tab working.

Question for the maintainers

Should CI get a job that runs pixi run -e odf test-odf? It would run the parity tests against the stored MTEX 7.2.0 reference. It installs pymtex in CI only, not in any distributed package.

🤖 Generated with Claude Code

jefrbunn and others added 17 commits November 26, 2026 11:05
gemmi (>=0.6,<0.8) reads CIF files and gives structure factors for
pyrs.pole_figures. trimesh and rtree go in the test feature only: the
pole-figure integration tests use them as an independent cross-check of
the STL ray tracer. pixi.lock adds only these packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Stage 1 of bringing the HB-2B path-length-corrected pole figure tool into
PyRS. Physics core only (no GUI, plots or file output):

- stl_mesh: closed STL mesh of the sample and a ray tracer for beam paths
- geometry: the HB-2B cradle (chi, phi, omega) and the sample mount
- gauge: gauge-volume Monte Carlo and the attenuated intensity factor F
- prediction: predicted correction F(0,0)/F on a chi/phi grid, per plane
- runs, peaks, polefig: read reduced HB2B runs, peak rates per sub-run,
  corrected pole figures with points above a cutoff ignored
- materials: phases (presets or CIF via gemmi), allowed reflections and
  mu; HB-2B wavelengths from MonoSetting
- table_scan, combine, parallel: scan planning, merging runs, worker pool

Tests: unit in tests/unit/pyrs/pole_figures (in-memory meshes; mu checked
against Sears 1992 cross sections; analytic sphere chords and
attenuation), integration in tests/integration/test_pole_figures_*.py
(parity with the reference script's outputs, STL fixtures with a trimesh
cross-check, a 13-sub-run HB2B test file; full runs when
HIDRA_PF_TEST_DATA is set). Fixtures in tests/data/pole_figures (test
data anonymized), helpers in tests/util/pole_figures_helpers.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ground_truths.md: the frames and angles of pyrs.pole_figures, the exact
mapping to PoleFigureCalculator (chi_PyRS = 90 - chi_HB2B, PyRS (x, y,
normal) = (vy, vz, -vx), checked at five 2theta/omega settings to 2e-8),
the attenuation model and the empirical parameters approved by the
instrument scientist.

Defects recorded, not fixed:
- DD-37: the texture window's chi zero differs from the HB-2B cradle's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the design review of this PR. Results are unchanged (the parity
tests pass).

- correction: Beams, check_reference and gauge_corrections, shared by
  prediction and polefig; GaugeCorrections groups the Monte Carlo
  results on PolePeak and PlanePrediction
- protocols.PoleFigureLike for the later plotting stage
- types: array aliases and progress callbacks in one place
- geometry split into rotation, projection and geometry; materials into
  neutron_xs, phase, reflections and hb2b; the grid into grid; peak
  measurement into peaks
- combine refuses runs with a different omega or mount
- text and table helpers moved out of core (they return in the file
  output stage); the reference brute-force tracer moved to the tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
openpyxl (>=3.1,<4) writes the HB-2B table-scan .xlsx files of
pyrs.pole_figures.io.table_scan. It is listed next to gemmi in the
package, default, dev, qa and prod dependencies. pixi.lock (pixi 0.81.0)
adds only openpyxl 3.1.5 and et_xmlfile 2.0.0.

The other plotting dependencies are already there: matplotlib is a
direct dependency, pillow and contourpy come with it, and scipy comes
with Mantid (pyrs.core and pyrs.dataobjects import it already).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Stage 2 of the pole-figure port (stacked on the core stage). Nothing
here imports Qt, the GUI or the ODF modules: each function takes core
results and returns a matplotlib Figure or writes a file.

- plots: predicted path and correction figures (summary, one plane,
  correction vs phi per chi ring with its volume and attenuation
  parts), measured pole figures (one cell per point or interpolated),
  the mount check, the table-scan preview, beam-path GIFs (drawn in
  worker processes for long GIFs), shared colors and a retrying save.
- io: per-run pole-figure CSVs (the reference script's columns), the
  HB-2B table-scan .xlsx workbooks, and mount matrices as text.

Tests: 31 unit tests in tests/unit/pyrs/pole_figures (synthetic inputs)
and 28 integration tests in tests/integration/test_pole_figures_plots.py
and test_pole_figures_plot_files.py (figures from a prediction, the
mount check on every STL fixture, workbook, CSV, PNG and GIF files).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
write_xlsx writes run titles and phase labels unchanged. The leading
apostrophe added by safe_text was stored in the text, so Excel and the
run-title and phase PVs got it. Text starting with "=" is now kept as
text with Excel's quote prefix instead. safe_text is removed.

draw_cells no longer wraps the hatched collections in rc_context on
matplotlib < 3.11. That changed process-wide rcParams while figures are
built on a worker thread. The hatch takes the edge color, which is the
wanted hatch color. matplotlib >= 3.11 still gets hatchcolor=.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Calculations that lived in plots move to core (design review of PR 2):
- correction.correction_parts(gauge, *, chi, phi): the correction as
  volume x attenuation, keyed by the CorrectionPart Literal (PARTS from
  typing.get_args)
- gauge.path_at_gauge: beam path along the centerlines from the gauge
  center
- grid.weighted_fraction and Grid.sphere_fraction: the solid-angle
  weighted fraction of masked points (predict_plane uses it)

Their tests are core unit tests. Results are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Design:
- plots import only core, the leaf modules text and io.retry, plots.style,
  plots.annotate and the pole-figure drawing helpers
- text.py: durations, matrices (parse_matrix rejects nan and inf), CSV
  labels and file-name parts. io/matrix_text.py is removed
- io/predicted_csv.py (write_predicted_csv), plots/correction_profile.py
- style.py holds the colormaps, ticks, colors, correction_norm and
  clip_correction. annotate.py holds add_colorbar, setup_line, vz_label
  and view_caption (checked with check_view)
- predicted_beam_gif(plane=...) and measured_beam_gif(peak=...);
  beam_frame.py holds Track and FrameRenderer with typed attributes, and
  gif_worker imports it at the top
- draw_X(fig, ...) / X_figure pairs for the predicted, plane, correction
  profile, pole-figure and table-scan figures
- view is required in pf_frame, draw_cells and draw_interp; the mount key
  uses pf_frame; method notes are keyed by core Method

Hardening:
- io/retry.py: retry_on_locked retries only PermissionError; write_atomic
  writes a temporary file in the same folder and moves it over the target
  (figures, GIFs, xlsx and both CSV writers)
- run and hkl labels are checked before a CSV is written; file names keep
  only letters and digits of the run, hkl and prefix
- GifSettings validates fps, dpi, every and workers; a GIF over
  MAX_GIF_PIXELS is refused before drawing

Output changes: the mount key panel (pole-figure frame labels and limits)
and the beam-path GIF frames (beam colors and light from style.py, the
cutoff mark on the color bar). Every other figure and file is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- test_pole_figures_reference_csv.py: the predicted CSV made from the
  reference config and the per-run CSV of the HB2B subset against the
  reference rows, column by column at the written rounding
- test_plots_layering.py: plots modules import only core, text, io.retry
  and the plots helper modules

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pyrs.interface.pole_figures: the Qt window (qtpy) with five tabs: Sample,
Experiment setup, Predict, Table scan, Data and Corrections. Pydantic models
hold the inputs, presenters call pyrs.pole_figures, long jobs and figure
builds run on worker threads, slot errors go to an error hook that chains to
the host's. The ODF tab (MTEX for Python) is not included: the window adds
it only when its module is installed (a later stage).

Tests: 10 GUI test files in tests/ui (gui + integration markers, 97 tests,
1 needs HIDRA_PF_TEST_DATA), 3 unit test files for the Qt-free helpers in
tests/unit/pyrs/interface/pole_figures (21 tests), wait_figure in
tests/util/pole_figures_gui_helpers.py; the shared helpers gain CU_CIF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A standard button in the PyRS main window (pyrsmain.ui, row 6) opens
pyrs.interface.pole_figures through do_launch_pole_figure_window: a new
window owned by the main window, or the open one raised. An error while
opening is logged and shown in a message box, so PyRS keeps running. The
quit action closes the window too. User docs: a short section on the
button. Tests: the button opens one window (PyRS guide, owned, raised on a
second click), and an error is shown instead of ending PyRS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hon)

The ODF step of pyrs.pole_figures needs MTEX for Python (pymtex, PyPI "mtex",
GPL-2.0-only). PyRS does not distribute it: it is installed separately on the
analysis cluster. So it is not in the default, prod, dev or qa environments,
and not in the conda package's run-dependencies.

- [project.optional-dependencies] odf = ["mtex>=1.0,<2"]
- pixi feature "odf": finufft and numba from conda-forge, mtex from PyPI,
  and a test-odf task for the ODF tests
- pixi environment "odf": the default features plus "odf", in the default
  solve group, so shared packages keep the default versions

Relocked with pixi 0.81.0 (CI's version). The lock only adds the odf
environment and its new packages: mtex 1.0.0, finufft 2.5.1, fftw, numba
0.68.1, llvmlite. pixi install --locked leaves default and prod without mtex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Stage 4 of the path-length-corrected pole figures. The ODF is fitted with
MTEX for Python (pymtex), an optional dependency installed separately (see
the previous commit). MATLAB is not used or needed.

- pyrs.pole_figures.core.odf: read the pole-figure CSVs, fit the ODF (de la
  Vallee Poussin kernel, 5 deg, no specimen symmetry), RP errors, maximum,
  texture index, entropy, color ranges, plot grids. pymtex_installed()
  checks for pymtex without importing it.
- core.mtex: MtexOptions, Laue class from the space group, chi-ring check,
  output names. plots.odf: the ODF plots in matplotlib (Peterson et al. 2021
  and Plotkowski et al. 2021 styles). io.odf: run_odf and the writers, every
  file through io.retry.write_atomic. io/__init__ lists the ODF output.
- pyrs.interface.pole_figures: odf_tab with the MTEX tab, model and
  presenter. The window of stage 3 adds the tab when odf_tab exists.
  Without pymtex the tab shows a note (installed separately on the analysis
  cluster) and Run stays off.
- "import mtex" only inside core.odf.compute and plots.odf.white_jet, with
  the reason (optional dependency, numba compile time). All 46
  pyrs.pole_figures and 37 pyrs.interface.pole_figures modules import
  without pymtex.

Tests: unit tests/unit/pyrs/pole_figures/test_odf.py, test_mtex_options.py
(36, no pymtex); integration test_pole_figures_odf_reference.py (parity with
the stored MTEX 7.2.0 reference values, skipped without pymtex) and
test_pole_figures_odf_settings.py; GUI tests/ui/test_pole_figures_odf_tab.py
(8). Fixtures in tests/data/pole_figures/reference/slab_vx29.4vy19.75/mtex.
default env: 45 passed + 7 skipped (need pymtex); odf env (pixi run -e odf
test-odf): 52 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- basics.rst: the MTEX tab fits the ODF with MTEX for Python and does not
  need MATLAB. pymtex is not part of PyRS and is installed separately on the
  analysis cluster. Without it the tab shows a note and Run stays off.
- ground_truths.md: the dependency decision and the parity of pymtex 1.0.0
  with the stored MTEX 7.2.0 reference values (RP errors equal to 3
  decimals, texture index 1.1508 vs 1.1475, ODF rms 0.035 mrd).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jefrbunn

Copy link
Copy Markdown
Author

@fanchercm @walshmm this is the last stage (4 of 4): the ODF step with MTEX for Python. As you suggested, pymtex is not distributed with PyRS. It is an optional odf extra and an opt-in pixi environment, and the default and prod environments do not contain it. It is stacked on #1167, so please review #1165, #1166 and #1167 first. One question for you is in the description: should CI get a job for the odf environment?

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: neutrons/PyRS
  • Branch: next
  • File: .coderabbit.yaml
  • Commit: e5b5024
  • Layers: Repository YAML
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e976280b-e286-46ff-8262-0d5990ffddf8
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai

coderabbitai Bot commented Nov 28, 2026

Copy link
Copy Markdown

Add Carrot credits or activate Agent usage billing to use Autofix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant