Exemplo n.º 1
0
def set_components_to_original_for_isis(move_info, workspace, component):
    """
    This function resets the components for ISIS instruments. These are normally HAB, LAB, the monitors and
    the sample holder

    :param move_info: a StateMove object.
    :param workspace: the workspace which is being reset.
    :param component: the component which is being reset on the workspace. If this is not specified, then
                      everything is being reset.
    """
    def _reset_detector(_key, _move_info, _component_names):
        if _key in _move_info.detectors:
            _detector_name = _move_info.detectors[_key].detector_name
            if _detector_name:
                _component_names.append(_detector_name)

    # We reset the HAB, the LAB, the sample holder and monitor 4
    if not component:
        component_names = list(move_info.monitor_names.values())

        hab_key = DetectorType.to_string(DetectorType.HAB)
        _reset_detector(hab_key, move_info, component_names)

        lab_key = DetectorType.to_string(DetectorType.LAB)
        _reset_detector(lab_key, move_info, component_names)

        component_names.append("some-sample-holder")
    else:
        component_names = [component]

    # We also want to check the sample holder
    set_selected_components_to_original_position(workspace, component_names)
Exemplo n.º 2
0
    def set_spectrum_range_on_detector(self, spectrum_range_start, spectrum_range_stop):
        """
        An unusual setter in the state framework. We cannot just call an automatic setter, since we have to decide
        on which detector the spectrum range lives.

        :param spectrum_range_start: a list of start spectra which we need to set on the right detector
        :param spectrum_range_stop: a list of stop spectra which we need to set on the right detector
        """
        instrument = self._data.instrument
        for start, stop in zip(spectrum_range_start, spectrum_range_stop):
            detector_bank_start = get_bank_for_spectrum_number(start, instrument)
            detector_bank_stop = get_bank_for_spectrum_number(stop, instrument)
            if detector_bank_start != detector_bank_stop:
                raise ValueError("The specified spectrum mask range S{0}{1} has spectra on more than one detector. "
                                 "Make sure that all spectra in the range are on a single detector".format(start, stop))
            else:
                detector_mask_state = self.state.detectors[DetectorType.to_string(detector_bank_start)]
                spec_range_start = detector_mask_state.spectrum_range_start
                spec_range_stop = detector_mask_state.spectrum_range_stop
                # Set the start spectrum range
                if spec_range_start is not None:
                    spec_range_start.append(start)
                else:
                    self.state.detectors[DetectorType.to_string(detector_bank_start)].spectrum_range_start = [start]

                # Set the stop spectrum range
                if spec_range_stop is not None:
                    spec_range_stop.append(stop)
                else:
                    self.state.detectors[DetectorType.to_string(detector_bank_start)].spectrum_range_stop = [stop]
    def PyInit(self):
        # ----------
        # INPUT
        # ----------
        # Workspace which is to be cropped
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        self.declareProperty(MatrixWorkspaceProperty("SampleScatterWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The sample scatter data')

        self.declareProperty(MatrixWorkspaceProperty('SampleScatterMonitorWorkspace', '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The scatter monitor workspace. This workspace only condtains monitors.')

        self.declareProperty("Centre1", 0.0, direction=Direction.InOut)
        self.declareProperty("Centre2", 0.0, direction=Direction.InOut)

        self.declareProperty("RMin", 0.06, direction=Direction.Input)

        self.declareProperty('Tolerance', 0.0001251, direction=Direction.Input)

        self.declareProperty('Iterations', 10, direction=Direction.Input)

        allowed_detectors = StringListValidator([DetectorType.to_string(DetectorType.LAB),
                                                 DetectorType.to_string(DetectorType.HAB)])
        self.declareProperty("Component", DetectorType.to_string(DetectorType.LAB),
                             validator=allowed_detectors, direction=Direction.Input,
                             doc="The component of the instrument which is to be reduced.")
Exemplo n.º 4
0
    def test_that_converter_methods_work(self):
        # Arrange
        state = StateReductionMode()

        state.reduction_mode = ISISReductionMode.Merged
        state.dimensionality = ReductionDimensionality.TwoDim
        state.merge_shift = 12.65
        state.merge_scale = 34.6
        state.merge_fit_mode = FitModeForMerge.ShiftOnly

        state.detector_names[DetectorType.to_string(DetectorType.LAB)] = "Test1"
        state.detector_names[DetectorType.to_string(DetectorType.HAB)] = "Test2"

        # Assert
        merge_strategy = state.get_merge_strategy()
        self.assertTrue(merge_strategy[0] is ISISReductionMode.LAB)
        self.assertTrue(merge_strategy[1] is ISISReductionMode.HAB)

        all_reductions = state.get_all_reduction_modes()
        self.assertTrue(len(all_reductions) == 2)
        self.assertTrue(all_reductions[0] is ISISReductionMode.LAB)
        self.assertTrue(all_reductions[1] is ISISReductionMode.HAB)

        result_lab = state.get_detector_name_for_reduction_mode(ISISReductionMode.LAB)
        self.assertTrue(result_lab == "Test1")
        result_hab = state.get_detector_name_for_reduction_mode(ISISReductionMode.HAB)
        self.assertTrue(result_hab == "Test2")

        self.assertRaises(RuntimeError, state.get_detector_name_for_reduction_mode, "non_sense")
    def test_that_wavelength_and_pixel_adjustment_state_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        file_information = SANSFileInformationMock(instrument=SANSInstrument.LOQ, run_number=74044)
        data_builder = get_data_builder(facility, file_information)
        data_builder.set_sample_scatter("LOQ74044")
        data_info = data_builder.build()

        # Act
        builder = get_wavelength_and_pixel_adjustment_builder(data_info)
        self.assertTrue(builder)

        builder.set_HAB_pixel_adjustment_file("test")
        builder.set_HAB_wavelength_adjustment_file("test2")
        builder.set_wavelength_low([1.5])
        builder.set_wavelength_high([2.7])
        builder.set_wavelength_step(0.5)
        builder.set_wavelength_step_type(RangeStepType.Lin)

        state = builder.build()

        # Assert
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
                                                                     DetectorType.HAB)].pixel_adjustment_file == "test")
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
                                                              DetectorType.HAB)].wavelength_adjustment_file == "test2")
        self.assertTrue(state.wavelength_low == [1.5])
        self.assertTrue(state.wavelength_high == [2.7])
        self.assertTrue(state.wavelength_step == 0.5)
        self.assertTrue(state.wavelength_step_type is RangeStepType.Lin)
Exemplo n.º 6
0
    def test_that_state_for_loq_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        file_information = SANSFileInformationMock(
            instrument=SANSInstrument.LOQ, run_number=74044)
        data_builder = get_data_builder(facility, file_information)
        data_builder.set_sample_scatter("LOQ74044")
        data_builder.set_sample_scatter_period(3)
        data_info = data_builder.build()

        # Act
        builder = get_move_builder(data_info)
        self.assertTrue(builder)
        value = 324.2
        builder.set_center_position(value)
        builder.set_HAB_x_translation_correction(value)
        builder.set_LAB_sample_centre_pos1(value)

        # Assert
        state = builder.build()
        self.assertEqual(state.center_position, value)
        self.assertEqual(
            state.detectors[DetectorType.to_string(
                DetectorType.HAB)].x_translation_correction, value)
        self.assertEqual(
            state.detectors[DetectorType.to_string(
                DetectorType.HAB)].detector_name_short, "HAB")
        self.assertEqual(
            state.detectors[DetectorType.to_string(
                DetectorType.LAB)].detector_name, "main-detector-bank")
        self.assertEqual(state.monitor_names[str(2)], "monitor2")
        self.assertEqual(len(state.monitor_names), 2)
        self.assertEqual(
            state.detectors[DetectorType.to_string(
                DetectorType.LAB)].sample_centre_pos1, value)
Exemplo n.º 7
0
    def __init__(self):
        super(StateMoveSANS2D, self).__init__()
        # Set the descriptors which corresponds to information which we gain through the IPF
        self.hab_detector_radius = 306.0 / 1000.
        self.hab_detector_default_sd_m = 4.0
        self.hab_detector_default_x_m = 1.1
        self.lab_detector_default_sd_m = 4.0

        # The actual values are found on the workspace and should be used from there. This is only a fall back.
        self.hab_detector_x = 0.0
        self.hab_detector_z = 0.0
        self.hab_detector_rotation = 0.0
        self.lab_detector_x = 0.0
        self.lab_detector_z = 0.0

        # Set the monitor names
        self.monitor_names = {}

        self.monitor_n_offset = 0.0

        # Setup the detectors
        self.detectors = {
            DetectorType.to_string(DetectorType.LAB): StateMoveDetector(),
            DetectorType.to_string(DetectorType.HAB): StateMoveDetector()
        }
