Skip to content

Commit 67f5631

Browse files
committed
Share the peak-range checks with both fitting tools (#1147)
Follow-up to the review of the first #1147 commits: - the texture fitting tool's from_json/to_json and the peak fitting tool's save now use the same checked reader and a new checked writer, write_peak_range_json, so a file PyRS writes is one it reads; a bad file or table is reported through the existing failure paths and leaves the table and disk unchanged (the texture reader used to turn a null d0 into 1.0) - a defaulted d0 (empty or wrong-length list) logs a warning naming the file and peak, since 1.0 is a placeholder - apply_d0() stores a peak's d0 on its fitted PeakCollection, so a caller cannot forget the step that set_d_reference's NaN default hides - two peaks may not share a label (the label is the peak tag) - error messages keep the file name when the path is long Tests: writer, apply_d0, warning, duplicate labels, the texture model's fit-range files, the peak fitting model's save, and a GUI test for a bad save. Defect recorded, not fixed: - DD-36: TextureFittingViewer.load calls TextureFittingModel.from_json with one argument instead of two, so the "Load Stress state" action raises TypeError out of a Qt slot Assisted-by: Claude
1 parent 3a27e33 commit 67f5631

10 files changed

Lines changed: 439 additions & 92 deletions

File tree

‎docs/deferred_defects.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,3 +207,7 @@ without renumbering.
207207
assertion when a peak is selected (#1147, [ground_truths.md](ground_truths.md)).
208208
- **DD-35**, 2026-11-25: strain/stress viewer: the `selectedPeak` setter calls `create_strain` outside any
209209
handler, so any `StrainField` error escapes a Qt slot and the viewer process aborts instead of reporting it.
210+
- **DD-36**, 2026-11-25: `TextureFittingViewer.load` ("Load Stress state") calls `Controller.load`, which calls
211+
`TextureFittingModel.from_json(filename)` with one argument; it needs `(filename, fit_range_table)`, so the
212+
menu action raises `TypeError` out of a Qt slot (`texture_fitting_viewer.py:1186`, `texture_fitting_crtl.py:225`).
213+
Found while moving `from_json` onto the checked peak-range reader (#1147).

‎docs/ground_truths.md‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,21 @@ d0 list to 1.0, the d0 the UI gives a newly drawn range. Fitted parameters do no
3636

3737
**Change made (approved, option B).** The d0 rule moved into one PyRS function,
3838
[`read_peak_range_json`](../pyrs/peaks/peak_ranges.py), which the peak fitting tool now calls (its behaviour is
39-
unchanged, covered by the existing tests) and which autoreduction should call too, setting
40-
`peakcollections[0].set_d_reference(values=peak.d0)` after each fit. The shared autoreduce script is outside this
39+
unchanged, covered by the existing tests) and which autoreduction should call too, followed by
40+
`apply_d0(peakcollections[0], peak)` after each fit (`set_d_reference` alone defaults to NaN, so forgetting it
41+
recreates this bug). The shared autoreduce script is outside this
4142
repository and has not been edited. Checked on run 2416: fit with this function, viewer strain NaN fraction 0.
4243
The function also checks its input: a `null`, empty-string, NaN, non-numeric or non-positive d0; a window that is not
43-
two finite numbers with x_min < x_max; a label that is not a non-empty printable string; a repeated key; and a file
44+
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
4445
with no peaks all raise a `ValueError` naming the file and peak. Only an empty or wrong-length d0 *list* defaults to
4546
1.0. `PeakCollection.set_d_reference` is unchanged (`None` still becomes NaN, `''` raises).
4647
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
4748
deep, a 5000-digit number, a non-path argument or a NUL in the path all raise `PeakRangeFileError` instead of hanging
4849
or leaking another exception (found by the #1147 security review).
50+
A defaulted d0 (empty or wrong-length list) logs a warning naming the file and peak, since 1.0 is a placeholder.
51+
`write_peak_range_json` checks with the same rules before opening the file, so a file PyRS writes is one it reads;
52+
the peak fitting tool's and the texture fitting tool's save and load now use these, and report a bad file or table
53+
instead of failing.
4954
Every bad-file case raises one type, `PeakRangeFileError`, which the peak fitting window catches (it reports the
5055
file and keeps the ranges on screen) and which autoreduction should catch to skip the peaks file and still finish.
5156
A patch for the HB2B GitLab script that does this (and leaves its plotting code alone) is kept outside the repo:

‎pyrs/interface/peak_fitting/peak_fitting_model.py‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
unify them without also rewriting the peak-fitting data path.
1515
"""
1616

17-
import json
1817
import os
1918
import traceback
2019
from pathlib import Path
@@ -28,7 +27,7 @@
2827
from pyrs.core.workspaces import HidraWorkspace
2928
from pyrs.peaks import FitEngineFactory as PeakFitEngineFactory # type: ignore
3029
from pyrs.peaks.peak_fit_engine import FitResult
31-
from pyrs.peaks.peak_ranges import read_peak_range_json
30+
from pyrs.peaks.peak_ranges import PeakRange, PeakRangeFileError, read_peak_range_json, write_peak_range_json
3231
from pyrs.projectfile import HidraProjectFile, HidraProjectFileMode # type: ignore
3332
from pyrs.utilities.NXstress.NXstress import NXstress
3433
from pyrs.interface.nxstress_load import read_single_workspace
@@ -306,20 +305,26 @@ def save_peak_range_json(self, filename, list_peak_ranges, list_peak_labels, lis
306305
307306
A ``.json`` extension is appended when ``filename`` has none, because the
308307
non-native Qt save dialog does not add it.
308+
309+
Raises:
310+
PeakRangeFileError: If a row could not be read back (see `write_peak_range_json`).
309311
"""
310312
if not os.path.splitext(filename)[1]:
311313
filename += ".json"
312314

313-
output = {}
314-
for _index, peak_range in enumerate(list_peak_ranges):
315-
output[_index] = {
316-
"peak_range": peak_range,
317-
"peak_label": list_peak_labels[_index],
318-
"d0": float(list_peak_d0[_index]),
319-
}
320-
321-
with open(filename, "w") as outfile:
322-
json.dump(output, outfile)
315+
if not len(list_peak_ranges) == len(list_peak_labels) == len(list_peak_d0):
316+
raise PeakRangeFileError(
317+
f"the table has {len(list_peak_ranges)} ranges, {len(list_peak_labels)} labels "
318+
f"and {len(list_peak_d0)} d0 values"
319+
)
320+
peaks = []
321+
for window, label, d0 in zip(list_peak_ranges, list_peak_labels, list_peak_d0):
322+
try:
323+
x_min, x_max = window
324+
except (TypeError, ValueError):
325+
raise PeakRangeFileError(f"peak_range must be [x_min, x_max], got {window!r}") from None
326+
peaks.append(PeakRange(label=label, x_min=x_min, x_max=x_max, d0=d0))
327+
write_peak_range_json(filename, peaks)
323328

324329
def load_peak_range_json(self, filename):
325330
"""Deserialize a peak-range JSON file; see `read_peak_range_json` for how d0 is resolved.

‎pyrs/interface/peak_fitting/peak_fitting_viewer.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -657,7 +657,12 @@ def clicked_save_peak_range(self):
657657
list_peak_labels = self._ui_graphicsView_fitSetup.list_fit_peak_labels
658658
list_peak_d0 = self._ui_graphicsView_fitSetup.list_fit_peak_d0
659659

660-
self._model.save_peak_range_json(json_file_name, list_peak_ranges, list_peak_labels, list_peak_d0)
660+
try:
661+
self._model.save_peak_range_json(json_file_name, list_peak_ranges, list_peak_labels, list_peak_d0)
662+
except PeakRangeFileError as err:
663+
pop_message(
664+
self, f"Cannot save '{Path(json_file_name).name}'", detailed_message=str(err), message_type="error"
665+
)
661666

662667
def clicked_load_peak_range(self):
663668
json_file_name = self._browse_json_file(save_file=False)

‎pyrs/interface/texture_fitting/texture_fitting_model.py‎

Lines changed: 33 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import json
21
import logging
32
import re
43
import traceback
@@ -20,6 +19,13 @@
2019
# from pyrs.interface.gui_helper import pop_message
2120
from pyrs.peaks import FitEngineFactory as PeakFitEngineFactory # type: ignore
2221
from pyrs.peaks.peak_fit_engine import FitResult
22+
from pyrs.peaks.peak_ranges import (
23+
DEFAULT_D0,
24+
PeakRange,
25+
PeakRangeFileError,
26+
read_peak_range_json,
27+
write_peak_range_json,
28+
)
2329
from pyrs.core.polefigurecalculator import PoleFigureCalculator
2430
from qtpy.QtWidgets import QTableWidgetItem # type:ignore
2531
from qtpy.QtCore import Signal, QObject # type:ignore
@@ -157,56 +163,40 @@ def to_json(self, filename, fit_range_table):
157163
filename = "{}.json".format(fileParts[0])
158164

159165
try:
160-
json_output = dict()
161-
166+
peaks = []
162167
for peak_row in range(fit_range_table.rowCount()):
163-
if fit_range_table.item(peak_row, 0) is not None and fit_range_table.item(peak_row, 1) is not None:
164-
if fit_range_table.item(peak_row, 2) is None:
165-
peak_tag = "peak_{}".format(peak_row + 1)
166-
else:
167-
peak_tag = fit_range_table.item(peak_row, 2).text()
168-
169-
if fit_range_table.item(peak_row, 3) is None:
170-
d0 = 1.0
171-
else:
172-
d0 = float(fit_range_table.item(peak_row, 3).text())
173-
174-
json_output[str(peak_row)] = {
175-
"peak_range": [
176-
float(fit_range_table.item(peak_row, 0).text()),
177-
float(fit_range_table.item(peak_row, 1).text()),
178-
],
179-
"peak_label": peak_tag,
180-
"d0": d0,
181-
}
182-
183-
with open(filename, "w") as f:
184-
json.dump(json_output, f)
168+
if fit_range_table.item(peak_row, 0) is None or fit_range_table.item(peak_row, 1) is None:
169+
continue # a row without both edges of its window is not a peak yet
170+
label_item = fit_range_table.item(peak_row, 2)
171+
d0_item = fit_range_table.item(peak_row, 3)
172+
peaks.append(
173+
PeakRange(
174+
label="peak_{}".format(peak_row + 1) if label_item is None else label_item.text(),
175+
x_min=float(fit_range_table.item(peak_row, 0).text()),
176+
x_max=float(fit_range_table.item(peak_row, 1).text()),
177+
d0=DEFAULT_D0 if d0_item is None else float(d0_item.text()),
178+
)
179+
)
180+
write_peak_range_json(filename, peaks)
185181

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

189185
def from_json(self, filename, fit_range_table):
190-
with open(filename) as f:
191-
data = json.load(f)
192-
193-
for peak_entry in data.keys():
194-
try:
195-
float(data[peak_entry]["d0"])
196-
except TypeError:
197-
data[peak_entry]["d0"] = 1.0
186+
try:
187+
peaks = read_peak_range_json(filename)
188+
except PeakRangeFileError as err:
189+
# a bad file leaves the table as it was
190+
self.failureMsg.emit(f"Cannot load '{os.path.basename(filename)}'", str(err), "")
191+
return
198192

193+
for peak in peaks:
199194
fit_range_table.insertRow(fit_range_table.rowCount())
200-
fit_range_table.setItem(
201-
fit_range_table.rowCount() - 1, 0, QTableWidgetItem(str(data[peak_entry]["peak_range"][0]))
202-
)
203-
fit_range_table.setItem(
204-
fit_range_table.rowCount() - 1, 1, QTableWidgetItem(str(data[peak_entry]["peak_range"][1]))
205-
)
206-
fit_range_table.setItem(
207-
fit_range_table.rowCount() - 1, 2, QTableWidgetItem(str(data[peak_entry]["peak_label"]))
208-
)
209-
fit_range_table.setItem(fit_range_table.rowCount() - 1, 3, QTableWidgetItem(str(data[peak_entry]["d0"])))
195+
row = fit_range_table.rowCount() - 1
196+
fit_range_table.setItem(row, 0, QTableWidgetItem(str(peak.x_min)))
197+
fit_range_table.setItem(row, 1, QTableWidgetItem(str(peak.x_max)))
198+
fit_range_table.setItem(row, 2, QTableWidgetItem(peak.label))
199+
fit_range_table.setItem(row, 3, QTableWidgetItem(str(peak.d0)))
210200

211201
return
212202

0 commit comments

Comments
 (0)