Skip to content

Add the path-length-corrected pole figure window (stage 3 of 4, stacked on #1166) - #1167

Open
jefrbunn wants to merge 13 commits into
neutrons:nextfrom
jefrbunn:feature/pole-figures-gui
Open

jefrbunn wants to merge 13 commits into
neutrons:nextfrom
jefrbunn:feature/pole-figures-gui

Conversation

@jefrbunn

Copy link
Copy Markdown

Summary

This PR adds the window for path-length-corrected pole figures: pyrs.interface.pole_figures. It drives pyrs.pole_figures from a Qt window, and a new button in the PyRS main window opens it.

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

The window uses qtpy like the other PyRS windows. Pydantic models hold the inputs of each tab. Presenters connect the models to the widgets and call pyrs.pole_figures. The widgets hold no logic. Long jobs and figure builds run on worker threads, so the window stays responsive.

What is in this PR

The window has five tabs, in workflow order:

  • Sample: load the sample STL and check it (closed, size, volume). Set the gauge center and the mount convention. Edit, rotate or reset the sample-to-stage matrix. A preview shows the sample on the stage with the beams at any χ, φ.
  • Experiment setup: the material (a preset, a CIF file or custom values) and the wavelength (an HB-2B setting or a custom value). Also μ (computed or set by hand), the beams and slits, and the reflections to use. Reflections outside 2θ 50° to 120° are listed gray and cannot be chosen.
  • Predict: the χ, φ grid and the Monte Carlo points, one plane per chosen reflection with editable 2θ and ω, and the prediction in the background with progress and cancel. The plots are the summary, the path and correction of one plane, and the correction against φ. The cutoff redraws the plots without a new prediction. Beam-path GIFs can be made for one plane or all planes, with a time estimate. The plots and the predicted CSV can be saved.
  • Table scan: one table scan per plane from the prediction. Count times are scaled with the correction or fixed, with an optional cap per point and alternating φ. The tab shows the totals and a preview, and it writes the HB-2B workbooks.
  • Data and Corrections: add reduced HB2B_<run>.h5 files. The wavelength, slits, motor angles and count times come from each file. The gauge position comes from the run logs, from the prediction, or by hand. Spatial-map runs are listed in red and left out. The analysis runs in the background. Pole figures show as point cells or interpolated. The cutoff and the option to combine runs by hkl update them without a new analysis. Export writes the per-run CSVs and the figures. Beam-path GIFs show the measured points.

Shared parts:

  • main_window, app (open_window), worker, figure_jobs (figures built off the GUI thread, newest request wins) and figure_cache.
  • excepthook: an exception in a slot is logged and passed on to the host's hook, so it does not end PyRS.
  • widgets: the plot panel (figures at their designed size, GIFs, save), model forms, a toggle switch, and a wheel guard. The wheel changes a spin box or combo box only after a click into it.
  • run_checks and mount_matrix: Qt-free helpers with their own unit tests.
  • help: the ? button and F1 open a PDF user guide when it is installed. The guide is not in this PR (see below), so in PyRS the button says that the guide is not installed.

The ODF tab (MTEX for Python) is not in this PR. The window adds it only when its module, odf_tab, is installed. That module comes with stage 4.

Change to the PyRS main window

This PR changes existing PyRS UI. The owner approved it.

  • pyrsmain.ui: a new button, Path-Length-Corrected Pole Figures, in row 6 below Strain/Stress Calculation. The window is 30 px taller.
  • pyrs_main.py: do_launch_pole_figure_window opens the window, owned by the main window, or raises the open one. An error while opening is logged and shown in a message box, and PyRS keeps running. Quit also closes the window.
  • The import of pyrs.interface.pole_figures.app is at the top of pyrs_main.py. It adds 0.18 s to the 5.2 s import of the main window.
  • docs/user/source/basics/basics.rst: a short section on the button.

Dependencies

None new. The window uses qtpy, matplotlib, pydantic and openpyxl, which PyRS already has.

User guide

The PDF user guide (3.9 MB, with screenshots of real data) is not included. A later PR adds it as pages in the PyRS user documentation, with new screenshots, and points the ? button there.

Tests

  • GUI tier (tests/ui, gui and integration markers): 97 tests in 10 files test_pole_figures_*.py. They drive each tab offscreen with the slab STL fixture, synthetic reduced runs and the HB-2B subset file. One test needs the full reference runs. It skips unless HIDRA_PF_TEST_DATA is set.
  • Two new tests in test_pyrslauncher.py. The button opens one window, owned by the main window and raised on a second click. An error while opening is shown instead of ending PyRS.
  • Unit tier: 21 tests in tests/unit/pyrs/interface/pole_figures for the Qt-free helpers (run checks, the figure cache, the help links).
  • The shared test helpers gain CU_CIF, a small CIF for the material tab test.
  • Local runs, default environment (PyQt6): pre-commit and pixi run mypy pyrs scripts tests are clean. pixi run test-gui passes (166 passed, 1 skipped, 2 xfailed). The new GUI tests and the launcher tests pass in the prod environment too. With HIDRA_PF_TEST_DATA set all 100 pass. The unit tier passes (1871 passed, 13 xfailed). The pole-figure unit tests are 480 now. The integration tier is unchanged from Add pyrs.pole_figures plots and file output (stage 2 of 4, stacked on #1165) #1166.
  • The new tests also pass with qtpy on PySide6 in the default environment. Under PySide6 the existing test_launcher fails in the manual-reduction canvas. That is not part of this PR.

Later stage

Stage 4 adds the ODF step through MTEX for Python (pymtex) as an optional pixi feature, with the MTEX tab. The license question from #1165 still applies: pymtex is GPL-2.0-only.

🤖 Generated with Claude Code

jefrbunn and others added 13 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>
@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: a51ae572-bdd7-42b9-a05c-5beab9ccfc8b
  • 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

@jefrbunn
jefrbunn marked this pull request as ready for review November 27, 2026 16:59
@jefrbunn

Copy link
Copy Markdown
Author

@fanchercm @walshmm this is ready for review after #1165 and #1166. It is stage 3 of 4: the pole-figure window and a new button in the PyRS main window. It is stacked on #1166, so until #1165 and #1166 merge it also shows their commits. Stage 4 (the ODF step) waits on the license question in #1165.

@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