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 fcdeb426a..19eee185d 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 @@ -16,9 +17,11 @@ RunType, SampleRun, ) +from .mirror import no_mirror, reflected_upstream_position from .types import ( DownstreamSlitCenters, IncidentAngleGraph, + MirrorGeometry, SampleSurfaceNormal, ShutterPositions, ShutterStatusLogs, @@ -62,6 +65,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 ------- @@ -102,28 +107,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( @@ -136,21 +147,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( @@ -190,53 +204,159 @@ def theta( return sc.asin(sc.dot(outgoing_direction, normal)) -def incident_beam_directions( - upstream_slit_centers: UpstreamSlitCenters[RunType], - downstream_slit_centers: DownstreamSlitCenters[RunType], +def assign_incident_angle( + reflection_angle: sc.Variable, + expected_reflection_angles: dict[str, sc.Variable], + incident_gravity_lengths: dict[str, sc.Variable], ) -> dict[str, sc.Variable]: - """Compute candidate incident directions from corresponding slit openings. + """Select the nominal incident angle closest to the geometrical reflection angle. - 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. + ``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 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(): - beam = downstream_slit_centers[key] - upstream - directions[key] = beam / sc.norm(beam) - return directions + 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_and_gravity_length( + upstream: sc.Variable, + downstream: sc.Variable, + normal: sc.Variable, + mirror: MirrorGeometry | None, + sample_position: sc.Variable, + gravity: sc.Variable, +) -> tuple[sc.Variable, sc.Variable]: + r"""Compute the nominal incident angle and D, which determines the size and + sign of its gravity correction at a given neutron wavelength. + 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: -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 - - 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 - - -def incident_angle( - incident_direction: sc.Variable, - sample_surface_normal: sc.Variable, + .. math:: + + \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}. + + 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:: + + D = -\frac{K \cdot [n_s-u(u \cdot n_s)]}{|g|\cos\alpha_0}. + + 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) + ) + 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) + normal_component = sc.dot(direction, normal) + angle = sc.asin(-normal_component) + if g.value == 0: + return angle, sc.scalar(0.0, unit='m') + + 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 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 + + +def gravity_corrected_incident_angle( + nominal_incident_angle: sc.Variable, + incident_gravity_length: sc.Variable, + wavelength: sc.Variable, + gravity: 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)) + 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 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: + Gravitational acceleration vector in laboratory coordinates. + A zero vector disables the correction. + + Returns + ------- + : + Incident angle at the sample, in radians. + + Notes + ----- + 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: + 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( @@ -244,6 +364,7 @@ def coordinate_transformation_graph( sample_position: Position[NXsample, RunType], sample_surface_normal: SampleSurfaceNormal[RunType], gravity: GravityVector, + mirror: MirrorGeometry[RunType] | None = None, ) -> CoordTransformationGraph[RunType]: """Build the scattering coordinates shared by sample and direct-beam runs.""" length = sc.norm(sample_surface_normal) @@ -257,7 +378,9 @@ def coordinate_transformation_graph( **graph.beamline.L2(), 'outgoing_direction': outgoing_direction, 'scattering_angle': scattering_angle, - 'source_position': lambda: source_position, + 'source_position': lambda: reflected_upstream_position( + source_position, sample_position, mirror + ), 'sample_position': lambda: sample_position, 'sample_surface_normal': lambda: sample_surface_normal, 'gravity': lambda: gravity, @@ -269,50 +392,109 @@ def sample_coordinate_transformation_graph( sample_position: Position[NXsample, SampleRun], sample_surface_normal: SampleSurfaceNormal[SampleRun], gravity: GravityVector, + 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 + source_position, sample_position, sample_surface_normal, gravity, mirror ) | {'theta': theta, 'Q': reflectometry_q} -def _incident_angles_from_slits( - upstream_slit_centers, downstream_slit_centers, sample_surface_normal -): - return { - beam_name: incident_angle(direction, sample_surface_normal) - for beam_name, direction in incident_beam_directions( - upstream_slit_centers, downstream_slit_centers - ).items() - } +def _incident_angle_parameters( + upstream_slit_centers: dict[str, sc.Variable], + downstream_slit_centers: dict[str, sc.Variable], + sample_surface_normal: sc.Variable, + mirror: MirrorGeometry | None, + 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, + mirror, + 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, + mirror: MirrorGeometry[RunType] | None = None, ) -> 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 - ).values() - return {'incident_angle': lambda: beam_incident_angle} + """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, + mirror, + 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, + mirror: MirrorGeometry[RunType] | None = None, ) -> 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 + """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, + mirror, + ) + angles, lengths = _incident_angle_parameters( + upstream_slit_centers, + downstream_slit_centers, + sample_surface_normal, + mirror, + 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( @@ -321,23 +503,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, + mirror: MirrorGeometry[RunType] | None = None, ) -> 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 + """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, + mirror, + 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(position, sample_position, mirror) + for key, position in shutter_positions.items() + } def select_incident_angle( event_time_zero: sc.Variable, @@ -345,19 +532,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=shutter_positions, + 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( @@ -366,11 +557,16 @@ def offspecular_coordinate_transformation_graph( sample_surface_normal: SampleSurfaceNormal[RunType], gravity: GravityVector, incident_angle_graph: IncidentAngleGraph[RunType], + mirror: MirrorGeometry[RunType] | None = None, ) -> 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, + mirror, ) | incident_angle_graph | { @@ -382,6 +578,7 @@ def offspecular_coordinate_transformation_graph( providers = ( + no_mirror, coordinate_transformation_graph, sample_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/mcstas.py b/packages/essreflectometry/src/ess/freia/mcstas.py index 72db25138..2763db4a8 100644 --- a/packages/essreflectometry/src/ess/freia/mcstas.py +++ b/packages/essreflectometry/src/ess/freia/mcstas.py @@ -335,6 +335,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..b56a80105 --- /dev/null +++ b/packages/essreflectometry/src/ess/freia/mirror.py @@ -0,0 +1,174 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026 Scipp contributors (https://github.com/scipp) +"""Geometry for FREIA's planar inversion mirror.""" + +import scipp as sc +import scippnexus as snx +from ess.reduce import nexus +from ess.reduce.nexus.types import ( + EmptyDetector, + NeutronSourcePosition, + 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 MirrorGeometry, MirrorNormal, MirrorPosition + + +def no_mirror() -> MirrorGeometry[RunType] | None: + """Use the ordinary geometry when inversion is disabled.""" + return None + + +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 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. + """ + 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_geometry( + position: MirrorPosition[RunType], + normal: MirrorNormal[RunType], +) -> 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 sc.isfinite(vector).value: + raise ValueError(f'{name} must be finite.') + 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( + upstream: sc.Variable, + downstream: sc.Variable, + mirror: MirrorGeometry | None = None, +) -> sc.Variable: + r"""Return the upstream position reflected across the mirror plane. + + 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 + If the physical upstream and downstream points are on opposite sides + of the mirror plane, so no reflected path connects them. + """ + if mirror is None: + return upstream + 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 upstream - 2 * mirror.normal * upstream_distance + + +def detector_ltotal_with_mirror( + detector: EmptyDetector[RunType], + source_position: NeutronSourcePosition[RunType], + sample_position: Position[snx.NXsample, RunType], + mirror: MirrorGeometry[RunType] | None, +) -> DetectorLtotal[RunType]: + """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. 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. + """ + reflected_source = reflected_upstream_position( + source_position, sample_position, mirror + ) + sample = sample_position.to(unit=reflected_source.unit) + pixels = detector.coords['position'].to(unit=reflected_source.unit) + return DetectorLtotal[RunType]( + sc.norm(sample - reflected_source) + sc.norm(pixels - sample) + ) + + +providers = ( + mirror_time_filter, + load_mirror_transformation, + mirror_position, + mirror_normal, + 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 c47cc80ff..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 @@ -34,12 +35,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.""" + + +@dataclass(frozen=True) +class MirrorGeometry[RunType]: + """A point on the mirror plane and its unit normal, in laboratory coordinates.""" + + position: sc.Variable + normal: sc.Variable + + 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): @@ -52,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): @@ -60,6 +83,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 6635126ea..fd6ba2a18 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. @@ -181,22 +206,39 @@ 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 ``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 +252,7 @@ def FreiaOffspecWorkflow( 'shutter_logs': conversions.shutter_log_incident_angle_graph, }[incident_beam_from] for provider in ( + mirror.no_mirror, conversions.offspecular_coordinate_transformation_graph, assignment_provider, corrections.add_offspecular_coords_and_masks, @@ -219,55 +262,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/conversions_test.py b/packages/essreflectometry/tests/freia/conversions_test.py index 2de964b36..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(): @@ -106,15 +130,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 +159,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 +246,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 +277,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 +311,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 +338,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 +350,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 +368,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 +387,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 +403,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 +415,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..06b808065 --- /dev/null +++ b/packages/essreflectometry/tests/freia/incident_gravity_test.py @@ -0,0 +1,349 @@ +# 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, NeutronSourcePosition, Position +from scipp.constants import h, m_n +from scipp.testing import assert_allclose, assert_identical +from scippnexus import NXsample +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 mirror_geometry +from ess.freia.types import ( + DownstreamSlitCenters, + MirrorNormal, + MirrorPosition, + 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'), + 'mirror': None + if mirror_tilt is None + 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))] + ), + ), + } + + +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['mirror'] = mirror_geometry( + 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', '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'] + if inversion: + wf[MirrorPosition[SampleRun]] = geometry['mirror'].position + wf[MirrorNormal[SampleRun]] = geometry['mirror'].normal + wf[Position[NXsample, SampleRun]] = geometry['sample_position'] + 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'] + 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/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..8b07c4952 --- /dev/null +++ b/packages/essreflectometry/tests/freia/mirror_test.py @@ -0,0 +1,407 @@ +# 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, + NeutronSourcePosition, + 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 ( + mirror_geometry, + reflected_upstream_position, +) +from ess.freia.types import ( + DetectorRegionOfInterest, + DownstreamSlitCenters, + MirrorGeometry, + 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 ordinary.compute(MirrorGeometry[SampleRun] | None) is None + inverted = factory(inversion=True) + _set_mirror(inverted) + assert_identical( + 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'), + ) + + +@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') + ) + 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.norm(downstream - reflected), sc.scalar(2.5 * np.sqrt(2), unit='m') + ) + + +@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_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): + 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( + 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'), + ) + + +def test_ordinary_path_preserves_positions_exactly(): + position = sc.vector([0.0, 1234.56789, -3456.78912], unit='mm') + assert_identical( + reflected_upstream_position(position, sc.vector([0.0, 0.0, 0.0], unit='m')), + position, + ) + + +def test_custom_conversion_pipeline_defaults_to_no_mirror(): + wf = sciline.Pipeline(conversions.providers, constraints={RunType: [SampleRun]}) + 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') + 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', '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 + 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') + ) + angle = np.deg2rad(80.0) + assert_allclose( + wf.compute(MirrorNormal[run]), sc.vector([0.0, np.sin(angle), -np.cos(angle)]) + ) + wf.compute(MirrorGeometry[run] | None) + + +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(MirrorGeometry[SampleRun] | None) + _set_mirror(wf) + wf.compute(MirrorGeometry[SampleRun] | None) + + +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[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]] = {} + # 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) + 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'), + ) + # 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')) + # 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(NeutronSourcePosition[run]), + sc.vector([0.0, 3.0, -4.0], 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[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]) + 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', ['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 diff --git a/packages/essreflectometry/tests/freia/workflow_test.py b/packages/essreflectometry/tests/freia/workflow_test.py index 44743d037..866684813 100644 --- a/packages/essreflectometry/tests/freia/workflow_test.py +++ b/packages/essreflectometry/tests/freia/workflow_test.py @@ -205,10 +205,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[NeutronSourcePosition[SampleRun]] = sc.vector([0.0, 0.0, -29.0], unit='m') wf[SampleSurfaceNormal[SampleRun]] = sc.vector([0.0, 1.0, 0.0]) @@ -272,10 +275,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) @@ -288,8 +299,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)