Exemplo n.º 8
0
    def PyInit(self):
        # State
        self.declareProperty(
            PropertyManagerProperty('SANSState'),
            doc='A property manager which fulfills the SANSState contract.')

        # Workspace which is to be masked
        self.declareProperty(
            MatrixWorkspaceProperty("Workspace",
                                    '',
                                    optional=PropertyMode.Mandatory,
                                    direction=Direction.InOut),
            doc=
            'The sample scatter workspace. This workspace does not contain monitors.'
        )

        # The component, i.e. HAB or LAB
        allowed_detectors = StringListValidator([
            DetectorType.to_string(DetectorType.LAB),
            DetectorType.to_string(DetectorType.HAB)
        ])
        self.declareProperty(
            "Component",
            DetectorType.to_string(DetectorType.LAB),
            validator=allowed_detectors,
            direction=Direction.Input,
            doc="The component of the instrument which is to be masked.")
Exemplo n.º 9
0
def run_integral(integral_ranges, mask, integral, detector, state):
    ranges = parse_range(integral_ranges)
    input_workspaces = load_workspace(state)

    is_multi_range = len(ranges) > 1

    output_workspaces = []
    for input_workspace in input_workspaces:
        input_workspace_name = input_workspace.name()
        if is_multi_range:
            AnalysisDataService.remove(input_workspace_name + '_ranges')
        input_workspace = crop_workspace(DetectorType.to_string(detector),
                                         input_workspace)

        if mask:
            input_workspace = apply_mask(state, input_workspace,
                                         DetectorType.to_string(detector))

        x_dim, y_dim = get_detector_size_from_sans_file(state, detector)

        output_workspace = integrate_ranges(ranges, integral, mask, detector,
                                            input_workspace_name,
                                            input_workspace, x_dim, y_dim,
                                            is_multi_range)
        plot_graph(output_workspace)

        output_workspaces.append(output_workspace)

    return output_workspaces
Exemplo n.º 10
0
    def do_move_initial(self, move_info, workspace, coordinates, component, is_transmission_workspace):
        # For LOQ we only have two coordinates
        assert len(coordinates) == 2
        if not is_transmission_workspace:
            # First move the sample holder
            move_sample_holder(workspace, move_info.sample_offset, move_info.sample_offset_direction)

            x = coordinates[0]
            y = coordinates[1]
            center_position = move_info.center_position

            x_shift = center_position - x
            y_shift = center_position - y

            detectors = [DetectorType.to_string(DetectorType.LAB), DetectorType.to_string(DetectorType.HAB)]
            for detector in detectors:
                # Get the detector name
                component_name = move_info.detectors[detector].detector_name

                # Shift the detector by the the input amount
                offset = {CanonicalCoordinates.X: x_shift,
                          CanonicalCoordinates.Y: y_shift}
                move_component(workspace, offset, component_name)

                # Shift the detector according to the corrections of the detector under investigation
                offset_from_corrections = {CanonicalCoordinates.X: move_info.detectors[detector].x_translation_correction,
                                           CanonicalCoordinates.Y: move_info.detectors[detector].y_translation_correction,
                                           CanonicalCoordinates.Z: move_info.detectors[detector].z_translation_correction}
                move_component(workspace, offset_from_corrections, component_name)
    def test_that_wavelength_and_pixel_adjustment_state_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        data_builder = get_data_builder(facility)
        data_builder.set_sample_scatter("LOQ74044")
        data_info = data_builder.build()

        # Act
        builder = get_wavelength_and_pixel_adjustment_builder(data_info)
        self.assertTrue(builder)

        builder.set_HAB_pixel_adjustment_file("test")
        builder.set_HAB_wavelength_adjustment_file("test2")
        builder.set_wavelength_low(1.5)
        builder.set_wavelength_high(2.7)
        builder.set_wavelength_step(0.5)
        builder.set_wavelength_step_type(RangeStepType.Lin)

        state = builder.build()

        # Assert
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
            DetectorType.HAB)].pixel_adjustment_file == "test")
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
            DetectorType.HAB)].wavelength_adjustment_file == "test2")
        self.assertTrue(state.wavelength_low == 1.5)
        self.assertTrue(state.wavelength_high == 2.7)
        self.assertTrue(state.wavelength_step == 0.5)
        self.assertTrue(state.wavelength_step_type is RangeStepType.Lin)
    def _run_test(state, sample_data, sample_monitor_data, transmission_data, direct_data, is_lab=True, is_sample=True):
        adjustment_name = "SANSCreateAdjustmentWorkspaces"
        adjustment_options = {"SANSState": state,
                              "SampleData": sample_data,
                              "MonitorWorkspace": sample_monitor_data,
                              "TransmissionWorkspace": transmission_data,
                              "DirectWorkspace": direct_data,
                              "OutputWorkspaceWavelengthAdjustment": EMPTY_NAME,
                              "OutputWorkspacePixelAdjustment": EMPTY_NAME,
                              "OutputWorkspaceWavelengthAndPixelAdjustment": EMPTY_NAME}
        if is_sample:
            adjustment_options.update({"DataType": DataType.to_string(DataType.Sample)})
        else:
            adjustment_options.update({"DataType": DataType.to_string(DataType.Can)})
        if is_lab:
            adjustment_options.update({"Component": DetectorType.to_string(DetectorType.LAB)})
        else:
            adjustment_options.update({"Component": DetectorType.to_string(DetectorType.HAB)})

        adjustment_alg = create_unmanaged_algorithm(adjustment_name, **adjustment_options)
        adjustment_alg.execute()
        wavelength_adjustment = adjustment_alg.getProperty("OutputWorkspaceWavelengthAdjustment").value
        pixel_adjustment = adjustment_alg.getProperty("OutputWorkspacePixelAdjustment").value
        wavelength_and_pixel_adjustment = adjustment_alg.getProperty(
                                                            "OutputWorkspaceWavelengthAndPixelAdjustment").value
        calculated_transmission = adjustment_alg.getProperty("CalculatedTransmissionWorkspace").value
        unfitted_transmission = adjustment_alg.getProperty("UnfittedTransmissionWorkspace").value
        return wavelength_adjustment, pixel_adjustment, wavelength_and_pixel_adjustment,\
               calculated_transmission, unfitted_transmission
Exemplo n.º 13
0
    def _get_mask_state(general_entries, detector_entries):
        state = StateMask()
        # Setup the general mask settings
        mask_settings = {"radius_min": 12., "radius_max": 17.,
                         "bin_mask_general_start": [1., 2., 3.], "bin_mask_general_stop": [2., 3., 4.],
                         "mask_files": None,
                         "phi_min": 0.5, "phi_max": 1., "use_mask_phi_mirror": True,
                         "beam_stop_arm_width": 1., "beam_stop_arm_angle": 24.5, "beam_stop_arm_pos1": 12.,
                         "beam_stop_arm_pos2": 34.,
                         "clear": False, "clear_time": False, "single_spectra": [1, 4, 6],
                         "spectrum_range_start": [1, 5, 7], "spectrum_range_stop": [2, 6, 8],
                         "idf_path": ""}

        for key, value in mask_settings.items():
            if key in general_entries:
                value = general_entries[key]
            if value is not None:  # If the value is None, then don't set it
                setattr(state, key, value)

        # Now setup the detector-specific settings
        detector_settings = {"single_vertical_strip_mask": [1, 2, 4], "range_vertical_strip_start": [1, 2, 4],
                             "range_vertical_strip_stop": [2, 3, 5], "single_horizontal_strip_mask": [1, 2, 4],
                             "range_horizontal_strip_start": [1, 2, 4], "range_horizontal_strip_stop": [2, 3, 5],
                             "block_horizontal_start": [1, 2, 4], "block_horizontal_stop": [2, 3, 5],
                             "block_vertical_start": [1, 2, 4], "block_vertical_stop": [2, 3, 5],
                             "block_cross_horizontal": [1, 2, 4], "block_cross_vertical": [2, 3, 5],
                             "bin_mask_start": [1., 2., 4.], "bin_mask_stop": [2., 3., 5.],
                             "detector_name": "name", "detector_name_short": "name_short"}

        StateMaskTest._set_detector(state, detector_settings, detector_entries,
                                    DetectorType.to_string(DetectorType.LAB))
        StateMaskTest._set_detector(state, detector_settings, detector_entries,
                                    DetectorType.to_string(DetectorType.HAB))

        return state
