From 4bfd858b2040831c6764962feb732d1ff3d0f6db Mon Sep 17 00:00:00 2001 From: Johannes Kasimir Date: Tue, 3 Nov 2026 13:46:08 +0100 Subject: [PATCH 1/7] feat: freia inversion mode --- .../docs/api-reference/index.md | 1 + .../src/ess/freia/__init__.py | 2 + .../src/ess/freia/conversions.py | 56 ++- .../essreflectometry/src/ess/freia/mcstas.py | 7 + .../essreflectometry/src/ess/freia/mirror.py | 169 +++++++ .../essreflectometry/src/ess/freia/types.py | 27 +- .../src/ess/freia/workflow.py | 91 +++- .../tests/freia/mcstas_test.py | 26 ++ .../tests/freia/mirror_test.py | 417 ++++++++++++++++++ 9 files changed, 764 insertions(+), 32 deletions(-) create mode 100644 packages/essreflectometry/src/ess/freia/mirror.py create mode 100644 packages/essreflectometry/tests/freia/mirror_test.py diff --git a/packages/essreflectometry/docs/api-reference/index.md b/packages/essreflectometry/docs/api-reference/index.md index d5429ceb0..127ab1575 100644 --- a/packages/essreflectometry/docs/api-reference/index.md +++ b/packages/essreflectometry/docs/api-reference/index.md @@ -100,6 +100,7 @@ corrections data mcstas + mirror load resolution types diff --git a/packages/essreflectometry/src/ess/freia/__init__.py b/packages/essreflectometry/src/ess/freia/__init__.py index bda910c00..b54bafcb7 100644 --- a/packages/essreflectometry/src/ess/freia/__init__.py +++ b/packages/essreflectometry/src/ess/freia/__init__.py @@ -7,6 +7,7 @@ conversions, maskings, mcstas, + mirror, normalization, orso, resolution, @@ -54,6 +55,7 @@ "conversions", "maskings", "mcstas", + "mirror", "normalization", "orso", "resolution", diff --git a/packages/essreflectometry/src/ess/freia/conversions.py b/packages/essreflectometry/src/ess/freia/conversions.py index c73e830a0..36069a860 100644 --- a/packages/essreflectometry/src/ess/freia/conversions.py +++ b/packages/essreflectometry/src/ess/freia/conversions.py @@ -15,9 +15,11 @@ RunType, SampleRun, ) +from .mirror import DIRECT_BEAM, direct_beam_transform, unfold_path from .types import ( DownstreamSlitCenters, IncidentAngleGraph, + IncidentBeamTransform, SampleSurfaceNormal, ShutterPositions, ShutterStatusLogs, @@ -192,12 +194,14 @@ def theta( def incident_beam_directions( upstream_slit_centers: UpstreamSlitCenters[RunType], downstream_slit_centers: DownstreamSlitCenters[RunType], + beam_transform: sc.Variable = DIRECT_BEAM, ) -> dict[str, sc.Variable]: """Compute candidate incident directions from corresponding slit openings. The two inputs map the names of open channels to their centers in the upstream and downstream slit assemblies. Matching keys describe one - possible incident beam. + possible incident beam. In inversion mode the mirror is between the + assemblies, so only the upstream slit is mapped to its virtual position. """ if upstream_slit_centers.keys() != downstream_slit_centers.keys(): raise ValueError( @@ -205,7 +209,9 @@ def incident_beam_directions( ) directions = {} for key, upstream in upstream_slit_centers.items(): - beam = downstream_slit_centers[key] - upstream + downstream = downstream_slit_centers[key] + virtual_upstream = unfold_path(beam_transform, upstream, downstream) + beam = downstream - virtual_upstream.to(unit=downstream.unit) directions[key] = beam / sc.norm(beam) return directions @@ -243,6 +249,7 @@ def coordinate_transformation_graph( sample_position: Position[NXsample, RunType], sample_surface_normal: SampleSurfaceNormal[RunType], gravity: GravityVector, + beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> CoordTransformationGraph[RunType]: """Build the scattering coordinates shared by sample and direct-beam runs.""" length = sc.norm(sample_surface_normal) @@ -256,7 +263,9 @@ def coordinate_transformation_graph( **graph.beamline.L2(), 'outgoing_direction': outgoing_direction, 'scattering_angle': scattering_angle, - 'source_position': lambda: source_position, + 'source_position': lambda: unfold_path( + beam_transform, source_position, sample_position + ), 'sample_position': lambda: sample_position, 'sample_surface_normal': lambda: sample_surface_normal, 'gravity': lambda: gravity, @@ -268,20 +277,24 @@ def sample_coordinate_transformation_graph( sample_position: Position[NXsample, SampleRun], sample_surface_normal: SampleSurfaceNormal[SampleRun], gravity: GravityVector, + beam_transform: IncidentBeamTransform[SampleRun] = DIRECT_BEAM, ) -> CoordTransformationGraph[SampleRun]: """Extend the scattering graph with the sample's reflection angle and Q.""" return coordinate_transformation_graph( - source_position, sample_position, sample_surface_normal, gravity + source_position, sample_position, sample_surface_normal, gravity, beam_transform ) | {'theta': theta, 'Q': reflectometry_q} def _incident_angles_from_slits( - upstream_slit_centers, downstream_slit_centers, sample_surface_normal + upstream_slit_centers, + downstream_slit_centers, + sample_surface_normal, + beam_transform, ): return { beam_name: incident_angle(direction, sample_surface_normal) for beam_name, direction in incident_beam_directions( - upstream_slit_centers, downstream_slit_centers + upstream_slit_centers, downstream_slit_centers, beam_transform ).items() } @@ -290,10 +303,14 @@ def fixed_slits_incident_angle_graph( upstream_slit_centers: UpstreamSlitCenters[RunType], downstream_slit_centers: DownstreamSlitCenters[RunType], sample_surface_normal: SampleSurfaceNormal[RunType], + beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> IncidentAngleGraph[RunType]: """Provide a constant incident angle from a single pair of fixed slit openings.""" (beam_incident_angle,) = _incident_angles_from_slits( - upstream_slit_centers, downstream_slit_centers, sample_surface_normal + upstream_slit_centers, + downstream_slit_centers, + sample_surface_normal, + beam_transform, ).values() return {'incident_angle': lambda: beam_incident_angle} @@ -302,10 +319,14 @@ def closest_beam_incident_angle_graph( upstream_slit_centers: UpstreamSlitCenters[RunType], downstream_slit_centers: DownstreamSlitCenters[RunType], sample_surface_normal: SampleSurfaceNormal[RunType], + beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> IncidentAngleGraph[RunType]: """Provide incidence assignment using the closest expected reflection angle.""" beam_incident_angles = _incident_angles_from_slits( - upstream_slit_centers, downstream_slit_centers, sample_surface_normal + upstream_slit_centers, + downstream_slit_centers, + sample_surface_normal, + beam_transform, ) def select_incident_angle(reflection_angle: sc.Variable) -> sc.Variable: @@ -320,10 +341,14 @@ def shutter_log_incident_angle_graph( sample_surface_normal: SampleSurfaceNormal[RunType], shutter_positions: ShutterPositions[RunType], shutter_status_logs: ShutterStatusLogs[RunType], + beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> IncidentAngleGraph[RunType]: """Identify candidate beams using each shutter's position and status log.""" beam_incident_angles = _incident_angles_from_slits( - upstream_slit_centers, downstream_slit_centers, sample_surface_normal + upstream_slit_centers, + downstream_slit_centers, + sample_surface_normal, + beam_transform, ) if not beam_incident_angles: @@ -352,7 +377,10 @@ def select_incident_angle( L2, sample_position, incident_angles=beam_incident_angles, - shutter_positions=shutter_positions, + shutter_positions={ + key: unfold_path(beam_transform, position, sample_position) + for key, position in shutter_positions.items() + }, shutter_status_logs=shutter_status_logs, ) @@ -365,11 +393,16 @@ def offspecular_coordinate_transformation_graph( sample_surface_normal: SampleSurfaceNormal[RunType], gravity: GravityVector, incident_angle_graph: IncidentAngleGraph[RunType], + beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> CoordTransformationGraph[RunType]: """Combine an incidence assignment with the shared offspecular coordinates.""" return ( coordinate_transformation_graph( - source_position, sample_position, sample_surface_normal, gravity + source_position, + sample_position, + sample_surface_normal, + gravity, + beam_transform, ) | incident_angle_graph | { @@ -381,6 +414,7 @@ def offspecular_coordinate_transformation_graph( providers = ( + direct_beam_transform, coordinate_transformation_graph, sample_coordinate_transformation_graph, ) diff --git a/packages/essreflectometry/src/ess/freia/mcstas.py b/packages/essreflectometry/src/ess/freia/mcstas.py index 98fa80d33..fd8e1762e 100644 --- a/packages/essreflectometry/src/ess/freia/mcstas.py +++ b/packages/essreflectometry/src/ess/freia/mcstas.py @@ -334,6 +334,13 @@ def mcstas_sample_surface_normal( return SampleSurfaceNormal[RunType](sc.vector(rotation[1], unit='dimensionless')) +def mcstas_inverted_sample_surface_normal( + filename: Filename[RunType], +) -> SampleSurfaceNormal[RunType]: + """Load the normal pointing out of the sample's underside in inversion mode.""" + return SampleSurfaceNormal[RunType](-mcstas_sample_surface_normal(filename)) + + def load_mcstas_monitor(filename: str | Path, monitor_name: str) -> sc.DataArray: """Read a selected one-dimensional McStas L_monitor histogram. diff --git a/packages/essreflectometry/src/ess/freia/mirror.py b/packages/essreflectometry/src/ess/freia/mirror.py new file mode 100644 index 000000000..bd18499fe --- /dev/null +++ b/packages/essreflectometry/src/ess/freia/mirror.py @@ -0,0 +1,169 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026 Scipp contributors (https://github.com/scipp) +"""Geometry for FREIA's planar inversion mirror.""" + +import numpy as np +import scipp as sc +import scippnexus as snx +from ess.reduce import nexus +from ess.reduce.nexus.types import ( + EmptyDetector, + NeXusComponentLocationSpec, + NeXusFileSpec, + NeXusName, + NeXusTransformation, + Position, + TimeInterval, + TransformationTimeFilter, +) +from ess.reduce.nexus.workflow import reject_time_dependent_transform, to_transformation +from ess.reduce.unwrap.types import DetectorLtotal + +from ..reflectometry.types import RunType +from .types import IncidentBeamTransform, MirrorNormal, MirrorPosition + +# Default for direct calls to coordinate-graph providers; never modified in place. +DIRECT_BEAM = sc.spatial.translation(value=[0.0, 0.0, 0.0], unit='m') + + +def direct_beam_transform() -> IncidentBeamTransform[RunType]: + """Leave upstream coordinates unchanged when inversion is disabled.""" + return IncidentBeamTransform[RunType](DIRECT_BEAM.copy()) + + +def mirror_time_filter() -> TransformationTimeFilter[snx.NXmirror, RunType]: + """Require one mirror pose, unless the caller explicitly selects a pose.""" + return reject_time_dependent_transform + + +def load_mirror_transformation( + file_spec: NeXusFileSpec[RunType], + name: NeXusName[snx.NXmirror], + interval: TimeInterval[RunType], + time_filter: TransformationTimeFilter[ + snx.NXmirror, RunType + ] = reject_time_dependent_transform, +) -> NeXusTransformation[snx.NXmirror, RunType]: + """Load a named NXmirror using the usual ESS transformation/time filtering. + + The component name is a provisional convention, configurable through + NeXusName[NXmirror]. No pose is inferred if the component is missing. + """ + location = NeXusComponentLocationSpec[snx.NXmirror, RunType]( + filename=file_spec.value, component_name=name + ) + try: + component = nexus.load_component(location, nx_class=snx.NXmirror) + except (KeyError, ValueError) as error: + raise ValueError( + f"Cannot load inversion mirror {name!r}. Set NeXusName[NXmirror] " + "to its component name, or supply MirrorPosition and MirrorNormal " + "for this run." + ) from error + if 'depends_on' not in component: + raise ValueError("The inversion NXmirror requires a depends_on chain.") + return to_transformation(component['depends_on'], interval, time_filter) + + +def mirror_position( + transformation: NeXusTransformation[snx.NXmirror, RunType], +) -> MirrorPosition[RunType]: + """Transform the NXmirror origin to a point on the reflecting plane.""" + transform = transformation.value + if isinstance(transform, sc.DataArray): + raise ValueError('The inversion mirror must have a static pose for the run.') + return MirrorPosition[RunType](transform * sc.vector([0.0, 0.0, 0.0], unit='m')) + + +def mirror_normal( + transformation: NeXusTransformation[snx.NXmirror, RunType], +) -> MirrorNormal[RunType]: + """Rotate local -z, the NXmirror reference-plane normal, to the lab frame.""" + origin = mirror_position(transformation) + tip = transformation.value * sc.vector([0.0, 0.0, -1.0], unit='m') + normal = tip - origin + return MirrorNormal[RunType](normal / sc.norm(normal)) + + +def mirror_reflection_transform( + position: MirrorPosition[RunType], + normal: MirrorNormal[RunType], +) -> IncidentBeamTransform[RunType]: + """Unfold a planar specular reflection using p' = p - 2 n (n dot (p-m)).""" + for name, vector in [('MirrorPosition', position), ('MirrorNormal', normal)]: + if vector.ndim != 0 or vector.dtype != sc.DType.vector3: + raise ValueError(f'{name} must be a scalar vector.') + if not np.isfinite(vector.value).all(): + raise ValueError(f'{name} must be finite.') + n = normal.value + scale = np.max(np.abs(n)) + if scale == 0: + raise ValueError('MirrorNormal must be nonzero.') + n = n / scale + n = n / np.linalg.norm(n) + matrix = np.eye(4) + matrix[:3, :3] -= 2 * np.outer(n, n) + p = position.to(unit='m').value + matrix[:3, 3] = p - matrix[:3, :3] @ p + return IncidentBeamTransform[RunType]( + sc.spatial.affine_transform(value=matrix, unit='m') + ) + + +def transform_position(transform: sc.Variable, position: sc.Variable) -> sc.Variable: + """Apply the beam-path transform, preserving the input length unit.""" + return (transform * position.to(unit=transform.unit)).to(unit=position.unit) + + +def unfold_path( + transform: sc.Variable, upstream: sc.Variable, downstream: sc.Variable +) -> sc.Variable: + """Return the virtual upstream point, checking that reflection is possible. + + A reflected ray connects points on the same side of the mirror plane. + The midpoint of a point and its image lies in that plane; their difference + points towards the physical upstream side. For the identity transform the + difference is zero, so ordinary paths pass unchanged. + """ + if sc.identical(transform, DIRECT_BEAM): + return upstream + virtual = transform_position(transform, upstream) + midpoint = (0.5 * (upstream + virtual)).to(unit=downstream.unit) + normal = (upstream - virtual).to(unit=downstream.unit) + if sc.dot(downstream - midpoint, normal).value < 0: + raise ValueError( + 'A reflected path requires its upstream and downstream positions ' + 'to be on the same side of the mirror plane. Check the mirror pose ' + 'and component positions.' + ) + return virtual + + +def detector_ltotal_with_mirror( + detector: EmptyDetector[RunType], + source_position: Position[snx.NXsource, RunType], + sample_position: Position[snx.NXsample, RunType], + transform: IncidentBeamTransform[RunType], +) -> DetectorLtotal[RunType]: + """Straight-segment source-mirror-sample-detector path via the virtual source. + + As in the ordinary workflow, this approximates the upstream guide by a + straight ray. It includes the mirror detour without moving the real source + used for chopper and upstream-monitor wavelength reconstruction. + """ + virtual_source = unfold_path(transform, source_position, sample_position) + sample = sample_position.to(unit=virtual_source.unit) + pixels = detector.coords['position'].to(unit=virtual_source.unit) + return DetectorLtotal[RunType]( + sc.norm(sample - virtual_source) + sc.norm(pixels - sample) + ) + + +providers = ( + mirror_time_filter, + load_mirror_transformation, + mirror_position, + mirror_normal, + mirror_reflection_transform, + detector_ltotal_with_mirror, +) diff --git a/packages/essreflectometry/src/ess/freia/types.py b/packages/essreflectometry/src/ess/freia/types.py index c47cc80ff..2f3dacc77 100644 --- a/packages/essreflectometry/src/ess/freia/types.py +++ b/packages/essreflectometry/src/ess/freia/types.py @@ -34,12 +34,34 @@ class SampleSurfaceNormal(sciline.Scope[RunType, sc.Variable], sc.Variable): """Normal pointing out of the reflecting surface, in global coordinates.""" +class MirrorPosition(sciline.Scope[RunType, sc.Variable], sc.Variable): + """A point on the inversion mirror's reflecting plane, in global coordinates.""" + + +class MirrorNormal(sciline.Scope[RunType, sc.Variable], sc.Variable): + """Normal to the inversion mirror in global coordinates; either sign is valid.""" + + +class IncidentBeamTransform(sciline.Scope[RunType, sc.Variable], sc.Variable): + """Map upstream positions to virtual positions after the inversion mirror. + + Identity in normal operation. In inversion mode this is reflection in the + mirror plane. Sample, detector, and gravity remain in the laboratory frame. + """ + + class UpstreamSlitCenters(sciline.Scope[RunType, dict], dict): - """Upstream beam names mapped to fixed slit centers in global coordinates.""" + """Beam names mapped to fixed slit centers before the inversion mirror. + + Positions are in global coordinates, also when inversion is disabled. + """ class DownstreamSlitCenters(sciline.Scope[RunType, dict], dict): - """Downstream beam names mapped to fixed slit centers in global coordinates.""" + """Beam names mapped to fixed slit centers after the inversion mirror. + + Positions are in global coordinates, also when inversion is disabled. + """ class DetectorRegionOfInterest(sciline.Scope[RunType, dict], dict): @@ -60,6 +82,7 @@ class ShutterPositions(sciline.Scope[RunType, dict], dict): Keys match UpstreamSlitCenters and DownstreamSlitCenters. Each beam has one shutter, whose position is independent of the slit centers used for angles. + In inversion mode, shutters must be upstream of the mirror. """ diff --git a/packages/essreflectometry/src/ess/freia/workflow.py b/packages/essreflectometry/src/ess/freia/workflow.py index b69841663..d252f35db 100644 --- a/packages/essreflectometry/src/ess/freia/workflow.py +++ b/packages/essreflectometry/src/ess/freia/workflow.py @@ -5,12 +5,13 @@ import sciline import scipp as sc -from ess.reduce.nexus.types import DetectorBankSizes +from ess.reduce.nexus.types import DetectorBankSizes, NeXusName from ess.reduce.uncertainty import UncertaintyBroadcastMode from ess.reduce.unwrap import WavelengthLutMode from ess.reduce.unwrap.types import KeepEventTimeOffset from ess.reduce.unwrap.workflow import GenericUnwrapWorkflow from ess.reduce.workflow import register_workflow +from scippnexus import NXmirror from ..reflectometry import providers as reflectometry_providers from ..reflectometry.types import ( @@ -21,7 +22,7 @@ ReferenceRun, SampleRun, ) -from . import conversions, corrections, mcstas, normalization, orso +from . import conversions, corrections, mcstas, mirror, normalization, orso from .corrections import RunNormalization, insert_run_normalization from .types import ( DetectorRegionOfInterest, @@ -88,6 +89,7 @@ def FreiaMcStasWorkflow( *, run_norm: RunNormalization = RunNormalization.none, wavelength_from: WavelengthLutMode = "analytical", + inversion: bool = False, **kwargs, ) -> sciline.Pipeline: """Workflow for reducing FREIA McStas events with a no-sample direct beam. @@ -103,14 +105,24 @@ def FreiaMcStasWorkflow( Mode for creating the wavelength lookup table. Possible values are 'analytical', 'simulation', and 'file'. See https://scipp.github.io/ess/reduce/user-guide/unwrap/lut-building-methods.html + inversion: + Use the inversion-mirror geometry described in :func:`FreiaWorkflow`. + Supply ``MirrorPosition`` and ``MirrorNormal`` for both runs; the McStas + adapter does not infer a mirror from guide walls. The loaded sample + normal is reversed to describe reflection from the underside. """ workflow = FreiaWorkflow( - run_norm=run_norm, wavelength_from=wavelength_from, **kwargs + run_norm=run_norm, + wavelength_from=wavelength_from, + inversion=inversion, + **kwargs, ) for provider in mcstas.providers: workflow.insert(provider) for name, param in mcstas_default_parameters().items(): workflow[name] = param + if inversion: + workflow.insert(mcstas.mcstas_inverted_sample_surface_normal) return workflow @@ -118,6 +130,7 @@ def FreiaWorkflow( *, run_norm: RunNormalization = RunNormalization.proton_charge, wavelength_from: WavelengthLutMode = "file", + inversion: bool = False, **kwargs, ) -> sciline.Pipeline: """Workflow for reduction of data for the Freia instrument. @@ -145,6 +158,15 @@ def FreiaWorkflow( Mode for creating the wavelength lookup table. Possible values are 'analytical', 'simulation', and 'file'. See https://scipp.github.io/ess/reduce/user-guide/unwrap/lut-building-methods.html + inversion: + Enable a planar mirror upstream of the sample for illumination from + below. Load its pose from the NXmirror named ``inversion_mirror`` + (configurable with ``NeXusName[NXmirror]``), or supply per-run + ``MirrorPosition`` and ``MirrorNormal`` in laboratory coordinates. + The detector flight path includes the mirror reflection. Supply the + actual sample/detector positions and a ``SampleSurfaceNormal`` pointing + out of the underside (normally -y) for both runs. The reference must be + measured with the same mirror configuration. """ workflow = GenericUnwrapWorkflow( run_types=[SampleRun, ReferenceRun], @@ -164,6 +186,8 @@ def FreiaWorkflow( insert_run_normalization(workflow, run_norm) for name, param in default_parameters().items(): workflow[name] = param + if inversion: + _insert_mirror(workflow) return workflow @@ -172,6 +196,7 @@ def FreiaOffspecWorkflow( *, incident_beam_from: Literal['closest', 'fixed_slits', 'shutter_logs'] = 'closest', wavelength_from: WavelengthLutMode = "file", + inversion: bool = False, **kwargs, ) -> sciline.Pipeline: """Workflow for unnormalized, coplanar off-specular FREIA data. @@ -197,6 +222,13 @@ def FreiaOffspecWorkflow( ``incident_beam_unassigned``. wavelength_from: Wavelength lookup table mode: 'analytical', 'simulation', or 'file'. + inversion: + Enable the mirror geometry described in :func:`FreiaWorkflow`. + The mirror is between the slit assemblies, after the shutters and + before the sample. Supply all positions in laboratory coordinates. + Incident angles and shutter crossing times include the reflection. + Use the actual sample position and a surface normal pointing out of + the underside. """ workflow = GenericUnwrapWorkflow( run_types=[SampleRun], @@ -210,6 +242,7 @@ def FreiaOffspecWorkflow( 'shutter_logs': conversions.shutter_log_incident_angle_graph, }[incident_beam_from] for provider in ( + mirror.direct_beam_transform, conversions.offspecular_coordinate_transformation_graph, assignment_provider, corrections.add_offspecular_coords_and_masks, @@ -219,55 +252,75 @@ def FreiaOffspecWorkflow( workflow[name] = param workflow[KeepEventTimeOffset] = incident_beam_from == 'shutter_logs' workflow[DetectorRegionOfInterest[SampleRun]] = {} + if inversion: + _insert_mirror(workflow) return workflow +def _insert_mirror(workflow: sciline.Pipeline) -> None: + for provider in mirror.providers: + workflow.insert(provider) + workflow[NeXusName[NXmirror]] = 'inversion_mirror' + + @register_workflow -def FreiaMcStasUnnormalizedWorkflow() -> sciline.Pipeline: +def FreiaMcStasUnnormalizedWorkflow(*, inversion: bool = False) -> sciline.Pipeline: """Workflow for Freia McStas data without run normalization.""" - return FreiaMcStasWorkflow(run_norm=RunNormalization.none) + return FreiaMcStasWorkflow(run_norm=RunNormalization.none, inversion=inversion) @register_workflow -def FreiaMcStasMonitorHistogramWorkflow() -> sciline.Pipeline: +def FreiaMcStasMonitorHistogramWorkflow(*, inversion: bool = False) -> sciline.Pipeline: """Workflow for Freia McStas data using histogrammed monitor normalization.""" - return FreiaMcStasWorkflow(run_norm=RunNormalization.monitor_histogram) + return FreiaMcStasWorkflow( + run_norm=RunNormalization.monitor_histogram, inversion=inversion + ) @register_workflow -def FreiaMcStasMonitorIntegratedWorkflow() -> sciline.Pipeline: +def FreiaMcStasMonitorIntegratedWorkflow( + *, inversion: bool = False +) -> sciline.Pipeline: """Workflow for Freia McStas data using integrated monitor normalization.""" - return FreiaMcStasWorkflow(run_norm=RunNormalization.monitor_integrated) + return FreiaMcStasWorkflow( + run_norm=RunNormalization.monitor_integrated, inversion=inversion + ) @register_workflow -def FreiaMcStasProtonChargeWorkflow() -> sciline.Pipeline: +def FreiaMcStasProtonChargeWorkflow(*, inversion: bool = False) -> sciline.Pipeline: """Workflow for Freia McStas data using proton charge normalization.""" - return FreiaMcStasWorkflow(run_norm=RunNormalization.proton_charge) + return FreiaMcStasWorkflow( + run_norm=RunNormalization.proton_charge, inversion=inversion + ) @register_workflow -def FreiaUnnormalizedWorkflow() -> sciline.Pipeline: +def FreiaUnnormalizedWorkflow(*, inversion: bool = False) -> sciline.Pipeline: """Workflow for Freia NeXus data without run normalization.""" - return FreiaWorkflow(run_norm=RunNormalization.none) + return FreiaWorkflow(run_norm=RunNormalization.none, inversion=inversion) @register_workflow -def FreiaMonitorHistogramWorkflow() -> sciline.Pipeline: +def FreiaMonitorHistogramWorkflow(*, inversion: bool = False) -> sciline.Pipeline: """Workflow for Freia NeXus data using histogrammed monitor normalization.""" - return FreiaWorkflow(run_norm=RunNormalization.monitor_histogram) + return FreiaWorkflow( + run_norm=RunNormalization.monitor_histogram, inversion=inversion + ) @register_workflow -def FreiaMonitorIntegratedWorkflow() -> sciline.Pipeline: +def FreiaMonitorIntegratedWorkflow(*, inversion: bool = False) -> sciline.Pipeline: """Workflow for Freia NeXus data using integrated monitor normalization.""" - return FreiaWorkflow(run_norm=RunNormalization.monitor_integrated) + return FreiaWorkflow( + run_norm=RunNormalization.monitor_integrated, inversion=inversion + ) @register_workflow -def FreiaProtonChargeWorkflow() -> sciline.Pipeline: +def FreiaProtonChargeWorkflow(*, inversion: bool = False) -> sciline.Pipeline: """Workflow for Freia NeXus data using proton charge normalization.""" - return FreiaWorkflow(run_norm=RunNormalization.proton_charge) + return FreiaWorkflow(run_norm=RunNormalization.proton_charge, inversion=inversion) __all__ = [ diff --git a/packages/essreflectometry/tests/freia/mcstas_test.py b/packages/essreflectometry/tests/freia/mcstas_test.py index 19dd4cb0a..0a17ad357 100644 --- a/packages/essreflectometry/tests/freia/mcstas_test.py +++ b/packages/essreflectometry/tests/freia/mcstas_test.py @@ -15,6 +15,7 @@ from ess.freia.types import ( DetectorRegionOfInterest, NormalizationMonitor, + SampleSurfaceNormal, WavelengthMonitor, ) from ess.reflectometry.types import CorrectedDetector, SampleRun, WavelengthBins @@ -85,6 +86,31 @@ def test_load_histogram_geometry(tmp_path: Path): ) +def test_inversion_uses_underside_of_tilted_mcstas_sample(tmp_path: Path): + filename = tmp_path / 'geometry.h5' + angle = np.deg2rad(10.0) + with h5py.File(filename, 'w') as f: + entry = f.create_group('entry1') + entry.create_group('data') + simulation = entry.create_group('simulation') + simulation.attrs['program'] = np.bytes_('3.7.18, git') + simulation.create_group('Param') + components = entry.create_group('instrument/components') + sample = _component(components, 'Arm_Sample', [0.0, 0.0, 22.0]) + sample['Rotation'][...] = [ + [1.0, 0.0, 0.0], + [0.0, np.cos(angle), -np.sin(angle)], + [0.0, np.sin(angle), np.cos(angle)], + ] + for inversion, sign in [(False, 1), (True, -1)]: + wf = FreiaMcStasWorkflow(inversion=inversion) + wf[Filename[SampleRun]] = filename + assert_allclose( + wf.compute(SampleSurfaceNormal[SampleRun]), + sign * sc.vector([0.0, np.cos(angle), -np.sin(angle)]), + ) + + @pytest.mark.parametrize( 'filename', [freia_mcstas_sample_run, freia_mcstas_reference_run] ) diff --git a/packages/essreflectometry/tests/freia/mirror_test.py b/packages/essreflectometry/tests/freia/mirror_test.py new file mode 100644 index 000000000..18b9a7cb3 --- /dev/null +++ b/packages/essreflectometry/tests/freia/mirror_test.py @@ -0,0 +1,417 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026 Scipp contributors (https://github.com/scipp) +import h5py +import numpy as np +import pytest +import sciline +import scipp as sc +import scippnexus as snx +from ess.reduce.nexus.types import ( + EmptyDetector, + Filename, + GravityVector, + NeXusName, + Position, + RawDetector, + TimeInterval, +) +from ess.reduce.unwrap.types import DetectorLtotal, ErrorLimitedLookupTable +from scipp.testing import assert_allclose, assert_identical + +from ess import freia +from ess.freia import conversions +from ess.freia.mirror import ( + DIRECT_BEAM, + mirror_reflection_transform, + transform_position, + unfold_path, +) +from ess.freia.types import ( + DetectorRegionOfInterest, + DownstreamSlitCenters, + IncidentBeamTransform, + MirrorNormal, + MirrorPosition, + SampleSurfaceNormal, + ShutterPositions, + ShutterStatusLogs, + UpstreamSlitCenters, +) +from ess.reflectometry.types import ( + CoordTransformationGraph, + CorrectedDetector, + QBins, + ReducibleData, + ReferenceRun, + ReflectivityOverQ, + RunType, + Sample, + SampleRun, + WavelengthDetector, +) + + +def _set_mirror(workflow, run=SampleRun): + workflow[MirrorPosition[run]] = sc.vector([0.0, 0.0, -1.0], unit='m') + workflow[MirrorNormal[run]] = sc.vector([0.0, 2.0, 0.0]) + + +@pytest.mark.parametrize( + 'factory', + [getattr(freia, name) for name in freia.__all__ if name.endswith('Workflow')], +) +def test_all_workflow_constructors_accept_inversion(factory): + point = sc.vector([0.0, 2.0, -3.0], unit='m') + ordinary = factory() + assert_identical( + transform_position(ordinary.compute(IncidentBeamTransform[SampleRun]), point), + point, + ) + inverted = factory(inversion=True) + _set_mirror(inverted) + assert_identical( + transform_position(inverted.compute(IncidentBeamTransform[SampleRun]), point), + sc.vector([0.0, -2.0, -3.0], unit='m'), + ) + + +def test_tilted_translated_mirror_is_an_involution_and_preserves_plane(): + position = sc.vector([100.0, 200.0, -300.0], unit='mm') + normal = sc.vector([1.0, 2.0, 3.0]) + transform = mirror_reflection_transform(position, normal) + point = sc.vector([1.0, 2.0, 3.0], unit='m') + reflected = transform_position(transform, point) + assert_allclose(transform_position(transform, reflected), point) + assert_allclose(transform_position(transform, position), position) + assert_allclose( + sc.dot(reflected - position.to(unit='m'), normal), + -sc.dot(point - position.to(unit='m'), normal), + ) + assert_allclose(transform, mirror_reflection_transform(position, -normal)) + + +@pytest.mark.parametrize('normal', [[0, 0, 0], [0, np.nan, 0], [0, np.inf, 0]]) +def test_invalid_mirror_normal_is_rejected(normal): + with pytest.raises(ValueError, match='MirrorNormal'): + mirror_reflection_transform( + sc.vector([0.0, 0.0, 0.0], unit='m'), sc.vector(normal) + ) + + +@pytest.mark.parametrize('scale', [1e-200, 1e200]) +def test_mirror_normal_magnitude_does_not_affect_reflection(scale): + point = sc.vector([0.0, 0.0, -1.0], unit='m') + normal = sc.vector([0.0, 1.0, 0.01]) + assert_allclose( + mirror_reflection_transform(point, scale * normal), + mirror_reflection_transform(point, normal), + ) + + +@pytest.mark.parametrize('side', [-1, 1]) +def test_unfold_path_supports_either_mirror_side_and_mixed_units(side): + transform = mirror_reflection_transform( + sc.vector([0.0, 0.0, -1.0], unit='m'), sc.vector([0.0, 1.0, 0.0]) + ) + assert_allclose( + unfold_path( + transform, + sc.vector([0.0, side * 2000.0, -3000.0], unit='mm'), + sc.vector([0.0, side * 0.5, -0.5], unit='m'), + ), + sc.vector([0.0, -side * 2000.0, -3000.0], unit='mm'), + ) + + +def test_ordinary_path_preserves_positions_exactly(): + position = sc.vector([0.0, 1234.56789, -3456.78912], unit='mm') + assert_identical( + unfold_path(DIRECT_BEAM, position, sc.vector([0.0, 0.0, 0.0], unit='m')), + position, + ) + + +def test_custom_conversion_pipeline_has_default_beam_transform(): + wf = sciline.Pipeline(conversions.providers, constraints={RunType: [SampleRun]}) + wf[Position[snx.NXsource, SampleRun]] = sc.vector([0.0, 0.0, -2.0], unit='m') + wf[Position[snx.NXsample, SampleRun]] = sc.vector([0.0, 0.0, 0.0], unit='m') + wf[SampleSurfaceNormal[SampleRun]] = sc.vector([0.0, 1.0, 0.0]) + wf[GravityVector] = sc.vector([0.0, -9.80665, 0.0], unit='m/s^2') + graph = wf.compute(CoordTransformationGraph[SampleRun]) + result = sc.DataArray(sc.scalar(0.0)).transform_coords('L1', graph=graph) + assert_allclose(result.coords['L1'], sc.scalar(2.0, unit='m')) + + +def _write_mirror(path, *, name='inversion_mirror', angles=(80.0,)): + with h5py.File(path, 'w') as f: + entry = f.create_group('entry') + entry.attrs['NX_class'] = 'NXentry' + instrument = entry.create_group('instrument') + instrument.attrs['NX_class'] = 'NXinstrument' + mirror = instrument.create_group(name) + mirror.attrs['NX_class'] = 'NXmirror' + mirror['depends_on'] = 'transformations/pitch' + transforms = mirror.create_group('transformations') + transforms.attrs['NX_class'] = 'NXtransformations' + z = transforms.create_dataset('distance', data=-1.0) + z.attrs.update( + transformation_type='translation', + vector=[0.0, 0.0, 1.0], + units='m', + depends_on='.', + ) + y = transforms.create_dataset('height', data=-300.0) + y.attrs.update( + transformation_type='translation', + vector=[0.0, 1.0, 0.0], + units='mm', + depends_on='distance', + ) + pitch = transforms.create_group('pitch') + pitch.attrs.update( + NX_class='NXlog', + transformation_type='rotation', + vector=[1.0, 0.0, 0.0], + depends_on='height', + ) + pitch['value'] = angles + pitch['value'].attrs['units'] = 'deg' + pitch['time'] = np.arange(len(angles), dtype=np.int64) + pitch['time'].attrs.update(units='s', start='2026-01-01T00:00:00Z') + + +@pytest.mark.parametrize('name', ['inversion_mirror', 'deflector']) +@pytest.mark.parametrize('run', [SampleRun, ReferenceRun]) +def test_nexus_mirror_loads_translation_and_local_minus_z_normal(tmp_path, name, run): + filename = tmp_path / 'mirror.nxs' + _write_mirror(filename, name=name) + wf = freia.FreiaWorkflow(inversion=True) + wf[Filename[run]] = filename + wf[NeXusName[snx.NXmirror]] = name + assert_allclose( + wf.compute(MirrorPosition[run]), sc.vector([0.0, -0.3, -1.0], unit='m') + ) + angle = np.deg2rad(80.0) + assert_allclose( + wf.compute(MirrorNormal[run]), sc.vector([0.0, np.sin(angle), -np.cos(angle)]) + ) + wf.compute(IncidentBeamTransform[run]) + + +def test_moving_mirror_requires_a_selected_pose(tmp_path): + filename = tmp_path / 'mirror.nxs' + _write_mirror(filename, angles=(80.0, 81.0)) + wf = freia.FreiaWorkflow(inversion=True) + wf[Filename[SampleRun]] = filename + with pytest.raises(ValueError, match='time-dependent'): + wf.compute(MirrorNormal[SampleRun]) + wf[TimeInterval[SampleRun]] = TimeInterval(slice(0, 1)) + assert_allclose( + wf.compute(MirrorNormal[SampleRun]), + sc.vector([0.0, np.sin(np.deg2rad(80)), -np.cos(np.deg2rad(80))]), + ) + + +def test_missing_mirror_fails_with_manual_geometry_instructions(tmp_path): + filename = tmp_path / 'mirror.nxs' + _write_mirror(filename, name='another_mirror') + wf = freia.FreiaWorkflow(inversion=True) + wf[Filename[SampleRun]] = filename + with pytest.raises(ValueError, match='supply MirrorPosition and MirrorNormal'): + wf.compute(IncidentBeamTransform[SampleRun]) + _set_mirror(wf) + wf.compute(IncidentBeamTransform[SampleRun]) + + +def _set_run(workflow, run, *, direct=False, supply_wavelength=True): + _set_mirror(workflow, run) + workflow[GravityVector] = sc.vector([0.0, 0.0, 0.0], unit='m/s^2') + workflow[Position[snx.NXsource, run]] = sc.vector([0.0, 3.0, -4.0], unit='m') + workflow[Position[snx.NXsample, run]] = sc.vector([0.0, 1.0, 0.0], unit='m') + workflow[SampleSurfaceNormal[run]] = sc.vector([0.0, -1.0, 0.0]) + workflow[DetectorRegionOfInterest[run]] = {} + # Incoming downward 45-degree ray reflects at (0,0,-1), hits (0,1,0), + # and reflects down onto the detector. The direct beam continues upwards. + data = sc.DataArray( + sc.array( + dims=['event'], + values=[100.0 if direct else 20.0], + variances=[100.0 if direct else 20.0], + unit='counts', + ), + coords={ + 'wavelength': sc.array(dims=['event'], values=[4.0], unit='angstrom'), + 'pixel_id': sc.array(dims=['event'], values=[0], unit=None), + }, + ).group('pixel_id') + data.coords['position'] = sc.vectors( + dims=['pixel_id'], values=[[0.0, 2.0 if direct else 0.0, 1.0]], unit='m' + ) + if supply_wavelength: + workflow[WavelengthDetector[run]] = data + workflow[EmptyDetector[run]] = data.bins.sum() + return data + + +@pytest.mark.parametrize('run', [SampleRun, ReferenceRun]) +def test_detector_flight_path_includes_mirror_detour(run): + wf = freia.FreiaWorkflow(inversion=True) + _set_run(wf, run, direct=run == ReferenceRun, supply_wavelength=False) + assert_allclose( + wf.compute(DetectorLtotal[run]), + sc.array(dims=['pixel_id'], values=[5 * np.sqrt(2)], unit='m'), + ) + # The angular graph must use the same unfolded incident path. + graph = wf.compute(CoordTransformationGraph[run]) + result = sc.DataArray(sc.scalar(0.0)).transform_coords('L1', graph=graph) + assert_allclose(result.coords['L1'], sc.scalar(4 * np.sqrt(2), unit='m')) + + +def test_mirror_before_sample_rejects_source_on_opposite_side_of_plane(): + wf = freia.FreiaWorkflow(inversion=True) + _set_run(wf, SampleRun, supply_wavelength=False) + wf[Position[snx.NXsource, SampleRun]] = sc.vector([0.0, -3.0, -4.0], unit='m') + with pytest.raises(ValueError, match='same side of the mirror plane'): + wf.compute(DetectorLtotal[SampleRun]) + graph = wf.compute(CoordTransformationGraph[SampleRun]) + with pytest.raises(ValueError, match='same side of the mirror plane'): + sc.DataArray(sc.scalar(0.0)).transform_coords('L1', graph=graph) + + +def test_slits_on_opposite_sides_of_mirror_plane_are_rejected(): + wf = freia.FreiaOffspecWorkflow(inversion=True, incident_beam_from='fixed_slits') + _set_run(wf, SampleRun) + wf[UpstreamSlitCenters[SampleRun]] = { + 'beam': sc.vector([0.0, -2.0, -3.0], unit='m') + } + wf[DownstreamSlitCenters[SampleRun]] = { + 'beam': sc.vector([0.0, 0.5, -0.5], unit='m') + } + with pytest.raises(ValueError, match='same side of the mirror plane'): + wf.compute(CorrectedDetector[SampleRun]) + + +def test_wavelength_reconstruction_uses_reflected_flight_path(): + wf = freia.FreiaWorkflow(inversion=True) + data = _set_run(wf, SampleRun, supply_wavelength=False) + wavelength = sc.scalar(4.0, unit='angstrom') + # Independent sum of the three physical segments: 3 sqrt(2), sqrt(2), sqrt(2). + distance = sc.scalar(5 * np.sqrt(2), unit='m') + arrival = (distance * sc.constants.m_n * wavelength / sc.constants.h).to(unit='s') + wf[RawDetector[SampleRun]] = data.bins.drop_coords('wavelength').bins.assign_coords( + event_time_offset=sc.bins_like(data, arrival) + ) + distances = sc.linspace('distance', 5.0, 10.0, 2, unit='m') + times = sc.linspace('event_time_offset', 0.0, 0.01, 2, unit='s') + # Ideal instantaneous source, with no choppers or frame overlap. + wf[ErrorLimitedLookupTable[SampleRun, snx.NXdetector]] = ErrorLimitedLookupTable( + array=sc.DataArray( + (sc.constants.h / sc.constants.m_n / distances * times).to(unit='angstrom'), + coords={'distance': distances, 'event_time_offset': times}, + ), + pulse_period=sc.scalar(1 / 14, unit='s'), + pulse_stride=1, + distance_resolution=sc.scalar(5.0, unit='m'), + time_resolution=sc.scalar(0.01, unit='s'), + ) + result = wf.compute(WavelengthDetector[SampleRun]) + assert_allclose( + result.bins.coords['wavelength'].bins.constituents['data'].squeeze(), wavelength + ) + assert_allclose(result.coords['Ltotal'].squeeze(), distance) + + +def test_inverted_specular_sample_and_direct_beam_normalization(): + wf = freia.FreiaUnnormalizedWorkflow(inversion=True) + for run in (SampleRun, ReferenceRun): + _set_run(wf, run, direct=run == ReferenceRun) + wf[QBins] = sc.array(dims=['Q'], values=[2.0, 2.5], unit='1/angstrom') + wf[Sample] = wf[ReducibleData[SampleRun]] # Skip footprint correction. + result = wf.compute(ReflectivityOverQ) + assert_allclose(result.data, sc.array(dims=['Q'], values=[0.2], variances=[0.0024])) + sample = wf.compute(CorrectedDetector[SampleRun]) + assert_allclose( + sample.bins.coords['theta'].bins.constituents['data'], + sc.array(dims=['event'], values=[np.pi / 4], unit='rad'), + ) + assert_allclose( + sample.bins.coords['scattering_angle'].bins.constituents['data'], + sc.array(dims=['event'], values=[-np.pi / 4], unit='rad'), + ) + + +@pytest.mark.parametrize('method', ['closest', 'fixed_slits', 'shutter_logs']) +def test_offspecular_inversion_reflects_slit_angles_and_shutter_paths(method): + wf = freia.FreiaOffspecWorkflow(inversion=True, incident_beam_from=method) + data = _set_run(wf, SampleRun) + wf[UpstreamSlitCenters[SampleRun]] = {'beam': sc.vector([0.0, 2.0, -3.0], unit='m')} + wf[DownstreamSlitCenters[SampleRun]] = { + 'beam': sc.vector([0.0, 0.5, -0.5], unit='m') + } + if method == 'shutter_logs': + # Shutter -> mirror -> sample -> detector is 4 sqrt(2) m. Place a + # closing edge between that arrival time and the incorrect direct path. + wf[ShutterPositions[SampleRun]] = { + 'beam': sc.vector([0.0, 2.0, -3.0], unit='m') + } + speed = ( + (sc.constants.h / sc.constants.m_n / sc.scalar(4.0, unit='angstrom')) + .to(unit='m/s') + .value + ) + arrival = 4 * np.sqrt(2) / speed + constituents = data.bins.constituents + content = constituents['data'] + content.coords['event_time_zero'] = sc.datetimes( + dims=['event'], values=['2026-01-01T00:00:00'], unit='ns' + ) + content.coords['event_time_offset'] = sc.array( + dims=['event'], values=[arrival], unit='s' + ) + data = sc.DataArray(sc.bins(**constituents), coords=data.coords) + wf[ShutterStatusLogs[SampleRun]] = { + 'beam': sc.DataArray( + sc.array(dims=['time'], values=[True, False]), + coords={ + 'time': sc.datetimes( + dims=['time'], + values=['2026-01-01T00:00:00', '2026-01-01T00:00:00.0005'], + unit='ns', + ) + }, + ) + } + wf[WavelengthDetector[SampleRun]] = data + result = wf.compute(CorrectedDetector[SampleRun]) + angles = result.coords.get( + 'incident_angle', result.bins.coords.get('incident_angle') + ) + if angles.bins is not None: + angles = angles.bins.constituents['data'].squeeze() + assert_allclose(angles, sc.scalar(np.pi / 4, unit='rad')) + assert_allclose( + result.bins.coords['Qx'].bins.constituents['data'], + sc.array(dims=['event'], values=[0.0], unit='1/angstrom'), + atol=sc.scalar(1e-15, unit='1/angstrom'), + ) + assert_allclose( + result.bins.coords['Qz'].bins.constituents['data'], + sc.array(dims=['event'], values=[np.pi / np.sqrt(2)], unit='1/angstrom'), + ) + assert result.sum().value == 20.0 + + +def test_gravity_and_physical_positions_remain_in_laboratory_frame(): + wf = freia.FreiaWorkflow(inversion=True) + _set_run(wf, SampleRun) + gravity = sc.vector([0.0, -9.80665, 0.0], unit='m/s^2') + wf[GravityVector] = gravity + graph = wf.compute(CoordTransformationGraph[SampleRun]) + assert_identical(graph['gravity'](), gravity) + assert_identical( + graph['sample_position'](), wf.compute(Position[snx.NXsample, SampleRun]) + ) + assert_identical( + wf.compute(Position[snx.NXsource, SampleRun]), + sc.vector([0.0, 3.0, -4.0], unit='m'), + ) From d192e74d1a4174fb473cf85290481d2ea4061524 Mon Sep 17 00:00:00 2001 From: Johannes Kasimir Date: Wed, 4 Nov 2026 08:18:07 +0100 Subject: [PATCH 2/7] feat: gravity correct incident beam --- .../src/ess/freia/conversions.py | 335 +++++++++++++---- .../src/ess/freia/corrections.py | 2 +- .../essreflectometry/src/ess/freia/mirror.py | 62 ++-- .../essreflectometry/src/ess/freia/types.py | 9 +- .../src/ess/freia/workflow.py | 24 +- .../tests/freia/conversions_test.py | 74 +++- .../tests/freia/incident_gravity_test.py | 346 ++++++++++++++++++ .../tests/freia/mirror_test.py | 12 +- .../tests/freia/workflow_test.py | 30 +- 9 files changed, 764 insertions(+), 130 deletions(-) create mode 100644 packages/essreflectometry/tests/freia/incident_gravity_test.py diff --git a/packages/essreflectometry/src/ess/freia/conversions.py b/packages/essreflectometry/src/ess/freia/conversions.py index 36069a860..a6bbb2891 100644 --- a/packages/essreflectometry/src/ess/freia/conversions.py +++ b/packages/essreflectometry/src/ess/freia/conversions.py @@ -2,6 +2,7 @@ # Copyright (c) 2026 Scipp contributors (https://github.com/scipp) import scipp as sc from ess.reduce.nexus.types import GravityVector, Position +from scipp.constants import h, m_n from scippneutron.conversion import graph, tof from scippnexus import NXsample, NXsource @@ -15,7 +16,7 @@ RunType, SampleRun, ) -from .mirror import DIRECT_BEAM, direct_beam_transform, unfold_path +from .mirror import DIRECT_BEAM, direct_beam_transform, reflected_upstream_position from .types import ( DownstreamSlitCenters, IncidentAngleGraph, @@ -63,6 +64,8 @@ def time_at_shutter( Sample position in global coordinates. shutter_position: Fixed shutter position in the same global frame as the sample. + In inversion mode, use its reflection across the mirror plane so the + distance to the sample includes the path through the mirror. Returns ------- @@ -103,28 +106,34 @@ def assign_incident_angle_from_shutter_logs( sample_position: sc.Variable, *, incident_angles: dict[str, sc.Variable], + incident_gravity_lengths: dict[str, sc.Variable], shutter_positions: dict[str, sc.Variable], shutter_status_logs: dict[str, sc.DataArray], -) -> sc.Variable: - """Assign incidence when all shutter states are known and exactly one is open. +) -> dict[str, sc.Variable]: + """Assign nominal angle and gravity length when exactly one known shutter is open. Each beam's log is evaluated at the neutron's crossing time at that beam's shutter. Process shutters sequentially, discarding each crossing-time array - after looking up its status. Keys in all three dictionaries must match. + after looking up its status. Keys in all dictionaries must match. An unknown state, no open shutter, or multiple open shutters yields NaN. """ if not ( - shutter_positions.keys() == incident_angles.keys() == shutter_status_logs.keys() + shutter_positions.keys() + == incident_angles.keys() + == incident_gravity_lengths.keys() + == shutter_status_logs.keys() ): raise ValueError( - 'Shutter positions, incident angles and logs must have the same keys.' + 'Incident angles, gravity lengths, shutter positions and logs ' + 'must have the same keys.' ) detector_time = time_at_detector(event_time_zero, event_time_offset) - unassigned_incident_angle = sc.scalar(float('nan'), unit='rad') - assigned_incident_angle = unassigned_incident_angle + unassigned_angle = sc.scalar(float('nan'), unit='rad') + unassigned_length = sc.scalar(float('nan'), unit='m') + assigned_angle, assigned_length = unassigned_angle, unassigned_length open_shutter_count = sc.scalar(0.0, dtype='float32', unit=None) - for beam_name, beam_incident_angle in incident_angles.items(): + for beam_name, angle in incident_angles.items(): shutter_log = shutter_status_logs[beam_name] shutter_state = _shutter_state_at_time( time_at_shutter( @@ -137,21 +146,24 @@ def assign_incident_angle_from_shutter_logs( shutter_log, ) shutter_is_open = shutter_state == sc.scalar(1.0, unit=shutter_log.unit) - assigned_incident_angle = sc.where( + assigned_angle = sc.where(shutter_is_open, angle.to(unit='rad'), assigned_angle) + assigned_length = sc.where( shutter_is_open, - beam_incident_angle.to(unit='rad', dtype='float64'), - assigned_incident_angle, + incident_gravity_lengths[beam_name].to(unit='m'), + assigned_length, ) # Unknown states propagate NaN, so they cannot yield exactly one open shutter. open_shutter_count = open_shutter_count + shutter_state # Release per-shutter temporaries before calculating the next crossing time. del shutter_state, shutter_is_open - return sc.where( - open_shutter_count == sc.scalar(1.0, unit=None), - assigned_incident_angle, - unassigned_incident_angle, - ) + assigned = open_shutter_count == sc.scalar(1.0, unit=None) + return { + 'nominal_incident_angle': sc.where(assigned, assigned_angle, unassigned_angle), + 'incident_gravity_length': sc.where( + assigned, assigned_length, unassigned_length + ), + } def outgoing_direction( @@ -201,7 +213,8 @@ def incident_beam_directions( The two inputs map the names of open channels to their centers in the upstream and downstream slit assemblies. Matching keys describe one possible incident beam. In inversion mode the mirror is between the - assemblies, so only the upstream slit is mapped to its virtual position. + assemblies, so the upstream slit position is reflected across the mirror + plane before computing the direction towards the downstream slit. """ if upstream_slit_centers.keys() != downstream_slit_centers.keys(): raise ValueError( @@ -210,29 +223,44 @@ def incident_beam_directions( directions = {} for key, upstream in upstream_slit_centers.items(): downstream = downstream_slit_centers[key] - virtual_upstream = unfold_path(beam_transform, upstream, downstream) - beam = downstream - virtual_upstream.to(unit=downstream.unit) - directions[key] = beam / sc.norm(beam) + reflected_upstream = reflected_upstream_position( + beam_transform, upstream, downstream + ) + beam = downstream - reflected_upstream.to(unit=downstream.unit) + length = sc.norm(beam) + if not sc.isfinite(length).value or length.value == 0: + raise ValueError('Slit centres must define a finite, nonzero flight path.') + directions[key] = beam / length return directions def assign_incident_angle( reflection_angle: sc.Variable, expected_reflection_angles: dict[str, sc.Variable], -) -> sc.Variable: - """Assign incidence using the closest expected specular reflection angle.""" - angles = iter(expected_reflection_angles.values()) - closest = next(angles) - if len(expected_reflection_angles) == 1: - return closest + incident_gravity_lengths: dict[str, sc.Variable], +) -> dict[str, sc.Variable]: + """Select the nominal incident angle closest to the geometrical reflection angle. - min_distance = sc.abs(reflection_angle - closest) - for angle in angles: - distance = sc.abs(reflection_angle - angle) - is_closer = distance < min_distance - closest = sc.where(is_closer, angle, closest) - min_distance = sc.where(is_closer, distance, min_distance) - return closest + ``reflection_angle`` is measured from the sample-to-pixel direction, without + gravity correction. Return ``nominal_incident_angle`` and the corresponding + ``incident_gravity_length`` together, for the subsequent gravity correction. + """ + if expected_reflection_angles.keys() != incident_gravity_lengths.keys(): + raise ValueError('Incident angles and gravity lengths must have the same keys.') + names = iter(expected_reflection_angles) + first = next(names) + closest = expected_reflection_angles[first] + length = incident_gravity_lengths[first] + if len(expected_reflection_angles) > 1: + min_distance = sc.abs(reflection_angle - closest) + for name in names: + angle = expected_reflection_angles[name] + distance = sc.abs(reflection_angle - angle) + is_closer = distance < min_distance + closest = sc.where(is_closer, angle, closest) + length = sc.where(is_closer, incident_gravity_lengths[name], length) + min_distance = sc.where(is_closer, distance, min_distance) + return {'nominal_incident_angle': closest, 'incident_gravity_length': length} def incident_angle( @@ -244,6 +272,118 @@ def incident_angle( return sc.asin(-sc.dot(incident_direction, normal)) +def _incident_angle_and_gravity_length( + upstream: sc.Variable, + downstream: sc.Variable, + normal: sc.Variable, + transform: sc.Variable, + sample_position: sc.Variable, + gravity: sc.Variable, +) -> tuple[sc.Variable, sc.Variable]: + r"""Compute the nominal incident angle and signed effective gravity length. + + Assumes FREIA's layout: distinct slits, the inversion mirror strictly + between them, and the sample downstream. The transform comes from the + direct-beam or mirror provider. Sample normal and gravity have arbitrary + orientations. Geometry is evaluated once per candidate. + + Returns + ------- + : + Scalar nominal angle in radians and signed effective length in metres. + + Notes + ----- + Let :math:`L` be the flight length between the slits, :math:`a` the length + from upstream slit to mirror, and :math:`c` from downstream slit to sample. + With mirror reflection matrix :math:`R`, gravity :math:`g`, nominal unit + direction :math:`u`, incident angle :math:`\alpha_0`, and unit sample normal + :math:`n`, the effective length is + + .. math:: + + K = g(c+L/2) + (Rg-g)\frac{a^2}{2L}, \qquad + D = -\frac{n \cdot [K-u(u \cdot K)]}{|g|\cos\alpha_0}. + + Without the mirror, the second term in :math:`K` is zero. The correction + using :math:`D` is applied by :func:`gravity_corrected_incident_angle`. + """ + upstream, downstream, sample_position = ( + position.to(unit='m') for position in (upstream, downstream, sample_position) + ) + transform = transform.to(unit='m') + reflected_upstream = reflected_upstream_position(transform, upstream, downstream) + beam = downstream - reflected_upstream + length, g = sc.norm(beam), sc.norm(gravity) + direction, normal = beam / length, normal / sc.norm(normal) + angle = incident_angle(direction, normal) + if g.value == 0: + return angle, sc.scalar(0.0, unit='m') + + normal_component = sc.dot(direction, normal) + transverse_normal = normal - direction * normal_component + cosine = sc.norm(sc.cross(normal, direction)) + c = sc.dot(sample_position - downstream, normal) / normal_component + gravity_direction = gravity / g + k = gravity_direction * (c + length / 2) + if not sc.identical(transform, DIRECT_BEAM): + # The mirror bisects the slit and its image. Rg-g = -2 n (n dot g). + displacement = upstream - reflected_upstream + separation = sc.norm(displacement) + mirror_normal = displacement / separation + a = separation / (2 * sc.dot(direction, mirror_normal)) + k -= mirror_normal * sc.dot(gravity_direction, mirror_normal) * a**2 / length + return angle, -sc.dot(k, transverse_normal) / cosine + + +def gravity_corrected_incident_angle( + nominal_incident_angle: sc.Variable, + incident_gravity_length: sc.Variable, + wavelength: sc.Variable, + gravity: sc.Variable, +) -> sc.Variable: + r"""Correct the selected incident angle for gravity at each event's wavelength. + + Parameters + ---------- + nominal_incident_angle: + Incident angle determined from slit geometry, before gravity correction. + incident_gravity_length: + Signed effective length for the selected beam, accounting for slit + positions, the sample plane, and the mirror when present. + wavelength: + Reconstructed neutron wavelengths. + gravity: + Gravitational acceleration vector in laboratory coordinates. + A zero vector disables the correction. + + Returns + ------- + : + Incident angle at the sample, in radians. + + Notes + ----- + With nominal angle :math:`\alpha_0` and effective length :math:`D`, the + first-order correction is + + .. math:: + + \alpha(\lambda) = \alpha_0 + |g|D\left(\frac{m_n\lambda}{h}\right)^2. + """ + g = sc.norm(gravity) + if g.value == 0: + return nominal_incident_angle + factor = g * (m_n / h) ** 2 + correction = ( + factor + * incident_gravity_length + * wavelength.to(dtype='float64', copy=False) ** 2 + ).to(unit='dimensionless') + correction.unit = 'rad' + return nominal_incident_angle + correction + + def coordinate_transformation_graph( source_position: Position[NXsource, RunType], sample_position: Position[NXsample, RunType], @@ -263,7 +403,7 @@ def coordinate_transformation_graph( **graph.beamline.L2(), 'outgoing_direction': outgoing_direction, 'scattering_angle': scattering_angle, - 'source_position': lambda: unfold_path( + 'source_position': lambda: reflected_upstream_position( beam_transform, source_position, sample_position ), 'sample_position': lambda: sample_position, @@ -285,54 +425,101 @@ def sample_coordinate_transformation_graph( ) | {'theta': theta, 'Q': reflectometry_q} -def _incident_angles_from_slits( - upstream_slit_centers, - downstream_slit_centers, - sample_surface_normal, - beam_transform, -): - return { - beam_name: incident_angle(direction, sample_surface_normal) - for beam_name, direction in incident_beam_directions( - upstream_slit_centers, downstream_slit_centers, beam_transform - ).items() - } +def _incident_angle_parameters( + upstream_slit_centers: dict[str, sc.Variable], + downstream_slit_centers: dict[str, sc.Variable], + sample_surface_normal: sc.Variable, + beam_transform: sc.Variable, + sample_position: sc.Variable, + gravity: sc.Variable, +) -> tuple[dict[str, sc.Variable], dict[str, sc.Variable]]: + """Compute a nominal angle and signed effective length for each slit pair.""" + if upstream_slit_centers.keys() != downstream_slit_centers.keys(): + raise ValueError( + 'UpstreamSlitCenters and DownstreamSlitCenters must have the same keys.' + ) + if not upstream_slit_centers: + raise ValueError('At least one incident beam is required.') + angles, lengths = {}, {} + for name, upstream in upstream_slit_centers.items(): + angles[name], lengths[name] = _incident_angle_and_gravity_length( + upstream, + downstream_slit_centers[name], + sample_surface_normal, + beam_transform, + sample_position, + gravity, + ) + return angles, lengths def fixed_slits_incident_angle_graph( upstream_slit_centers: UpstreamSlitCenters[RunType], downstream_slit_centers: DownstreamSlitCenters[RunType], sample_surface_normal: SampleSurfaceNormal[RunType], + sample_position: Position[NXsample, RunType], + gravity: GravityVector, beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> IncidentAngleGraph[RunType]: - """Provide a constant incident angle from a single pair of fixed slit openings.""" - (beam_incident_angle,) = _incident_angles_from_slits( + """Use one slit pair's nominal angle and effective length, then apply gravity.""" + angles, lengths = _incident_angle_parameters( upstream_slit_centers, downstream_slit_centers, sample_surface_normal, beam_transform, - ).values() - return {'incident_angle': lambda: beam_incident_angle} + sample_position, + gravity, + ) + (angle,), (length,) = angles.values(), lengths.values() + return { + 'nominal_incident_angle': lambda: angle, + 'incident_gravity_length': lambda: length, + 'incident_angle': gravity_corrected_incident_angle, + } def closest_beam_incident_angle_graph( upstream_slit_centers: UpstreamSlitCenters[RunType], downstream_slit_centers: DownstreamSlitCenters[RunType], sample_surface_normal: SampleSurfaceNormal[RunType], + sample_position: Position[NXsample, RunType], + gravity: GravityVector, beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> IncidentAngleGraph[RunType]: - """Provide incidence assignment using the closest expected reflection angle.""" - beam_incident_angles = _incident_angles_from_slits( + """Select the closest nominal angle using detector geometry, then apply gravity. + + Compare the sample-to-pixel angle with each candidate's nominal incident + angle, without gravity correction. Select its effective length along with + the angle for the subsequent wavelength-dependent correction. + """ + if len(upstream_slit_centers) == 1: + return fixed_slits_incident_angle_graph( + upstream_slit_centers, + downstream_slit_centers, + sample_surface_normal, + sample_position, + gravity, + beam_transform, + ) + angles, lengths = _incident_angle_parameters( upstream_slit_centers, downstream_slit_centers, sample_surface_normal, beam_transform, + sample_position, + gravity, ) - def select_incident_angle(reflection_angle: sc.Variable) -> sc.Variable: - return assign_incident_angle(reflection_angle, beam_incident_angles) + def select_incident_angle(geometric_reflection_angle: sc.Variable): + return assign_incident_angle(geometric_reflection_angle, angles, lengths) - return {'incident_angle': select_incident_angle} + return { + 'geometric_reflection_angle': lambda scattered_beam: theta( + scattered_beam / sc.norm(scattered_beam), sample_surface_normal + ), + ('nominal_incident_angle', 'incident_gravity_length'): select_incident_angle, + 'incident_angle': gravity_corrected_incident_angle, + } def shutter_log_incident_angle_graph( @@ -341,27 +528,28 @@ def shutter_log_incident_angle_graph( sample_surface_normal: SampleSurfaceNormal[RunType], shutter_positions: ShutterPositions[RunType], shutter_status_logs: ShutterStatusLogs[RunType], + sample_position: Position[NXsample, RunType], + gravity: GravityVector, beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, ) -> IncidentAngleGraph[RunType]: - """Identify candidate beams using each shutter's position and status log.""" - beam_incident_angles = _incident_angles_from_slits( + """Assign nominal angle and length from shutter logs, then apply gravity.""" + angles, lengths = _incident_angle_parameters( upstream_slit_centers, downstream_slit_centers, sample_surface_normal, beam_transform, + sample_position, + gravity, ) - - if not beam_incident_angles: - raise ValueError('At least one incident beam is required.') - if not ( - beam_incident_angles.keys() - == shutter_positions.keys() - == shutter_status_logs.keys() - ): + if not (angles.keys() == shutter_positions.keys() == shutter_status_logs.keys()): raise ValueError( 'Slit centers, ShutterPositions and ShutterStatusLogs ' 'must have the same keys.' ) + reflected_shutter_positions = { + key: reflected_upstream_position(beam_transform, position, sample_position) + for key, position in shutter_positions.items() + } def select_incident_angle( event_time_zero: sc.Variable, @@ -369,22 +557,23 @@ def select_incident_angle( wavelength: sc.Variable, L2: sc.Variable, sample_position: sc.Variable, - ) -> sc.Variable: + ): return assign_incident_angle_from_shutter_logs( event_time_zero, event_time_offset, wavelength, L2, sample_position, - incident_angles=beam_incident_angles, - shutter_positions={ - key: unfold_path(beam_transform, position, sample_position) - for key, position in shutter_positions.items() - }, + incident_angles=angles, + incident_gravity_lengths=lengths, + shutter_positions=reflected_shutter_positions, shutter_status_logs=shutter_status_logs, ) - return {'incident_angle': select_incident_angle} + return { + ('nominal_incident_angle', 'incident_gravity_length'): select_incident_angle, + 'incident_angle': gravity_corrected_incident_angle, + } def offspecular_coordinate_transformation_graph( diff --git a/packages/essreflectometry/src/ess/freia/corrections.py b/packages/essreflectometry/src/ess/freia/corrections.py index 53ead2bc4..427d3a33b 100644 --- a/packages/essreflectometry/src/ess/freia/corrections.py +++ b/packages/essreflectometry/src/ess/freia/corrections.py @@ -66,7 +66,7 @@ def add_offspecular_coords_and_masks( keep_intermediate=False, ) da = add_roi_masks(da, roi) - # Fixed slits and closest-beam assignment with one candidate give scalar incidence. + # Without gravity, fixed/closest incidence can be scalar or per pixel. if 'incident_angle' in da.bins.coords: da = da.bins.assign_masks( incident_beam_unassigned=~sc.isfinite(da.bins.coords['incident_angle']) diff --git a/packages/essreflectometry/src/ess/freia/mirror.py b/packages/essreflectometry/src/ess/freia/mirror.py index bd18499fe..594c645cc 100644 --- a/packages/essreflectometry/src/ess/freia/mirror.py +++ b/packages/essreflectometry/src/ess/freia/mirror.py @@ -44,10 +44,10 @@ def load_mirror_transformation( snx.NXmirror, RunType ] = reject_time_dependent_transform, ) -> NeXusTransformation[snx.NXmirror, RunType]: - """Load a named NXmirror using the usual ESS transformation/time filtering. + """Load the mirror's transformation for the selected time interval. The component name is a provisional convention, configurable through - NeXusName[NXmirror]. No pose is inferred if the component is missing. + ``NeXusName[NXmirror]``. No pose is inferred if the component is missing. """ location = NeXusComponentLocationSpec[snx.NXmirror, RunType]( filename=file_spec.value, component_name=name @@ -89,7 +89,17 @@ def mirror_reflection_transform( position: MirrorPosition[RunType], normal: MirrorNormal[RunType], ) -> IncidentBeamTransform[RunType]: - """Unfold a planar specular reflection using p' = p - 2 n (n dot (p-m)).""" + r"""Build a transform that reflects positions across the mirror plane. + + For a point :math:`m` on the plane and its unit normal :math:`n`, the + transform maps a position :math:`p` to + + .. math:: + + p' = p - 2n\,[n \cdot (p-m)]. + + The magnitude and sign of ``normal`` do not affect the transform. + """ for name, vector in [('MirrorPosition', position), ('MirrorNormal', normal)]: if vector.ndim != 0 or vector.dtype != sc.DType.vector3: raise ValueError(f'{name} must be a scalar vector.') @@ -115,28 +125,35 @@ def transform_position(transform: sc.Variable, position: sc.Variable) -> sc.Vari return (transform * position.to(unit=transform.unit)).to(unit=position.unit) -def unfold_path( +def reflected_upstream_position( transform: sc.Variable, upstream: sc.Variable, downstream: sc.Variable ) -> sc.Variable: - """Return the virtual upstream point, checking that reflection is possible. - - A reflected ray connects points on the same side of the mirror plane. - The midpoint of a point and its image lies in that plane; their difference - points towards the physical upstream side. For the identity transform the - difference is zero, so ordinary paths pass unchanged. + """Return the upstream position reflected across the mirror plane. + + The straight segment from this position to ``downstream`` has the same + length as the path through the mirror and points along its final segment. + The returned point is used for geometry calculations; the physical + component remains in place. With ``DIRECT_BEAM``, return ``upstream`` + unchanged. The result retains the upstream position's length unit. + + Raises + ------ + ValueError + If the physical upstream and downstream points are on opposite sides + of the mirror plane, so no reflected path connects them. """ if sc.identical(transform, DIRECT_BEAM): return upstream - virtual = transform_position(transform, upstream) - midpoint = (0.5 * (upstream + virtual)).to(unit=downstream.unit) - normal = (upstream - virtual).to(unit=downstream.unit) + reflected = transform_position(transform, upstream) + midpoint = (0.5 * (upstream + reflected)).to(unit=downstream.unit) + normal = (upstream - reflected).to(unit=downstream.unit) if sc.dot(downstream - midpoint, normal).value < 0: raise ValueError( 'A reflected path requires its upstream and downstream positions ' 'to be on the same side of the mirror plane. Check the mirror pose ' 'and component positions.' ) - return virtual + return reflected def detector_ltotal_with_mirror( @@ -145,17 +162,20 @@ def detector_ltotal_with_mirror( sample_position: Position[snx.NXsample, RunType], transform: IncidentBeamTransform[RunType], ) -> DetectorLtotal[RunType]: - """Straight-segment source-mirror-sample-detector path via the virtual source. + """Compute the source-to-detector flight length through the mirror and sample. As in the ordinary workflow, this approximates the upstream guide by a - straight ray. It includes the mirror detour without moving the real source - used for chopper and upstream-monitor wavelength reconstruction. + straight ray. Reflecting the source position across the mirror plane gives + the length of the path from source through mirror to sample. Chopper and + upstream-monitor wavelength reconstruction use the physical source position. """ - virtual_source = unfold_path(transform, source_position, sample_position) - sample = sample_position.to(unit=virtual_source.unit) - pixels = detector.coords['position'].to(unit=virtual_source.unit) + reflected_source = reflected_upstream_position( + transform, source_position, sample_position + ) + sample = sample_position.to(unit=reflected_source.unit) + pixels = detector.coords['position'].to(unit=reflected_source.unit) return DetectorLtotal[RunType]( - sc.norm(sample - virtual_source) + sc.norm(pixels - sample) + sc.norm(sample - reflected_source) + sc.norm(pixels - sample) ) diff --git a/packages/essreflectometry/src/ess/freia/types.py b/packages/essreflectometry/src/ess/freia/types.py index 2f3dacc77..e00b22da9 100644 --- a/packages/essreflectometry/src/ess/freia/types.py +++ b/packages/essreflectometry/src/ess/freia/types.py @@ -43,10 +43,11 @@ class MirrorNormal(sciline.Scope[RunType, sc.Variable], sc.Variable): class IncidentBeamTransform(sciline.Scope[RunType, sc.Variable], sc.Variable): - """Map upstream positions to virtual positions after the inversion mirror. + """Reflect upstream positions across the inversion mirror's plane. - Identity in normal operation. In inversion mode this is reflection in the - mirror plane. Sample, detector, and gravity remain in the laboratory frame. + Identity when inversion is disabled. Reflected positions are used to + calculate flight lengths and the beam direction after the mirror. + Sample, detector, and gravity remain in the laboratory frame. """ @@ -74,7 +75,7 @@ class DetectorRegionOfInterest(sciline.Scope[RunType, dict], dict): class IncidentAngleGraph(sciline.Scope[RunType, dict], dict): - """Coordinate graph fragment defining how incident angles are assigned.""" + """Coordinate graph for assigning incident angles and correcting for gravity.""" class ShutterPositions(sciline.Scope[RunType, dict], dict): diff --git a/packages/essreflectometry/src/ess/freia/workflow.py b/packages/essreflectometry/src/ess/freia/workflow.py index d252f35db..45a42bab1 100644 --- a/packages/essreflectometry/src/ess/freia/workflow.py +++ b/packages/essreflectometry/src/ess/freia/workflow.py @@ -206,16 +206,26 @@ def FreiaOffspecWorkflow( The assigned ``incident_angle`` and measured ``reflection_angle`` determine ``Qx`` and ``Qz``. The output is ``CorrectedDetector[SampleRun]``. + All three modes assign a nominal angle and signed effective gravity length. + These are computed once per candidate from the slit centres, sample plane, + and (in inversion mode) mirror pose. A coordinate kernel then corrects the + assigned angle using the event's wavelength. Gravity stays in the lab frame. + Setting ``GravityVector`` to zero disables both incident and outgoing + gravity corrections. Flight lengths and shutter crossing times retain + their straight-segment approximations. + Parameters ---------- incident_beam_from: - ``'closest'`` assigns the beam whose specular reflection angle is closest - to the measured reflection angle. ``'fixed_slits'`` uses the single beam - defined by one matching pair of slit centers, independently of the - reflection angle and without shutter positions or status logs. - ``'shutter_logs'`` uses - ``ShutterStatusLogs[SampleRun]`` and ``ShutterPositions[SampleRun]`` for - all candidate beams. Each log is evaluated at the neutron's crossing + ``'closest'`` assigns the beam whose nominal specular reflection angle + is closest to the geometrical sample-to-pixel angle. This heuristic uses + no gravity correction; gravity is applied after the beam is selected. + ``'fixed_slits'`` uses the single beam defined by one matching pair of + slit centers, independently of the reflection angle and without shutter + positions or status logs. + ``'shutter_logs'`` uses ``ShutterStatusLogs[SampleRun]`` and + ``ShutterPositions[SampleRun]`` for all candidate beams. + Each log is evaluated at the neutron's crossing time at that shutter, independently of the slit positions. Exactly one open shutter, with all states known, determines the incident beam. Otherwise the incidence is NaN and the event is masked as diff --git a/packages/essreflectometry/tests/freia/conversions_test.py b/packages/essreflectometry/tests/freia/conversions_test.py index 2de964b36..f5a28e74c 100644 --- a/packages/essreflectometry/tests/freia/conversions_test.py +++ b/packages/essreflectometry/tests/freia/conversions_test.py @@ -106,15 +106,27 @@ def test_assigns_each_neutron_to_closest_expected_reflection_angle(): unit='rad' ) - assigned = assign_incident_angle(reflection_angles, incident_angles) + assigned = assign_incident_angle( + reflection_angles, + incident_angles, + { + 'bottom': sc.scalar(3.0, unit='m'), + 'top': sc.scalar(1.0, unit='m'), + 'middle': sc.scalar(2.0, unit='m'), + }, + ) + assert_allclose( + assigned['incident_gravity_length'], + sc.array(dims=['event'], values=[1.0, 2.0, 3.0], unit='m'), + ) assert_allclose( - assigned, + assigned['nominal_incident_angle'], sc.array(dims=['event'], values=[0.3, 1.0, 3.5], unit='deg').to(unit='rad'), ) -def test_fixed_slits_incidence_needs_no_event_coordinates(): +def test_fixed_slits_zero_gravity_returns_nominal_scalar_incidence(): graph = fixed_slits_incident_angle_graph( upstream_slit_centers={'beam': sc.vector([0.0, 0.0, -2.0], unit='m')}, downstream_slit_centers={ @@ -123,8 +135,16 @@ def test_fixed_slits_incidence_needs_no_event_coordinates(): sample_surface_normal=sc.vector( [0.0, np.cos(np.deg2rad(10.0)), -np.sin(np.deg2rad(10.0))] ), + sample_position=sc.vector([0.0, 0.0, 0.0], unit='m'), + gravity=sc.vector([0.0, 0.0, 0.0], unit='m/s^2'), + ) + data = sc.DataArray( + sc.ones(dims=['event'], shape=[2], unit='counts'), + coords={ + 'wavelength': sc.array(dims=['event'], values=[2.0, 10.0], unit='angstrom'), + 'gravity': sc.vector([0.0, 0.0, 0.0], unit='m/s^2'), + }, ) - data = sc.DataArray(sc.ones(dims=['event'], shape=[2], unit='counts')) result = data.transform_coords('incident_angle', graph=graph) @@ -202,19 +222,29 @@ def test_shutter_assignment_requires_exactly_one_open_shutter(): result = assign_incident_angle_from_shutter_logs( **_events(), incident_angles=angles, + incident_gravity_lengths={ + 'a': sc.scalar(1.0, unit='m'), + 'b': sc.scalar(2.0, unit='m'), + }, shutter_positions={ name: sc.vector([0.0, 0.0, 20.0], unit='m') for name in angles }, shutter_status_logs=logs, ) assert_allclose( - result, + result['nominal_incident_angle'], sc.array(dims=['event'], values=[0.3, 1.0, np.nan, np.nan], unit='deg').to( unit='rad' ), equal_nan=True, ) + assert_allclose( + result['incident_gravity_length'], + sc.array(dims=['event'], values=[1.0, 2.0, np.nan, np.nan], unit='m'), + equal_nan=True, + ) + def test_shutter_assignment_uses_crossing_time_instead_of_pulse_or_detector_time(): inputs = _events(offsets=[30, 32, 42]) @@ -223,11 +253,12 @@ def test_shutter_assignment_uses_crossing_time_instead_of_pulse_or_detector_time result = assign_incident_angle_from_shutter_logs( **inputs, incident_angles={'a': sc.scalar(1.0, unit='deg')}, + incident_gravity_lengths={'a': sc.scalar(1.0, unit='m')}, shutter_positions={'a': sc.vector([0.0, 0.0, 20.0], unit='m')}, shutter_status_logs={'a': _log([0, 21, 23], [False, True, False])}, ) assert_allclose( - result, + result['nominal_incident_angle'], sc.array(dims=['event'], values=[np.nan, 1.0, np.nan], unit='deg').to( unit='rad' ), @@ -256,11 +287,12 @@ def test_shutter_assignment_resolves_hundreds_of_microseconds_at_modern_dates(): result = assign_incident_angle_from_shutter_logs( **inputs, incident_angles={'a': sc.scalar(1.0, unit='deg')}, + incident_gravity_lengths={'a': sc.scalar(1.0, unit='m')}, shutter_positions={'a': sc.vector([0.0, 0.0, 20.0], unit='m')}, shutter_status_logs={'a': log}, ) assert_allclose( - result, + result['nominal_incident_angle'], sc.array(dims=['event'], values=[np.nan, 1.0, 1.0, np.nan], unit='deg').to( unit='rad' ), @@ -282,6 +314,10 @@ def test_unknown_shutter_status_does_not_silently_identify_another_beam( 'a': sc.scalar(0.3, unit='deg'), 'b': sc.scalar(1.0, unit='deg'), }, + incident_gravity_lengths={ + 'a': sc.scalar(1.0, unit='m'), + 'b': sc.scalar(2.0, unit='m'), + }, shutter_positions={ name: sc.vector([0.0, 0.0, 20.0], unit='m') for name in ('a', 'b') }, @@ -290,7 +326,7 @@ def test_unknown_shutter_status_does_not_silently_identify_another_beam( 'b': _log(unknown_times, unknown_states), }, ) - assert sc.all(sc.isnan(result)).value + assert sc.all(sc.isnan(result['nominal_incident_angle'])).value def test_shutter_logs_are_sampled_at_each_shutters_crossing_time(): @@ -308,12 +344,16 @@ def test_shutter_logs_are_sampled_at_each_shutters_crossing_time(): 'a': sc.scalar(0.3, unit='deg'), 'b': sc.scalar(1.0, unit='deg'), }, + incident_gravity_lengths={ + 'a': sc.scalar(1.0, unit='m'), + 'b': sc.scalar(2.0, unit='m'), + }, shutter_status_logs={ name: _log([0, 15, 25], [False, True, False]) for name in positions }, ) assert_allclose( - result, + result['nominal_incident_angle'], sc.array(dims=['event'], values=[1.0, 0.3, np.nan], unit='deg').to(unit='rad'), equal_nan=True, ) @@ -323,11 +363,13 @@ def test_final_shutter_state_persists(): result = assign_incident_angle_from_shutter_logs( **_events(offsets=[30.2, 60]), incident_angles={'a': sc.scalar(1.0, unit='deg')}, + incident_gravity_lengths={'a': sc.scalar(1.0, unit='m')}, shutter_positions={'a': sc.vector([0.0, 0.0, 20.0], unit='m')}, shutter_status_logs={'a': _log([0, 20], [False, True])}, ) assert_allclose( - result, sc.array(dims=['event'], values=[1.0, 1.0], unit='deg').to(unit='rad') + result['nominal_incident_angle'], + sc.array(dims=['event'], values=[1.0, 1.0], unit='deg').to(unit='rad'), ) @@ -337,6 +379,8 @@ def test_shutter_graph_requires_matching_beam_names(input_name): 'upstream_slit_centers': {'a': sc.vector([0.0, 0.1, -2.0], unit='m')}, 'downstream_slit_centers': {'a': sc.vector([0.0, 0.0, -1.0], unit='m')}, 'sample_surface_normal': sc.vector([0.0, 1.0, 0.0]), + 'sample_position': sc.vector([0.0, 0.0, 0.0], unit='m'), + 'gravity': sc.vector([0.0, 0.0, 0.0], unit='m/s^2'), 'shutter_positions': {'a': sc.vector([0.0, 0.0, -3.0], unit='m')}, 'shutter_status_logs': {'a': _log([0], [True])}, } @@ -347,4 +391,12 @@ def test_shutter_graph_requires_matching_beam_names(input_name): def test_shutter_graph_requires_at_least_one_beam(): with pytest.raises(ValueError, match='At least one incident beam'): - shutter_log_incident_angle_graph({}, {}, sc.vector([0.0, 1.0, 0.0]), {}, {}) + shutter_log_incident_angle_graph( + {}, + {}, + sc.vector([0.0, 1.0, 0.0]), + {}, + {}, + sc.vector([0.0, 0.0, 0.0], unit='m'), + sc.vector([0.0, 0.0, 0.0], unit='m/s^2'), + ) diff --git a/packages/essreflectometry/tests/freia/incident_gravity_test.py b/packages/essreflectometry/tests/freia/incident_gravity_test.py new file mode 100644 index 000000000..5001d5bfd --- /dev/null +++ b/packages/essreflectometry/tests/freia/incident_gravity_test.py @@ -0,0 +1,346 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026 Scipp contributors (https://github.com/scipp) +import numpy as np +import pytest +import scipp as sc +from ess.reduce.nexus.types import GravityVector, Position +from scipp.constants import h, m_n +from scipp.testing import assert_allclose, assert_identical +from scippnexus import NXsample, NXsource +from scipy.optimize import root_scalar +from scipy.spatial.transform import Rotation + +from ess.freia import FreiaOffspecWorkflow +from ess.freia.conversions import ( + closest_beam_incident_angle_graph, + fixed_slits_incident_angle_graph, + shutter_log_incident_angle_graph, +) +from ess.freia.mirror import DIRECT_BEAM, mirror_reflection_transform +from ess.freia.types import ( + DownstreamSlitCenters, + IncidentBeamTransform, + SampleSurfaceNormal, + ShutterPositions, + ShutterStatusLogs, + UpstreamSlitCenters, +) +from ess.reflectometry.types import CorrectedDetector, SampleRun, WavelengthDetector + + +def _geometry(mirror_tilt=0.0, *, a=1.0, b=1.0, c=0.375): + """A nominal 0.3-degree ray through two slits, with the mirror at the origin.""" + beta = np.deg2rad(-0.3 if mirror_tilt is None else 0.3) + alpha = beta if mirror_tilt is None else 2 * np.deg2rad(mirror_tilt) - beta + direction = sc.vector([0.0, np.sin(beta), np.cos(beta)]) + return { + 'upstream_slit_centers': { + 'beam': sc.vector([0.0, -a * np.sin(alpha), -a * np.cos(alpha)], unit='m') + }, + 'downstream_slit_centers': {'beam': sc.scalar(b, unit='m') * direction}, + 'sample_position': sc.scalar(b + c, unit='m') * direction, + 'sample_surface_normal': sc.vector( + [0.0, 1.0 if mirror_tilt is None else -1.0, 0.0] + ), + 'gravity': sc.vector([0.0, -9.80665, 0.0], unit='m/s^2'), + 'beam_transform': DIRECT_BEAM + if mirror_tilt is None + else mirror_reflection_transform( + sc.vector([0.0, 0.0, 0.0], unit='m'), + sc.vector( + [0.0, np.cos(np.deg2rad(mirror_tilt)), -np.sin(np.deg2rad(mirror_tilt))] + ), + ), + } + + +def _angles(geometry, wavelength): + graph = fixed_slits_incident_angle_graph(**geometry) + coords = {'wavelength': wavelength, 'gravity': geometry['gravity']} + data = sc.DataArray(sc.zeros(sizes=wavelength.sizes), coords=coords) + return data.transform_coords('incident_angle', graph=graph).coords['incident_angle'] + + +def _ballistic_angle(geometry, wavelength, mirror_tilt): + """Independent 2-D shooting solution with exact parabolic free flights. + + Find the launch angle at fixed speed that passes through both slit centres. + Intersect the actual trajectories with the mirror and sample planes, rather + than using nominal flight times or the first-order correction coefficient. + """ + + def yz(vector): + return vector.value[[2, 1]] # longitudinal, vertical + + gravity = yz(geometry['gravity']) + upstream = yz(geometry['upstream_slit_centers']['beam']) + downstream = yz(geometry['downstream_slit_centers']['beam']) + sample = yz(geometry['sample_position']) + sample_normal = yz(geometry['sample_surface_normal']) + speed = (h / m_n / sc.scalar(wavelength, unit='angstrom')).to(unit='m/s').value + + def intersect(point, velocity, plane_point, normal): + coefficients = [ + 0.5 * np.dot(gravity, normal), + np.dot(velocity, normal), + np.dot(point - plane_point, normal), + ] + roots = np.roots(np.trim_zeros(coefficients, 'f')) + time = min(t.real for t in roots if abs(t.imag) < 1e-12 and t.real > 1e-10) + return ( + point + velocity * time + 0.5 * gravity * time**2, + velocity + gravity * time, + ) + + def at_downstream(launch_angle): + point = upstream + velocity = speed * np.array([np.cos(launch_angle), np.sin(launch_angle)]) + if mirror_tilt is not None: + tilt = np.deg2rad(mirror_tilt) + normal = np.array([-np.sin(tilt), np.cos(tilt)]) + point, velocity = intersect(point, velocity, np.zeros(2), normal) + velocity = velocity - 2 * np.dot(velocity, normal) * normal + return intersect(point, velocity, downstream, np.array([1.0, 0.0])) + + nominal = downstream - upstream if mirror_tilt is None else -upstream + guess = np.arctan2(nominal[1], nominal[0]) + root = root_scalar( + lambda angle: at_downstream(angle)[0][1] - downstream[1], + x0=guess, + x1=guess + 1e-6, + xtol=1e-13, + ) + assert root.converged + point, velocity = at_downstream(root.root) + _, velocity = intersect(point, velocity, sample, sample_normal) + return np.arcsin(-np.dot(sample_normal, velocity) / np.linalg.norm(velocity)) + + +@pytest.mark.parametrize( + ('mirror_tilt', 'a', 'b'), + [ + (None, 1.0, 1.0), + (0.0, 1.0, 1.0), + (-1.0, 1.0, 1.0), + (0.0, 1.8, 0.2), + ], +) +@pytest.mark.parametrize( + ('wavelength', 'tolerance'), [(2.0, 1e-8), (10.0, 1e-6), (18.0, 1e-5)] +) +def test_incidence_matches_exact_ballistic_trajectories( + mirror_tilt, a, b, wavelength, tolerance +): + geometry = _geometry(mirror_tilt, a=a, b=b) + result = _angles(geometry, sc.scalar(wavelength, unit='angstrom')) + exact = _ballistic_angle(geometry, wavelength, mirror_tilt) + # Tolerance allows the neglected second-order terms, largest at long lambda. + assert_allclose( + result, sc.scalar(exact, unit='rad'), atol=sc.scalar(tolerance, unit='rad') + ) + + +def test_coefficient_is_invariant_under_rotation_translation_and_length_units(): + geometry = _geometry(-1.0) + wavelengths = sc.array(dims=['event'], values=[0.2, 0.5, 1.0], unit='nm') + expected = _angles(geometry, wavelengths) + rotation = sc.spatial.linear_transform( + value=Rotation.from_rotvec([0.3, -0.4, 0.1]).as_matrix() + ) + shift = sc.vector([0.2, -0.1, 4.0], unit='m') + # Moving the reference point within the sample plane must not change c. + geometry['sample_position'] += sc.vector([0.3, 0.0, 0.7], unit='m') + for key, unit in [ + ('upstream_slit_centers', 'mm'), + ('downstream_slit_centers', 'cm'), + ]: + geometry[key] = { + 'beam': (rotation * geometry[key]['beam'] + shift).to(unit=unit) + } + geometry['sample_position'] = (rotation * geometry['sample_position'] + shift).to( + unit='mm' + ) + geometry['sample_surface_normal'] = rotation * geometry['sample_surface_normal'] + geometry['gravity'] = rotation * geometry['gravity'] + tilt = np.deg2rad(-1.0) + geometry['beam_transform'] = mirror_reflection_transform( + shift, rotation * sc.vector([0.0, np.cos(tilt), -np.sin(tilt)]) + ) + assert_allclose(_angles(geometry, wavelengths), expected) + + +@pytest.mark.parametrize(('detector_angle', 'selected'), [(0.303, 0), (0.307, 1)]) +def test_closest_selection_uses_nominal_geometry_before_correcting_incidence( + detector_angle, selected +): + angles = {'low': 0.3, 'high': 0.31} + graph = closest_beam_incident_angle_graph( + upstream_slit_centers={ + name: sc.vector([0.0, 2.5 * np.tan(np.deg2rad(angle)), -2.5], unit='m') + for name, angle in angles.items() + }, + downstream_slit_centers={ + name: sc.vector([0.0, 0.5 * np.tan(np.deg2rad(angle)), -0.5], unit='m') + for name, angle in angles.items() + }, + sample_surface_normal=sc.vector([0.0, 1.0, 0.0]), + sample_position=sc.vector([0.0, 0.0, 0.0], unit='m'), + gravity=sc.vector([0.0, -9.80665, 0.0], unit='m/s^2'), + ) + wavelengths = sc.array(dims=['event'], values=[2.0, 10.0], unit='angstrom') + result = sc.DataArray( + sc.ones(dims=['event'], shape=[2]), + coords={ + 'wavelength': wavelengths, + 'sample_position': sc.vector([0.0, 0.0, 0.0], unit='m'), + 'gravity': sc.vector([0.0, -9.80665, 0.0], unit='m/s^2'), + 'scattered_beam': sc.vector( + [ + 0.0, + 3 * np.sin(np.deg2rad(detector_angle)), + 3 * np.cos(np.deg2rad(detector_angle)), + ], + unit='m', + ), + # A corrected outgoing angle must not influence beam identification. + 'reflection_angle': sc.array( + dims=['event'], values=[0.32, 0.29], unit='deg' + ).to(unit='rad'), + }, + ).transform_coords( + ['nominal_incident_angle', 'incident_gravity_length', 'incident_angle'], + graph=graph, + ) + # Both wavelengths select the same beam; the correction is applied afterwards. + assert_allclose( + result.coords['nominal_incident_angle'], + sc.scalar([0.3, 0.31][selected], unit='deg').to(unit='rad'), + ) + assert_allclose(result.coords['incident_gravity_length'], sc.scalar(1.5, unit='m')) + delta = ( + sc.scalar(9.80665 * 1.5, unit='m^2/s^2') * (m_n / h * wavelengths) ** 2 + ).to(unit='dimensionless') * sc.scalar(1.0, unit='rad') + expected = sc.scalar([0.3, 0.31][selected], unit='deg').to(unit='rad') + delta + assert_allclose(result.coords['incident_angle'], expected) + + +@pytest.mark.parametrize('method', ['fixed_slits', 'closest', 'shutter_logs']) +@pytest.mark.parametrize('inversion', [False, True]) +def test_workflow_corrects_binned_incidence_and_preserves_counts(method, inversion): + geometry = _geometry(0.0 if inversion else None) + wf = FreiaOffspecWorkflow(incident_beam_from=method, inversion=inversion) + wf[GravityVector] = geometry['gravity'] + wf[IncidentBeamTransform[SampleRun]] = geometry['beam_transform'] + wf[Position[NXsample, SampleRun]] = geometry['sample_position'] + wf[Position[NXsource, SampleRun]] = 5 * geometry['upstream_slit_centers']['beam'] + wf[SampleSurfaceNormal[SampleRun]] = geometry['sample_surface_normal'] + wf[UpstreamSlitCenters[SampleRun]] = geometry['upstream_slit_centers'] + wf[DownstreamSlitCenters[SampleRun]] = geometry['downstream_slit_centers'] + wavelengths = sc.array(dims=['event'], values=[2.0, 10.0, 18.0], unit='angstrom') + data = sc.DataArray( + sc.ones(dims=['event'], shape=[3], with_variances=True, unit='counts'), + coords={ + 'wavelength': wavelengths, + 'pixel': sc.array(dims=['event'], values=[0, 0, 1], unit=None), + 'event_time_zero': sc.datetimes( + dims=['event'], values=[0, 0, 0], unit='ns' + ), + 'event_time_offset': sc.full( + dims=['event'], shape=[3], value=0.05, unit='s' + ), + }, + ).group('pixel') + beta = np.deg2rad(-0.3 if inversion else 0.3) + pixel_position = geometry['sample_position'] + sc.vector( + [0.0, 3 * np.sin(beta), 3 * np.cos(beta)], unit='m' + ) + data.coords['position'] = sc.concat([pixel_position, pixel_position], dim='pixel') + wf[WavelengthDetector[SampleRun]] = data + if method == 'shutter_logs': + wf[ShutterPositions[SampleRun]] = geometry['upstream_slit_centers'] + wf[ShutterStatusLogs[SampleRun]] = { + 'beam': sc.DataArray( + sc.array(dims=['time'], values=[True]), + coords={'time': sc.datetimes(dims=['time'], values=[0], unit='ns')}, + ) + } + result = wf.compute(CorrectedDetector[SampleRun]) + # Analytic horizontal-mirror / ordinary-slit limits for a=b=1, c=.375. + effective_length = -0.875 if inversion else 1.375 + delta = ( + sc.scalar(9.80665 * effective_length * np.cos(beta), unit='m^2/s^2') + * (m_n / h * wavelengths) ** 2 + ).to(unit='dimensionless') * sc.scalar(1.0, unit='rad') + expected = sc.scalar(0.3, unit='deg').to(unit='rad') + delta + assert_allclose( + result.bins.coords['incident_angle'].bins.constituents['data'], expected + ) + assert_identical(result.bins.data, data.bins.data) + assert result.sum().value == 3.0 + assert sc.all(sc.isfinite(result.bins.coords['Qx'])).value + assert sc.all(sc.isfinite(result.bins.coords['Qz'])).value + + +@pytest.mark.parametrize('dtype', ['int64', 'float32', 'float64']) +def test_incident_correction_accepts_numeric_wavelengths_without_modifying_them(dtype): + wavelengths = sc.array(dims=['event'], values=[2, 10], unit='angstrom', dtype=dtype) + original = wavelengths.copy() + geometry = _geometry(0.0) + expected = _angles(geometry, wavelengths.to(dtype='float64')) + assert_allclose(_angles(geometry, wavelengths), expected) + assert_identical(wavelengths, original) + + +def test_shutter_selection_assigns_distinct_lengths_with_equal_nominal_angles(): + angle = sc.scalar(0.3, unit='deg').to(unit='rad') + direction = sc.vector([0.0, -np.sin(angle.value), np.cos(angle.value)]) + upstream = { + name: sc.scalar(-distance, unit='m') * direction + for name, distance in [('a', 3.0), ('b', 5.0)] + } + graph = shutter_log_incident_angle_graph( + upstream_slit_centers=upstream, + downstream_slit_centers={ + name: sc.scalar(-1.0, unit='m') * direction for name in upstream + }, + sample_surface_normal=sc.vector([0.0, 1.0, 0.0]), + sample_position=sc.vector([0.0, 0.0, 0.0], unit='m'), + gravity=sc.vector([0.0, -9.80665, 0.0], unit='m/s^2'), + shutter_positions=upstream, + shutter_status_logs={ + name: sc.DataArray( + sc.array(dims=['time'], values=states), + coords={'time': sc.datetimes(dims=['time'], values=[0, 40], unit='ms')}, + ) + for name, states in [('b', [False, True]), ('a', [True, False])] + }, + ) + wavelength = sc.scalar(10.0, unit='angstrom') + result = sc.DataArray( + sc.ones(sizes={'event': 2}), + coords={ + 'wavelength': wavelength, + 'gravity': sc.vector([0.0, -9.80665, 0.0], unit='m/s^2'), + 'sample_position': sc.vector([0.0, 0.0, 0.0], unit='m'), + 'L2': sc.scalar(1.0, unit='m'), + 'event_time_zero': sc.datetime(0, unit='ns'), + 'event_time_offset': sc.array(dims=['event'], values=[30, 60], unit='ms'), + }, + ).transform_coords( + ['nominal_incident_angle', 'incident_gravity_length', 'incident_angle'], + graph=graph, + ) + assert_allclose( + result.coords['nominal_incident_angle'], sc.concat([angle, angle], dim='event') + ) + assert_allclose( + result.coords['incident_gravity_length'], + sc.array(dims=['event'], values=[2.0, 3.0], unit='m') * np.cos(angle.value), + ) + effective_lengths = sc.array(dims=['event'], values=[2.0, 3.0], unit='m') + delta = ( + sc.scalar(9.80665 * np.cos(angle.value), unit='m/s^2') + * effective_lengths + * (m_n / h * wavelength) ** 2 + ).to(unit='dimensionless') * sc.scalar(1.0, unit='rad') + assert_allclose(result.coords['incident_angle'], angle + delta) diff --git a/packages/essreflectometry/tests/freia/mirror_test.py b/packages/essreflectometry/tests/freia/mirror_test.py index 18b9a7cb3..5d78e1299 100644 --- a/packages/essreflectometry/tests/freia/mirror_test.py +++ b/packages/essreflectometry/tests/freia/mirror_test.py @@ -23,8 +23,8 @@ from ess.freia.mirror import ( DIRECT_BEAM, mirror_reflection_transform, + reflected_upstream_position, transform_position, - unfold_path, ) from ess.freia.types import ( DetectorRegionOfInterest, @@ -109,12 +109,12 @@ def test_mirror_normal_magnitude_does_not_affect_reflection(scale): @pytest.mark.parametrize('side', [-1, 1]) -def test_unfold_path_supports_either_mirror_side_and_mixed_units(side): +def test_reflected_upstream_position_supports_either_mirror_side_and_mixed_units(side): transform = mirror_reflection_transform( sc.vector([0.0, 0.0, -1.0], unit='m'), sc.vector([0.0, 1.0, 0.0]) ) assert_allclose( - unfold_path( + reflected_upstream_position( transform, sc.vector([0.0, side * 2000.0, -3000.0], unit='mm'), sc.vector([0.0, side * 0.5, -0.5], unit='m'), @@ -126,7 +126,9 @@ def test_unfold_path_supports_either_mirror_side_and_mixed_units(side): def test_ordinary_path_preserves_positions_exactly(): position = sc.vector([0.0, 1234.56789, -3456.78912], unit='mm') assert_identical( - unfold_path(DIRECT_BEAM, position, sc.vector([0.0, 0.0, 0.0], unit='m')), + reflected_upstream_position( + DIRECT_BEAM, position, sc.vector([0.0, 0.0, 0.0], unit='m') + ), position, ) @@ -261,7 +263,7 @@ def test_detector_flight_path_includes_mirror_detour(run): wf.compute(DetectorLtotal[run]), sc.array(dims=['pixel_id'], values=[5 * np.sqrt(2)], unit='m'), ) - # The angular graph must use the same unfolded incident path. + # The angular graph must use the same incident path through the mirror. graph = wf.compute(CoordTransformationGraph[run]) result = sc.DataArray(sc.scalar(0.0)).transform_coords('L1', graph=graph) assert_allclose(result.coords['L1'], sc.scalar(4 * np.sqrt(2), unit='m')) diff --git a/packages/essreflectometry/tests/freia/workflow_test.py b/packages/essreflectometry/tests/freia/workflow_test.py index 27f2ecaeb..29d7919a9 100644 --- a/packages/essreflectometry/tests/freia/workflow_test.py +++ b/packages/essreflectometry/tests/freia/workflow_test.py @@ -204,10 +204,13 @@ def test_offspec_workflow_supports_scalar_incidence_for_a_single_beam(method): ('method', 'expected'), [('closest', [1.0, 1.0, 1.0, 1.0]), ('shutter_logs', [0.3, 1.0, np.nan, np.nan])], ) -def test_offspec_workflow_assigns_incidence_with_independent_methods(method, expected): +@pytest.mark.parametrize('gravity', [0.0, 9.80665]) +def test_offspec_workflow_assigns_incidence_with_independent_methods( + method, expected, gravity +): wf = FreiaOffspecWorkflow(incident_beam_from=method) assert wf.compute(KeepEventTimeOffset) is (method == 'shutter_logs') - wf[GravityVector] = sc.vector([0.0, 0.0, 0.0], unit='m/s^2') + wf[GravityVector] = sc.vector([0.0, -gravity, 0.0], unit='m/s^2') wf[Position[NXsample, SampleRun]] = sc.vector([0.0, 0.0, 0.0], unit='m') wf[Position[NXsource, SampleRun]] = sc.vector([0.0, 0.0, -29.0], unit='m') wf[SampleSurfaceNormal[SampleRun]] = sc.vector([0.0, 1.0, 0.0]) @@ -271,10 +274,18 @@ def log(times, states): } result = wf.compute(CorrectedDetector[SampleRun]) - assigned = result.bins.coords['incident_angle'].bins.constituents['data'] + assigned = ( + result.bins.coords['incident_angle'] + if 'incident_angle' in result.bins.coords + else sc.bins_like(data, result.coords['incident_angle']) + ).bins.constituents['data'] + # All events travel at 1000 m/s. The horizontal slit separation is 1 m + # and the last slit is 1 m before the sample: effective distance 1.5 m. + correction = sc.scalar(gravity * 1.5 / 1000.0**2, unit='rad') assert_allclose( assigned, - sc.array(dims=['event'], values=expected, unit='deg').to(unit='rad'), + sc.array(dims=['event'], values=expected, unit='deg').to(unit='rad') + + correction, equal_nan=True, ) input_coords = set(data.coords) | set(data.bins.coords) @@ -287,8 +298,11 @@ def log(times, states): } assert_identical(result.bins.data, data.bins.data) unassigned = np.isnan(expected) - assert_identical( - result.bins.masks['incident_beam_unassigned'].bins.constituents['data'], - sc.array(dims=['event'], values=unassigned), - ) + if 'incident_beam_unassigned' in result.bins.masks: + assert_identical( + result.bins.masks['incident_beam_unassigned'].bins.constituents['data'], + sc.array(dims=['event'], values=unassigned), + ) + else: + assert not np.any(unassigned) assert result.sum().value == np.count_nonzero(~unassigned) From 182f6e576fe9cef4f1f613acc11c8e6572ba91eb Mon Sep 17 00:00:00 2001 From: Johannes Kasimir Date: Wed, 4 Nov 2026 10:35:48 +0100 Subject: [PATCH 3/7] fix: use explicit mirror position and orientation instead of transformation --- .../src/ess/freia/conversions.py | 112 ++++++------------ .../essreflectometry/src/ess/freia/mirror.py | 86 ++++++-------- .../essreflectometry/src/ess/freia/types.py | 12 +- .../src/ess/freia/workflow.py | 2 +- .../tests/freia/conversions_test.py | 60 +++++++--- .../tests/freia/incident_gravity_test.py | 15 ++- .../tests/freia/mirror_test.py | 76 ++++++------ 7 files changed, 160 insertions(+), 203 deletions(-) diff --git a/packages/essreflectometry/src/ess/freia/conversions.py b/packages/essreflectometry/src/ess/freia/conversions.py index a6bbb2891..756861f82 100644 --- a/packages/essreflectometry/src/ess/freia/conversions.py +++ b/packages/essreflectometry/src/ess/freia/conversions.py @@ -16,11 +16,11 @@ RunType, SampleRun, ) -from .mirror import DIRECT_BEAM, direct_beam_transform, reflected_upstream_position +from .mirror import no_mirror, reflected_upstream_position from .types import ( DownstreamSlitCenters, IncidentAngleGraph, - IncidentBeamTransform, + MirrorGeometry, SampleSurfaceNormal, ShutterPositions, ShutterStatusLogs, @@ -203,37 +203,6 @@ def theta( return sc.asin(sc.dot(outgoing_direction, normal)) -def incident_beam_directions( - upstream_slit_centers: UpstreamSlitCenters[RunType], - downstream_slit_centers: DownstreamSlitCenters[RunType], - beam_transform: sc.Variable = DIRECT_BEAM, -) -> dict[str, sc.Variable]: - """Compute candidate incident directions from corresponding slit openings. - - The two inputs map the names of open channels to their centers in the - upstream and downstream slit assemblies. Matching keys describe one - possible incident beam. In inversion mode the mirror is between the - assemblies, so the upstream slit position is reflected across the mirror - plane before computing the direction towards the downstream slit. - """ - if upstream_slit_centers.keys() != downstream_slit_centers.keys(): - raise ValueError( - 'UpstreamSlitCenters and DownstreamSlitCenters must have the same keys.' - ) - directions = {} - for key, upstream in upstream_slit_centers.items(): - downstream = downstream_slit_centers[key] - reflected_upstream = reflected_upstream_position( - beam_transform, upstream, downstream - ) - beam = downstream - reflected_upstream.to(unit=downstream.unit) - length = sc.norm(beam) - if not sc.isfinite(length).value or length.value == 0: - raise ValueError('Slit centres must define a finite, nonzero flight path.') - directions[key] = beam / length - return directions - - def assign_incident_angle( reflection_angle: sc.Variable, expected_reflection_angles: dict[str, sc.Variable], @@ -263,29 +232,19 @@ def assign_incident_angle( return {'nominal_incident_angle': closest, 'incident_gravity_length': length} -def incident_angle( - incident_direction: sc.Variable, - sample_surface_normal: sc.Variable, -) -> sc.Variable: - """Angle at which the assigned incident beam approaches the sample.""" - normal = sample_surface_normal / sc.norm(sample_surface_normal) - return sc.asin(-sc.dot(incident_direction, normal)) - - def _incident_angle_and_gravity_length( upstream: sc.Variable, downstream: sc.Variable, normal: sc.Variable, - transform: sc.Variable, + mirror: MirrorGeometry | None, sample_position: sc.Variable, gravity: sc.Variable, ) -> tuple[sc.Variable, sc.Variable]: r"""Compute the nominal incident angle and signed effective gravity length. Assumes FREIA's layout: distinct slits, the inversion mirror strictly - between them, and the sample downstream. The transform comes from the - direct-beam or mirror provider. Sample normal and gravity have arbitrary - orientations. Geometry is evaluated once per candidate. + between them, and the sample downstream. Sample normal and gravity have + arbitrary orientations. Geometry is evaluated once per candidate. Returns ------- @@ -296,14 +255,14 @@ def _incident_angle_and_gravity_length( ----- Let :math:`L` be the flight length between the slits, :math:`a` the length from upstream slit to mirror, and :math:`c` from downstream slit to sample. - With mirror reflection matrix :math:`R`, gravity :math:`g`, nominal unit + With unit mirror normal :math:`n_m`, gravity :math:`g`, nominal unit direction :math:`u`, incident angle :math:`\alpha_0`, and unit sample normal - :math:`n`, the effective length is + :math:`n_s`, the effective length is .. math:: - K = g(c+L/2) + (Rg-g)\frac{a^2}{2L}, \qquad - D = -\frac{n \cdot [K-u(u \cdot K)]}{|g|\cos\alpha_0}. + K = g(c+L/2) - n_m(n_m \cdot g)\frac{a^2}{L}, \qquad + D = -\frac{n_s \cdot [K-u(u \cdot K)]}{|g|\cos\alpha_0}. Without the mirror, the second term in :math:`K` is zero. The correction using :math:`D` is applied by :func:`gravity_corrected_incident_angle`. @@ -311,28 +270,25 @@ def _incident_angle_and_gravity_length( upstream, downstream, sample_position = ( position.to(unit='m') for position in (upstream, downstream, sample_position) ) - transform = transform.to(unit='m') - reflected_upstream = reflected_upstream_position(transform, upstream, downstream) + reflected_upstream = reflected_upstream_position(upstream, downstream, mirror) beam = downstream - reflected_upstream length, g = sc.norm(beam), sc.norm(gravity) direction, normal = beam / length, normal / sc.norm(normal) - angle = incident_angle(direction, normal) + normal_component = sc.dot(direction, normal) + angle = sc.asin(-normal_component) if g.value == 0: return angle, sc.scalar(0.0, unit='m') - normal_component = sc.dot(direction, normal) transverse_normal = normal - direction * normal_component cosine = sc.norm(sc.cross(normal, direction)) c = sc.dot(sample_position - downstream, normal) / normal_component gravity_direction = gravity / g k = gravity_direction * (c + length / 2) - if not sc.identical(transform, DIRECT_BEAM): - # The mirror bisects the slit and its image. Rg-g = -2 n (n dot g). - displacement = upstream - reflected_upstream - separation = sc.norm(displacement) - mirror_normal = displacement / separation - a = separation / (2 * sc.dot(direction, mirror_normal)) - k -= mirror_normal * sc.dot(gravity_direction, mirror_normal) * a**2 / length + if mirror is not None: + a = sc.dot( + mirror.position.to(unit='m') - reflected_upstream, mirror.normal + ) / sc.dot(direction, mirror.normal) + k -= mirror.normal * sc.dot(gravity_direction, mirror.normal) * a**2 / length return angle, -sc.dot(k, transverse_normal) / cosine @@ -389,7 +345,7 @@ def coordinate_transformation_graph( sample_position: Position[NXsample, RunType], sample_surface_normal: SampleSurfaceNormal[RunType], gravity: GravityVector, - beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, + mirror: MirrorGeometry[RunType] | None = None, ) -> CoordTransformationGraph[RunType]: """Build the scattering coordinates shared by sample and direct-beam runs.""" length = sc.norm(sample_surface_normal) @@ -404,7 +360,7 @@ def coordinate_transformation_graph( 'outgoing_direction': outgoing_direction, 'scattering_angle': scattering_angle, 'source_position': lambda: reflected_upstream_position( - beam_transform, source_position, sample_position + source_position, sample_position, mirror ), 'sample_position': lambda: sample_position, 'sample_surface_normal': lambda: sample_surface_normal, @@ -417,11 +373,11 @@ def sample_coordinate_transformation_graph( sample_position: Position[NXsample, SampleRun], sample_surface_normal: SampleSurfaceNormal[SampleRun], gravity: GravityVector, - beam_transform: IncidentBeamTransform[SampleRun] = DIRECT_BEAM, + mirror: MirrorGeometry[SampleRun] | None = None, ) -> CoordTransformationGraph[SampleRun]: """Extend the scattering graph with the sample's reflection angle and Q.""" return coordinate_transformation_graph( - source_position, sample_position, sample_surface_normal, gravity, beam_transform + source_position, sample_position, sample_surface_normal, gravity, mirror ) | {'theta': theta, 'Q': reflectometry_q} @@ -429,7 +385,7 @@ def _incident_angle_parameters( upstream_slit_centers: dict[str, sc.Variable], downstream_slit_centers: dict[str, sc.Variable], sample_surface_normal: sc.Variable, - beam_transform: sc.Variable, + mirror: MirrorGeometry | None, sample_position: sc.Variable, gravity: sc.Variable, ) -> tuple[dict[str, sc.Variable], dict[str, sc.Variable]]: @@ -446,7 +402,7 @@ def _incident_angle_parameters( upstream, downstream_slit_centers[name], sample_surface_normal, - beam_transform, + mirror, sample_position, gravity, ) @@ -459,14 +415,14 @@ def fixed_slits_incident_angle_graph( sample_surface_normal: SampleSurfaceNormal[RunType], sample_position: Position[NXsample, RunType], gravity: GravityVector, - beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, + mirror: MirrorGeometry[RunType] | None = None, ) -> IncidentAngleGraph[RunType]: """Use one slit pair's nominal angle and effective length, then apply gravity.""" angles, lengths = _incident_angle_parameters( upstream_slit_centers, downstream_slit_centers, sample_surface_normal, - beam_transform, + mirror, sample_position, gravity, ) @@ -484,7 +440,7 @@ def closest_beam_incident_angle_graph( sample_surface_normal: SampleSurfaceNormal[RunType], sample_position: Position[NXsample, RunType], gravity: GravityVector, - beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, + mirror: MirrorGeometry[RunType] | None = None, ) -> IncidentAngleGraph[RunType]: """Select the closest nominal angle using detector geometry, then apply gravity. @@ -499,13 +455,13 @@ def closest_beam_incident_angle_graph( sample_surface_normal, sample_position, gravity, - beam_transform, + mirror, ) angles, lengths = _incident_angle_parameters( upstream_slit_centers, downstream_slit_centers, sample_surface_normal, - beam_transform, + mirror, sample_position, gravity, ) @@ -530,14 +486,14 @@ def shutter_log_incident_angle_graph( shutter_status_logs: ShutterStatusLogs[RunType], sample_position: Position[NXsample, RunType], gravity: GravityVector, - beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, + mirror: MirrorGeometry[RunType] | None = None, ) -> IncidentAngleGraph[RunType]: """Assign nominal angle and length from shutter logs, then apply gravity.""" angles, lengths = _incident_angle_parameters( upstream_slit_centers, downstream_slit_centers, sample_surface_normal, - beam_transform, + mirror, sample_position, gravity, ) @@ -547,7 +503,7 @@ def shutter_log_incident_angle_graph( 'must have the same keys.' ) reflected_shutter_positions = { - key: reflected_upstream_position(beam_transform, position, sample_position) + key: reflected_upstream_position(position, sample_position, mirror) for key, position in shutter_positions.items() } @@ -582,7 +538,7 @@ def offspecular_coordinate_transformation_graph( sample_surface_normal: SampleSurfaceNormal[RunType], gravity: GravityVector, incident_angle_graph: IncidentAngleGraph[RunType], - beam_transform: IncidentBeamTransform[RunType] = DIRECT_BEAM, + mirror: MirrorGeometry[RunType] | None = None, ) -> CoordTransformationGraph[RunType]: """Combine an incidence assignment with the shared offspecular coordinates.""" return ( @@ -591,7 +547,7 @@ def offspecular_coordinate_transformation_graph( sample_position, sample_surface_normal, gravity, - beam_transform, + mirror, ) | incident_angle_graph | { @@ -603,7 +559,7 @@ def offspecular_coordinate_transformation_graph( providers = ( - direct_beam_transform, + no_mirror, coordinate_transformation_graph, sample_coordinate_transformation_graph, ) diff --git a/packages/essreflectometry/src/ess/freia/mirror.py b/packages/essreflectometry/src/ess/freia/mirror.py index 594c645cc..29dca475e 100644 --- a/packages/essreflectometry/src/ess/freia/mirror.py +++ b/packages/essreflectometry/src/ess/freia/mirror.py @@ -2,7 +2,6 @@ # Copyright (c) 2026 Scipp contributors (https://github.com/scipp) """Geometry for FREIA's planar inversion mirror.""" -import numpy as np import scipp as sc import scippnexus as snx from ess.reduce import nexus @@ -20,15 +19,12 @@ from ess.reduce.unwrap.types import DetectorLtotal from ..reflectometry.types import RunType -from .types import IncidentBeamTransform, MirrorNormal, MirrorPosition +from .types import MirrorGeometry, MirrorNormal, MirrorPosition -# Default for direct calls to coordinate-graph providers; never modified in place. -DIRECT_BEAM = sc.spatial.translation(value=[0.0, 0.0, 0.0], unit='m') - -def direct_beam_transform() -> IncidentBeamTransform[RunType]: - """Leave upstream coordinates unchanged when inversion is disabled.""" - return IncidentBeamTransform[RunType](DIRECT_BEAM.copy()) +def no_mirror() -> MirrorGeometry[RunType] | None: + """Use the ordinary geometry when inversion is disabled.""" + return None def mirror_time_filter() -> TransformationTimeFilter[snx.NXmirror, RunType]: @@ -85,82 +81,68 @@ def mirror_normal( return MirrorNormal[RunType](normal / sc.norm(normal)) -def mirror_reflection_transform( +def mirror_geometry( position: MirrorPosition[RunType], normal: MirrorNormal[RunType], -) -> IncidentBeamTransform[RunType]: - r"""Build a transform that reflects positions across the mirror plane. - - For a point :math:`m` on the plane and its unit normal :math:`n`, the - transform maps a position :math:`p` to - - .. math:: - - p' = p - 2n\,[n \cdot (p-m)]. - - The magnitude and sign of ``normal`` do not affect the transform. - """ +) -> MirrorGeometry[RunType] | None: + """Validate the mirror position and normalize its surface normal.""" for name, vector in [('MirrorPosition', position), ('MirrorNormal', normal)]: if vector.ndim != 0 or vector.dtype != sc.DType.vector3: raise ValueError(f'{name} must be a scalar vector.') - if not np.isfinite(vector.value).all(): + if not sc.isfinite(vector).value: raise ValueError(f'{name} must be finite.') - n = normal.value - scale = np.max(np.abs(n)) - if scale == 0: - raise ValueError('MirrorNormal must be nonzero.') - n = n / scale - n = n / np.linalg.norm(n) - matrix = np.eye(4) - matrix[:3, :3] -= 2 * np.outer(n, n) - p = position.to(unit='m').value - matrix[:3, 3] = p - matrix[:3, :3] @ p - return IncidentBeamTransform[RunType]( - sc.spatial.affine_transform(value=matrix, unit='m') - ) - - -def transform_position(transform: sc.Variable, position: sc.Variable) -> sc.Variable: - """Apply the beam-path transform, preserving the input length unit.""" - return (transform * position.to(unit=transform.unit)).to(unit=position.unit) + length = sc.norm(normal) + if not sc.isfinite(length).value or length.value == 0: + raise ValueError('MirrorNormal must have a finite, nonzero norm.') + return MirrorGeometry(position=position, normal=normal / length) def reflected_upstream_position( - transform: sc.Variable, upstream: sc.Variable, downstream: sc.Variable + upstream: sc.Variable, + downstream: sc.Variable, + mirror: MirrorGeometry | None = None, ) -> sc.Variable: - """Return the upstream position reflected across the mirror plane. + r"""Return the upstream position reflected across the mirror plane. The straight segment from this position to ``downstream`` has the same length as the path through the mirror and points along its final segment. The returned point is used for geometry calculations; the physical - component remains in place. With ``DIRECT_BEAM``, return ``upstream`` + component remains in place. With no mirror, return ``upstream`` unchanged. The result retains the upstream position's length unit. + For a point :math:`m` on the plane and its unit normal :math:`n`, + + .. math:: + + p' = p - 2n\,[n \cdot (p-m)]. + Raises ------ ValueError If the physical upstream and downstream points are on opposite sides of the mirror plane, so no reflected path connects them. """ - if sc.identical(transform, DIRECT_BEAM): + if mirror is None: return upstream - reflected = transform_position(transform, upstream) - midpoint = (0.5 * (upstream + reflected)).to(unit=downstream.unit) - normal = (upstream - reflected).to(unit=downstream.unit) - if sc.dot(downstream - midpoint, normal).value < 0: + position = mirror.position.to(unit=upstream.unit) + upstream_distance = sc.dot(upstream - position, mirror.normal) + downstream_distance = sc.dot( + downstream.to(unit=upstream.unit) - position, mirror.normal + ) + if (upstream_distance * downstream_distance).value < 0: raise ValueError( 'A reflected path requires its upstream and downstream positions ' 'to be on the same side of the mirror plane. Check the mirror pose ' 'and component positions.' ) - return reflected + return upstream - 2 * mirror.normal * upstream_distance def detector_ltotal_with_mirror( detector: EmptyDetector[RunType], source_position: Position[snx.NXsource, RunType], sample_position: Position[snx.NXsample, RunType], - transform: IncidentBeamTransform[RunType], + mirror: MirrorGeometry[RunType] | None, ) -> DetectorLtotal[RunType]: """Compute the source-to-detector flight length through the mirror and sample. @@ -170,7 +152,7 @@ def detector_ltotal_with_mirror( upstream-monitor wavelength reconstruction use the physical source position. """ reflected_source = reflected_upstream_position( - transform, source_position, sample_position + source_position, sample_position, mirror ) sample = sample_position.to(unit=reflected_source.unit) pixels = detector.coords['position'].to(unit=reflected_source.unit) @@ -184,6 +166,6 @@ def detector_ltotal_with_mirror( load_mirror_transformation, mirror_position, mirror_normal, - mirror_reflection_transform, + mirror_geometry, detector_ltotal_with_mirror, ) diff --git a/packages/essreflectometry/src/ess/freia/types.py b/packages/essreflectometry/src/ess/freia/types.py index e00b22da9..dca59c162 100644 --- a/packages/essreflectometry/src/ess/freia/types.py +++ b/packages/essreflectometry/src/ess/freia/types.py @@ -1,4 +1,5 @@ # Copyright (c) 2025 Scipp contributors (https://github.com/scipp) +from dataclasses import dataclass from typing import NewType import sciline @@ -42,13 +43,12 @@ class MirrorNormal(sciline.Scope[RunType, sc.Variable], sc.Variable): """Normal to the inversion mirror in global coordinates; either sign is valid.""" -class IncidentBeamTransform(sciline.Scope[RunType, sc.Variable], sc.Variable): - """Reflect upstream positions across the inversion mirror's plane. +@dataclass(frozen=True) +class MirrorGeometry[RunType]: + """A point on the mirror plane and its unit normal, in laboratory coordinates.""" - Identity when inversion is disabled. Reflected positions are used to - calculate flight lengths and the beam direction after the mirror. - Sample, detector, and gravity remain in the laboratory frame. - """ + position: sc.Variable + normal: sc.Variable class UpstreamSlitCenters(sciline.Scope[RunType, dict], dict): diff --git a/packages/essreflectometry/src/ess/freia/workflow.py b/packages/essreflectometry/src/ess/freia/workflow.py index 45a42bab1..5d3f65ebc 100644 --- a/packages/essreflectometry/src/ess/freia/workflow.py +++ b/packages/essreflectometry/src/ess/freia/workflow.py @@ -252,7 +252,7 @@ def FreiaOffspecWorkflow( 'shutter_logs': conversions.shutter_log_incident_angle_graph, }[incident_beam_from] for provider in ( - mirror.direct_beam_transform, + mirror.no_mirror, conversions.offspecular_coordinate_transformation_graph, assignment_provider, corrections.add_offspecular_coords_and_masks, diff --git a/packages/essreflectometry/tests/freia/conversions_test.py b/packages/essreflectometry/tests/freia/conversions_test.py index f5a28e74c..b538b069c 100644 --- a/packages/essreflectometry/tests/freia/conversions_test.py +++ b/packages/essreflectometry/tests/freia/conversions_test.py @@ -9,8 +9,8 @@ _shutter_state_at_time, assign_incident_angle, assign_incident_angle_from_shutter_logs, + closest_beam_incident_angle_graph, fixed_slits_incident_angle_graph, - incident_beam_directions, outgoing_direction, scattering_angle, shutter_log_incident_angle_graph, @@ -67,33 +67,57 @@ def test_scattering_angle_with_gravity(): ) -def test_incident_directions_are_computed_from_corresponding_slit_centers(): +def test_incident_angles_use_corresponding_slit_centers(): + angles = {'top': 0.3, 'middle': 0.8, 'bottom': 1.5} upstream = { - 'top': sc.vector([0.0, 0.0, -2.0], unit='m'), - 'middle': sc.vector([0.0, 1.0, -2.0], unit='m'), - 'bottom': sc.vector([0.0, 2.0, -2.0], unit='m'), + name: sc.vector([0.0, 2.5 * np.tan(np.deg2rad(angle)), -2.5], unit='m') + for name, angle in angles.items() } # Deliberately use a different order to ensure channels are paired by name. downstream = { - 'bottom': sc.vector([0.0, 5.0, 2.0], unit='m'), - 'top': sc.vector([0.0, -3.0, 2.0], unit='m'), - 'middle': sc.vector([0.0, 1.0, 0.0], unit='m'), + name: sc.vector([0.0, 0.5 * np.tan(np.deg2rad(angles[name])), -0.5], unit='m') + for name in ['bottom', 'top', 'middle'] } - - result = incident_beam_directions(upstream, downstream) - - assert result.keys() == upstream.keys() - assert_allclose(result['top'], sc.vector([0.0, -0.6, 0.8])) - assert_allclose(result['middle'], sc.vector([0.0, 0.0, 1.0])) - assert_allclose(result['bottom'], sc.vector([0.0, 0.6, 0.8])) + gravity = sc.vector([0.0, 0.0, 0.0], unit='m/s^2') + graph = closest_beam_incident_angle_graph( + upstream, + downstream, + sample_surface_normal=sc.vector([0.0, 1.0, 0.0]), + sample_position=sc.vector([0.0, 0.0, 0.0], unit='m'), + gravity=gravity, + ) + data = sc.DataArray( + sc.ones(dims=['pixel'], shape=[3]), + coords={ + 'scattered_beam': sc.vectors( + dims=['pixel'], + values=[[0.0, np.tan(np.deg2rad(a)), 1.0] for a in angles.values()], + unit='m', + ), + 'gravity': gravity, + 'wavelength': sc.scalar(4.0, unit='angstrom'), + }, + ) + result = data.transform_coords('incident_angle', graph=graph) + assert_allclose( + result.coords['incident_angle'], + sc.array(dims=['pixel'], values=list(angles.values()), unit='deg').to( + unit='rad' + ), + ) -def test_incident_directions_require_matching_slit_names(): +def test_incident_angles_require_matching_slit_names(): upstream = {'top': sc.vector([0.0, 0.0, -2.0], unit='m')} downstream = {'bottom': sc.vector([0.0, 0.0, -1.0], unit='m')} - with pytest.raises(ValueError, match='must have the same keys'): - incident_beam_directions(upstream, downstream) + closest_beam_incident_angle_graph( + upstream, + downstream, + sample_surface_normal=sc.vector([0.0, 1.0, 0.0]), + sample_position=sc.vector([0.0, 0.0, 0.0], unit='m'), + gravity=sc.vector([0.0, 0.0, 0.0], unit='m/s^2'), + ) def test_assigns_each_neutron_to_closest_expected_reflection_angle(): diff --git a/packages/essreflectometry/tests/freia/incident_gravity_test.py b/packages/essreflectometry/tests/freia/incident_gravity_test.py index 5001d5bfd..beeebfc84 100644 --- a/packages/essreflectometry/tests/freia/incident_gravity_test.py +++ b/packages/essreflectometry/tests/freia/incident_gravity_test.py @@ -16,10 +16,11 @@ fixed_slits_incident_angle_graph, shutter_log_incident_angle_graph, ) -from ess.freia.mirror import DIRECT_BEAM, mirror_reflection_transform +from ess.freia.mirror import mirror_geometry from ess.freia.types import ( DownstreamSlitCenters, - IncidentBeamTransform, + MirrorNormal, + MirrorPosition, SampleSurfaceNormal, ShutterPositions, ShutterStatusLogs, @@ -43,9 +44,9 @@ def _geometry(mirror_tilt=0.0, *, a=1.0, b=1.0, c=0.375): [0.0, 1.0 if mirror_tilt is None else -1.0, 0.0] ), 'gravity': sc.vector([0.0, -9.80665, 0.0], unit='m/s^2'), - 'beam_transform': DIRECT_BEAM + 'mirror': None if mirror_tilt is None - else mirror_reflection_transform( + else mirror_geometry( sc.vector([0.0, 0.0, 0.0], unit='m'), sc.vector( [0.0, np.cos(np.deg2rad(mirror_tilt)), -np.sin(np.deg2rad(mirror_tilt))] @@ -163,7 +164,7 @@ def test_coefficient_is_invariant_under_rotation_translation_and_length_units(): geometry['sample_surface_normal'] = rotation * geometry['sample_surface_normal'] geometry['gravity'] = rotation * geometry['gravity'] tilt = np.deg2rad(-1.0) - geometry['beam_transform'] = mirror_reflection_transform( + geometry['mirror'] = mirror_geometry( shift, rotation * sc.vector([0.0, np.cos(tilt), -np.sin(tilt)]) ) assert_allclose(_angles(geometry, wavelengths), expected) @@ -230,7 +231,9 @@ def test_workflow_corrects_binned_incidence_and_preserves_counts(method, inversi geometry = _geometry(0.0 if inversion else None) wf = FreiaOffspecWorkflow(incident_beam_from=method, inversion=inversion) wf[GravityVector] = geometry['gravity'] - wf[IncidentBeamTransform[SampleRun]] = geometry['beam_transform'] + if inversion: + wf[MirrorPosition[SampleRun]] = geometry['mirror'].position + wf[MirrorNormal[SampleRun]] = geometry['mirror'].normal wf[Position[NXsample, SampleRun]] = geometry['sample_position'] wf[Position[NXsource, SampleRun]] = 5 * geometry['upstream_slit_centers']['beam'] wf[SampleSurfaceNormal[SampleRun]] = geometry['sample_surface_normal'] diff --git a/packages/essreflectometry/tests/freia/mirror_test.py b/packages/essreflectometry/tests/freia/mirror_test.py index 5d78e1299..578c97d48 100644 --- a/packages/essreflectometry/tests/freia/mirror_test.py +++ b/packages/essreflectometry/tests/freia/mirror_test.py @@ -21,15 +21,13 @@ from ess import freia from ess.freia import conversions from ess.freia.mirror import ( - DIRECT_BEAM, - mirror_reflection_transform, + mirror_geometry, reflected_upstream_position, - transform_position, ) from ess.freia.types import ( DetectorRegionOfInterest, DownstreamSlitCenters, - IncidentBeamTransform, + MirrorGeometry, MirrorNormal, MirrorPosition, SampleSurfaceNormal, @@ -63,61 +61,57 @@ def _set_mirror(workflow, run=SampleRun): def test_all_workflow_constructors_accept_inversion(factory): point = sc.vector([0.0, 2.0, -3.0], unit='m') ordinary = factory() - assert_identical( - transform_position(ordinary.compute(IncidentBeamTransform[SampleRun]), point), - point, - ) + assert ordinary.compute(MirrorGeometry[SampleRun] | None) is None inverted = factory(inversion=True) _set_mirror(inverted) assert_identical( - transform_position(inverted.compute(IncidentBeamTransform[SampleRun]), point), + reflected_upstream_position( + point, + sc.vector([0.0, 1.0, 0.0], unit='m'), + inverted.compute(MirrorGeometry[SampleRun] | None), + ), sc.vector([0.0, -2.0, -3.0], unit='m'), ) -def test_tilted_translated_mirror_is_an_involution_and_preserves_plane(): - position = sc.vector([100.0, 200.0, -300.0], unit='mm') - normal = sc.vector([1.0, 2.0, 3.0]) - transform = mirror_reflection_transform(position, normal) - point = sc.vector([1.0, 2.0, 3.0], unit='m') - reflected = transform_position(transform, point) - assert_allclose(transform_position(transform, reflected), point) - assert_allclose(transform_position(transform, position), position) +@pytest.mark.parametrize('normal_scale', [0.5, -2.0, 3.0]) +def test_reflected_path_through_tilted_translated_mirror(normal_scale): + rotation = sc.spatial.rotations_from_rotvecs( + sc.vector([0.3, -0.4, 0.1], unit='rad') + ) + position = sc.vector([0.1, 0.2, -0.3], unit='m') + normal = rotation * sc.vector([0.0, 1.0, 0.0]) + # A 45-degree ray hits the mirror at position. Rotate the whole setup. + upstream = position + rotation * sc.vector([0.0, 2.0, -2.0], unit='m') + downstream = position + rotation * sc.vector([0.0, 0.5, 0.5], unit='m') + reflected = reflected_upstream_position( + upstream, + downstream.to(unit='cm'), + mirror_geometry(position.to(unit='mm'), normal_scale * normal), + ) + expected = position + rotation * sc.vector([0.0, -2.0, -2.0], unit='m') + assert_allclose(reflected, expected) assert_allclose( - sc.dot(reflected - position.to(unit='m'), normal), - -sc.dot(point - position.to(unit='m'), normal), + sc.norm(downstream - reflected), sc.scalar(2.5 * np.sqrt(2), unit='m') ) - assert_allclose(transform, mirror_reflection_transform(position, -normal)) @pytest.mark.parametrize('normal', [[0, 0, 0], [0, np.nan, 0], [0, np.inf, 0]]) def test_invalid_mirror_normal_is_rejected(normal): with pytest.raises(ValueError, match='MirrorNormal'): - mirror_reflection_transform( - sc.vector([0.0, 0.0, 0.0], unit='m'), sc.vector(normal) - ) - - -@pytest.mark.parametrize('scale', [1e-200, 1e200]) -def test_mirror_normal_magnitude_does_not_affect_reflection(scale): - point = sc.vector([0.0, 0.0, -1.0], unit='m') - normal = sc.vector([0.0, 1.0, 0.01]) - assert_allclose( - mirror_reflection_transform(point, scale * normal), - mirror_reflection_transform(point, normal), - ) + mirror_geometry(sc.vector([0.0, 0.0, 0.0], unit='m'), sc.vector(normal)) @pytest.mark.parametrize('side', [-1, 1]) def test_reflected_upstream_position_supports_either_mirror_side_and_mixed_units(side): - transform = mirror_reflection_transform( + mirror = mirror_geometry( sc.vector([0.0, 0.0, -1.0], unit='m'), sc.vector([0.0, 1.0, 0.0]) ) assert_allclose( reflected_upstream_position( - transform, sc.vector([0.0, side * 2000.0, -3000.0], unit='mm'), sc.vector([0.0, side * 0.5, -0.5], unit='m'), + mirror, ), sc.vector([0.0, -side * 2000.0, -3000.0], unit='mm'), ) @@ -126,14 +120,12 @@ def test_reflected_upstream_position_supports_either_mirror_side_and_mixed_units def test_ordinary_path_preserves_positions_exactly(): position = sc.vector([0.0, 1234.56789, -3456.78912], unit='mm') assert_identical( - reflected_upstream_position( - DIRECT_BEAM, position, sc.vector([0.0, 0.0, 0.0], unit='m') - ), + reflected_upstream_position(position, sc.vector([0.0, 0.0, 0.0], unit='m')), position, ) -def test_custom_conversion_pipeline_has_default_beam_transform(): +def test_custom_conversion_pipeline_defaults_to_no_mirror(): wf = sciline.Pipeline(conversions.providers, constraints={RunType: [SampleRun]}) wf[Position[snx.NXsource, SampleRun]] = sc.vector([0.0, 0.0, -2.0], unit='m') wf[Position[snx.NXsample, SampleRun]] = sc.vector([0.0, 0.0, 0.0], unit='m') @@ -197,7 +189,7 @@ def test_nexus_mirror_loads_translation_and_local_minus_z_normal(tmp_path, name, assert_allclose( wf.compute(MirrorNormal[run]), sc.vector([0.0, np.sin(angle), -np.cos(angle)]) ) - wf.compute(IncidentBeamTransform[run]) + wf.compute(MirrorGeometry[run] | None) def test_moving_mirror_requires_a_selected_pose(tmp_path): @@ -220,9 +212,9 @@ def test_missing_mirror_fails_with_manual_geometry_instructions(tmp_path): wf = freia.FreiaWorkflow(inversion=True) wf[Filename[SampleRun]] = filename with pytest.raises(ValueError, match='supply MirrorPosition and MirrorNormal'): - wf.compute(IncidentBeamTransform[SampleRun]) + wf.compute(MirrorGeometry[SampleRun] | None) _set_mirror(wf) - wf.compute(IncidentBeamTransform[SampleRun]) + wf.compute(MirrorGeometry[SampleRun] | None) def _set_run(workflow, run, *, direct=False, supply_wavelength=True): From f80ece967963d42e3f48d2307f976d9913e9b5bd Mon Sep 17 00:00:00 2001 From: Johannes Kasimir Date: Wed, 4 Nov 2026 12:01:46 +0100 Subject: [PATCH 4/7] docs --- .../src/ess/freia/conversions.py | 39 ++++++++++++------- .../essreflectometry/src/ess/freia/mirror.py | 16 ++++---- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/packages/essreflectometry/src/ess/freia/conversions.py b/packages/essreflectometry/src/ess/freia/conversions.py index 756861f82..4598091a9 100644 --- a/packages/essreflectometry/src/ess/freia/conversions.py +++ b/packages/essreflectometry/src/ess/freia/conversions.py @@ -249,23 +249,30 @@ def _incident_angle_and_gravity_length( Returns ------- : - Scalar nominal angle in radians and signed effective length in metres. + Nominal incident angle in radians and the geometric coefficient of the + angular gravity correction, in metres. Both are scalars. The coefficient + combines flight lengths and orientations; positive values mean gravity + increases the incident angle. Notes ----- - Let :math:`L` be the flight length between the slits, :math:`a` the length - from upstream slit to mirror, and :math:`c` from downstream slit to sample. - With unit mirror normal :math:`n_m`, gravity :math:`g`, nominal unit - direction :math:`u`, incident angle :math:`\alpha_0`, and unit sample normal - :math:`n_s`, the effective length is + All lengths follow the ray calculated without gravity: :math:`L` is the + path between slit centres, :math:`a` the upstream-slit-to-mirror path, and + :math:`c` the downstream-slit-to-sample-plane path. + Let :math:`u` be the unit incident direction at the sample, :math:`\alpha_0` + its angle to the surface, :math:`n_s` the outward unit sample normal, + :math:`n_m` the unit mirror normal, and :math:`g` gravitational acceleration. + + The vector :math:`K` weights gravity by these flight lengths. Projecting + its effect onto the sample angle gives the returned coefficient :math:`D`: .. math:: K = g(c+L/2) - n_m(n_m \cdot g)\frac{a^2}{L}, \qquad - D = -\frac{n_s \cdot [K-u(u \cdot K)]}{|g|\cos\alpha_0}. + D = -\frac{K \cdot [n_s-u(u \cdot n_s)]}{|g|\cos\alpha_0}. - Without the mirror, the second term in :math:`K` is zero. The correction - using :math:`D` is applied by :func:`gravity_corrected_incident_angle`. + Here :math:`|g|` is the acceleration magnitude. Without the mirror, omit the + second term in :math:`K`. For zero gravity, return zero for the coefficient. """ upstream, downstream, sample_position = ( position.to(unit='m') for position in (upstream, downstream, sample_position) @@ -305,8 +312,9 @@ def gravity_corrected_incident_angle( nominal_incident_angle: Incident angle determined from slit geometry, before gravity correction. incident_gravity_length: - Signed effective length for the selected beam, accounting for slit - positions, the sample plane, and the mirror when present. + Signed geometric coefficient, in metres, combining the selected beam's + flight lengths and mirror, sample, and gravity orientations. Positive + values increase the incident angle. wavelength: Reconstructed neutron wavelengths. gravity: @@ -320,12 +328,17 @@ def gravity_corrected_incident_angle( Notes ----- - With nominal angle :math:`\alpha_0` and effective length :math:`D`, the - first-order correction is + The first-order correction is .. math:: \alpha(\lambda) = \alpha_0 + |g|D\left(\frac{m_n\lambda}{h}\right)^2. + + Here :math:`\alpha_0` is ``nominal_incident_angle``, :math:`D` is + ``incident_gravity_length``, :math:`\lambda` is ``wavelength``, and + :math:`|g|` is the magnitude of ``gravity``. The constants :math:`m_n` and + :math:`h` are the neutron mass and Planck's constant. The result + :math:`\alpha(\lambda)` is the corrected angle in radians. """ g = sc.norm(gravity) if g.value == 0: diff --git a/packages/essreflectometry/src/ess/freia/mirror.py b/packages/essreflectometry/src/ess/freia/mirror.py index 29dca475e..1f30c193a 100644 --- a/packages/essreflectometry/src/ess/freia/mirror.py +++ b/packages/essreflectometry/src/ess/freia/mirror.py @@ -104,18 +104,20 @@ def reflected_upstream_position( ) -> sc.Variable: r"""Return the upstream position reflected across the mirror plane. - The straight segment from this position to ``downstream`` has the same - length as the path through the mirror and points along its final segment. - The returned point is used for geometry calculations; the physical - component remains in place. With no mirror, return ``upstream`` - unchanged. The result retains the upstream position's length unit. - - For a point :math:`m` on the plane and its unit normal :math:`n`, + Let :math:`p` be ``upstream``, :math:`m` be ``mirror.position``, and :math:`n` + be the unit normal ``mirror.normal``. + The returned position :math:`p'` is .. math:: p' = p - 2n\,[n \cdot (p-m)]. + The straight segment from :math:`p'` to ``downstream`` has the same + length as the path through the mirror and points along its final segment. + The returned point is used for geometry calculations; the physical + component remains in place. With no mirror, return ``upstream`` + unchanged. The result retains the upstream position's length unit. + Raises ------ ValueError From e00bed7174e790e1ad14b185a5683183a4b97d36 Mon Sep 17 00:00:00 2001 From: Johannes Kasimir Date: Wed, 4 Nov 2026 15:12:45 +0100 Subject: [PATCH 5/7] docs: improve description --- .../src/ess/freia/conversions.py | 53 ++++++++++--------- 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/packages/essreflectometry/src/ess/freia/conversions.py b/packages/essreflectometry/src/ess/freia/conversions.py index 4598091a9..25426c0cd 100644 --- a/packages/essreflectometry/src/ess/freia/conversions.py +++ b/packages/essreflectometry/src/ess/freia/conversions.py @@ -240,39 +240,44 @@ def _incident_angle_and_gravity_length( sample_position: sc.Variable, gravity: sc.Variable, ) -> tuple[sc.Variable, sc.Variable]: - r"""Compute the nominal incident angle and signed effective gravity length. + r"""Compute the nominal incident angle and D, which determines the size and + sign of its gravity correction at a given neutron wavelength. - Assumes FREIA's layout: distinct slits, the inversion mirror strictly - between them, and the sample downstream. Sample normal and gravity have - arbitrary orientations. Geometry is evaluated once per candidate. + Return the angle :math:`\alpha_0` between the nominal incident ray and the + sample surface (in radians), and the gravity correction factor :math:`D` + (in metres). + For neutron speed :math:`v` and gravitational acceleration :math:`g`, with + magnitude :math:`|g|`, the incident angle at the sample is, to first order: - Returns - ------- - : - Nominal incident angle in radians and the geometric coefficient of the - angular gravity correction, in metres. Both are scalars. The coefficient - combines flight lengths and orientations; positive values mean gravity - increases the incident angle. + .. math:: - Notes - ----- - All lengths follow the ray calculated without gravity: :math:`L` is the - path between slit centres, :math:`a` the upstream-slit-to-mirror path, and - :math:`c` the downstream-slit-to-sample-plane path. - Let :math:`u` be the unit incident direction at the sample, :math:`\alpha_0` - its angle to the surface, :math:`n_s` the outward unit sample normal, - :math:`n_m` the unit mirror normal, and :math:`g` gravitational acceleration. + \alpha(v) \simeq \alpha_0 + \frac{|g|D}{v^2}. + + The starting point is motion under constant gravitational acceleration, + constrained to pass through both slit centres, with specular reflection at + the mirror between them when present. Use flight times from the nominal + path without gravity. Along this path, :math:`L` is the distance between + slits, :math:`a` the upstream-slit-to-mirror distance, and :math:`c` the + distance from the downstream slit to the intersection with the sample plane. + + Integrating this motion with the slit positions fixed gives a direction at + the sample proportional to :math:`u+K/v^2`, where :math:`u` is the nominal unit + incident direction and + + .. math:: + + K = g(c+L/2) - n_m(n_m \cdot g)\frac{a^2}{L}. - The vector :math:`K` weights gravity by these flight lengths. Projecting - its effect onto the sample angle gives the returned coefficient :math:`D`: + Here :math:`n_m` is the unit mirror normal. Normalizing the direction and + expanding the angle to the surface with outward unit normal :math:`n_s` + gives the returned coefficient: .. math:: - K = g(c+L/2) - n_m(n_m \cdot g)\frac{a^2}{L}, \qquad D = -\frac{K \cdot [n_s-u(u \cdot n_s)]}{|g|\cos\alpha_0}. - Here :math:`|g|` is the acceleration magnitude. Without the mirror, omit the - second term in :math:`K`. For zero gravity, return zero for the coefficient. + Without a mirror, omit the second term in :math:`K`. For zero gravity, + return :math:`D=0`. """ upstream, downstream, sample_position = ( position.to(unit='m') for position in (upstream, downstream, sample_position) From 490f9041a997f2370e9c2045c165a0481bf74d33 Mon Sep 17 00:00:00 2001 From: Johannes Kasimir Date: Tue, 17 Nov 2026 13:54:56 +0100 Subject: [PATCH 6/7] test: simplify tests --- .../tests/freia/incident_gravity_test.py | 2 +- .../tests/freia/mirror_test.py | 37 ++++++++----------- 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/packages/essreflectometry/tests/freia/incident_gravity_test.py b/packages/essreflectometry/tests/freia/incident_gravity_test.py index beeebfc84..6479175dd 100644 --- a/packages/essreflectometry/tests/freia/incident_gravity_test.py +++ b/packages/essreflectometry/tests/freia/incident_gravity_test.py @@ -225,7 +225,7 @@ def test_closest_selection_uses_nominal_geometry_before_correcting_incidence( assert_allclose(result.coords['incident_angle'], expected) -@pytest.mark.parametrize('method', ['fixed_slits', 'closest', 'shutter_logs']) +@pytest.mark.parametrize('method', ['fixed_slits', 'shutter_logs']) @pytest.mark.parametrize('inversion', [False, True]) def test_workflow_corrects_binned_incidence_and_preserves_counts(method, inversion): geometry = _geometry(0.0 if inversion else None) diff --git a/packages/essreflectometry/tests/freia/mirror_test.py b/packages/essreflectometry/tests/freia/mirror_test.py index 578c97d48..30249cfe4 100644 --- a/packages/essreflectometry/tests/freia/mirror_test.py +++ b/packages/essreflectometry/tests/freia/mirror_test.py @@ -74,7 +74,7 @@ def test_all_workflow_constructors_accept_inversion(factory): ) -@pytest.mark.parametrize('normal_scale', [0.5, -2.0, 3.0]) +@pytest.mark.parametrize('normal_scale', [0.5, -2.0]) def test_reflected_path_through_tilted_translated_mirror(normal_scale): rotation = sc.spatial.rotations_from_rotvecs( sc.vector([0.3, -0.4, 0.1], unit='rad') @@ -174,14 +174,16 @@ def _write_mirror(path, *, name='inversion_mirror', angles=(80.0,)): pitch['time'].attrs.update(units='s', start='2026-01-01T00:00:00Z') -@pytest.mark.parametrize('name', ['inversion_mirror', 'deflector']) -@pytest.mark.parametrize('run', [SampleRun, ReferenceRun]) +@pytest.mark.parametrize( + ('name', 'run'), [('inversion_mirror', SampleRun), ('deflector', ReferenceRun)] +) def test_nexus_mirror_loads_translation_and_local_minus_z_normal(tmp_path, name, run): filename = tmp_path / 'mirror.nxs' _write_mirror(filename, name=name) wf = freia.FreiaWorkflow(inversion=True) wf[Filename[run]] = filename - wf[NeXusName[snx.NXmirror]] = name + if name != 'inversion_mirror': + wf[NeXusName[snx.NXmirror]] = name assert_allclose( wf.compute(MirrorPosition[run]), sc.vector([0.0, -0.3, -1.0], unit='m') ) @@ -251,6 +253,8 @@ def _set_run(workflow, run, *, direct=False, supply_wavelength=True): def test_detector_flight_path_includes_mirror_detour(run): wf = freia.FreiaWorkflow(inversion=True) _set_run(wf, run, direct=run == ReferenceRun, supply_wavelength=False) + gravity = sc.vector([0.0, -9.80665, 0.0], unit='m/s^2') + wf[GravityVector] = gravity assert_allclose( wf.compute(DetectorLtotal[run]), sc.array(dims=['pixel_id'], values=[5 * np.sqrt(2)], unit='m'), @@ -259,6 +263,13 @@ def test_detector_flight_path_includes_mirror_detour(run): graph = wf.compute(CoordTransformationGraph[run]) result = sc.DataArray(sc.scalar(0.0)).transform_coords('L1', graph=graph) assert_allclose(result.coords['L1'], sc.scalar(4 * np.sqrt(2), unit='m')) + # Only the virtual source is reflected; physical inputs stay in the lab frame. + assert_identical(graph['gravity'](), gravity) + assert_identical(graph['sample_position'](), sc.vector([0.0, 1.0, 0.0], unit='m')) + assert_identical( + wf.compute(Position[snx.NXsource, run]), + sc.vector([0.0, 3.0, -4.0], unit='m'), + ) def test_mirror_before_sample_rejects_source_on_opposite_side_of_plane(): @@ -334,7 +345,7 @@ def test_inverted_specular_sample_and_direct_beam_normalization(): ) -@pytest.mark.parametrize('method', ['closest', 'fixed_slits', 'shutter_logs']) +@pytest.mark.parametrize('method', ['fixed_slits', 'shutter_logs']) def test_offspecular_inversion_reflects_slit_angles_and_shutter_paths(method): wf = freia.FreiaOffspecWorkflow(inversion=True, incident_beam_from=method) data = _set_run(wf, SampleRun) @@ -393,19 +404,3 @@ def test_offspecular_inversion_reflects_slit_angles_and_shutter_paths(method): sc.array(dims=['event'], values=[np.pi / np.sqrt(2)], unit='1/angstrom'), ) assert result.sum().value == 20.0 - - -def test_gravity_and_physical_positions_remain_in_laboratory_frame(): - wf = freia.FreiaWorkflow(inversion=True) - _set_run(wf, SampleRun) - gravity = sc.vector([0.0, -9.80665, 0.0], unit='m/s^2') - wf[GravityVector] = gravity - graph = wf.compute(CoordTransformationGraph[SampleRun]) - assert_identical(graph['gravity'](), gravity) - assert_identical( - graph['sample_position'](), wf.compute(Position[snx.NXsample, SampleRun]) - ) - assert_identical( - wf.compute(Position[snx.NXsource, SampleRun]), - sc.vector([0.0, 3.0, -4.0], unit='m'), - ) From 5c4b4c7324e049cc5471e71168aea545fe672e0a Mon Sep 17 00:00:00 2001 From: Johannes Kasimir Date: Thu, 19 Nov 2026 16:30:13 +0100 Subject: [PATCH 7/7] fix: use updated source position --- packages/essreflectometry/src/ess/freia/mirror.py | 3 ++- .../tests/freia/incident_gravity_test.py | 6 +++--- packages/essreflectometry/tests/freia/mirror_test.py | 9 +++++---- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/essreflectometry/src/ess/freia/mirror.py b/packages/essreflectometry/src/ess/freia/mirror.py index 1f30c193a..b56a80105 100644 --- a/packages/essreflectometry/src/ess/freia/mirror.py +++ b/packages/essreflectometry/src/ess/freia/mirror.py @@ -7,6 +7,7 @@ from ess.reduce import nexus from ess.reduce.nexus.types import ( EmptyDetector, + NeutronSourcePosition, NeXusComponentLocationSpec, NeXusFileSpec, NeXusName, @@ -142,7 +143,7 @@ def reflected_upstream_position( def detector_ltotal_with_mirror( detector: EmptyDetector[RunType], - source_position: Position[snx.NXsource, RunType], + source_position: NeutronSourcePosition[RunType], sample_position: Position[snx.NXsample, RunType], mirror: MirrorGeometry[RunType] | None, ) -> DetectorLtotal[RunType]: diff --git a/packages/essreflectometry/tests/freia/incident_gravity_test.py b/packages/essreflectometry/tests/freia/incident_gravity_test.py index 6479175dd..06b808065 100644 --- a/packages/essreflectometry/tests/freia/incident_gravity_test.py +++ b/packages/essreflectometry/tests/freia/incident_gravity_test.py @@ -3,10 +3,10 @@ import numpy as np import pytest import scipp as sc -from ess.reduce.nexus.types import GravityVector, Position +from ess.reduce.nexus.types import GravityVector, NeutronSourcePosition, Position from scipp.constants import h, m_n from scipp.testing import assert_allclose, assert_identical -from scippnexus import NXsample, NXsource +from scippnexus import NXsample from scipy.optimize import root_scalar from scipy.spatial.transform import Rotation @@ -235,7 +235,7 @@ def test_workflow_corrects_binned_incidence_and_preserves_counts(method, inversi wf[MirrorPosition[SampleRun]] = geometry['mirror'].position wf[MirrorNormal[SampleRun]] = geometry['mirror'].normal wf[Position[NXsample, SampleRun]] = geometry['sample_position'] - wf[Position[NXsource, SampleRun]] = 5 * geometry['upstream_slit_centers']['beam'] + wf[NeutronSourcePosition[SampleRun]] = 5 * geometry['upstream_slit_centers']['beam'] wf[SampleSurfaceNormal[SampleRun]] = geometry['sample_surface_normal'] wf[UpstreamSlitCenters[SampleRun]] = geometry['upstream_slit_centers'] wf[DownstreamSlitCenters[SampleRun]] = geometry['downstream_slit_centers'] diff --git a/packages/essreflectometry/tests/freia/mirror_test.py b/packages/essreflectometry/tests/freia/mirror_test.py index 30249cfe4..8b07c4952 100644 --- a/packages/essreflectometry/tests/freia/mirror_test.py +++ b/packages/essreflectometry/tests/freia/mirror_test.py @@ -10,6 +10,7 @@ EmptyDetector, Filename, GravityVector, + NeutronSourcePosition, NeXusName, Position, RawDetector, @@ -127,7 +128,7 @@ def test_ordinary_path_preserves_positions_exactly(): def test_custom_conversion_pipeline_defaults_to_no_mirror(): wf = sciline.Pipeline(conversions.providers, constraints={RunType: [SampleRun]}) - wf[Position[snx.NXsource, SampleRun]] = sc.vector([0.0, 0.0, -2.0], unit='m') + wf[NeutronSourcePosition[SampleRun]] = sc.vector([0.0, 0.0, -2.0], unit='m') wf[Position[snx.NXsample, SampleRun]] = sc.vector([0.0, 0.0, 0.0], unit='m') wf[SampleSurfaceNormal[SampleRun]] = sc.vector([0.0, 1.0, 0.0]) wf[GravityVector] = sc.vector([0.0, -9.80665, 0.0], unit='m/s^2') @@ -222,7 +223,7 @@ def test_missing_mirror_fails_with_manual_geometry_instructions(tmp_path): def _set_run(workflow, run, *, direct=False, supply_wavelength=True): _set_mirror(workflow, run) workflow[GravityVector] = sc.vector([0.0, 0.0, 0.0], unit='m/s^2') - workflow[Position[snx.NXsource, run]] = sc.vector([0.0, 3.0, -4.0], unit='m') + workflow[NeutronSourcePosition[run]] = sc.vector([0.0, 3.0, -4.0], unit='m') workflow[Position[snx.NXsample, run]] = sc.vector([0.0, 1.0, 0.0], unit='m') workflow[SampleSurfaceNormal[run]] = sc.vector([0.0, -1.0, 0.0]) workflow[DetectorRegionOfInterest[run]] = {} @@ -267,7 +268,7 @@ def test_detector_flight_path_includes_mirror_detour(run): assert_identical(graph['gravity'](), gravity) assert_identical(graph['sample_position'](), sc.vector([0.0, 1.0, 0.0], unit='m')) assert_identical( - wf.compute(Position[snx.NXsource, run]), + wf.compute(NeutronSourcePosition[run]), sc.vector([0.0, 3.0, -4.0], unit='m'), ) @@ -275,7 +276,7 @@ def test_detector_flight_path_includes_mirror_detour(run): def test_mirror_before_sample_rejects_source_on_opposite_side_of_plane(): wf = freia.FreiaWorkflow(inversion=True) _set_run(wf, SampleRun, supply_wavelength=False) - wf[Position[snx.NXsource, SampleRun]] = sc.vector([0.0, -3.0, -4.0], unit='m') + wf[NeutronSourcePosition[SampleRun]] = sc.vector([0.0, -3.0, -4.0], unit='m') with pytest.raises(ValueError, match='same side of the mirror plane'): wf.compute(DetectorLtotal[SampleRun]) graph = wf.compute(CoordTransformationGraph[SampleRun])