Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/deferred_defects.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,30 @@ without renumbering.

**Found during:** #1098 step 4, running the project-file and NeXus reduction tests together.
**Why it is deferred.** A test defect outside #1098, and CI is not affected.

- **DD-34**, 2026-11-20: a project file that reduction writes to a new path has no instrument geometry, so NXstress
cannot be written from it.
- **Cause:** `ReductionApp.save_diffraction_data` (`pyrs/core/powder_pattern.py`) opens a new output file in
`OVERWRITE` mode and writes the sample logs, wavelength, reduction record and patterns, but never calls
`write_instrument_geometry`. Only `NeXusConvertingApp.save` (`pyrs/core/nexus_conversion.py`) writes it.
- **Where it bites:** Manual Reduction's `reduce_hidra_workflow` (`pyrs/interface/manual_reduction/pyrs_api.py`)
converts in memory and saves through that call, so its output files carry no `geometry setup`.
- **Failure:** loading such a file gives a workspace without an instrument setup, and NXstress's instrument group
cannot be written from it.
- **Workaround in the tests:** `tests/integration/test_nxstress_calibration.py` adds the geometry to the reduced
file itself (`write_instrument_geometry`) before loading it.
- **Fix:** have `save_diffraction_data` write the workspace's instrument geometry when it creates a new file.

**Found during:** #1099, writing the real-data NXstress test (T1).
**Why it is deferred.** It predates #1099 and changes what reduction writes, which needs its own approval.

- **DD-36**, 2026-11-24: a refused NXstress write can leave a partial file. `NXstress(path, "w")` creates and opens
the file when its `with` block starts (`NXstress.__enter__`), so a write refused after that -- a workspace without
a `2theta` log, mixed calibrations, a missing field -- closes an incomplete file (about 800 bytes) at `path`
instead of leaving none. GUI saves are not affected: they write a temporary sibling and replace the destination
only on success (`gui_helper.write_nxstress_or_report`, see DD-10); scripts and code that use `NXstress`
directly are.

**Found during:** the test review of #1132 (#1099), which adds refusals during a write.
**Why it is deferred.** It predates #1099. The fix -- `NXstress` writing a temporary file and renaming it on
success -- changes how every NXstress write handles its file, outside the scope of #1132.
78 changes: 75 additions & 3 deletions docs/ground_truths.md
Original file line number Diff line number Diff line change
Expand Up @@ -3081,11 +3081,12 @@ becomes this check), `PyRsCore`, and the calibration GUI's "From file…" overla
- **The chain is `DetectorModel`'s order, innermost first** (`detector_model.CALIBRATION_TRANSFORMATIONS`,
built by `transformation_chain`): shift_x, shift_y, rotation_z, rotation_y, rotation_x (R = Rx·Ry·Rz, so Rz
acts first), arm_length, shift_z, two_theta_0 (about Y), arm_rotation (about Y; stored as 0, because the arm
angle belongs to each sub-run). Each value is float64 in m or deg, right-handed, in the PyRS frame (+Z beam,
angle belongs to each sub-run — **superseded by #1099:** the calibration file's chain now ends at
two_theta_0, see *NXstress detector chain is the calibration file's*). Each value is float64 in m or deg, right-handed, in the PyRS frame (+Z beam,
+Y up), with `<name>_errors` beside it (the JSON's -1 / -2 codes). The reader checks every transformation's
type, vector, units and `depends_on` against this chain, and refuses (`ValueError`) a file that would be
applied differently. It also checks that the detector's `depends_on` starts the chain at `shift_x`, that
`arm_rotation` is 0, and that the pixel offsets are PyRS's layout (`DetectorModel.local_positions`:
applied differently. It also checks that the detector's `depends_on` starts the chain at `shift_x` (the
`arm_rotation` = 0 check was dropped with the field, #1099), and that the pixel offsets are PyRS's layout (`DetectorModel.local_positions`:
X decreasing with `index_0`, Y increasing with `index_1`). The old NXstress chain, with 2θ₀ about X, would
be refused. One-element string arrays and shape-(1,) values, as other tools write them, are read. Also
refused (CodeRabbit review): a transformation with a non-zero NeXus `offset` (`DetectorModel` applies none),
Expand Down Expand Up @@ -3650,6 +3651,77 @@ the Docs: `docs/user/source`), so nothing caught it.
- **User docs:** `docs/user/source/conf.py` still uses plain `Mock` objects. It builds, because it documents
nothing they replace.