Exemplo n.º 14
0
def run_integral(integral_ranges, mask, integral, detector, state):
    ranges = parse_range(integral_ranges)
    input_workspaces = load_workspace(state)

    is_multi_range = len (ranges) > 1

    output_workspaces = []
    for input_workspace in input_workspaces:
        input_workspace_name = input_workspace.name()
        if is_multi_range:
            AnalysisDataService.remove(input_workspace_name + '_ranges')
        input_workspace = crop_workspace(DetectorType.to_string(detector), input_workspace)

        if mask:
            input_workspace = apply_mask(state, input_workspace, DetectorType.to_string(detector))

        x_dim, y_dim = get_detector_size_from_sans_file(state, detector)

        output_workspace = integrate_ranges(ranges, integral, mask, detector, input_workspace_name, input_workspace, x_dim, y_dim,
                                            is_multi_range)
        plot_graph(output_workspace)

        output_workspaces.append(output_workspace)

    return output_workspaces
Exemplo n.º 15
0
    def _run_test(state, sample_data, sample_monitor_data, transmission_data, direct_data, is_lab=True, is_sample=True):
        adjustment_name = "SANSCreateAdjustmentWorkspaces"
        adjustment_options = {"SANSState": state,
                              "SampleData": sample_data,
                              "MonitorWorkspace": sample_monitor_data,
                              "TransmissionWorkspace": transmission_data,
                              "DirectWorkspace": direct_data,
                              "OutputWorkspaceWavelengthAdjustment": EMPTY_NAME,
                              "OutputWorkspacePixelAdjustment": EMPTY_NAME,
                              "OutputWorkspaceWavelengthAndPixelAdjustment": EMPTY_NAME}
        if is_sample:
            adjustment_options.update({"DataType": DataType.to_string(DataType.Sample)})
        else:
            adjustment_options.update({"DataType": DataType.to_string(DataType.Can)})
        if is_lab:
            adjustment_options.update({"Component": DetectorType.to_string(DetectorType.LAB)})
        else:
            adjustment_options.update({"Component": DetectorType.to_string(DetectorType.HAB)})

        adjustment_alg = create_unmanaged_algorithm(adjustment_name, **adjustment_options)
        adjustment_alg.execute()
        wavelength_adjustment = adjustment_alg.getProperty("OutputWorkspaceWavelengthAdjustment").value
        pixel_adjustment = adjustment_alg.getProperty("OutputWorkspacePixelAdjustment").value
        wavelength_and_pixel_adjustment = adjustment_alg.getProperty(
                                                            "OutputWorkspaceWavelengthAndPixelAdjustment").value
        calculated_transmission = adjustment_alg.getProperty("CalculatedTransmissionWorkspace").value
        unfitted_transmission = adjustment_alg.getProperty("UnfittedTransmissionWorkspace").value
        return wavelength_adjustment, pixel_adjustment, wavelength_and_pixel_adjustment,\
               calculated_transmission, unfitted_transmission
Exemplo n.º 16
0
 def __init__(self):
     super(StateMaskLOQ, self).__init__()
     # Setup the detectors
     self.detectors = {
         DetectorType.to_string(DetectorType.LAB): StateMaskDetector(),
         DetectorType.to_string(DetectorType.HAB): StateMaskDetector()
     }
Exemplo n.º 17
0
    def test_that_wavelength_and_pixel_adjustment_state_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        data_builder = get_data_builder(facility)
        data_builder.set_sample_scatter("LOQ74044")
        data_info = data_builder.build()

        # Act
        builder = get_wavelength_and_pixel_adjustment_builder(data_info)
        self.assertTrue(builder)

        builder.set_HAB_pixel_adjustment_file("test")
        builder.set_HAB_wavelength_adjustment_file("test2")
        builder.set_wavelength_low(1.5)
        builder.set_wavelength_high(2.7)
        builder.set_wavelength_step(0.5)
        builder.set_wavelength_step_type(RangeStepType.Lin)

        state = builder.build()

        # Assert
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
                                                                     DetectorType.HAB)].pixel_adjustment_file == "test")
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
                                                              DetectorType.HAB)].wavelength_adjustment_file == "test2")
        self.assertTrue(state.wavelength_low == 1.5)
        self.assertTrue(state.wavelength_high == 2.7)
        self.assertTrue(state.wavelength_step == 0.5)
        self.assertTrue(state.wavelength_step_type is RangeStepType.Lin)
    def PyInit(self):
        # State
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')
        # Input workspaces
        workspace_validator = CompositeValidator()
        workspace_validator.add(WorkspaceUnitValidator("Wavelength"))

        self.declareProperty(MatrixWorkspaceProperty("TransmissionWorkspace", '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input,
                                                     validator=workspace_validator),
                             doc='The calculated transmission workspace in wavelength units.')
        self.declareProperty(MatrixWorkspaceProperty("NormalizeToMonitorWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input,
                                                     validator=workspace_validator),
                             doc='The monitor normalization workspace in wavelength units.')
        allowed_detector_types = StringListValidator([DetectorType.to_string(DetectorType.HAB),
                                                      DetectorType.to_string(DetectorType.LAB)])
        self.declareProperty("Component", DetectorType.to_string(DetectorType.LAB),
                             validator=allowed_detector_types, direction=Direction.Input,
                             doc="The component of the instrument which is currently being investigated.")

        # Output workspace
        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspaceWavelengthAdjustment", '',
                                                     direction=Direction.Output),
                             doc='A wavelength adjustment output workspace.')
        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspacePixelAdjustment", '',
                                                     direction=Direction.Output),
                             doc='A pixel adjustment output workspace.')
Exemplo n.º 19
0
    def do_move_initial(self, move_info, workspace, coordinates, component, is_transmission_workspace):
        _is_transmission_workspace = is_transmission_workspace  # noqa

        # For LARMOR we only have to coordinates
        assert len(coordinates) == 2

        # Move the sample holder
        move_sample_holder(workspace, move_info.sample_offset, move_info.sample_offset_direction)

        # Shift the low-angle bank detector in the y direction
        y_shift = -coordinates[1]
        coordinates_for_only_y = [0.0, y_shift]
        apply_standard_displacement(move_info, workspace, coordinates_for_only_y,
                                    DetectorType.to_string(DetectorType.LAB))

        # Shift the low-angle bank detector in the x direction
        angle = coordinates[0]

        bench_rot_tag = "Bench_Rot"
        log_names = [bench_rot_tag]
        log_types = [float]
        log_values = get_single_valued_logs_from_workspace(workspace, log_names, log_types)
        bench_rotation = move_info.bench_rotation \
            if log_values[bench_rot_tag] is None else log_values[bench_rot_tag]

        self._rotate_around_y_axis(move_info, workspace, angle,
                                   DetectorType.to_string(DetectorType.LAB), bench_rotation)
Exemplo n.º 20
0
    def test_that_state_for_loq_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        data_builder = get_data_builder(facility)
        data_builder.set_sample_scatter("LOQ74044")
        data_builder.set_sample_scatter_period(3)
        data_info = data_builder.build()

        # Act
        builder = get_move_builder(data_info)
        self.assertTrue(builder)
        value = 324.2
        builder.set_center_position(value)
        builder.set_HAB_x_translation_correction(value)
        builder.set_LAB_sample_centre_pos1(value)

        # Assert
        state = builder.build()
        self.assertTrue(state.center_position == value)
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.HAB)].x_translation_correction == value)
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.HAB)].detector_name_short == "HAB")
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.LAB)].detector_name == "main-detector-bank")
        self.assertTrue(state.monitor_names[str(2)] == "monitor2")
        self.assertTrue(len(state.monitor_names) == 2)
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.LAB)].sample_centre_pos1 == value)
Exemplo n.º 21
0
def set_components_to_original_for_isis(move_info, workspace, component):
    """
    This function resets the components for ISIS instruments. These are normally HAB, LAB, the monitors and
    the sample holder

    :param move_info: a StateMove object.
    :param workspace: the workspace which is being reset.
    :param component: the component which is being reset on the workspace. If this is not specified, then
                      everything is being reset.
    """
    def _reset_detector(_key, _move_info, _component_names):
        if _key in _move_info.detectors:
            _detector_name = _move_info.detectors[_key].detector_name
            if _detector_name:
                _component_names.append(_detector_name)

    # We reset the HAB, the LAB, the sample holder and monitor 4
    if not component:
        component_names = list(move_info.monitor_names.values())

        hab_key = DetectorType.to_string(DetectorType.HAB)
        _reset_detector(hab_key, move_info, component_names)

        lab_key = DetectorType.to_string(DetectorType.LAB)
        _reset_detector(lab_key, move_info, component_names)

        component_names.append("some-sample-holder")
    else:
        component_names = [component]

    # We also want to check the sample holder
    set_selected_components_to_original_position(workspace, component_names)
