essreduce 25.12.0__py3-none-any.whl → 25.12.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -370,6 +370,8 @@ def get_calibrated_detector(
370
370
  ----------
371
371
  detector:
372
372
  NeXus detector group.
373
+ transform:
374
+ Transformation matrix for the detector.
373
375
  offset:
374
376
  Offset to add to the detector position.
375
377
  bank_sizes:
@@ -430,8 +432,8 @@ def assemble_detector_data(
430
432
 
431
433
  def get_calibrated_monitor(
432
434
  monitor: NeXusComponent[MonitorType, RunType],
435
+ transform: NeXusTransformation[MonitorType, RunType],
433
436
  offset: MonitorPositionOffset[RunType, MonitorType],
434
- source_position: Position[snx.NXsource, RunType],
435
437
  ) -> EmptyMonitor[RunType, MonitorType]:
436
438
  """
437
439
  Extract the data array corresponding to a monitor's signal field.
@@ -443,16 +445,16 @@ def get_calibrated_monitor(
443
445
  ----------
444
446
  monitor:
445
447
  NeXus monitor group.
448
+ transform:
449
+ Transformation matrix for the monitor.
446
450
  offset:
447
451
  Offset to add to the monitor position.
448
- source_position:
449
- Position of the neutron source.
450
452
  """
451
- monitor = nexus.compute_component_position(monitor)
453
+ transform_unit = transform.value.unit
452
454
  return EmptyMonitor[RunType, MonitorType](
453
455
  nexus.extract_signal_data_array(monitor).assign_coords(
454
- position=monitor['position'] + offset.to(unit=monitor['position'].unit),
455
- source_position=source_position,
456
+ position=transform.value * sc.vector([0, 0, 0], unit=transform_unit)
457
+ + offset.to(unit=transform_unit),
456
458
  )
457
459
  )
458
460
 
@@ -2,7 +2,11 @@
2
2
  # Copyright (c) 2025 Scipp contributors (https://github.com/scipp)
3
3
  """Normalization routines for neutron data reduction."""
4
4
 
5
+ from __future__ import annotations
6
+
7
+ import enum
5
8
  import functools
9
+ import warnings
6
10
 
7
11
  import scipp as sc
8
12
 
@@ -14,6 +18,7 @@ def normalize_by_monitor_histogram(
14
18
  *,
15
19
  monitor: sc.DataArray,
16
20
  uncertainty_broadcast_mode: UncertaintyBroadcastMode,
21
+ skip_range_check: bool = False,
17
22
  ) -> sc.DataArray:
18
23
  """Normalize detector data by a normalized histogrammed monitor.
19
24
 
@@ -23,10 +28,13 @@ def normalize_by_monitor_histogram(
23
28
  - For *event* detectors, the monitor values are mapped to the detector
24
29
  using :func:`scipp.lookup`. That is, for detector event :math:`d_i`,
25
30
  :math:`m_i` is the monitor bin value at the same coordinate.
26
- - For *histogram* detectors, the monitor is rebinned using to the detector
31
+ - For *histogram* detectors, the monitor is generally rebinned using the detector
27
32
  binning using :func:`scipp.rebin`. Thus, detector value :math:`d_i` and
28
33
  monitor value :math:`m_i` correspond to the same bin.
29
34
 
35
+ - In case the detector coordinate does not have a dimension in common with the
36
+ monitor, :func:`scipp.lookup` is used as in the event case.
37
+
30
38
  In both cases, let :math:`x_i` be the lower bound of monitor bin :math:`i`
31
39
  and let :math:`\\Delta x_i = x_{i+1} - x_i` be the width of that bin.
32
40
 
@@ -47,6 +55,16 @@ def normalize_by_monitor_histogram(
47
55
  Must be one-dimensional and have a dimension coordinate, typically "wavelength".
48
56
  uncertainty_broadcast_mode:
49
57
  Choose how uncertainties of the monitor are broadcast to the sample data.
58
+ skip_range_check:
59
+ If false (default), the detector data must be within the range of the monitor
60
+ coordinate. Set this to true to disable the check.
61
+ The value of out-of-range bins / events is undefined in that case.
62
+
63
+ This is useful when the detector contains data outside the monitor range, and it
64
+ is difficult or impossible to slice the detector without also removing in-range
65
+ data. In this case, the caller can mask those data points and skip the range
66
+ check. ``normalize_by_monitor_histogram`` does not take masks into account when
67
+ checking ranges as that is expensive to implement in a general case.
50
68
 
51
69
  Returns
52
70
  -------
@@ -60,22 +78,45 @@ def normalize_by_monitor_histogram(
60
78
  normalize_by_monitor_integrated:
61
79
  Normalize by an integrated monitor.
62
80
  """
63
- _check_monitor_range_contains_detector(monitor=monitor, detector=detector)
81
+ if not skip_range_check:
82
+ _check_monitor_range_contains_detector(monitor=monitor, detector=detector)
64
83
 
65
84
  dim = monitor.dim
66
85
 
67
- if detector.bins is None:
68
- monitor = monitor.rebin({dim: detector.coords[dim]})
69
- detector = _mask_detector_for_norm(detector=detector, monitor=monitor)
70
- coord = monitor.coords[dim]
71
- delta_w = sc.DataArray(coord[1:] - coord[:-1], masks=monitor.masks)
72
- norm = broadcast_uncertainties(
73
- monitor / delta_w, prototype=detector, mode=uncertainty_broadcast_mode
74
- )
75
-
76
- if detector.bins is None:
77
- return detector / norm.rebin({dim: detector.coords[dim]})
78
- return detector.bins / sc.lookup(norm, dim=dim)
86
+ match _HistogramNormalizationMode.deduce(detector, dim):
87
+ case _HistogramNormalizationMode.Events:
88
+ detector = _mask_detector_for_norm(detector=detector, monitor=monitor)
89
+ norm = _histogram_monitor_term(
90
+ monitor,
91
+ dim,
92
+ broadcast_to=detector,
93
+ uncertainty_broadcast_mode=uncertainty_broadcast_mode,
94
+ )
95
+ if dim in detector.bins.coords:
96
+ return detector.bins / sc.lookup(norm, dim=dim)
97
+ else:
98
+ return detector / norm
99
+
100
+ case _HistogramNormalizationMode.BinsCommonDim:
101
+ monitor = monitor.rebin({dim: detector.coords[dim]})
102
+ detector = _mask_detector_for_norm(detector=detector, monitor=monitor)
103
+ norm = _histogram_monitor_term(
104
+ monitor,
105
+ dim,
106
+ broadcast_to=detector,
107
+ uncertainty_broadcast_mode=uncertainty_broadcast_mode,
108
+ )
109
+ return detector / norm
110
+
111
+ case _HistogramNormalizationMode.BinsDifferentDim:
112
+ detector = _mask_detector_for_norm(detector=detector, monitor=monitor)
113
+ # No broadcast here because there are no common dims, use lookup instead.
114
+ norm = _histogram_monitor_term(
115
+ monitor,
116
+ dim,
117
+ uncertainty_broadcast_mode=uncertainty_broadcast_mode,
118
+ )
119
+ return detector / sc.lookup(norm)[_compute_bin_centers(detector, dim)]
79
120
 
80
121
 
81
122
  def normalize_by_monitor_integrated(
@@ -83,6 +124,7 @@ def normalize_by_monitor_integrated(
83
124
  *,
84
125
  monitor: sc.DataArray,
85
126
  uncertainty_broadcast_mode: UncertaintyBroadcastMode,
127
+ skip_range_check: bool = False,
86
128
  ) -> sc.DataArray:
87
129
  """Normalize detector data by an integrated monitor.
88
130
 
@@ -113,6 +155,16 @@ def normalize_by_monitor_integrated(
113
155
  Must be one-dimensional and have a dimension coordinate, typically "wavelength".
114
156
  uncertainty_broadcast_mode:
115
157
  Choose how uncertainties of the monitor are broadcast to the sample data.
158
+ skip_range_check:
159
+ If false (default), the detector data must be within the range of the monitor
160
+ coordinate. Set this to true to disable the check.
161
+ The value of out-of-range bins / events is undefined in that case.
162
+
163
+ This is useful when the detector contains data outside the monitor range, and it
164
+ is difficult or impossible to slice the detector without also removing in-range
165
+ data. In this case, the caller can mask those data points and skip the range
166
+ check. ``normalize_by_monitor_histogram`` does not take masks into account when
167
+ checking ranges as that is expensive to implement in a general case.
116
168
 
117
169
  Returns
118
170
  -------
@@ -126,7 +178,8 @@ def normalize_by_monitor_integrated(
126
178
  normalize_by_monitor_histogram:
127
179
  Normalize by a monitor histogram.
128
180
  """
129
- _check_monitor_range_contains_detector(monitor=monitor, detector=detector)
181
+ if not skip_range_check:
182
+ _check_monitor_range_contains_detector(monitor=monitor, detector=detector)
130
183
  detector = _mask_detector_for_norm(detector=detector, monitor=monitor)
131
184
  norm = monitor.nansum().data
132
185
  norm = broadcast_uncertainties(
@@ -149,15 +202,15 @@ def _check_monitor_range_contains_detector(
149
202
  # monitor range that is less than the detector bins which is fine for the events,
150
203
  # but would be wrong if the detector was subsequently histogrammed.
151
204
  if (det_coord := detector.coords.get(dim)) is not None:
152
- lo = det_coord[dim, :-1].nanmin()
153
- hi = det_coord[dim, 1:].nanmax()
205
+ ...
154
206
  elif (det_coord := detector.bins.coords.get(dim)) is not None:
155
- lo = det_coord.nanmin()
156
- hi = det_coord.nanmax()
207
+ ...
157
208
  else:
158
209
  raise sc.CoordError(
159
210
  f"Missing '{dim}' coordinate in detector for monitor normalization."
160
211
  )
212
+ lo = det_coord.nanmin()
213
+ hi = det_coord.nanmax()
161
214
 
162
215
  if monitor.coords[dim].min() > lo or monitor.coords[dim].max() < hi:
163
216
  raise ValueError(
@@ -181,13 +234,17 @@ def _mask_detector_for_norm(
181
234
  if (monitor_mask := _monitor_mask(monitor)) is None:
182
235
  return detector
183
236
 
184
- if (detector_coord := detector.coords.get(monitor.dim)) is not None:
237
+ if (detector_coord := detector.coords.get(dim)) is not None:
185
238
  # Apply the mask to the bins or a dense detector.
186
- # Use rebin to reshape the mask to the detector.
187
- mask = sc.DataArray(monitor_mask, coords={dim: monitor.coords[dim]}).rebin(
188
- {dim: detector_coord}
189
- ).data != sc.scalar(0, unit=None)
190
- return detector.assign_masks({"_monitor_mask": mask})
239
+ mask_da = sc.DataArray(monitor_mask, coords={dim: monitor.coords[dim]})
240
+ if dim in detector_coord.dims:
241
+ # Use rebin to reshape the mask to the detector.
242
+ mask = mask_da.rebin({dim: detector_coord}).data != sc.scalar(0, unit=None)
243
+ return detector.assign_masks(_monitor_mask=mask)
244
+ # else: need to use lookup to apply mask at matching coord elements
245
+ return detector.assign_masks(
246
+ _monitor_mask=sc.lookup(mask_da)[_compute_bin_centers(detector, dim)]
247
+ )
191
248
 
192
249
  # else: Apply the mask to the events.
193
250
  if dim not in detector.bins.coords:
@@ -197,7 +254,7 @@ def _mask_detector_for_norm(
197
254
  event_mask = sc.lookup(
198
255
  sc.DataArray(monitor_mask, coords={dim: monitor.coords[dim]})
199
256
  )[detector.bins.coords[dim]]
200
- return detector.bins.assign_masks({"_monitor_mask": event_mask})
257
+ return detector.bins.assign_masks(_monitor_mask=event_mask)
201
258
 
202
259
 
203
260
  def _monitor_mask(monitor: sc.DataArray) -> sc.Variable | None:
@@ -213,3 +270,74 @@ def _monitor_mask(monitor: sc.DataArray) -> sc.Variable | None:
213
270
  if not masks:
214
271
  return None
215
272
  return functools.reduce(sc.logical_or, masks)
273
+
274
+
275
+ def _histogram_monitor_term(
276
+ monitor: sc.DataArray,
277
+ dim: str,
278
+ *,
279
+ broadcast_to: sc.DataArray | None = None,
280
+ uncertainty_broadcast_mode: UncertaintyBroadcastMode,
281
+ ) -> sc.DataArray:
282
+ if not monitor.coords.is_edges(dim, dim):
283
+ raise sc.CoordError(
284
+ f"Monitor coordinage {dim} must be bin-edges for normalization."
285
+ )
286
+ coord = monitor.coords[dim]
287
+ delta_w = sc.DataArray(coord[1:] - coord[:-1], masks=monitor.masks)
288
+ norm = monitor / delta_w
289
+
290
+ if broadcast_to is not None:
291
+ return broadcast_uncertainties(
292
+ norm, prototype=broadcast_to, mode=uncertainty_broadcast_mode
293
+ )
294
+
295
+ match uncertainty_broadcast_mode:
296
+ case UncertaintyBroadcastMode.fail:
297
+ return norm
298
+ case UncertaintyBroadcastMode.drop:
299
+ return sc.values(norm)
300
+ case _:
301
+ warnings.warn(
302
+ "Cannot broadcast uncertainties in this case.",
303
+ UserWarning,
304
+ stacklevel=3,
305
+ )
306
+ return norm
307
+
308
+
309
+ class _HistogramNormalizationMode(enum.Enum):
310
+ Events = enum.auto()
311
+ """Use an event coordinate to lookup monitor values."""
312
+ BinsCommonDim = enum.auto()
313
+ """Use a bin coordinate which contains the monitor dimension.
314
+
315
+ The coordinate may be multi-dimensional but one dimension matches
316
+ the dimension of the monitor.
317
+ """
318
+ BinsDifferentDim = enum.auto()
319
+ """Use a bin coordinate which does not contain the monitor dimension.
320
+
321
+ The coordinate may be multi-dimensions, e.g., in the DREAM powder workflow
322
+ where it has dims (two_theta, dspacing [bin-edges]).
323
+ """
324
+
325
+ @classmethod
326
+ def deduce(cls, detector: sc.DataArray, dim: str) -> _HistogramNormalizationMode:
327
+ # Use an event-coord when available:
328
+ if detector.bins is not None and dim in detector.bins.coords:
329
+ return _HistogramNormalizationMode.Events
330
+ # else: use a bin-coord.
331
+
332
+ det_coord = detector.coords[dim]
333
+ if dim in det_coord.dims:
334
+ return _HistogramNormalizationMode.BinsCommonDim
335
+ return _HistogramNormalizationMode.BinsDifferentDim
336
+
337
+
338
+ def _compute_bin_centers(da: sc.DataArray, name: str) -> sc.Variable:
339
+ coord = da.coords[name]
340
+ for dim in coord.dims:
341
+ if da.coords.is_edges(name, dim):
342
+ coord = sc.midpoints(coord, dim=dim)
343
+ return coord
@@ -317,7 +317,19 @@ def _time_of_flight_data_events(
317
317
  parts = da.bins.constituents
318
318
  parts["data"] = tofs
319
319
  result = da.bins.assign_coords(tof=sc.bins(**parts, validate_indices=False))
320
- return result.bins.drop_coords("event_time_offset")
320
+ out = result.bins.drop_coords("event_time_offset")
321
+
322
+ # The result may still have an 'event_time_zero' dimension (in the case of an
323
+ # event monitor where events were not grouped by pixel).
324
+ if "event_time_zero" in out.dims:
325
+ if ("event_time_zero" in out.coords) and (
326
+ "event_time_zero" not in out.bins.coords
327
+ ):
328
+ out.bins.coords["event_time_zero"] = sc.bins_like(
329
+ out, out.coords["event_time_zero"]
330
+ )
331
+ out = out.bins.concat("event_time_zero")
332
+ return out
321
333
 
322
334
 
323
335
  def detector_ltotal_from_straight_line_approximation(
@@ -357,6 +369,7 @@ def detector_ltotal_from_straight_line_approximation(
357
369
 
358
370
  def monitor_ltotal_from_straight_line_approximation(
359
371
  monitor_beamline: EmptyMonitor[RunType, MonitorType],
372
+ source_position: Position[snx.NXsource, RunType],
360
373
  ) -> MonitorLtotal[RunType, MonitorType]:
361
374
  """
362
375
  Compute Ltotal for the monitor.
@@ -369,7 +382,10 @@ def monitor_ltotal_from_straight_line_approximation(
369
382
  Beamline data for the monitor that contains the positions necessary to compute
370
383
  the straight-line approximation to Ltotal (source and monitor positions).
371
384
  """
372
- graph = scn.conversion.graph.beamline.beamline(scatter=False)
385
+ graph = {
386
+ **scn.conversion.graph.beamline.beamline(scatter=False),
387
+ 'source_position': lambda: source_position,
388
+ }
373
389
  return MonitorLtotal[RunType, MonitorType](
374
390
  monitor_beamline.transform_coords(
375
391
  "Ltotal", graph=graph, keep_intermediate=False
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: essreduce
3
- Version: 25.12.0
3
+ Version: 25.12.1
4
4
  Summary: Common data reduction tools for the ESS facility
5
5
  Author: Scipp contributors
6
6
  License-Expression: BSD-3-Clause
@@ -1,6 +1,6 @@
1
1
  ess/reduce/__init__.py,sha256=9iqQ57K3stwyujDzOk30hj7WqZt1Ycnb9AVDDDmk3K0,451
2
2
  ess/reduce/logging.py,sha256=6n8Czq4LZ3OK9ENlKsWSI1M3KvKv6_HSoUiV4__IUlU,357
3
- ess/reduce/normalization.py,sha256=B4O5W3CV_ti-zeU7tyQEAXk5pCUebZ0BG30YN2I3TyY,7844
3
+ ess/reduce/normalization.py,sha256=r8H6SZgT94a1HE9qZ6Bx3N6c3VG3FzlJPzoCVMNI5-0,13081
4
4
  ess/reduce/parameter.py,sha256=4sCfoKOI2HuO_Q7JLH_jAXnEOFANSn5P3NdaOBzhJxc,4635
5
5
  ess/reduce/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
6
  ess/reduce/streaming.py,sha256=zbqxQz5dASDq4ZVyx-TdbapBXMyBttImCYz_6WOj4pg,17978
@@ -18,10 +18,10 @@ ess/reduce/nexus/_nexus_loader.py,sha256=5J26y_t-kabj0ik0jf3OLSYda3lDLDQhvPd2_ro
18
18
  ess/reduce/nexus/json_generator.py,sha256=ME2Xn8L7Oi3uHJk9ZZdCRQTRX-OV_wh9-DJn07Alplk,2529
19
19
  ess/reduce/nexus/json_nexus.py,sha256=QrVc0p424nZ5dHX9gebAJppTw6lGZq9404P_OFl1giA,10282
20
20
  ess/reduce/nexus/types.py,sha256=g5oBBEYPH7urF1tDP0tqXtixhQN8JDpe8vmiKrPiUW0,9320
21
- ess/reduce/nexus/workflow.py,sha256=KRzG_flkAGNCkwDGwhTjX3h3Hi4GexMEz84trMw7HIg,24944
21
+ ess/reduce/nexus/workflow.py,sha256=bVRnVZ6HTEdIFwZv61JuvFUeTt9efUwe1MR65gBhyw8,24995
22
22
  ess/reduce/scripts/grow_nexus.py,sha256=hET3h06M0xlJd62E3palNLFvJMyNax2kK4XyJcOhl-I,3387
23
23
  ess/reduce/time_of_flight/__init__.py,sha256=jn8x9rZ6PzyP_wK8ACd3cg9rOpDAu_IqHyTNSeKfVn0,1461
24
- ess/reduce/time_of_flight/eto_to_tof.py,sha256=Zh7jxah1hwHY7_O9XNmYD3IfJz6mYUKo5vtr74NWUUQ,18236
24
+ ess/reduce/time_of_flight/eto_to_tof.py,sha256=WkCmp8aDpnFTSbPnWosjb17oY5TnCnPDbL66ZeCHo_E,18849
25
25
  ess/reduce/time_of_flight/fakes.py,sha256=BqpO56PQyO9ua7QlZw6xXMAPBrqjKZEM_jc-VB83CyE,4289
26
26
  ess/reduce/time_of_flight/interpolator_numba.py,sha256=wh2YS3j2rOu30v1Ok3xNHcwS7t8eEtZyZvbfXOCtgrQ,3835
27
27
  ess/reduce/time_of_flight/interpolator_scipy.py,sha256=_InoAPuMm2qhJKZQBAHOGRFqtvvuQ8TStoN7j_YgS4M,1853
@@ -41,9 +41,9 @@ ess/reduce/widgets/_spinner.py,sha256=2VY4Fhfa7HMXox2O7UbofcdKsYG-AJGrsgGJB85nDX
41
41
  ess/reduce/widgets/_string_widget.py,sha256=iPAdfANyXHf-nkfhgkyH6gQDklia0LebLTmwi3m-iYQ,1482
42
42
  ess/reduce/widgets/_switchable_widget.py,sha256=fjKz99SKLhIF1BLgGVBSKKn3Lu_jYBwDYGeAjbJY3Q8,2390
43
43
  ess/reduce/widgets/_vector_widget.py,sha256=aTaBqCFHZQhrIoX6-sSqFWCPePEW8HQt5kUio8jP1t8,1203
44
- essreduce-25.12.0.dist-info/licenses/LICENSE,sha256=nVEiume4Qj6jMYfSRjHTM2jtJ4FGu0g-5Sdh7osfEYw,1553
45
- essreduce-25.12.0.dist-info/METADATA,sha256=ZsK4VI14-0O1zyzUlUAZS3PuqygkEgO7wsc5yIvjWyI,1988
46
- essreduce-25.12.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
47
- essreduce-25.12.0.dist-info/entry_points.txt,sha256=PMZOIYzCifHMTe4pK3HbhxUwxjFaZizYlLD0td4Isb0,66
48
- essreduce-25.12.0.dist-info/top_level.txt,sha256=0JxTCgMKPLKtp14wb1-RKisQPQWX7i96innZNvHBr-s,4
49
- essreduce-25.12.0.dist-info/RECORD,,
44
+ essreduce-25.12.1.dist-info/licenses/LICENSE,sha256=nVEiume4Qj6jMYfSRjHTM2jtJ4FGu0g-5Sdh7osfEYw,1553
45
+ essreduce-25.12.1.dist-info/METADATA,sha256=ALXVOH9hCHFE8rKM8p14XLErG_3gk24HyvWwhX1FzKc,1988
46
+ essreduce-25.12.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
47
+ essreduce-25.12.1.dist-info/entry_points.txt,sha256=PMZOIYzCifHMTe4pK3HbhxUwxjFaZizYlLD0td4Isb0,66
48
+ essreduce-25.12.1.dist-info/top_level.txt,sha256=0JxTCgMKPLKtp14wb1-RKisQPQWX7i96innZNvHBr-s,4
49
+ essreduce-25.12.1.dist-info/RECORD,,