## NXstress detector chain is the calibration file's (2026-11-20, #1099)

- **Before:** NXstress wrote its own detector chain, and it did not place pixels where reduction does.
- **Order:** entering at the detector's `depends_on` (the innermost transformation, the NeXus rule) gave
two_theta_zero → Rz → Ry → Rx → distance → z → y → x. That does not match `DetectorModel.lab_positions`:
the rotation order (Rz → Ry → Rx) agrees, but 2θ₀ was applied first instead of after the arm length, and
the x/y shifts were applied last instead of before the rotations.
- **2θ₀ axis:** about X.
- **Arm angle:** missing.
- **Impact:** nothing in PyRS read the chain (`instrumentFromNexus` reads the values by name), so reduction was
unaffected; only external NeXus tools were misled.
- **Now:** `calibration_nexus.detector_transformations`, shared with the calibration file, writes it:
- shift_x, shift_y, rotation_z, rotation_y, rotation_x, arm_length, shift_z, two_theta_0 (about Y), arm_rotation;
- each calibration parameter with its `<name>_errors`;
- the detector's `depends_on` is `transformations/shift_x`.
- **The calibration file has no arm angle (user decision, #1132 review):** it holds the calibration parameters
only, and PyRS builds the instrument from them and each sub-run's arm angle. Its chain ends at `two_theta_0`
(`depends_on = "."`); only NXstress writes `arm_rotation`. The reader checks the chain up to `two_theta_0`
and skips an `arm_rotation` entry if a file has one (no check, no refusal). No calibration NeXus files had
been written before this, so the old layout (`arm_rotation` = 0) needs no support. Replaces the old shared
note, which told calibration files they held −(DAS arm 2theta).
- **Arm angle:** `arm_rotation` holds one value per scan point, −(the `2theta` log), and grows on append. Data
without a `2theta` log are refused (user decision, #1132 review G9): without the arm angle the detector cannot
be placed, so the write fails, naming the workspace. (It used to write NaN.)
- **Calibration defaults and L2 (user decisions, #1132 review G9):** a default calibration parameter is 0 with
error −1 (the nominal calibration), so a calibration JSON missing a parameter reads as the default
(`check_calibration_dictionary`, unchanged). L2 is part of the calibration and is to be compared by its hash
(#1141); until then it is compared for exact equality.
- **Arm length (user decision):** a single value, the runs' `L2` log when present (the one reduction uses), else
the instrument's. An entry whose L2 differs between scan points is refused.
- **Errors (user decision):** those of the applied calibration. −1 where none are known.
**Superseded (user decision, #1132 review G3; implemented by #1141):** −1 is the default (not refined, as
in the nominal calibration) and −2 an unknown error, so an error that is not known is written as −2. Until
#1141 lands, this PR still writes −1.
- **NXstress used to write the nominal detector for real data.** A workspace loaded from a project file never
got the calibration reduction applied: only FitCalibration and NXstress read-back set its shift. So every
NXstress file written from reduced data said `calibrated = False`.
- **Fix:** loading now keeps the file's recorded calibration (shift and errors, `get_recorded_calibration()`),
and NXstress writes that.
- **Kept apart from `get_detector_shift()` on purpose:** `ReductionApp` applies the workspace's shift
whenever no calibration file is given. Setting the shift would have made reducing a project file again,
without a calibration file, silently switch from the nominal geometry to the recorded one.
- **No backward compatibility (user decision, #1132 review):** NXstress and the NeXus calibration file are new
formats and may break old layouts. `instrumentFromNexus` reads only the current names (`shift_*`,
`arm_length`, `two_theta_0`); an entry written before #1099 (`translation_*`, `distance`, `two_theta_zero`, no
`arm_rotation`) is not supported, and an append to one is refused for its missing `arm_rotation`
("write a new entry"). This replaces the earlier decision to read old entries.
- **A missing field is a corrupt file (user decision, #1132 review, G9):** NXstress and the calibration file
always write every field, so a missing one means a failed write or a corrupt file. `instrumentFromNexus`
refuses it (`RuntimeError` naming the field), for the pixel layout, the `calibrated` flag, `arm_length`, each
calibration value and the wavelength. Before, a missing field read as 0.0: a calibration parameter silently
became 0, and a missing arm length failed with a message that did not name it.
- **Tested:** applied independently of `DetectorModel`, the written chain reproduces `lab_positions` at every scan
point to 1e-12 m.
- **The chain is a self-consistent choice (user decision, #1132 review R5):** PyRS defines the detector's
placement (`DetectorModel.lab_positions`, `CALIBRATION_TRANSFORMATIONS`), and the calibration refines its
parameters in that same model; NXstress and the calibration file write exactly that chain. It is not grounded in
an external reference (unlike the sample chain, which follows He, *Two-Dimensional X-ray Diffraction*, ch. 8.3),
and needs none: the check that matters is that the written chain places pixels where reduction does.
- **Errors survive a round trip.** Reading an NXstress entry back sets both the workspace's shift and its recorded
calibration with the entry's errors (`_Instrument.shiftErrorFromNexus`), so writing it again keeps them. Before
the code-review fix they came back as −1.
- **Which errors are written:** the workspace's own shift, with the recorded errors only when the recorded shift is
that same shift; with no shift, the recorded calibration. Errors are never lent to a different shift.
- **Mixed files record none.** Appending a project file reduced with another calibration (or none) clears the
recorded calibration, with a warning, so NXstress does not label every scan point with the first file's.
- **An unreadable record is optional:** it is warned about, the recorded calibration stays None, and the data load.
- **Fresh reductions carry no geometry (DD-34):** a project file that reduction writes to a new path has no
instrument geometry, so NXstress cannot be written from it until the geometry is added. See
[deferred_defects.md](deferred_defects.md).

## Calibration study: what the measurement conditions and the settings change (2026-11, #1097)

A study with no production change: ring calibrations (`calibrate_rings`, default settings unless stated) of 11 powder runs
Expand Down
4 changes: 2 additions & 2 deletions pyrs/core/detector_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,13 +358,13 @@ def transformation_chain(

Applied in order to a pixel's uncalibrated position (:meth:`DetectorModel.local_positions`), the chain
gives its lab position, as :meth:`DetectorModel.lab_positions` does: the one description of the
detector's geometry, for the NeXus calibration file (and, later, NXstress output).
detector's geometry, for the NeXus calibration file and NXstress output.

Args:
calibration: Detector shift, rotations and 2theta_0, or None for the nominal geometry.
arm_length: Sample-to-detector distance L2 (m).
arm_two_theta: Arm angle in the Mantid/PyRS convention (``-get_detector_2theta()``); a calibration
file stores 0, since the arm angle belongs to each sub-run, not to the calibration.
file omits the arm angle, which belongs to each sub-run.

Returns:
The transformations of :data:`CALIBRATION_TRANSFORMATIONS`, with their values.
Expand Down
54 changes: 54 additions & 0 deletions pyrs/core/workspaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
_logger = logging.getLogger(__name__)


def _shift_values(recorded):
"""The seven calibration values of a recorded calibration, to compare two (#1099); None for none."""
return None if recorded is None else tuple(recorded[0].convert_to_dict().values())


class HidraWorkspace:
"""
This workspace is the central data structure to manage all the raw and/or processed data.
Expand Down Expand Up @@ -47,6 +52,9 @@ def __init__(self, name="hidradata"):
# instrument
self._instrument_setup = None
self._instrument_geometry_shift = None # geometry shift
# the calibration reduction applied, from a project file's record (#1099): kept apart from the shift
# above, which reduction applies when no calibration file is given (ReductionApp)
self._recorded_calibration = None

# sample logs
self._sample_logs = SampleLogs() # sample logs: [log name, sub run] = value
Expand Down Expand Up @@ -603,6 +611,34 @@ def load_hidra_project(self, hidra_file, load_raw_counts, load_reduced_diffracti
# load the wave length
self._load_wave_length(hidra_file)

# the calibration the reduction applied, as the file recorded it (#1099)
self._load_recorded_calibration(hidra_file)

def _load_recorded_calibration(self, hidra_file) -> None:
"""Keep the calibration the reduction applied (shift and errors), from the file's calibration record
(#1053, #1099). A file with no record (reduced before #1053, or never calibrated) keeps None; a record
that cannot be read is warned about and kept None, as the file must still load."""
self._recorded_calibration = self._read_recorded_calibration(hidra_file)

def _read_recorded_calibration(self, hidra_file):
"""``(shift, shift_error)`` the file's reduction applied, or None (no record, or unreadable: warned)."""
try:
record = hidra_file.read_reduction_provenance()
if record.get("source", "none") == "none" or "calibration" not in record:
return None
instrument = hidra_file.read_reduction_instrument(self._instrument_setup)
except Exception as read_err: # noqa: BLE001 - the record is optional; the data must load
self._log.warning(f"applied calibration could not be read: {type(read_err).__name__}: {read_err}")
return None
if instrument.geometry_shift is None:
return None
return instrument.geometry_shift, instrument.geometry_shift_error

def set_recorded_calibration(self, shift, shift_error) -> None:
"""Set the calibration applied to this data and its errors (#1099), e.g. as read back from NXstress;
None for none. Reduction never applies it (that is :meth:`set_detector_shift`)."""
self._recorded_calibration = None if shift is None else (shift, shift_error)

def append_hidra_project(self, hidra_file):
"""
Load HIDRA project file
Expand All @@ -628,6 +664,15 @@ def append_hidra_project(self, hidra_file):
# # load masks
# self._load_masks(hidra_file)

# the appended data must have had the same calibration applied, or none can be claimed for the whole (#1099)
appended = self._read_recorded_calibration(hidra_file)
if _shift_values(appended) != _shift_values(self._recorded_calibration):
self._log.warning(
f"{hidra_file.name} was reduced with a different calibration (or none) than the data before it; "
"the combined data records no applied calibration"
)
self._recorded_calibration = None

def get_detector_mask(self, is_default, mask_id=None):
"""Get detector mask

Expand Down Expand Up @@ -665,6 +710,15 @@ def get_detector_shift(self):
"""
return self._instrument_geometry_shift

def get_recorded_calibration(self):
"""The calibration a reduction applied to this data, as its project file recorded it (#1099).

Returns:
``(shift, shift_error)`` (``DENEXDetectorShift``; the error None if not recorded), or None if the file
records no calibration. Unlike :meth:`get_detector_shift`, reduction never applies it.
"""
return self._recorded_calibration

def get_reduced_diffraction_data_set(self, mask_id=None):
"""Get reduced diffraction data set including 2theta and intensities

Expand Down
2 changes: 2 additions & 0 deletions pyrs/utilities/NXstress/NXstress.py
Original file line number Diff line number Diff line change
Expand Up @@ -1018,6 +1018,8 @@ def _workspaceFromNexus(cls, entry, rows, default_mask, mask_dict) -> HidraWorks
ws.set_instrument_geometry(geometry)
if shift is not None:
ws.set_detector_shift(shift)
# its errors too, so a workspace read back and written again keeps them (#1099)
ws.set_recorded_calibration(shift, _Instrument.shiftErrorFromNexus(entry[GROUP_NAME.INSTRUMENT]))
ws.set_masks_from_dict(default_mask, mask_dict)

# Read raw counts if present
Expand Down
Loading
Loading