Exemplo n.º 22
0
    def test_that_converter_methods_work(self):
        # Arrange
        state = StateReductionMode()

        state.reduction_mode = ISISReductionMode.Merged
        state.dimensionality = ReductionDimensionality.TwoDim
        state.merge_shift = 12.65
        state.merge_scale = 34.6
        state.merge_fit_mode = FitModeForMerge.ShiftOnly

        state.detector_names[DetectorType.to_string(DetectorType.LAB)] = "Test1"
        state.detector_names[DetectorType.to_string(DetectorType.HAB)] = "Test2"

        state.merge_mask = True
        state.merge_min = 78.89
        state.merge_max = 56.4


        # Assert
        merge_strategy = state.get_merge_strategy()
        self.assertTrue(merge_strategy[0] is ISISReductionMode.LAB)
        self.assertTrue(merge_strategy[1] is ISISReductionMode.HAB)

        all_reductions = state.get_all_reduction_modes()
        self.assertTrue(len(all_reductions) == 2)
        self.assertTrue(all_reductions[0] is ISISReductionMode.LAB)
        self.assertTrue(all_reductions[1] is ISISReductionMode.HAB)

        result_lab = state.get_detector_name_for_reduction_mode(ISISReductionMode.LAB)
        self.assertTrue(result_lab == "Test1")
        result_hab = state.get_detector_name_for_reduction_mode(ISISReductionMode.HAB)
        self.assertTrue(result_hab == "Test2")

        self.assertRaises(RuntimeError, state.get_detector_name_for_reduction_mode, "non_sense")
Exemplo n.º 23
0
    def test_that_state_for_loq_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        data_builder = get_data_builder(facility)
        data_builder.set_sample_scatter("LOQ74044")
        data_builder.set_sample_scatter_period(3)
        data_info = data_builder.build()

        # Act
        builder = get_move_builder(data_info)
        self.assertTrue(builder)
        value = 324.2
        builder.set_center_position(value)
        builder.set_HAB_x_translation_correction(value)
        builder.set_LAB_sample_centre_pos1(value)

        # Assert
        state = builder.build()
        self.assertTrue(state.center_position == value)
        self.assertTrue(state.detectors[DetectorType.to_string(DetectorType.HAB)].x_translation_correction == value)
        self.assertTrue(state.detectors[DetectorType.to_string(DetectorType.HAB)].detector_name_short == "HAB")
        self.assertTrue(state.detectors[DetectorType.to_string(DetectorType.LAB)].detector_name == "main-detector-bank")
        self.assertTrue(state.monitor_names[str(2)] == "monitor2")
        self.assertTrue(len(state.monitor_names) == 2)
        self.assertTrue(state.detectors[DetectorType.to_string(DetectorType.LAB)].sample_centre_pos1 == value)
Exemplo n.º 24
0
    def test_that_missing_beam_centre_is_taken_from_lab_move_state_when_no_component_is_specified(self):
        # Arrange
        file_name = "SANS2D00028784"
        lab_z_translation_correction = 123.

        workspace = load_workspace(file_name)
        state = SANSMoveTest._get_simple_state(sample_scatter=file_name,
                                               lab_z_translation_correction=lab_z_translation_correction)
        # These values should be used instead of an explicitly specified beam centre
        state.move.detectors[DetectorType.to_string(DetectorType.LAB)].sample_centre_pos1 = 26.
        state.move.detectors[DetectorType.to_string(DetectorType.LAB)].sample_centre_pos2 = 98.

        # Act
        # The component input is not relevant for SANS2D's initial move. All detectors are moved
        component = None
        self._run_move(state, workspace=workspace, move_type="InitialMove", component=component)

        # Assert for initial move for low angle bank
        # These values are on the workspace and in the sample logs,
        component_to_investigate = DetectorType.to_string(DetectorType.LAB)
        initial_z_position = 23.281
        rear_det_z = 11.9989755859
        offset = 4.
        total_x = 0.
        total_y = 0.
        total_z = initial_z_position + rear_det_z - offset + lab_z_translation_correction
        expected_position = V3D(total_x - 26., total_y - 98., total_z)
        expected_rotation = Quat(1., 0., 0., 0.)
        self.compare_expected_position(expected_position, expected_rotation,
                                       component_to_investigate, state.move, workspace)
    def validate(self):
        is_invalid = {}

        if one_is_none([self.wavelength_low, self.wavelength_high, self.wavelength_step, self.wavelength_step_type]):
            entry = validation_message("A wavelength entry has not been set.",
                                       "Make sure that all entries are set.",
                                       {"wavelength_low": self.wavelength_low,
                                        "wavelength_high": self.wavelength_high,
                                        "wavelength_step": self.wavelength_step,
                                        "wavelength_step_type": self.wavelength_step_type})
            is_invalid.update(entry)

        if is_not_none_and_first_larger_than_second([self.wavelength_low, self.wavelength_high]):
            entry = validation_message("Incorrect wavelength bounds.",
                                       "Make sure that lower wavelength bound is smaller then upper bound.",
                                       {"wavelength_low": self.wavelength_low,
                                        "wavelength_high": self.wavelength_high})
            is_invalid.update(entry)

        try:
            self.adjustment_files[DetectorType.to_string(DetectorType.LAB)].validate()
            self.adjustment_files[DetectorType.to_string(DetectorType.HAB)].validate()
        except ValueError as e:
            is_invalid.update({"adjustment_files": str(e)})

        if is_invalid:
            raise ValueError("StateWavelengthAndPixelAdjustment: The provided inputs are illegal. "
                             "Please see: {0}".format(json.dumps(is_invalid)))
Exemplo n.º 26
0
    def do_move_initial(self, move_info, workspace, coordinates, component,
                        is_transmission_workspace):
        _is_transmission_workspace = is_transmission_workspace  # noqa

        # For LARMOR we only have to coordinates
        assert len(coordinates) == 2

        # Move the sample holder
        move_sample_holder(workspace, move_info.sample_offset,
                           move_info.sample_offset_direction)

        # Shift the low-angle bank detector in the y direction
        y_shift = -coordinates[1]
        coordinates_for_only_y = [0.0, y_shift]
        apply_standard_displacement(move_info, workspace,
                                    coordinates_for_only_y,
                                    DetectorType.to_string(DetectorType.LAB))

        # Shift the low-angle bank detector in the x direction
        angle = coordinates[0]

        bench_rot_tag = "Bench_Rot"
        log_names = [bench_rot_tag]
        log_types = [float]
        log_values = get_single_valued_logs_from_workspace(
            workspace, log_names, log_types)
        bench_rotation = move_info.bench_rotation \
            if log_values[bench_rot_tag] is None else log_values[bench_rot_tag]

        self._rotate_around_y_axis(move_info, workspace, angle,
                                   DetectorType.to_string(DetectorType.LAB),
                                   bench_rotation)
Exemplo n.º 27
0
    def test_that_missing_beam_centre_is_taken_from_move_state(self):
        # Arrange
        file_name = "SANS2D00028784"
        lab_z_translation_correction = 123.

        workspace = load_workspace(file_name)
        state = SANSMoveTest._get_simple_state(sample_scatter=file_name,
                                               lab_z_translation_correction=lab_z_translation_correction)
        # These values should be used instead of an explicitly specified beam centre
        state.move.detectors[DetectorType.to_string(DetectorType.HAB)].sample_centre_pos1 = 26.
        state.move.detectors[DetectorType.to_string(DetectorType.HAB)].sample_centre_pos2 = 98.

        # Act
        # The component input is not relevant for SANS2D's initial move. All detectors are moved
        component = "front-detector"
        self._run_move(state, workspace=workspace, move_type="InitialMove", component=component)

        # Assert for initial move for high angle bank
        # These values are on the workspace and in the sample logs
        component_to_investigate = DetectorType.to_string(DetectorType.HAB)
        initial_x_position = 1.1
        x_correction = -0.187987540973
        initial_z_position = 23.281
        z_correction = 1.00575649188
        total_x = initial_x_position + x_correction
        total_y = 0.
        total_z = initial_z_position + z_correction
        expected_position = V3D(total_x - 26., total_y - 98., total_z)
        expected_rotation = Quat(0.9968998362876025, 0., 0.07868110579898738, 0.)
        self.compare_expected_position(expected_position, expected_rotation,
                                       component_to_investigate, state.move, workspace)
