Skip to content
Merged
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
10 changes: 10 additions & 0 deletions docs/deferred_defects.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,13 @@ 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-25: `calculate_sub_run_time_average` (`pyrs/core/nexus_conversion.py`) returns NaN for
`vx/vy/vz` (about 47% of autoreduced files, usually sub-run 0) because the raw logs start with a NaN placeholder
that overlaps the sub-run window by milliseconds. The strain/stress viewer then aborts on `PointList`'s finite-value
assertion when a peak is selected (#1147, [ground_truths.md](ground_truths.md)).
- **DD-35**, 2026-11-25: strain/stress viewer: the `selectedPeak` setter calls `create_strain` outside any
handler, so any `StrainField` error escapes a Qt slot and the viewer process aborts instead of reporting it.
- **DD-36**, 2026-11-25: `TextureFittingViewer.load` ("Load Stress state") calls `Controller.load`, which calls
`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).
65 changes: 65 additions & 0 deletions docs/ground_truths.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,71 @@
Key findings recorded here for future reference. Link to this file from related
documentation and code comments when relevant.

## Autoreduced, peak-fit files crash the strain/stress viewer (#1147, 2026-11)

**Root cause: a NaN sample position in the file, not the peak fit.** The viewer reads the file without error and fails
when it builds the strain field (`selectedPeak` setter → `Model.create_strain` → `StrainField` →
`PointList.__init__`, which asserts `np.isfinite` on `vx/vy/vz`). The `AssertionError` escapes a Qt slot, and the
viewer process aborts (core dump, offscreen test).

- **Where the NaN comes from.** The raw NeXus `DASlogs/vx|vy|vz` each start with a `NaN` placeholder at t = 0, and the
first real reading arrives after sub-run 1 has started. Run 6528 (IPTS-39954): scan_index 1 starts at 11.9936 s, the
first reading at 11.9964 s, a 2.8 ms gap. `calculate_sub_run_time_average`
([nexus_conversion.py](../pyrs/core/nexus_conversion.py)) time-averages the log over the sub-run window, and one NaN
sample makes the whole average NaN. Current code (1.9.0.dev435) reproduces it: `vx`, `vy`, `vz` of sub-run 0 are NaN,
`sx` is not. `__correct_starting_scan_index_time` does not help, since it moves only sweeping motors.
- **It is common.** 2397 of 5147 autoreduced files (47%) have a NaN in `vx/vy/vz`, mostly in sub-run 0 alone (1622)
or the first three (754), in every run-number range from 1001 to 6528. The loader alone never notices, which is why
150 recent files with peaks all loaded: `Model.load_hidra_project_file` does not build the point list.
- **What was ruled out.** The peak fit itself: a fresh autoreduce of run 2122 (IPTS-24907, `IN718_311.json`) with a
stubbed `plot_publisher` writes a normal `peaks/IN718_311` group, with a NaN `d reference` (from `"d0": []`) that the
viewer accepts, and loads and computes a stress. Peak-tag layout, parameter names, project-file version and the
`direction` log are likewise fine.
- **Reproduction.** Fit any peak inside the data of `HB2B_6528.h5` (2θ 73.4–90.4°, so not IN718 311 at 87.4–92.5°) and
set `model.e11 = [file]; model.selectedPeak = tag`.

**Second cause: a NaN d-reference (run 2416, IPTS-27567; no NaN positions in this run).** The autoreduce script reads
the peak-range JSON itself and never applies its d0, so a fit made with `"d0": []` stores `d reference = NaN`. The
file loads, but the viewer's strain is NaN at every point and the plot is silently empty (no error). The manually fit
file of the same run holds `d reference = 1.0`: the peak fitting tool's `load_peak_range_json` already maps an empty
d0 list to 1.0, the d0 the UI gives a newly drawn range. Fitted parameters do not depend on d0, so only the stored
`d reference` differs (NaN → 1.0, error 0). **1.0 Å is a placeholder, not a measured d0**: strain computed against it
(about 87,000 on run 2416) is meaningless until a real d0 is entered in the viewer.

**Change made (approved, option B).** The d0 rule moved into one PyRS function,
[`read_peak_range_json`](../pyrs/peaks/peak_ranges.py), which the peak fitting tool now calls (its behaviour is
unchanged, covered by the existing tests) and which autoreduction should call too, followed by
`apply_d0(peakcollections[0], peak)` after each fit (`set_d_reference` alone defaults to NaN, so forgetting it
recreates this bug). The shared autoreduce script is outside this
repository and has not been edited. Checked on run 2416: fit with this function, viewer strain NaN fraction 0.
The function also checks its input: a `null`, empty-string, NaN, non-numeric or non-positive d0; a window that is not
two finite numbers with x_min < x_max; a label that is not a non-empty printable string or is used by two peaks; a repeated key; and a file
with no peaks all raise a `ValueError` naming the file and peak. Only an empty or wrong-length d0 *list* defaults to
1.0. `PeakCollection.set_d_reference` is unchanged (`None` still becomes NaN, `''` raises).
It is also safe on any path: a FIFO, directory or device, a file over 1 MB, a non-UTF-8 file, JSON nested 100,000
deep, a 5000-digit number, a non-path argument or a NUL in the path all raise `PeakRangeFileError` instead of hanging
or leaking another exception (found by the #1147 security review).
A defaulted d0 (empty or wrong-length list) logs a warning naming the file and peak, since 1.0 is a placeholder.
`write_peak_range_json` checks with the same rules before opening the file, so a file PyRS writes is one it reads;
the peak fitting tool's and the texture fitting tool's save and load now use these, and report a bad file or table
instead of failing.
Every bad-file case raises one type, `PeakRangeFileError`, which the peak fitting window catches (it reports the
file and keeps the ranges on screen) and which autoreduction should catch to skip the peaks file and still finish.
A patch for the HB2B GitLab script that does this (and leaves its plotting code alone) is kept outside the repo:
`~/Testing/hb2b_autoreduction_peak_ranges.patch`. The deployed PyRS must contain `pyrs/peaks/peak_ranges.py` before
the patched script runs.

**Proposed fixes for the NaN positions (none applied; each needs approval).**
1. *Converter* (production): skip non-finite samples in the sub-run time average. Only values that are NaN today
change (to the first valid reading, e.g. vx[0] = 0); every finite value is bit-identical.
2. *Viewer* (production): catch the failure in the selection step and report which sub-runs have no position
instead of aborting.

**Autoreduce script (outside this repository, HB2B GitLab).** `reduce_HB2B_plots.py::plot1d_V2` uses `pd` and `px`
without importing pandas or plotly.express, so `generate_plotly` raises `NameError` after the first fitted peak
(the peaks are already written, but no summary page is published and later peaks are not fitted).
It also fits nothing when `peaks_file` is blank, or when the peak range is not wholly inside the data.

## Upgrade to Mantid 7.0 (2026-11)

Mantid 7.0.0 (released on `mantid/label/main`; 7.0 nightlies on
Expand Down
52 changes: 20 additions & 32 deletions pyrs/interface/peak_fitting/peak_fitting_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
unify them without also rewriting the peak-fitting data path.
"""

import json
import os
import traceback
from pathlib import Path
Expand All @@ -28,6 +27,7 @@
from pyrs.core.workspaces import HidraWorkspace
from pyrs.peaks import FitEngineFactory as PeakFitEngineFactory # type: ignore
from pyrs.peaks.peak_fit_engine import FitResult
from pyrs.peaks.peak_ranges import PeakRange, PeakRangeFileError, read_peak_range_json, write_peak_range_json
from pyrs.projectfile import HidraProjectFile, HidraProjectFileMode # type: ignore
from pyrs.utilities.NXstress.NXstress import NXstress
from pyrs.interface.nxstress_load import read_single_workspace
Expand Down Expand Up @@ -305,47 +305,35 @@ def save_peak_range_json(self, filename, list_peak_ranges, list_peak_labels, lis

A ``.json`` extension is appended when ``filename`` has none, because the
non-native Qt save dialog does not add it.

Raises:
PeakRangeFileError: If a row could not be read back (see `write_peak_range_json`).
"""
if not os.path.splitext(filename)[1]:
filename += ".json"

output = {}
for _index, peak_range in enumerate(list_peak_ranges):
output[_index] = {
"peak_range": peak_range,
"peak_label": list_peak_labels[_index],
"d0": float(list_peak_d0[_index]),
}

with open(filename, "w") as outfile:
json.dump(output, outfile)
if not len(list_peak_ranges) == len(list_peak_labels) == len(list_peak_d0):
raise PeakRangeFileError(
f"the table has {len(list_peak_ranges)} ranges, {len(list_peak_labels)} labels "
f"and {len(list_peak_d0)} d0 values"
)
peaks = []
for window, label, d0 in zip(list_peak_ranges, list_peak_labels, list_peak_d0):
try:
x_min, x_max = window
except (TypeError, ValueError):
raise PeakRangeFileError(f"peak_range must be [x_min, x_max], got {window!r}") from None
peaks.append(PeakRange(label=label, x_min=x_min, x_max=x_max, d0=d0))
write_peak_range_json(filename, peaks)

def load_peak_range_json(self, filename):
"""Deserialize a peak-range JSON file.

Files written before #925 stored the whole d0 list on every peak. A list
holding one value per peak is resolved to that peak's own value; any other
list (in practice the empty list) falls back to 1.0, the d0 the UI assigns
to a newly drawn peak range.
"""Deserialize a peak-range JSON file; see `read_peak_range_json` for how d0 is resolved.

Returns:
A tuple ``(peak_range, peak_label, peak_d0)`` of parallel lists.
"""
with open(filename) as json_file:
data = json.load(json_file)

peak_range = []
peak_label = []
peak_d0 = []
for _position, _index in enumerate(data.keys()):
peak_range.append(data[_index]["peak_range"])
peak_label.append(data[_index]["peak_label"])
d0 = data[_index]["d0"]
if isinstance(d0, list):
d0 = d0[_position] if len(d0) == len(data) else 1.0
peak_d0.append(float(d0))

return peak_range, peak_label, peak_d0
peaks = read_peak_range_json(filename)
return [[p.x_min, p.x_max] for p in peaks], [p.label for p in peaks], [p.d0 for p in peaks]

def save_nexus(self, data_key, file_name):
"""Save data to a Mantid-compatible NeXus file."""
Expand Down
18 changes: 16 additions & 2 deletions pyrs/interface/peak_fitting/peak_fitting_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"""

import os
from pathlib import Path
from typing import List, Optional

import numpy as np
Expand Down Expand Up @@ -44,6 +45,7 @@
from pyrs.interface.ui import qt_util
from pyrs.interface.ui.diffdataviews import GeneralDiffDataView, PeakFitSetupView
from pyrs.interface.ui.rstables import FitResultTable
from pyrs.peaks.peak_ranges import PeakRangeFileError
from pyrs.utilities import get_input_project_file # type: ignore
from pyrs.utilities import load_ui # type: ignore
from pyrs.utilities.config import Config
Expand Down Expand Up @@ -655,14 +657,26 @@ def clicked_save_peak_range(self):
list_peak_labels = self._ui_graphicsView_fitSetup.list_fit_peak_labels
list_peak_d0 = self._ui_graphicsView_fitSetup.list_fit_peak_d0

self._model.save_peak_range_json(json_file_name, list_peak_ranges, list_peak_labels, list_peak_d0)
try:
self._model.save_peak_range_json(json_file_name, list_peak_ranges, list_peak_labels, list_peak_d0)
except PeakRangeFileError as err:
pop_message(
self, f"Cannot save '{Path(json_file_name).name}'", detailed_message=str(err), message_type="error"
)

def clicked_load_peak_range(self):
json_file_name = self._browse_json_file(save_file=False)
if json_file_name is None:
return # user clicked cancel

peak_range, peak_label, peak_d0 = self._model.load_peak_range_json(json_file_name)
try:
peak_range, peak_label, peak_d0 = self._model.load_peak_range_json(json_file_name)
except PeakRangeFileError as err:
# a bad file leaves the ranges already on screen untouched
pop_message(
self, f"Cannot load '{Path(json_file_name).name}'", detailed_message=str(err), message_type="error"
)
return

self._ui_graphicsView_fitSetup.list_peak_ranges = peak_range
self._ui_graphicsView_fitSetup.list_fit_peak_labels = peak_label
Expand Down
76 changes: 33 additions & 43 deletions pyrs/interface/texture_fitting/texture_fitting_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import json
import logging
import re
import traceback
Expand All @@ -20,6 +19,13 @@
# from pyrs.interface.gui_helper import pop_message
from pyrs.peaks import FitEngineFactory as PeakFitEngineFactory # type: ignore
from pyrs.peaks.peak_fit_engine import FitResult
from pyrs.peaks.peak_ranges import (
DEFAULT_D0,
PeakRange,
PeakRangeFileError,
read_peak_range_json,
write_peak_range_json,
)
from pyrs.core.polefigurecalculator import PoleFigureCalculator
from qtpy.QtWidgets import QTableWidgetItem # type:ignore
from qtpy.QtCore import Signal, QObject # type:ignore
Expand Down Expand Up @@ -157,56 +163,40 @@ def to_json(self, filename, fit_range_table):
filename = "{}.json".format(fileParts[0])

try:
json_output = dict()

peaks = []
for peak_row in range(fit_range_table.rowCount()):
if fit_range_table.item(peak_row, 0) is not None and fit_range_table.item(peak_row, 1) is not None:
if fit_range_table.item(peak_row, 2) is None:
peak_tag = "peak_{}".format(peak_row + 1)
else:
peak_tag = fit_range_table.item(peak_row, 2).text()

if fit_range_table.item(peak_row, 3) is None:
d0 = 1.0
else:
d0 = float(fit_range_table.item(peak_row, 3).text())

json_output[str(peak_row)] = {
"peak_range": [
float(fit_range_table.item(peak_row, 0).text()),
float(fit_range_table.item(peak_row, 1).text()),
],
"peak_label": peak_tag,
"d0": d0,
}

with open(filename, "w") as f:
json.dump(json_output, f)
if fit_range_table.item(peak_row, 0) is None or fit_range_table.item(peak_row, 1) is None:
continue # a row without both edges of its window is not a peak yet
label_item = fit_range_table.item(peak_row, 2)
d0_item = fit_range_table.item(peak_row, 3)
peaks.append(
PeakRange(
label="peak_{}".format(peak_row + 1) if label_item is None else label_item.text(),
x_min=float(fit_range_table.item(peak_row, 0).text()),
x_max=float(fit_range_table.item(peak_row, 1).text()),
d0=DEFAULT_D0 if d0_item is None else float(d0_item.text()),
)
)
write_peak_range_json(filename, peaks)

except Exception as e:
self.failureMsg.emit(f"Failed save json file to {filename}", str(e), traceback.format_exc())

def from_json(self, filename, fit_range_table):
with open(filename) as f:
data = json.load(f)

for peak_entry in data.keys():
try:
float(data[peak_entry]["d0"])
except TypeError:
data[peak_entry]["d0"] = 1.0
try:
peaks = read_peak_range_json(filename)
except PeakRangeFileError as err:
# a bad file leaves the table as it was
self.failureMsg.emit(f"Cannot load '{os.path.basename(filename)}'", str(err), "")
return

for peak in peaks:
fit_range_table.insertRow(fit_range_table.rowCount())
fit_range_table.setItem(
fit_range_table.rowCount() - 1, 0, QTableWidgetItem(str(data[peak_entry]["peak_range"][0]))
)
fit_range_table.setItem(
fit_range_table.rowCount() - 1, 1, QTableWidgetItem(str(data[peak_entry]["peak_range"][1]))
)
fit_range_table.setItem(
fit_range_table.rowCount() - 1, 2, QTableWidgetItem(str(data[peak_entry]["peak_label"]))
)
fit_range_table.setItem(fit_range_table.rowCount() - 1, 3, QTableWidgetItem(str(data[peak_entry]["d0"])))
row = fit_range_table.rowCount() - 1
fit_range_table.setItem(row, 0, QTableWidgetItem(str(peak.x_min)))
fit_range_table.setItem(row, 1, QTableWidgetItem(str(peak.x_max)))
fit_range_table.setItem(row, 2, QTableWidgetItem(peak.label))
fit_range_table.setItem(row, 3, QTableWidgetItem(str(peak.d0)))

return

Expand Down
Loading
Loading