Exemplo n.º 28
0
    def set_spectrum_range_on_detector(self, spectrum_range_start, spectrum_range_stop):
        """
        An unusual setter in the state framework. We cannot just call an automatic setter, since we have to decide
        on which detector the spectrum range lives.

        :param spectrum_range_start: a list of start spectra which we need to set on the right detector
        :param spectrum_range_stop: a list of stop spectra which we need to set on the right detector
        """
        instrument = self._data.instrument
        for start, stop in zip(spectrum_range_start, spectrum_range_stop):
            detector_bank_start = get_bank_for_spectrum_number(start, instrument)
            detector_bank_stop = get_bank_for_spectrum_number(stop, instrument)
            if detector_bank_start != detector_bank_stop:
                raise ValueError("The specified spectrum mask range S{0}{1} has spectra on more than one detector. "
                                 "Make sure that all spectra in the range are on a single detector".format(start, stop))
            else:
                detector_mask_state = self.state.detectors[DetectorType.to_string(detector_bank_start)]
                spec_range_start = detector_mask_state.spectrum_range_start
                spec_range_stop = detector_mask_state.spectrum_range_stop
                # Set the start spectrum range
                if spec_range_start is not None:
                    spec_range_start.append(start)
                else:
                    self.state.detectors[DetectorType.to_string(detector_bank_start)].spectrum_range_start = [start]

                # Set the stop spectrum range
                if spec_range_stop is not None:
                    spec_range_stop.append(stop)
                else:
                    self.state.detectors[DetectorType.to_string(detector_bank_start)].spectrum_range_stop = [stop]
    def PyInit(self):
        # ----------
        # INPUT
        # ----------
        # Workspace which is to be cropped
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        self.declareProperty(MatrixWorkspaceProperty("SampleScatterWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The sample scatter data')

        self.declareProperty(MatrixWorkspaceProperty('SampleScatterMonitorWorkspace', '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The scatter monitor workspace. This workspace only condtains monitors.')

        self.declareProperty("Centre1", 0.0, direction=Direction.InOut)
        self.declareProperty("Centre2", 0.0, direction=Direction.InOut)

        self.declareProperty("RMin", 0.06, direction=Direction.Input)

        self.declareProperty('Tolerance', 0.0001251, direction=Direction.Input)

        self.declareProperty('Iterations', 10, direction=Direction.Input)

        allowed_detectors = StringListValidator([DetectorType.to_string(DetectorType.LAB),
                                                 DetectorType.to_string(DetectorType.HAB)])
        self.declareProperty("Component", DetectorType.to_string(DetectorType.LAB),
                             validator=allowed_detectors, direction=Direction.Input,
                             doc="The component of the instrument which is to be reduced.")
Exemplo n.º 30
0
def set_detector_names(state, ipf_path):
    """
    Sets the detectors names on a State object which has a `detector` map entry, e.g. StateMask

    @param state: the state object
    @param ipf_path: the path to the Instrument Parameter File
    """
    lab_keyword = DetectorType.to_string(DetectorType.LAB)
    hab_keyword = DetectorType.to_string(DetectorType.HAB)
    detector_names = {lab_keyword: "low-angle-detector-name",
                      hab_keyword: "high-angle-detector-name"}
    detector_names_short = {lab_keyword: "low-angle-detector-short-name",
                            hab_keyword: "high-angle-detector-short-name"}

    names_to_search = []
    names_to_search.extend(detector_names.values())
    names_to_search.extend(detector_names_short.values())

    found_detector_names = get_named_elements_from_ipf_file(ipf_path, names_to_search, str)

    for detector_type in state.detectors:
        try:
            detector_name_tag = detector_names[detector_type]
            detector_name_short_tag = detector_names_short[detector_type]
            detector_name = found_detector_names[detector_name_tag]
            detector_name_short = found_detector_names[detector_name_short_tag]
        except KeyError:
            continue

        state.detectors[detector_type].detector_name = detector_name
        state.detectors[detector_type].detector_name_short = detector_name_short
Exemplo n.º 31
0
    def test_that_wavelength_and_pixel_adjustment_state_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        file_information = SANSFileInformationMock(
            instrument=SANSInstrument.LOQ, run_number=74044)
        data_builder = get_data_builder(facility, file_information)
        data_builder.set_sample_scatter("LOQ74044")
        data_info = data_builder.build()

        # Act
        builder = get_wavelength_and_pixel_adjustment_builder(data_info)
        self.assertTrue(builder)

        builder.set_HAB_pixel_adjustment_file("test")
        builder.set_HAB_wavelength_adjustment_file("test2")
        builder.set_wavelength_low([1.5])
        builder.set_wavelength_high([2.7])
        builder.set_wavelength_step(0.5)
        builder.set_wavelength_step_type(RangeStepType.Lin)

        state = builder.build()

        # Assert
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
            DetectorType.HAB)].pixel_adjustment_file == "test")
        self.assertTrue(state.adjustment_files[DetectorType.to_string(
            DetectorType.HAB)].wavelength_adjustment_file == "test2")
        self.assertTrue(state.wavelength_low == [1.5])
        self.assertTrue(state.wavelength_high == [2.7])
        self.assertTrue(state.wavelength_step == 0.5)
        self.assertTrue(state.wavelength_step_type is RangeStepType.Lin)
Exemplo n.º 32
0
    def test_that_state_for_sans2d_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        file_information = SANSFileInformationMock(
            instrument=SANSInstrument.SANS2D, run_number=22048)
        data_builder = get_data_builder(facility, file_information)
        data_builder.set_sample_scatter("SANS2D00022048")
        data_info = data_builder.build()

        # Act
        builder = get_move_builder(data_info)
        self.assertTrue(builder)
        value = 324.2
        builder.set_HAB_x_translation_correction(value)

        # Assert
        state = builder.build()
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.HAB)].x_translation_correction == value)
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.HAB)].detector_name_short == "front")
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.LAB)].detector_name == "rear-detector")
        self.assertTrue(state.monitor_names[str(4)] == "monitor4")
        self.assertTrue(len(state.monitor_names) == 4)
Exemplo n.º 33
0
    def PyInit(self):
        # ----------
        # INPUT
        # ----------
        # Workspace which is to be cropped
        self.declareProperty(MatrixWorkspaceProperty(
            "InputWorkspace",
            '',
            optional=PropertyMode.Mandatory,
            direction=Direction.Input),
                             doc='The input workspace')

        # The component, i.e. HAB or LAB
        allowed_detectors = StringListValidator([
            DetectorType.to_string(DetectorType.LAB),
            DetectorType.to_string(DetectorType.HAB)
        ])
        self.declareProperty(
            "Component",
            DetectorType.to_string(DetectorType.LAB),
            validator=allowed_detectors,
            direction=Direction.Input,
            doc="The component of the instrument to which we want to crop.")

        self.declareProperty(MatrixWorkspaceProperty(
            "OutputWorkspace",
            '',
            optional=PropertyMode.Mandatory,
            direction=Direction.Output),
                             doc='The cropped output workspace')
Exemplo n.º 34
0
    def test_that_state_for_larmor_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        file_information = SANSFileInformationMock(
            instrument=SANSInstrument.LARMOR, run_number=2260)
        data_builder = get_data_builder(facility, file_information)
        data_builder.set_sample_scatter("LARMOR00002260")
        data_info = data_builder.build()

        # Act
        builder = get_move_builder(data_info)
        self.assertTrue(builder)
        value = 324.2
        builder.set_LAB_x_translation_correction(value)

        # Assert
        state = builder.build()
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.LAB)].x_translation_correction == value)
        self.assertTrue(state.detectors[DetectorType.to_string(
            DetectorType.LAB)].detector_name == "DetectorBench")
        self.assertTrue(
            DetectorType.to_string(DetectorType.HAB) not in state.detectors)
        self.assertTrue(state.monitor_names[str(5)] == "monitor5")
        self.assertTrue(len(state.monitor_names) == 5)
Exemplo n.º 35
0
    def do_move_initial(self, move_info, workspace, coordinates, component, is_transmission_workspace):
        # For LOQ we only have to coordinates
        assert len(coordinates) == 2

        if not is_transmission_workspace:
            # First move the sample holder
            move_sample_holder(workspace, move_info.sample_offset, move_info.sample_offset_direction)

            x = coordinates[0]
            y = coordinates[1]
            center_position = move_info.center_position

            x_shift = center_position - x
            y_shift = center_position - y

            detectors = [DetectorType.to_string(DetectorType.LAB), DetectorType.to_string(DetectorType.HAB)]
            for detector in detectors:
                # Get the detector name
                component_name = move_info.detectors[detector].detector_name

                # Shift the detector by the the input amount
                offset = {CanonicalCoordinates.X: x_shift,
                          CanonicalCoordinates.Y: y_shift}
                move_component(workspace, offset, component_name)

                # Shift the detector according to the corrections of the detector under investigation
                offset_from_corrections = {CanonicalCoordinates.X: move_info.detectors[detector].x_translation_correction,
                                           CanonicalCoordinates.Y: move_info.detectors[detector].y_translation_correction,
                                           CanonicalCoordinates.Z: move_info.detectors[detector].z_translation_correction}
                move_component(workspace, offset_from_corrections, component_name)
Exemplo n.º 36
0
 def test_that_raises_if_the_short_detector_name_is_not_set_up(self):
     state = StateMove()
     state.detectors[DetectorType.to_string(DetectorType.HAB)].detector_name = "test"
     state.detectors[DetectorType.to_string(DetectorType.LAB)].detector_name = "test"
     state.detectors[DetectorType.to_string(DetectorType.HAB)].detector_name_short = "test"
     assert_validate_error(self, ValueError, state)
     state.detectors[DetectorType.to_string(DetectorType.LAB)].detector_name_short = "test"
     assert_raises_nothing(self, state)
Exemplo n.º 37
0
    def PyInit(self):
        # ----------
        # INPUT
        # ----------
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        # WORKSPACES
        # Scatter Workspaces
        self.declareProperty(MatrixWorkspaceProperty('ScatterWorkspace', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The scatter workspace. This workspace does not contain monitors.')
        self.declareProperty(MatrixWorkspaceProperty('ScatterMonitorWorkspace', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The scatter monitor workspace. This workspace only contains monitors.')

        # Transmission Workspace
        self.declareProperty(MatrixWorkspaceProperty('TransmissionWorkspace', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The transmission workspace.')

        # Direct Workspace
        self.declareProperty(MatrixWorkspaceProperty('DirectWorkspace', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The direct workspace.')

        self.setPropertyGroup("ScatterWorkspace", 'Data')
        self.setPropertyGroup("ScatterMonitorWorkspace", 'Data')
        self.setPropertyGroup("TransmissionWorkspace", 'Data')
        self.setPropertyGroup("DirectWorkspace", 'Data')

        # The component
        allowed_detectors = StringListValidator([DetectorType.to_string(DetectorType.LAB),
                                                 DetectorType.to_string(DetectorType.HAB)])
        self.declareProperty("Component", DetectorType.to_string(DetectorType.LAB),
                             validator=allowed_detectors, direction=Direction.Input,
                             doc="The component of the instrument which is to be reduced.")

        # The data type
        allowed_data = StringListValidator([DataType.to_string(DataType.Sample),
                                            DataType.to_string(DataType.Can)])
        self.declareProperty("DataType", DataType.to_string(DataType.Sample),
                             validator=allowed_data, direction=Direction.Input,
                             doc="The component of the instrument which is to be reduced.")

        # ----------
        # OUTPUT
        # ----------
        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", '', direction=Direction.Output),
                             doc='The output workspace.')

        self.declareProperty(MatrixWorkspaceProperty('SumOfCounts', '', optional=PropertyMode.Optional,
                                                     direction=Direction.Output),
                             doc='The sum of the counts of the output workspace.')

        self.declareProperty(MatrixWorkspaceProperty('SumOfNormFactors', '', optional=PropertyMode.Optional,
                                                     direction=Direction.Output),
                             doc='The sum of the counts of the output workspace.')
Exemplo n.º 38
0
 def get_detector_name_for_reduction_mode(self, reduction_mode):
     if reduction_mode is ISISReductionMode.LAB:
         bank_type = DetectorType.to_string(DetectorType.LAB)
     elif reduction_mode is ISISReductionMode.HAB:
         bank_type = DetectorType.to_string(DetectorType.HAB)
     else:
         raise RuntimeError("SANStateReductionISIS: There is no detector available for the"
                            " reduction mode {0}.".format(reduction_mode))
     return self.detector_names[bank_type]
Exemplo n.º 39
0
 def get_detector_name_for_reduction_mode(self, reduction_mode):
     if reduction_mode is ISISReductionMode.LAB:
         bank_type = DetectorType.to_string(DetectorType.LAB)
     elif reduction_mode is ISISReductionMode.HAB:
         bank_type = DetectorType.to_string(DetectorType.HAB)
     else:
         raise RuntimeError("SANStateReductionISIS: There is no detector available for the"
                            " reduction mode {0}.".format(reduction_mode))
     return self.detector_names[bank_type]
Exemplo n.º 40
0
    def test_that_SANS2D_can_move(self):
        # Arrange
        file_name = "SANS2D00028784"
        lab_z_translation_correction = 123.

        workspace = load_workspace(file_name)
        state = SANSMoveTest._get_simple_state(sample_scatter=file_name,
                                               lab_z_translation_correction=lab_z_translation_correction)
        beam_coordinates = [0.1076, -0.0835]

        # Act
        # The component input is not relevant for SANS2D's initial move. All detectors are moved
        component = None
        move_alg = self._run_move(state, workspace=workspace, move_type="InitialMove",
                                  beam_coordinates=beam_coordinates, component=component)

        # Assert for initial move for low angle bank
        # These values are on the workspace and in the sample logs,
        component_to_investigate = DetectorType.to_string(DetectorType.LAB)
        initial_z_position = 23.281
        rear_det_z = 11.9989755859
        offset = 4.
        total_x = 0.
        total_y = 0.
        total_z = initial_z_position + rear_det_z - offset + lab_z_translation_correction
        expected_position = V3D(total_x - beam_coordinates[0], total_y - beam_coordinates[1], total_z)
        expected_rotation = Quat(1., 0., 0., 0.)
        self.compare_expected_position(expected_position, expected_rotation,
                                       component_to_investigate, state.move, workspace)

        # Assert for initial move for high angle bank
        # These values are on the workspace and in the sample logs
        component_to_investigate = DetectorType.to_string(DetectorType.HAB)
        initial_x_position = 1.1
        x_correction = -0.187987540973
        initial_z_position = 23.281
        z_correction = 1.00575649188
        total_x = initial_x_position + x_correction
        total_y = 0.
        total_z = initial_z_position + z_correction
        expected_position = V3D(total_x - beam_coordinates[0], total_y - beam_coordinates[1], total_z)
        expected_rotation = Quat(0.9968998362876025, 0., 0.07868110579898738, 0.)
        self.compare_expected_position(expected_position, expected_rotation,
                                       component_to_investigate, state.move, workspace)

        # Act + Assert for elementary move
        component_elementary_move = "rear-detector"
        component_elementary_move_key = DetectorType.to_string(DetectorType.LAB)
        beam_coordinates_elementary_move = [120, 135]
        self.check_that_elementary_displacement_with_only_translation_is_correct(workspace, move_alg, state.move,
                                                                                 beam_coordinates_elementary_move,
                                                                                 component_elementary_move,
                                                                                 component_elementary_move_key)

        # # Act + Assert for setting to zero position for all
        self.check_that_sets_to_zero(workspace, move_alg, state.move, comp_name=None)
Exemplo n.º 41
0
    def _get_mask_state(general_entries, detector_entries):
        state = StateMaskSANS2D()
        # Setup the general mask settings
        mask_settings = {
            "radius_min": 12.,
            "radius_max": 17.,
            "bin_mask_general_start": [1., 2., 3.],
            "bin_mask_general_stop": [2., 3., 4.],
            "mask_files": None,
            "phi_min": 0.5,
            "phi_max": 1.,
            "use_mask_phi_mirror": True,
            "beam_stop_arm_width": 1.,
            "beam_stop_arm_angle": 24.5,
            "beam_stop_arm_pos1": 12.,
            "beam_stop_arm_pos2": 34.,
            "clear": False,
            "clear_time": False,
            "idf_path": ""
        }

        for key, value in list(mask_settings.items()):
            if key in general_entries:
                value = general_entries[key]
            if value is not None:  # If the value is None, then don't set it
                setattr(state, key, value)

        # Now setup the detector-specific settings
        detector_settings = {
            "single_vertical_strip_mask": [1, 2, 4],
            "range_vertical_strip_start": [1, 2, 4],
            "range_vertical_strip_stop": [2, 3, 5],
            "single_horizontal_strip_mask": [1, 2, 4],
            "range_horizontal_strip_start": [1, 2, 4],
            "range_horizontal_strip_stop": [2, 3, 5],
            "block_horizontal_start": [1, 2, 4],
            "block_horizontal_stop": [2, 3, 5],
            "block_vertical_start": [1, 2, 4],
            "block_vertical_stop": [2, 3, 5],
            "block_cross_horizontal": [1, 2, 4],
            "block_cross_vertical": [2, 3, 5],
            "bin_mask_start": [1., 2., 4.],
            "bin_mask_stop": [2., 3., 5.],
            "detector_name": "name",
            "detector_name_short": "name_short",
            "single_spectra": [1, 4, 6],
            "spectrum_range_start": [1, 5, 7],
            "spectrum_range_stop": [2, 6, 8]
        }

        StateMaskTest._set_detector(state, detector_settings, detector_entries,
                                    DetectorType.to_string(DetectorType.LAB))
        StateMaskTest._set_detector(state, detector_settings, detector_entries,
                                    DetectorType.to_string(DetectorType.HAB))

        return state
Exemplo n.º 42
0
    def __init__(self):
        super(StateMask, self).__init__()
        # Setup the detectors
        self.detectors = {
            DetectorType.to_string(DetectorType.LAB): StateMaskDetector(),
            DetectorType.to_string(DetectorType.HAB): StateMaskDetector()
        }

        # IDF Path
        self.idf_path = ""
Exemplo n.º 43
0
    def check_that_sets_to_zero(self,
                                workspace,
                                move_alg,
                                move_info,
                                comp_name=None):
        def _get_components_to_compare(_key, _move_info, _component_names):
            if _key in _move_info.detectors:
                _name = _move_info.detectors[_key].detector_name
                _component_names.append(_name)

        # Reset the position to zero
        move_alg.setProperty("Workspace", workspace)
        move_alg.setProperty("MoveType", "SetToZero")
        if comp_name is not None:
            move_alg.setProperty("Component", comp_name)
        else:
            move_alg.setProperty("Component", "")
        move_alg.execute()
        self.assertTrue(move_alg.isExecuted())

        # Get the components to compare
        if comp_name is None:
            component_names = list(move_info.monitor_names.values())
            hab_name = DetectorType.to_string(DetectorType.HAB)
            lab_name = DetectorType.to_string(DetectorType.LAB),
            _get_components_to_compare(hab_name, move_info, component_names)
            _get_components_to_compare(lab_name, move_info, component_names)
            component_names.append("some-sample-holder")
        else:
            component_names = [comp_name]

        # Ensure that the positions on the base instrument and the instrument are the same
        instrument = workspace.getInstrument()
        base_instrument = instrument.getBaseInstrument()
        for component_name in component_names:
            # Confirm that the positions are the same
            component = instrument.getComponentByName(component_name)
            base_component = base_instrument.getComponentByName(component_name)

            # If we are dealing with a monitor which has not been implemented we need to continue
            if component is None or base_component is None:
                continue

            position = component.getPos()
            position_base = base_component.getPos()
            for index in range(0, 3):
                self.assertAlmostEquals(position[index],
                                        position_base[index],
                                        delta=1e-4)
            rotation = component.getRotation()
            rotation_base = base_component.getRotation()
            for index in range(0, 4):
                self.assertAlmostEquals(rotation[index],
                                        rotation_base[index],
                                        delta=1e-4)
Exemplo n.º 44
0
    def __init__(self):
        super(StateMoveLOQ, self).__init__()
        # Set the center_position in meter
        self.center_position = 317.5 / 1000.

        # Set the monitor names
        self.monitor_names = {}

        # Setup the detectors
        self.detectors = {DetectorType.to_string(DetectorType.LAB): StateMoveDetector(),
                          DetectorType.to_string(DetectorType.HAB): StateMoveDetector()}
Exemplo n.º 45
0
    def __init__(self):
        super(StateMoveLOQ, self).__init__()
        # Set the center_position in meter
        self.center_position = 317.5 / 1000.

        # Set the monitor names
        self.monitor_names = {}

        # Setup the detectors
        self.detectors = {DetectorType.to_string(DetectorType.LAB): StateMoveDetector(),
                          DetectorType.to_string(DetectorType.HAB): StateMoveDetector()}
Exemplo n.º 46
0
    def __init__(self):
        super(StateMove, self).__init__()

        # Setup the sample offset
        self.sample_offset = 0.0

        # The sample offset direction is Z for the ISIS instruments
        self.sample_offset_direction = CanonicalCoordinates.Z

        # Setup the detectors
        self.detectors = {DetectorType.to_string(DetectorType.LAB): StateMoveDetector(),
                          DetectorType.to_string(DetectorType.HAB): StateMoveDetector()}
    def _generate_masking_information(self, state):
        if state is None:
            return []
        mask_info = state.mask
        masks = []

        mask_info_lab = mask_info.detectors[DetectorType.to_string(
            DetectorType.LAB)]
        mask_info_hab = mask_info.detectors[DetectorType.to_string(
            DetectorType.HAB)] if DetectorType.to_string(
                DetectorType.HAB) in mask_info.detectors else None  # noqa

        # Add the radius mask
        radius_mask = self._get_radius(mask_info)
        masks.extend(radius_mask)

        # Add the spectrum masks for LAB
        spectrum_masks_lab = self._get_spectrum_masks(mask_info_lab)
        masks.extend(spectrum_masks_lab)

        # Add the spectrum masks for HAB
        if mask_info_hab:
            spectrum_masks_hab = self._get_spectrum_masks(mask_info_hab)
            masks.extend(spectrum_masks_hab)

        # Add the general time mask
        time_masks_general = self._get_time_masks_general(mask_info)
        masks.extend(time_masks_general)

        # Add the time masks for LAB
        time_masks_lab = self._get_time_masks(mask_info_lab)
        masks.extend(time_masks_lab)

        # Add the time masks for HAB
        if mask_info_hab:
            time_masks_hab = self._get_time_masks(mask_info_hab)
            masks.extend(time_masks_hab)

        # Add arm mask
        arm_mask = self._get_arm_mask(mask_info)
        masks.extend(arm_mask)

        # Add phi mask
        phi_mask = self._get_phi_mask(mask_info)
        masks.extend(phi_mask)

        # Add mask files
        mask_files = self._get_mask_files(mask_info)
        masks.extend(mask_files)
        return masks
def mask_workspace(state, workspace_to_mask):
    serialized_state = state.property_manager
    masking_algorithm = create_masking_algorithm(serialized_state, workspace_to_mask)
    mask_info = state.mask

    detectors = [DetectorType.to_string(DetectorType.LAB), DetectorType.to_string(DetectorType.HAB)] \
                if DetectorType.to_string(DetectorType.HAB) in mask_info.detectors else\
                [DetectorType.to_string(DetectorType.LAB)]  # noqa

    for detector in detectors:
        masking_algorithm.setProperty("Component", detector)
        masking_algorithm.execute()

    return masking_algorithm.getProperty("Workspace").value
Exemplo n.º 49
0
 def _assert_mask(self, state):
     mask = state.mask
     self.assertEqual(mask.radius_min, 12 / 1000.)
     self.assertEqual(mask.radius_max, 15 / 1000.)
     self.assertEqual(mask.clear, True)
     self.assertEqual(mask.clear_time, True)
     self.assertEqual(
         mask.detectors[DetectorType.to_string(
             DetectorType.LAB)].single_horizontal_strip_mask, [0])
     self.assertEqual(
         mask.detectors[DetectorType.to_string(
             DetectorType.LAB)].single_vertical_strip_mask, [0, 191])
     self.assertEqual(
         mask.detectors[DetectorType.to_string(
             DetectorType.HAB)].single_horizontal_strip_mask, [0])
     self.assertEqual(
         mask.detectors[DetectorType.to_string(
             DetectorType.HAB)].single_vertical_strip_mask, [0, 191])
     self.assertTrue(mask.detectors[DetectorType.to_string(
         DetectorType.LAB)].range_horizontal_strip_start == [190, 167])
     self.assertTrue(mask.detectors[DetectorType.to_string(
         DetectorType.LAB)].range_horizontal_strip_stop == [191, 172])
     self.assertTrue(mask.detectors[DetectorType.to_string(
         DetectorType.HAB)].range_horizontal_strip_start == [190, 156])
     self.assertTrue(mask.detectors[DetectorType.to_string(
         DetectorType.HAB)].range_horizontal_strip_stop == [191, 159])
Exemplo n.º 50
0
def mask_workspace(state, workspace_to_mask):
    serialized_state = state.property_manager
    masking_algorithm = create_masking_algorithm(serialized_state, workspace_to_mask)
    mask_info = state.mask

    detectors = [DetectorType.to_string(DetectorType.LAB), DetectorType.to_string(DetectorType.HAB)] \
                if DetectorType.to_string(DetectorType.HAB) in mask_info.detectors else\
                [DetectorType.to_string(DetectorType.LAB)]  # noqa

    for detector in detectors:
        masking_algorithm.setProperty("Component", detector)
        masking_algorithm.execute()

    return masking_algorithm.getProperty("Workspace").value
Exemplo n.º 51
0
    def __init__(self):
        super(StateReductionMode, self).__init__()
        self.reduction_mode = ISISReductionMode.LAB
        self.reduction_dimensionality = ReductionDimensionality.OneDim

        # Set the shifts to defaults which essentially don't do anything.
        self.merge_shift = 0.0
        self.merge_scale = 1.0
        self.merge_fit_mode = FitModeForMerge.NoFit
        self.merge_range_min = None
        self.merge_range_max = None

        # Set the detector names to empty strings
        self.detector_names = {DetectorType.to_string(DetectorType.LAB): "",
                               DetectorType.to_string(DetectorType.HAB): ""}
Exemplo n.º 52
0
    def __init__(self):
        super(StateReductionMode, self).__init__()
        self.reduction_mode = ISISReductionMode.LAB
        self.reduction_dimensionality = ReductionDimensionality.OneDim

        # Set the shifts to defaults which essentially don't do anything.
        self.merge_shift = 0.0
        self.merge_scale = 1.0
        self.merge_fit_mode = FitModeForMerge.NoFit
        self.merge_range_min = None
        self.merge_range_max = None

        # Set the detector names to empty strings
        self.detector_names = {DetectorType.to_string(DetectorType.LAB): "",
                               DetectorType.to_string(DetectorType.HAB): ""}
Exemplo n.º 53
0
    def _get_coordinates(self, move_info, full_component_name):
        """
        Gets the coordinates for a particular component.

        If the coordinates were not specified by the user then the coordinates are taken from the move state.
        There are several possible scenarios
        1. component is specified => take the beam centre from the appropriate detector
        2. component is not specified => take the beam centre from the LAB
        :param move_info: a SANSStateMove object
        :param full_component_name: The full component name as it is known to the Mantid instrument
        :return:
        """
        coordinates = self.getProperty("BeamCoordinates").value.tolist()
        if not coordinates:
            # Get the selected detector
            detectors = move_info.detectors
            selected_detector = get_detector_for_component(move_info, full_component_name)

            # If the detector is unknown take the position from the LAB
            if selected_detector is None:
                selected_detector = detectors[DetectorType.to_string(DetectorType.LAB)]
            pos1 = selected_detector.sample_centre_pos1
            pos2 = selected_detector.sample_centre_pos2
            coordinates = [pos1, pos2]
        return coordinates
    def _run_beam_centre_core(self, state, workspace, monitor, transmission=None, direct=None,
                              detector_type=DetectorType.LAB, component=DataType.Sample, centre_1 = 0.1, centre_2 = -0.1
                              ,r_min = 0.06, r_max = 0.26):
        beam_centre_core_alg = AlgorithmManager.createUnmanaged("SANSBeamCentreFinderCore")
        beam_centre_core_alg.setChild(True)
        beam_centre_core_alg.initialize()

        state_dict = state.property_manager
        beam_centre_core_alg.setProperty("SANSState", state_dict)
        beam_centre_core_alg.setProperty("ScatterWorkspace", workspace)
        beam_centre_core_alg.setProperty("ScatterMonitorWorkspace", monitor)

        if transmission:
            beam_centre_core_alg.setProperty("TransmissionWorkspace", transmission)

        if direct:
            beam_centre_core_alg.setProperty("DirectWorkspace", direct)

        beam_centre_core_alg.setProperty("Component", DetectorType.to_string(detector_type))
        beam_centre_core_alg.setProperty("DataType", DataType.to_string(component))
        beam_centre_core_alg.setProperty("Centre1", centre_1)
        beam_centre_core_alg.setProperty("Centre2", centre_2)
        beam_centre_core_alg.setProperty("RMax", r_max)
        beam_centre_core_alg.setProperty("RMin", r_min)

        beam_centre_core_alg.setProperty("OutputWorkspaceLeft", EMPTY_NAME)
        beam_centre_core_alg.setProperty("OutputWorkspaceRight", EMPTY_NAME)
        beam_centre_core_alg.setProperty("OutputWorkspaceTop", EMPTY_NAME)
        beam_centre_core_alg.setProperty("OutputWorkspaceBottom", EMPTY_NAME)

        # Act
        beam_centre_core_alg.execute()
        self.assertTrue(beam_centre_core_alg.isExecuted())
        return beam_centre_core_alg
Exemplo n.º 55
0
    def test_that_mask_can_be_built(self):
        # Arrange
        facility = SANSFacility.ISIS
        data_builder = get_data_builder(facility)
        data_builder.set_sample_scatter("LOQ74044")
        data_builder.set_sample_scatter_period(3)
        data_info = data_builder.build()

        # Act
        builder = get_mask_builder(data_info)
        self.assertTrue(builder)

        start_time = [0.1, 1.3]
        end_time = [0.2, 1.6]
        builder.set_bin_mask_general_start(start_time)
        builder.set_bin_mask_general_stop(end_time)
        builder.set_LAB_single_vertical_strip_mask([1, 2, 3])

        # Assert
        state = builder.build()
        self.assertTrue(len(state.bin_mask_general_start) == 2)
        self.assertTrue(state.bin_mask_general_start[0] == start_time[0])
        self.assertTrue(state.bin_mask_general_start[1] == start_time[1])

        self.assertTrue(len(state.bin_mask_general_stop) == 2)
        self.assertTrue(state.bin_mask_general_stop[0] == end_time[0])
        self.assertTrue(state.bin_mask_general_stop[1] == end_time[1])

        strip_mask = state.detectors[DetectorType.to_string(DetectorType.LAB)].single_vertical_strip_mask
        self.assertTrue(len(strip_mask) == 3)
        self.assertTrue(strip_mask[2] == 3)
Exemplo n.º 56
0
    def PyInit(self):
        # State
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        # Workspace which is to be masked
        self.declareProperty(MatrixWorkspaceProperty("Workspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.InOut),
                             doc='The sample scatter workspace. This workspace does not contain monitors.')

        # The component, i.e. HAB or LAB
        allowed_detectors = StringListValidator([DetectorType.to_string(DetectorType.LAB),
                                                 DetectorType.to_string(DetectorType.HAB)])
        self.declareProperty("Component", DetectorType.to_string(DetectorType.LAB), validator=allowed_detectors,
                             direction=Direction.Input,
                             doc="The component of the instrument which is to be masked.")
Exemplo n.º 57
0
    def _sort_list(elements):
        if len(elements) == 1:
            return

        if isinstance(elements[0], single_entry_with_detector):
            UserFileReaderTest._sort(elements, lambda x: x.entry)
        elif isinstance(elements[0], simple_range):
            UserFileReaderTest._sort(elements, lambda x: x.start)
        elif isinstance(elements[0], complex_range):
            UserFileReaderTest._sort(elements, lambda x: x.start)
        elif isinstance(elements[0], back_single_monitor_entry):
            UserFileReaderTest._sort(elements, lambda x: x.monitor)
        elif isinstance(elements[0], fit_general):
            UserFileReaderTest._sort(elements, lambda x: x.start)
        elif isinstance(elements[0], range_entry_with_detector):
            UserFileReaderTest._sort(elements, lambda x: x.start)
        elif isinstance(elements[0], monitor_file):
            UserFileReaderTest._sort(elements, lambda x: (x.file_path, DetectorType.to_string(x.detector_type)))
        elif isinstance(elements[0], monitor_spectrum):
            UserFileReaderTest._sort(elements, lambda x: x.spectrum)
        elif isinstance(elements[0], position_entry):
            UserFileReaderTest._sort(elements, lambda x: x.pos1)
        elif isinstance(elements[0], set_scales_entry):
            UserFileReaderTest._sort(elements, lambda x: x.s)
        elif isinstance(elements[0], range_entry):
            UserFileReaderTest._sort(elements, lambda x: x.start)
        else:
            elements.sort()