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
Example #2
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
Example #3
0
    def _get_calculate_transmission_state(trans_entries, fit_entries):
        state = StateCalculateTransmission()
        if trans_entries is None:
            trans_entries = {}
        trans_settings = {"transmission_radius_on_detector": 12., "transmission_roi_files": ["test.xml"],
                          "transmission_mask_files": ["test.xml"], "default_transmission_monitor": 3,
                          "transmission_monitor": 4, "default_incident_monitor": 1, "incident_monitor": 2,
                          "prompt_peak_correction_min": 123., "prompt_peak_correction_max": 1234.,
                          "rebin_type": RebinType.Rebin, "wavelength_low": 1., "wavelength_high": 2.7,
                          "wavelength_step": 0.5,  "wavelength_step_type": RangeStepType.Lin,
                          "use_full_wavelength_range": True, "wavelength_full_range_low": 12.,
                          "wavelength_full_range_high": 434., "background_TOF_general_start": 1.4,
                          "background_TOF_general_stop": 24.5, "background_TOF_monitor_start": {"1": 123, "2": 123},
                          "background_TOF_monitor_stop": {"1": 234, "2": 2323}, "background_TOF_roi_start": 12.,
                          "background_TOF_roi_stop": 123.}

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

        fit_settings = {"fit_type": FitType.Polynomial, "polynomial_order": 1, "wavelength_low": 12.,
                        "wavelength_high": 232.}
        if fit_entries is None:
            fit_entries = {}
        StateCalculateTransmissionTest._set_fit(state, fit_settings, fit_entries,
                                                DataType.to_string(DataType.Sample))
        StateCalculateTransmissionTest._set_fit(state, fit_settings, fit_entries,
                                                DataType.to_string(DataType.Can))
        return state
    def _get_calculate_transmission_state(trans_entries, fit_entries):
        state = StateCalculateTransmission()
        if trans_entries is None:
            trans_entries = {}
        trans_settings = {"transmission_radius_on_detector": 12., "transmission_roi_files": ["test.xml"],
                          "transmission_mask_files": ["test.xml"], "default_transmission_monitor": 3,
                          "transmission_monitor": 4, "default_incident_monitor": 1, "incident_monitor": 2,
                          "prompt_peak_correction_min": 123., "prompt_peak_correction_max": 1234.,
                          "rebin_type": RebinType.Rebin, "wavelength_low": [1.], "wavelength_high": [2.7],
                          "wavelength_step": 0.5,  "wavelength_step_type": RangeStepType.Lin,
                          "use_full_wavelength_range": True, "wavelength_full_range_low": 12.,
                          "wavelength_full_range_high": 434., "background_TOF_general_start": 1.4,
                          "background_TOF_general_stop": 24.5, "background_TOF_monitor_start": {"1": 123, "2": 123},
                          "background_TOF_monitor_stop": {"1": 234, "2": 2323}, "background_TOF_roi_start": 12.,
                          "background_TOF_roi_stop": 123.}

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

        fit_settings = {"fit_type": FitType.Polynomial, "polynomial_order": 1, "wavelength_low": 12.,
                        "wavelength_high": 232.}
        if fit_entries is None:
            fit_entries = {}
        StateCalculateTransmissionTest._set_fit(state, fit_settings, fit_entries,
                                                DataType.to_string(DataType.Sample))
        StateCalculateTransmissionTest._set_fit(state, fit_settings, fit_entries,
                                                DataType.to_string(DataType.Can))
        return state
Example #5
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.')
Example #6
0
    def __init__(self):
        super(StateCalculateTransmission, self).__init__()
        # The keys of this dictionaries are the spectrum number of the monitors (as a string)
        self.background_TOF_monitor_start = {}
        self.background_TOF_monitor_stop = {}

        self.fit = {DataType.to_string(DataType.Sample): StateTransmissionFit(),
                    DataType.to_string(DataType.Can): StateTransmissionFit()}
        self.use_full_wavelength_range = False
    def __init__(self):
        super(StateCalculateTransmission, self).__init__()
        # The keys of this dictionaries are the spectrum number of the monitors (as a string)
        self.background_TOF_monitor_start = {}
        self.background_TOF_monitor_stop = {}

        self.fit = {DataType.to_string(DataType.Sample): StateTransmissionFit(),
                    DataType.to_string(DataType.Can): StateTransmissionFit()}
        self.use_full_wavelength_range = False

        # Default rebin type is a standard Rebin
        self.rebin_type = RebinType.Rebin

        self.prompt_peak_correction_enabled = False
    def validateInputs(self):
        errors = dict()
        # Check that the input can be converted into the right state object
        state_property_manager = self.getProperty("SANSState").value
        try:
            state = create_deserialized_sans_state_from_property_manager(
                state_property_manager)
            state.property_manager = state_property_manager
            state.validate()
        except ValueError as err:
            errors.update({"SANSCalculateTransmission": str(err)})
            state = None

        if state is not None:
            transmission_workspace = self.getProperty(
                "TransmissionWorkspace").value
            calculate_transmission_state = state.adjustment.calculate_transmission
            try:
                incident_monitor = calculate_transmission_state.incident_monitor
                if incident_monitor is None:
                    incident_monitor = calculate_transmission_state.default_incident_monitor
                transmission_workspace.getIndexFromSpectrumNumber(
                    incident_monitor)
            except RuntimeError:
                errors.update({
                    "IncidentMonitorSpectrumNumber":
                    "The spectrum number for the incident monitor spectrum "
                    "does not seem to exist for the transmission"
                    " workspace."
                })

        if state is not None:
            calculate_transmission_state = state.adjustment.calculate_transmission
            fit = calculate_transmission_state.fit
            data_type_string = self.getProperty("DataType").value
            data_type = DataType.from_string(data_type_string)
            sample = fit[DataType.to_string(DataType.Sample)]
            can = fit[DataType.to_string(DataType.Can)]
            if data_type is DataType.Sample and sample.fit_type is None:
                errors.update({
                    "DataType":
                    "There does not seem to be a fit type set for the selected data type"
                })
            if data_type is DataType.Can and can.fit_type is None:
                errors.update({
                    "DataType":
                    "There does not seem to be a fit type set for the selected data type"
                })

        return errors
Example #9
0
    def PyExec(self):
        # Read the state
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(state_property_manager)

        progress = Progress(self, start=0.0, end=1.0, nreports=3)
        input_workspace = self.getProperty("InputWorkspace").value

        data_type_as_string = self.getProperty("DataType").value
        data_type = DataType.from_string(data_type_as_string)

        slicer = SliceEventFactory.create_slicer(state, input_workspace, data_type)
        slice_info = state.slice

        # Perform the slicing
        progress.report("Starting to slice the workspace.")
        sliced_workspace, slice_factor = slicer.create_slice(input_workspace, slice_info)

        # Scale the monitor accordingly
        progress.report("Scaling the monitors.")
        self.scale_monitors(slice_factor)

        # Set the outputs
        append_to_sans_file_tag(sliced_workspace, "_sliced")
        self.setProperty("OutputWorkspace", sliced_workspace)
        self.setProperty("SliceEventFactor", slice_factor)
        progress.report("Finished slicing.")
Example #10
0
    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
Example #11
0
 def set_transmission_workspaces_on_output(self, transmission_bundles,
                                           fit_state):
     for transmission_bundle in transmission_bundles:
         fit_performed = fit_state[DataType.to_string(
             transmission_bundle.data_type)].fit_type != FitType.NoFit
         calculated_transmission_workspace = transmission_bundle.calculated_transmission_workspace
         unfitted_transmission_workspace = transmission_bundle.unfitted_transmission_workspace
         if transmission_bundle.data_type is DataType.Can:
             if does_can_workspace_exist_on_ads(
                     calculated_transmission_workspace):
                 # The workspace is cloned here because the transmission runs are diagnostic output so even though
                 # the values already exist they need to be labelled seperately for each reduction.
                 calculated_transmission_workspace = CloneWorkspace(
                     calculated_transmission_workspace, StoreInADS=False)
             if does_can_workspace_exist_on_ads(
                     unfitted_transmission_workspace):
                 unfitted_transmission_workspace = CloneWorkspace(
                     unfitted_transmission_workspace, StoreInADS=False)
             if fit_performed:
                 self.setProperty(
                     "OutputWorkspaceCalculatedTransmissionCan",
                     calculated_transmission_workspace)
             self.setProperty("OutputWorkspaceUnfittedTransmissionCan",
                              unfitted_transmission_workspace)
         elif transmission_bundle.data_type is DataType.Sample:
             if fit_performed:
                 self.setProperty("OutputWorkspaceCalculatedTransmission",
                                  calculated_transmission_workspace)
             self.setProperty("OutputWorkspaceUnfittedTransmission",
                              unfitted_transmission_workspace)
         else:
             raise RuntimeError(
                 "SANSSingleReduction: The data type {0} should be"
                 " sample or can.".format(transmission_bundle.data_type))
def calculate_transmission(transmission_ws, direct_ws,
                           state_adjustment_calculate_transmission,
                           data_type_str):
    """
    Calculates the transmission for a SANS reduction.
    :param transmission_ws: The transmission workspace in time-of-light units.
    :param direct_ws: The direct workspace in time-of-flight units.
    :param state_adjustment_calculate_transmission: The state.adjustment.calculate_transmission object
    :param data_type_str: The component of the instrument which is to be reduced. Allowed values: ['Sample', 'Can']
    :return: Tuple of: Output Workspace and Unfitted Data - Both in wavelength
    """
    calculate_transmission_state = state_adjustment_calculate_transmission
    # The calculation of the transmission has the following steps:
    # 1. Get all spectrum numbers which take part in the transmission calculation
    # 2. Clean up the transmission and direct workspaces, ie peak prompt correction, flat background calculation,
    #    wavelength conversion and rebinning of the data.
    # 3. Run the CalculateTransmission algorithm
    incident_monitor_spectrum_number = calculate_transmission_state.incident_monitor
    if incident_monitor_spectrum_number is None:
        incident_monitor_spectrum_number = calculate_transmission_state.default_incident_monitor

    # 1. Get relevant spectra
    detector_id_incident_monitor = get_detector_id_for_spectrum_number(
        transmission_ws, incident_monitor_spectrum_number)
    detector_ids_roi, detector_id_transmission_monitor, detector_id_default_transmission_monitor = \
        _get_detector_ids_for_transmission_calculation(transmission_ws, calculate_transmission_state)
    all_detector_ids = [detector_id_incident_monitor]

    if len(detector_ids_roi) > 0:
        all_detector_ids.extend(detector_ids_roi)
    elif detector_id_transmission_monitor is not None:
        all_detector_ids.append(detector_id_transmission_monitor)
    elif detector_id_default_transmission_monitor is not None:
        all_detector_ids.append(detector_id_default_transmission_monitor)
    else:
        raise RuntimeError(
            "SANSCalculateTransmission: No region of interest or transmission monitor selected."
        )

    # 2. Clean transmission data

    data_type = DataType(data_type_str)
    transmission_ws = _get_corrected_wavelength_workspace(
        transmission_ws,
        all_detector_ids,
        calculate_transmission_state,
        data_type=data_type)
    direct_ws = _get_corrected_wavelength_workspace(
        direct_ws,
        all_detector_ids,
        calculate_transmission_state,
        data_type=data_type)

    # 3. Fit
    output_workspace, unfitted_transmission_workspace = \
        _perform_fit(transmission_ws, direct_ws, detector_ids_roi,
                     detector_id_transmission_monitor, detector_id_default_transmission_monitor,
                     detector_id_incident_monitor, calculate_transmission_state, data_type)

    return output_workspace, unfitted_transmission_workspace
    def _run_reduction_core(self, state, workspace, monitor, transmission=None, direct=None,
                            detector_type=DetectorType.LAB, component=DataType.Sample):
        reduction_core_alg = AlgorithmManager.createUnmanaged("SANSReductionCore")
        reduction_core_alg.setChild(True)
        reduction_core_alg.initialize()

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

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

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

        reduction_core_alg.setProperty("Component", DetectorType.to_string(detector_type))
        reduction_core_alg.setProperty("DataType", DataType.to_string(component))

        reduction_core_alg.setProperty("OutputWorkspace", EMPTY_NAME)

        reduction_core_alg.setProperty("CalculatedTransmissionWorkspace", EMPTY_NAME)
        reduction_core_alg.setProperty("UnfittedTransmissionWorkspace", EMPTY_NAME)

        # Act
        reduction_core_alg.execute()
        self.assertTrue(reduction_core_alg.isExecuted())
        return reduction_core_alg
Example #14
0
def get_transmission_output_name(state,
                                 data_type=DataType.Sample,
                                 multi_reduction_type=None,
                                 fitted=True):
    user_specified_output_name = state.save.user_specified_output_name

    data = state.data
    short_run_number = data.sample_scatter_run_number
    short_run_number_as_string = str(short_run_number)

    calculated_transmission_state = state.adjustment.calculate_transmission
    fit = calculated_transmission_state.fit[DataType.to_string(
        DataType.Sample)]
    wavelength_range_string = "_" + str(fit.wavelength_low) + "_" + str(
        fit.wavelength_high)

    trans_suffix = "_trans_Sample" if data_type == DataType.Sample else "_trans_Can"
    trans_suffix = trans_suffix + '_unfitted' if not fitted else trans_suffix

    if user_specified_output_name:
        output_name = user_specified_output_name + trans_suffix
        output_base_name = user_specified_output_name + '_trans'
    else:
        output_name = short_run_number_as_string + trans_suffix + wavelength_range_string
        output_base_name = short_run_number_as_string + '_trans' + wavelength_range_string

    if multi_reduction_type and fitted:
        if multi_reduction_type["wavelength_range"]:
            wavelength = state.wavelength
            wavelength_range_string = "_" + str(
                wavelength.wavelength_low[0]) + "_" + str(
                    wavelength.wavelength_high[0])
            output_name += wavelength_range_string

    return output_name, output_base_name
Example #15
0
    def PyExec(self):
        # Read the state
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(state_property_manager)

        progress = Progress(self, start=0.0, end=1.0, nreports=3)
        input_workspace = self.getProperty("InputWorkspace").value

        data_type_as_string = self.getProperty("DataType").value
        data_type = DataType.from_string(data_type_as_string)

        slicer = SliceEventFactory.create_slicer(state, input_workspace, data_type)
        slice_info = state.slice

        # Perform the slicing
        progress.report("Starting to slice the workspace.")
        sliced_workspace, slice_factor = slicer.create_slice(input_workspace, slice_info)

        # Scale the monitor accordingly
        progress.report("Scaling the monitors.")
        self.scale_monitors(slice_factor)

        # Set the outputs
        append_to_sans_file_tag(sliced_workspace, "_sliced")
        self.setProperty("OutputWorkspace", sliced_workspace)
        self.setProperty("SliceEventFactor", slice_factor)
        progress.report("Finished slicing.")
def get_transmission_output_name(state, data_type=DataType.Sample, multi_reduction_type=None, fitted=True):
    user_specified_output_name = state.save.user_specified_output_name

    data = state.data
    short_run_number = data.sample_scatter_run_number
    short_run_number_as_string = str(short_run_number)

    calculated_transmission_state = state.adjustment.calculate_transmission
    fit = calculated_transmission_state.fit[DataType.to_string(DataType.Sample)]
    wavelength_range_string = "_" + str(fit.wavelength_low) + "_" + str(fit.wavelength_high)

    trans_suffix = "_trans_Sample" if data_type == DataType.Sample else "_trans_Can"
    trans_suffix = trans_suffix + '_unfitted' if not fitted else trans_suffix

    if user_specified_output_name:
        output_name = user_specified_output_name + trans_suffix
        output_base_name = user_specified_output_name + '_trans'
    else:
        output_name = short_run_number_as_string + trans_suffix + wavelength_range_string
        output_base_name = short_run_number_as_string + '_trans' + wavelength_range_string

    if multi_reduction_type and fitted:
        if multi_reduction_type["wavelength_range"]:
            wavelength = state.wavelength
            wavelength_range_string = "_" + str(wavelength.wavelength_low[0]) + "_" + str(
                wavelength.wavelength_high[0])
            output_name += wavelength_range_string

    return output_name, output_base_name
    def _run_reduction_core(self, state, workspace, monitor, transmission=None, direct=None,
                            detector_type=DetectorType.LAB, component=DataType.Sample):
        reduction_core_alg = AlgorithmManager.createUnmanaged("SANSReductionCore")
        reduction_core_alg.setChild(True)
        reduction_core_alg.initialize()

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

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

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

        reduction_core_alg.setProperty("Component", DetectorType.to_string(detector_type))
        reduction_core_alg.setProperty("DataType", DataType.to_string(component))

        reduction_core_alg.setProperty("OutputWorkspace", EMPTY_NAME)

        reduction_core_alg.setProperty("CalculatedTransmissionWorkspace", EMPTY_NAME)
        reduction_core_alg.setProperty("UnfittedTransmissionWorkspace", EMPTY_NAME)

        # Act
        reduction_core_alg.execute()
        self.assertTrue(reduction_core_alg.isExecuted())
        return reduction_core_alg
def run_core_reduction(reduction_alg, reduction_setting_bundle):
    """
    This function runs a core reduction. This is essentially half a reduction (either smaple or can).

    :param reduction_alg: a handle to the reduction algorithm.
    :param reduction_setting_bundle: a ReductionSettingBundle tuple
    :return: an OutputBundle and an OutputPartsBundle
    """

    # Get component to reduce
    component = get_component_to_reduce(reduction_setting_bundle)
    # Set the properties on the reduction algorithms
    serialized_state = reduction_setting_bundle.state.property_manager
    reduction_alg.setProperty("SANSState", serialized_state)
    reduction_alg.setProperty("Component", component)
    reduction_alg.setProperty("ScatterWorkspace",
                              reduction_setting_bundle.scatter_workspace)
    reduction_alg.setProperty(
        "ScatterMonitorWorkspace",
        reduction_setting_bundle.scatter_monitor_workspace)
    reduction_alg.setProperty(
        "DataType", DataType.to_string(reduction_setting_bundle.data_type))

    if reduction_setting_bundle.transmission_workspace is not None:
        reduction_alg.setProperty(
            "TransmissionWorkspace",
            reduction_setting_bundle.transmission_workspace)

    if reduction_setting_bundle.direct_workspace is not None:
        reduction_alg.setProperty("DirectWorkspace",
                                  reduction_setting_bundle.direct_workspace)

    reduction_alg.setProperty("OutputWorkspace", EMPTY_NAME)
    reduction_alg.setProperty("SumOfCounts", EMPTY_NAME)
    reduction_alg.setProperty("SumOfNormFactors", EMPTY_NAME)

    # Run the reduction core
    reduction_alg.execute()

    # Get the results
    output_workspace = reduction_alg.getProperty("OutputWorkspace").value
    output_workspace_count = reduction_alg.getProperty("SumOfCounts").value
    output_workspace_norm = reduction_alg.getProperty("SumOfNormFactors").value
    # Pull the result out of the workspace
    output_bundle = OutputBundle(
        state=reduction_setting_bundle.state,
        data_type=reduction_setting_bundle.data_type,
        reduction_mode=reduction_setting_bundle.reduction_mode,
        output_workspace=output_workspace)

    output_parts_bundle = OutputPartsBundle(
        state=reduction_setting_bundle.state,
        data_type=reduction_setting_bundle.data_type,
        reduction_mode=reduction_setting_bundle.reduction_mode,
        output_workspace_count=output_workspace_count,
        output_workspace_norm=output_workspace_norm)
    return output_bundle, output_parts_bundle
def run_core_reduction(reduction_alg, reduction_setting_bundle):
    """
    This function runs a core reduction. This is essentially half a reduction (either sample or can).

    :param reduction_alg: a handle to the reduction algorithm.
    :param reduction_setting_bundle: a ReductionSettingBundle tuple
    :return: an OutputBundle and an OutputPartsBundle
    """

    # Get component to reduce
    component = get_component_to_reduce(reduction_setting_bundle)
    # Set the properties on the reduction algorithms
    serialized_state = reduction_setting_bundle.state.property_manager
    reduction_alg.setProperty("SANSState", serialized_state)
    reduction_alg.setProperty("Component", component)
    reduction_alg.setProperty("ScatterWorkspace", reduction_setting_bundle.scatter_workspace)
    reduction_alg.setProperty("ScatterMonitorWorkspace", reduction_setting_bundle.scatter_monitor_workspace)
    reduction_alg.setProperty("DataType", DataType.to_string(reduction_setting_bundle.data_type))

    if reduction_setting_bundle.transmission_workspace is not None:
        reduction_alg.setProperty("TransmissionWorkspace", reduction_setting_bundle.transmission_workspace)

    if reduction_setting_bundle.direct_workspace is not None:
        reduction_alg.setProperty("DirectWorkspace", reduction_setting_bundle.direct_workspace)

    reduction_alg.setProperty("OutputWorkspace", EMPTY_NAME)
    reduction_alg.setProperty("SumOfCounts", EMPTY_NAME)
    reduction_alg.setProperty("SumOfNormFactors", EMPTY_NAME)

    # Run the reduction core
    reduction_alg.execute()

    # Get the results
    output_workspace = reduction_alg.getProperty("OutputWorkspace").value
    output_workspace_count = reduction_alg.getProperty("SumOfCounts").value
    output_workspace_norm = reduction_alg.getProperty("SumOfNormFactors").value
    output_calculated_transmission_workspace = reduction_alg.getProperty("CalculatedTransmissionWorkspace").value
    output_unfitted_transmission_workspace = reduction_alg.getProperty("UnfittedTransmissionWorkspace").value
    # Pull the result out of the workspace
    output_bundle = OutputBundle(state=reduction_setting_bundle.state,
                                 data_type=reduction_setting_bundle.data_type,
                                 reduction_mode=reduction_setting_bundle.reduction_mode,
                                 output_workspace=output_workspace)

    output_parts_bundle = OutputPartsBundle(state=reduction_setting_bundle.state,
                                            data_type=reduction_setting_bundle.data_type,
                                            reduction_mode=reduction_setting_bundle.reduction_mode,
                                            output_workspace_count=output_workspace_count,
                                            output_workspace_norm=output_workspace_norm)

    output_transmission_bundle = OutputTransmissionBundle(state=reduction_setting_bundle.state,
                                                          data_type=reduction_setting_bundle.data_type,
                                                          calculated_transmission_workspace=output_calculated_transmission_workspace,
                                                          unfitted_transmission_workspace=output_unfitted_transmission_workspace
                                                          )
    return output_bundle, output_parts_bundle, output_transmission_bundle
    def PyExec(self):
        # Read the state
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(
            state_property_manager)
        calculate_transmission_state = state.adjustment.calculate_transmission
        # The calculation of the transmission has the following steps:
        # 1. Get all spectrum numbers which take part in the transmission calculation
        # 2. Clean up the transmission and direct workspaces, ie peak prompt correction, flat background calculation,
        #    wavelength conversion and rebinning of the data.
        # 3. Run the CalculateTransmission algorithm
        transmission_workspace = self.getProperty(
            "TransmissionWorkspace").value
        direct_workspace = self.getProperty("DirectWorkspace").value
        incident_monitor_spectrum_number = calculate_transmission_state.incident_monitor
        if incident_monitor_spectrum_number is None:
            incident_monitor_spectrum_number = calculate_transmission_state.default_incident_monitor

        # 1. Get relevant spectra
        detector_id_incident_monitor = get_detector_id_for_spectrum_number(
            transmission_workspace, incident_monitor_spectrum_number)
        detector_ids_roi, detector_id_transmission_monitor, detector_id_default_transmission_monitor = \
            self._get_detector_ids_for_transmission_calculation(transmission_workspace, calculate_transmission_state)
        all_detector_ids = [detector_id_incident_monitor]

        if len(detector_ids_roi) > 0:
            all_detector_ids.extend(detector_ids_roi)
        elif detector_id_transmission_monitor is not None:
            all_detector_ids.append(detector_id_transmission_monitor)
        elif detector_id_default_transmission_monitor is not None:
            all_detector_ids.append(detector_id_default_transmission_monitor)
        else:
            raise RuntimeError(
                "SANSCalculateTransmission: No region of interest or transmission monitor selected."
            )

        # 2. Clean transmission data
        data_type_string = self.getProperty("DataType").value
        data_type = DataType.from_string(data_type_string)
        transmission_workspace = self._get_corrected_wavelength_workspace(
            transmission_workspace, all_detector_ids,
            calculate_transmission_state)
        direct_workspace = self._get_corrected_wavelength_workspace(
            direct_workspace, all_detector_ids, calculate_transmission_state)

        # 3. Fit
        output_workspace, unfitted_transmission_workspace = \
            self._perform_fit(transmission_workspace, direct_workspace, detector_ids_roi,
                              detector_id_transmission_monitor, detector_id_default_transmission_monitor,
                              detector_id_incident_monitor, calculate_transmission_state, data_type)

        self.setProperty("OutputWorkspace", output_workspace)
        if unfitted_transmission_workspace:
            self.setProperty("UnfittedData", unfitted_transmission_workspace)
    def PyInit(self):
        # State
        self.declareProperty(
            PropertyManagerProperty('SANSState'),
            doc='A property manager which fulfills the SANSState contract.')

        # Input workspace in TOF
        self.declareProperty(
            MatrixWorkspaceProperty("TransmissionWorkspace",
                                    '',
                                    optional=PropertyMode.Mandatory,
                                    direction=Direction.Input),
            doc='The transmission workspace in time-of-flight units.')
        self.declareProperty(
            MatrixWorkspaceProperty("DirectWorkspace",
                                    '',
                                    optional=PropertyMode.Mandatory,
                                    direction=Direction.Input),
            doc='The direct workspace in time-of-flight units.')
        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 workspace
        self.declareProperty(
            MatrixWorkspaceProperty("OutputWorkspace",
                                    '',
                                    direction=Direction.Output),
            doc='A calculated transmission workspace in units of wavelength.')
        self.declareProperty(MatrixWorkspaceProperty(
            "UnfittedData", '', direction=Direction.Output),
                             doc='An unfitted data in units of wavelength.')
Example #22
0
    def PyInit(self):
        # ---------------
        # INPUT
        # ---------------
        # State
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        # Workspace which is to be moved
        self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The input workspace. If it is an event workspace, then the slice is taken. '
                                 'In case of a Workspace2D the original workspace is returned')

        self.declareProperty(MatrixWorkspaceProperty("InputWorkspaceMonitor", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The monitor workspace associated with the main input workspace.')

        # 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('SliceEventFactor', defaultValue=1.0,
                             direction=Direction.Output,
                             doc='The factor of the event slicing. This corresponds to the proportion of the the total '
                                 'proton charge, which the slice corresponds to.')

        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", '', direction=Direction.Output),
                             doc='The sliced workspace')

        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspaceMonitor", '', direction=Direction.Output),
                             doc='The output monitor workspace which has the correct slice factor applied to it.')
    def validateInputs(self):
        errors = dict()
        # Check that the input can be converted into the right state object
        state_property_manager = self.getProperty("SANSState").value
        try:
            state = create_deserialized_sans_state_from_property_manager(state_property_manager)
            state.property_manager = state_property_manager
            state.validate()
        except ValueError as err:
            errors.update({"SANSCalculateTransmission": str(err)})
            state = None

        if state is not None:
            transmission_workspace = self.getProperty("TransmissionWorkspace").value
            calculate_transmission_state = state.adjustment.calculate_transmission
            try:
                incident_monitor = calculate_transmission_state.incident_monitor
                if incident_monitor is None:
                    incident_monitor = calculate_transmission_state.default_incident_monitor
                transmission_workspace.getIndexFromSpectrumNumber(incident_monitor)
            except RuntimeError:
                errors.update({"IncidentMonitorSpectrumNumber": "The spectrum number for the incident monitor spectrum "
                                                                "does not seem to exist for the transmission"
                                                                " workspace."})

        if state is not None:
            calculate_transmission_state = state.adjustment.calculate_transmission
            fit = calculate_transmission_state.fit
            data_type_string = self.getProperty("DataType").value
            data_type = DataType.from_string(data_type_string)
            sample = fit[DataType.to_string(DataType.Sample)]
            can = fit[DataType.to_string(DataType.Can)]
            if data_type is DataType.Sample and sample.fit_type is None:
                errors.update({"DataType": "There does not seem to be a fit type set for the selected data type"})
            if data_type is DataType.Can and can.fit_type is None:
                errors.update({"DataType": "There does not seem to be a fit type set for the selected data type"})

        return errors
Example #24
0
    def PyInit(self):
        # ---------------
        # INPUT
        # ---------------
        # State
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        # Workspace which is to be moved
        self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The input workspace. If it is an event workspace, then the slice is taken. '
                                 'In case of a Workspace2D the original workspace is returned')

        self.declareProperty(MatrixWorkspaceProperty("InputWorkspaceMonitor", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The monitor workspace associated with the main input workspace.')

        # 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('SliceEventFactor', defaultValue=1.0,
                             direction=Direction.Output,
                             doc='The factor of the event slicing. This corresponds to the proportion of the the total '
                                 'proton charge, which the slice corresponds to.')

        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", '', direction=Direction.Output),
                             doc='The sliced workspace')

        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspaceMonitor", '', direction=Direction.Output),
                             doc='The output monitor workspace which has the correct slice factor applied to it.')
    def PyInit(self):
        # State
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        # Input workspace in TOF
        self.declareProperty(MatrixWorkspaceProperty("TransmissionWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The transmission workspace in time-of-flight units.')
        self.declareProperty(MatrixWorkspaceProperty("DirectWorkspace", '',
                                                     optional=PropertyMode.Mandatory, direction=Direction.Input),
                             doc='The direct workspace in time-of-flight units.')
        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 workspace
        self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", '', direction=Direction.Output),
                             doc='A calculated transmission workspace in units of wavelength.')
        self.declareProperty(MatrixWorkspaceProperty("UnfittedData", '', direction=Direction.Output),
                             doc='An unfitted data in units of wavelength.')
    def PyExec(self):
        # Read the state
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(state_property_manager)
        calculate_transmission_state = state.adjustment.calculate_transmission
        # The calculation of the transmission has the following steps:
        # 1. Get all spectrum numbers which take part in the transmission calculation
        # 2. Clean up the transmission and direct workspaces, ie peak prompt correction, flat background calculation,
        #    wavelength conversion and rebinning of the data.
        # 3. Run the CalculateTransmission algorithm
        transmission_workspace = self.getProperty("TransmissionWorkspace").value
        direct_workspace = self.getProperty("DirectWorkspace").value
        incident_monitor_spectrum_number = calculate_transmission_state.incident_monitor
        if incident_monitor_spectrum_number is None:
            incident_monitor_spectrum_number = calculate_transmission_state.default_incident_monitor

        # 1. Get relevant spectra
        detector_id_incident_monitor = get_detector_id_for_spectrum_number(transmission_workspace,
                                                                           incident_monitor_spectrum_number)
        detector_ids_roi, detector_id_transmission_monitor, detector_id_default_transmission_monitor = \
            self._get_detector_ids_for_transmission_calculation(transmission_workspace, calculate_transmission_state)
        all_detector_ids = [detector_id_incident_monitor]

        if len(detector_ids_roi) > 0:
            all_detector_ids.extend(detector_ids_roi)
        elif detector_id_transmission_monitor is not None:
            all_detector_ids.append(detector_id_transmission_monitor)
        elif detector_id_default_transmission_monitor is not None:
            all_detector_ids.append(detector_id_default_transmission_monitor)
        else:
            raise RuntimeError("SANSCalculateTransmission: No region of interest or transmission monitor selected.")

        # 2. Clean transmission data
        data_type_string = self.getProperty("DataType").value
        data_type = DataType.from_string(data_type_string)
        transmission_workspace = self._get_corrected_wavelength_workspace(transmission_workspace, all_detector_ids,
                                                                          calculate_transmission_state)
        direct_workspace = self._get_corrected_wavelength_workspace(direct_workspace, all_detector_ids,
                                                                    calculate_transmission_state)

        # 3. Fit
        output_workspace, unfitted_transmission_workspace = \
            self._perform_fit(transmission_workspace, direct_workspace, detector_ids_roi,
                              detector_id_transmission_monitor, detector_id_default_transmission_monitor,
                              detector_id_incident_monitor, calculate_transmission_state, data_type)

        self.setProperty("OutputWorkspace", output_workspace)
        if unfitted_transmission_workspace:
            self.setProperty("UnfittedData", unfitted_transmission_workspace)
Example #27
0
def slice_sans_event(state_slice,
                     input_ws,
                     input_ws_monitor,
                     data_type_str="Sample"):
    """
    Takes an event slice from an event workspace
    :param state_slice: The state.slice object
    :param input_ws: The input workspace. If it is an event workspace, then the slice is taken.
                     In case of a Workspace2D the original workspace is returned
    :param input_ws_monitor: The monitor workspace associated with the main input workspace.
    :param data_type_str: The component of the instrument which is to be reduced. Allowed values: ['Sample', 'Can']
    :return: A dict with the following:
             'SliceEventFactor': The factor of the event slicing. This corresponds to the proportion of the
                                 the total proton charge, which the slice corresponds to.
             'OutputWorkspace' : The slice workspace
             'OutputWorkspaceMonitor' : The output monitor workspace which has the correct slice factor applied to it.
    """

    data_type = DataType(data_type_str)

    # This should be removed in the future when cycle 19/1 data is unlikely to be processed by users
    # This prevents time slicing falling over, since we wrap around and get -0
    _clean_logs(ws=input_ws, estimate_logs=True)

    if isinstance(input_ws, Workspace2D):
        sliced_workspace = input_ws
        slice_factor = 1.0
    else:
        sliced_workspace, slice_factor = _create_slice(workspace=input_ws,
                                                       slice_info=state_slice,
                                                       data_type=data_type)

    # Scale the monitor accordingly
    slice_monitor = _scale_monitors(slice_factor=slice_factor,
                                    input_monitor_ws=input_ws_monitor)

    # Set the outputs
    append_to_sans_file_tag(sliced_workspace, "_sliced")

    to_return = {
        "OutputWorkspace": sliced_workspace,
        "SliceEventFactor": slice_factor,
        "OutputWorkspaceMonitor": slice_monitor
    }

    return to_return
Example #28
0
def run_initial_event_slice_reduction(reduction_alg, reduction_setting_bundle):
    """
    This function runs the initial core reduction for event slice data. This is essentially half
    a reduction (either sample or can), and is run before event slicing has been performed.

    :param reduction_alg: a handle to the initial event slice reduction algorithm.
    :param reduction_setting_bundle: a ReductionSettingBundle tuple
    :return: a EventSliceReductionSettingBundle tuple
    """
    # Get component to reduce
    component = get_component_to_reduce(reduction_setting_bundle)
    # Set the properties on the reduction algorithms
    serialized_state = reduction_setting_bundle.state.property_manager
    reduction_alg.setProperty("SANSState", serialized_state)
    reduction_alg.setProperty("Component", component)
    reduction_alg.setProperty("ScatterWorkspace",
                              reduction_setting_bundle.scatter_workspace)
    reduction_alg.setProperty(
        "ScatterMonitorWorkspace",
        reduction_setting_bundle.scatter_monitor_workspace)
    reduction_alg.setProperty(
        "DataType", DataType.to_string(reduction_setting_bundle.data_type))

    reduction_alg.setProperty("OutputWorkspace", EMPTY_NAME)
    reduction_alg.setProperty("OutputMonitorWorkspace", EMPTY_NAME)

    # Run the reduction core
    reduction_alg.execute()

    # Get the results
    output_workspace = reduction_alg.getProperty("OutputWorkspace").value
    mask_workspace = reduction_alg.getProperty("DummyMaskWorkspace").value
    output_monitor_workspace = reduction_alg.getProperty(
        "OutputMonitorWorkspace").value

    return EventSliceSettingBundle(
        state=reduction_setting_bundle.state,
        data_type=reduction_setting_bundle.data_type,
        reduction_mode=reduction_setting_bundle.reduction_mode,
        output_parts=reduction_setting_bundle.output_parts,
        scatter_workspace=output_workspace,
        dummy_mask_workspace=mask_workspace,
        scatter_monitor_workspace=output_monitor_workspace,
        direct_workspace=reduction_setting_bundle.direct_workspace,
        transmission_workspace=reduction_setting_bundle.transmission_workspace)
 def set_transmission_workspaces_on_output(self, transmission_bundles, fit_state):
     for transmission_bundle in transmission_bundles:
         fit_performed = fit_state[DataType.to_string(transmission_bundle.data_type)].fit_type != FitType.NoFit
         calculated_transmission_workspace = transmission_bundle.calculated_transmission_workspace
         unfitted_transmission_workspace = transmission_bundle.unfitted_transmission_workspace
         if transmission_bundle.data_type is DataType.Can:
             if does_can_workspace_exist_on_ads(calculated_transmission_workspace):
                 # The workspace is cloned here because the transmission runs are diagnostic output so even though
                 # the values already exist they need to be labelled seperately for each reduction.
                 calculated_transmission_workspace = CloneWorkspace(calculated_transmission_workspace, StoreInADS=False)
             if does_can_workspace_exist_on_ads(unfitted_transmission_workspace):
                 unfitted_transmission_workspace = CloneWorkspace(unfitted_transmission_workspace, StoreInADS=False)
             if fit_performed:
                 self.setProperty("OutputWorkspaceCalculatedTransmissionCan", calculated_transmission_workspace)
             self.setProperty("OutputWorkspaceUnfittedTransmissionCan", unfitted_transmission_workspace)
         elif transmission_bundle.data_type is DataType.Sample:
             if fit_performed:
                 self.setProperty("OutputWorkspaceCalculatedTransmission", calculated_transmission_workspace)
             self.setProperty("OutputWorkspaceUnfittedTransmission", unfitted_transmission_workspace)
         else:
             raise RuntimeError("SANSSingleReduction: The data type {0} should be"
                                " sample or can.".format(transmission_bundle.data_type))
Example #30
0
    def _assert_adjustment(self, state):
        adjustment = state.adjustment

        # Normalize to monitor settings
        normalize_to_monitor = adjustment.normalize_to_monitor
        self.assertEqual(normalize_to_monitor.prompt_peak_correction_min,  1000)
        self.assertEqual(normalize_to_monitor.prompt_peak_correction_max,  2000)
        self.assertEqual(normalize_to_monitor.rebin_type, RebinType.InterpolatingRebin)
        self.assertEqual(normalize_to_monitor.wavelength_low,  [1.5])
        self.assertEqual(normalize_to_monitor.wavelength_high,  [12.5])
        self.assertEqual(normalize_to_monitor.wavelength_step,  0.125)
        self.assertEqual(normalize_to_monitor.wavelength_step_type, RangeStepType.Lin)
        self.assertEqual(normalize_to_monitor.background_TOF_general_start,  3500)
        self.assertEqual(normalize_to_monitor.background_TOF_general_stop,  4500)
        self.assertEqual(normalize_to_monitor.background_TOF_monitor_start["1"],  35000)
        self.assertEqual(normalize_to_monitor.background_TOF_monitor_stop["1"],  65000)
        self.assertEqual(normalize_to_monitor.background_TOF_monitor_start["2"],  85000)
        self.assertEqual(normalize_to_monitor.background_TOF_monitor_stop["2"],  98000)
        self.assertEqual(normalize_to_monitor.incident_monitor,  1)

        # Calculate Transmission
        calculate_transmission = adjustment.calculate_transmission
        self.assertEqual(calculate_transmission.prompt_peak_correction_min,  1000)
        self.assertEqual(calculate_transmission.prompt_peak_correction_max,  2000)
        self.assertEqual(calculate_transmission.default_transmission_monitor,  3)
        self.assertEqual(calculate_transmission.default_incident_monitor,  2)
        self.assertEqual(calculate_transmission.incident_monitor,  1)
        self.assertEqual(calculate_transmission.transmission_radius_on_detector,  0.007)  # This is in mm
        self.assertEqual(calculate_transmission.transmission_roi_files,  ["test.xml", "test2.xml"])
        self.assertEqual(calculate_transmission.transmission_mask_files,  ["test3.xml", "test4.xml"])
        self.assertEqual(calculate_transmission.transmission_monitor,  4)
        self.assertEqual(calculate_transmission.rebin_type, RebinType.InterpolatingRebin)
        self.assertEqual(calculate_transmission.wavelength_low,  [1.5])
        self.assertEqual(calculate_transmission.wavelength_high,  [12.5])
        self.assertEqual(calculate_transmission.wavelength_step,  0.125)
        self.assertEqual(calculate_transmission.wavelength_step_type, RangeStepType.Lin)
        self.assertFalse(calculate_transmission.use_full_wavelength_range)
        self.assertEqual(calculate_transmission.wavelength_full_range_low,
                         Configurations.SANS2D.wavelength_full_range_low)
        self.assertEqual(calculate_transmission.wavelength_full_range_high,
                         Configurations.SANS2D.wavelength_full_range_high)
        self.assertEqual(calculate_transmission.background_TOF_general_start,  3500)
        self.assertEqual(calculate_transmission.background_TOF_general_stop,  4500)
        self.assertEqual(calculate_transmission.background_TOF_monitor_start["1"],  35000)
        self.assertEqual(calculate_transmission.background_TOF_monitor_stop["1"],  65000)
        self.assertEqual(calculate_transmission.background_TOF_monitor_start["2"],  85000)
        self.assertEqual(calculate_transmission.background_TOF_monitor_stop["2"],  98000)
        self.assertEqual(calculate_transmission.background_TOF_roi_start,  123)
        self.assertEqual(calculate_transmission.background_TOF_roi_stop,  466)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Sample)].fit_type, FitType.Logarithmic)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Sample)].wavelength_low,  1.5)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Sample)].wavelength_high,  12.5)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Sample)].polynomial_order,  0)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Can)].fit_type, FitType.Logarithmic)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Can)].wavelength_low,  1.5)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Can)].wavelength_high,  12.5)
        self.assertEqual(calculate_transmission.fit[DataType.to_string(DataType.Can)].polynomial_order,  0)

        # Wavelength and Pixel Adjustment
        wavelength_and_pixel_adjustment = adjustment.wavelength_and_pixel_adjustment
        self.assertEqual(wavelength_and_pixel_adjustment.wavelength_low,  [1.5])
        self.assertEqual(wavelength_and_pixel_adjustment.wavelength_high,  [12.5])
        self.assertEqual(wavelength_and_pixel_adjustment.wavelength_step,  0.125)
        self.assertEqual(wavelength_and_pixel_adjustment.wavelength_step_type, RangeStepType.Lin)
        self.assertTrue(wavelength_and_pixel_adjustment.adjustment_files[
                        DetectorType.to_string(DetectorType.LAB)].wavelength_adjustment_file ==
                        "DIRECTM1_15785_12m_31Oct12_v12.dat")
        self.assertTrue(wavelength_and_pixel_adjustment.adjustment_files[
                        DetectorType.to_string(DetectorType.HAB)].wavelength_adjustment_file ==
                        "DIRECTM1_15785_12m_31Oct12_v12.dat")

        # Assert wide angle correction
        self.assertTrue(state.adjustment.wide_angle_correction)
Example #31
0
def get_standard_output_workspace_name(state, reduction_data_type, transmission = False,
                                       data_type = DataType.to_string(DataType.Sample)):
    """
    Creates the name of the output workspace from a state object.

    The name of the output workspace is:
    1. The short run number
    2. If specific period is being reduced: 'p' + number
    3. Short detector name of the current reduction or "merged"
    4. The reduction dimensionality: "_" + dimensionality
    5. A wavelength range: wavelength_low + "_" + wavelength_high
    6. In case of a 1D reduction, then add phi limits
    7. If we are dealing with an actual slice limit, then specify it: "_tXX_TYY" Note that the time set to
       two decimals
    :param state: a SANSState object
    :param reduction_data_type: which reduced data type is being looked at, ie HAB, LAB or Merged
    :return: the name of the reduced workspace, and the base name fo the reduced workspace
    """
    # 1. Short run number
    data = state.data
    short_run_number = data.sample_scatter_run_number
    short_run_number_as_string = str(short_run_number)

    # 2. Multiperiod
    if state.data.sample_scatter_period != ALL_PERIODS:
        period = data.sample_scatter_period
        period_as_string = "p"+str(period)
    else:
        period_as_string = ""

    # 3. Detector name
    move = state.move
    detectors = move.detectors
    if reduction_data_type is ISISReductionMode.Merged:
        detector_name_short = "merged"
    elif reduction_data_type is ISISReductionMode.HAB:
        det_name = detectors[DetectorType.to_string(DetectorType.HAB)].detector_name_short
        detector_name_short = det_name if det_name is not None else "hab"
    elif reduction_data_type is ISISReductionMode.LAB:
        det_name = detectors[DetectorType.to_string(DetectorType.LAB)].detector_name_short
        detector_name_short = det_name if det_name is not None else "lab"
    else:
        raise RuntimeError("SANSStateFunctions: Unknown reduction data type {0} cannot be used to "
                           "create an output name".format(reduction_data_type))

    # 4. Dimensionality
    reduction = state.reduction
    if reduction.reduction_dimensionality is ReductionDimensionality.OneDim:
        dimensionality_as_string = "_1D"
    else:
        dimensionality_as_string = "_2D"

    # 5. Wavelength range
    wavelength = state.wavelength
    wavelength_range_string = "_" + str(wavelength.wavelength_low) + "_" + str(wavelength.wavelength_high)

    # 6. Phi Limits
    mask = state.mask
    if reduction.reduction_dimensionality is ReductionDimensionality.OneDim:
        if mask.phi_min and mask.phi_max and (abs(mask.phi_max - mask.phi_min) != 180.0):
            phi_limits_as_string = 'Phi' + str(mask.phi_min) + '_' + str(mask.phi_max)
        else:
            phi_limits_as_string = ""
    else:
        phi_limits_as_string = ""

    # 7. Slice limits
    slice_state = state.slice
    start_time = slice_state.start_time
    end_time = slice_state.end_time
    if start_time and end_time:
        start_time_as_string = '_t%.2f' % start_time[0]
        end_time_as_string = '_T%.2f' % end_time[0]
    else:
        start_time_as_string = ""
        end_time_as_string = ""

    # 8. Transmission name
    transmission_name = "_trans_" + data_type

    # Piece it all together
    if not transmission:
        output_workspace_name = (short_run_number_as_string + period_as_string + detector_name_short +
                                 dimensionality_as_string + wavelength_range_string + phi_limits_as_string +
                                 start_time_as_string + end_time_as_string)
        output_workspace_base_name = (short_run_number_as_string + detector_name_short + dimensionality_as_string +
                                      wavelength_range_string + phi_limits_as_string)
    else:
        output_workspace_name = (short_run_number_as_string + period_as_string + transmission_name +
                                 wavelength_range_string + phi_limits_as_string + start_time_as_string
                                 + end_time_as_string)
        output_workspace_base_name = (short_run_number_as_string + transmission_name +
                                      wavelength_range_string + phi_limits_as_string)
    return output_workspace_name, output_workspace_base_name
Example #32
0
    def validate(self):  # noqa
        is_invalid = {}
        # -----------------
        # Incident monitor
        # -----------------
        if self.incident_monitor is None and self.default_incident_monitor is None:
            entry = validation_message("No incident monitor was specified.",
                                       "Make sure that incident monitor has been specified.",
                                       {"incident_monitor": self.incident_monitor,
                                        "default_incident_monitor": self.default_incident_monitor})
            is_invalid.update(entry)

        # --------------
        # Transmission, either we need some ROI (ie radius, roi files /mask files) or a transmission monitor
        # --------------
        has_no_transmission_monitor_setting = self.transmission_monitor is None and\
                                              self.default_transmission_monitor is None  # noqa
        has_no_transmission_roi_setting = self.transmission_radius_on_detector is None and\
                                          self.transmission_roi_files is None  # noqa
        if has_no_transmission_monitor_setting and has_no_transmission_roi_setting:
            entry = validation_message("No transmission settings were specified.",
                                       "Make sure that transmission settings are specified.",
                                       {"transmission_monitor": self.transmission_monitor,
                                        "default_transmission_monitor": self.default_transmission_monitor,
                                        "transmission_radius_on_detector": self.transmission_radius_on_detector,
                                        "transmission_roi_files": self.transmission_roi_files})
            is_invalid.update(entry)

        # -----------------
        # Prompt peak
        # -----------------
        if not is_pure_none_or_not_none([self.prompt_peak_correction_min, self.prompt_peak_correction_max]):
            entry = validation_message("Inconsistent prompt peak setting.",
                                       "Make sure that you have specified both prompt peak bounds (or none).",
                                       {"prompt_peak_correction_min": self.prompt_peak_correction_min,
                                        "prompt_peak_correction_max": self.prompt_peak_correction_max})
            is_invalid.update(entry)

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

        # -----------------
        # Wavelength rebin
        # -----------------
        if one_is_none([self.wavelength_low, self.wavelength_high, self.wavelength_step, self.wavelength_step_type,
                        self.rebin_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,
                                        "rebin_type": self.rebin_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)

        if self.use_full_wavelength_range:
            if self.wavelength_full_range_low is None or self.wavelength_full_range_high is None:
                entry = validation_message("Incorrect full wavelength settings.",
                                           "Make sure that both full wavelength entries have been set.",
                                           {"wavelength_full_range_low": self.wavelength_full_range_low,
                                            "wavelength_full_range_high": self.wavelength_full_range_high})
                is_invalid.update(entry)
            if is_not_none_and_first_larger_than_second([self.wavelength_full_range_low,
                                                         self.wavelength_full_range_high]):
                entry = validation_message("Incorrect wavelength bounds.",
                                           "Make sure that lower full wavelength bound is smaller then upper bound.",
                                           {"wavelength_full_range_low": self.wavelength_full_range_low,
                                            "wavelength_full_range_high": self.wavelength_full_range_high})
                is_invalid.update(entry)

        # ----------------------
        # Background correction
        # ----------------------
        if not is_pure_none_or_not_none([self.background_TOF_general_start, self.background_TOF_general_stop]):
            entry = validation_message("A general background TOF entry has not been set.",
                                       "Make sure that either all general background TOF entries are set or none.",
                                       {"background_TOF_general_start": self.background_TOF_general_start,
                                        "background_TOF_general_stop": self.background_TOF_general_stop})
            is_invalid.update(entry)
        if is_not_none_and_first_larger_than_second([self.background_TOF_general_start,
                                                     self.background_TOF_general_stop]):
            entry = validation_message("Incorrect general background TOF bounds.",
                                       "Make sure that lower general background TOF bound is smaller then upper bound.",
                                       {"background_TOF_general_start": self.background_TOF_general_start,
                                        "background_TOF_general_stop": self.background_TOF_general_stop})
            is_invalid.update(entry)

        if not is_pure_none_or_not_none([self.background_TOF_roi_start, self.background_TOF_roi_stop]):
            entry = validation_message("A ROI background TOF entry has not been set.",
                                       "Make sure that either all ROI background TOF entries are set or none.",
                                       {"background_TOF_roi_start": self.background_TOF_roi_start,
                                        "background_TOF_roi_stop": self.background_TOF_roi_stop})
            is_invalid.update(entry)

        if is_not_none_and_first_larger_than_second([self.background_TOF_roi_start,
                                                     self.background_TOF_roi_stop]):
            entry = validation_message("Incorrect ROI background TOF bounds.",
                                       "Make sure that lower ROI background TOF bound is smaller then upper bound.",
                                       {"background_TOF_roi_start": self.background_TOF_roi_start,
                                        "background_TOF_roi_stop": self.background_TOF_roi_stop})
            is_invalid.update(entry)

        if not is_pure_none_or_not_none([self.background_TOF_monitor_start, self.background_TOF_monitor_stop]):
            entry = validation_message("A monitor background TOF entry has not been set.",
                                       "Make sure that either all monitor background TOF entries are set or none.",
                                       {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                        "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
            is_invalid.update(entry)

        if self.background_TOF_monitor_start is not None and self.background_TOF_monitor_stop is not None:
            if len(self.background_TOF_monitor_start) != len(self.background_TOF_monitor_stop):
                entry = validation_message("The monitor background TOF entries have a length mismatch.",
                                           "Make sure that all monitor background TOF entries have the same length.",
                                           {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                            "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
                is_invalid.update(entry)
            for key_start, value_start in self.background_TOF_monitor_start.items():
                if key_start not in self.background_TOF_monitor_stop:
                    entry = validation_message("The monitor background TOF had spectrum number mismatch.",
                                               "Make sure that all monitors have entries for start and stop.",
                                               {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                                "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
                    is_invalid.update(entry)
                else:
                    value_stop = self.background_TOF_monitor_stop[key_start]
                    if value_start > value_stop:
                        entry = validation_message("Incorrect monitor background TOF bounds.",
                                                   "Make sure that lower monitor background TOF bound is"
                                                   " smaller then upper bound.",
                                                   {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                                    "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
                        is_invalid.update(entry)

        # -----
        # Fit
        # -----
        self.fit[DataType.to_string(DataType.Sample)].validate()
        self.fit[DataType.to_string(DataType.Can)].validate()

        if is_invalid:
            raise ValueError("StateCalculateTransmission: The provided inputs are illegal. "
                             "Please see: {0}".format(json.dumps(is_invalid)))
Example #33
0
    def _assert_adjustment(self, state):
        adjustment = state.adjustment

        # Normalize to monitor settings
        normalize_to_monitor = adjustment.normalize_to_monitor
        self.assertTrue(normalize_to_monitor.prompt_peak_correction_min == 1000)
        self.assertTrue(normalize_to_monitor.prompt_peak_correction_max == 2000)
        self.assertTrue(normalize_to_monitor.rebin_type is RebinType.InterpolatingRebin)
        self.assertTrue(normalize_to_monitor.wavelength_low == 1.5)
        self.assertTrue(normalize_to_monitor.wavelength_high == 12.5)
        self.assertTrue(normalize_to_monitor.wavelength_step == 0.125)
        self.assertTrue(normalize_to_monitor.wavelength_step_type is RangeStepType.Lin)
        self.assertTrue(normalize_to_monitor.background_TOF_general_start == 3500)
        self.assertTrue(normalize_to_monitor.background_TOF_general_stop == 4500)
        self.assertTrue(normalize_to_monitor.background_TOF_monitor_start["1"] == 35000)
        self.assertTrue(normalize_to_monitor.background_TOF_monitor_stop["1"] == 65000)
        self.assertTrue(normalize_to_monitor.background_TOF_monitor_start["2"] == 85000)
        self.assertTrue(normalize_to_monitor.background_TOF_monitor_stop["2"] == 98000)
        self.assertTrue(normalize_to_monitor.incident_monitor == 1)

        # Calculate Transmission
        calculate_transmission = adjustment.calculate_transmission
        self.assertTrue(calculate_transmission.prompt_peak_correction_min == 1000)
        self.assertTrue(calculate_transmission.prompt_peak_correction_max == 2000)
        self.assertTrue(calculate_transmission.default_transmission_monitor == 3)
        self.assertTrue(calculate_transmission.default_incident_monitor == 2)
        self.assertTrue(calculate_transmission.incident_monitor == 1)
        self.assertTrue(calculate_transmission.transmission_radius_on_detector == 0.007)  # This is in mm
        self.assertTrue(calculate_transmission.transmission_roi_files == ["test.xml", "test2.xml"])
        self.assertTrue(calculate_transmission.transmission_mask_files == ["test3.xml", "test4.xml"])
        self.assertTrue(calculate_transmission.transmission_monitor == 4)
        self.assertTrue(calculate_transmission.rebin_type is RebinType.InterpolatingRebin)
        self.assertTrue(calculate_transmission.wavelength_low == 1.5)
        self.assertTrue(calculate_transmission.wavelength_high == 12.5)
        self.assertTrue(calculate_transmission.wavelength_step == 0.125)
        self.assertTrue(calculate_transmission.wavelength_step_type is RangeStepType.Lin)
        self.assertFalse(calculate_transmission.use_full_wavelength_range)
        self.assertTrue(calculate_transmission.wavelength_full_range_low ==
                        Configurations.SANS2D.wavelength_full_range_low)
        self.assertTrue(calculate_transmission.wavelength_full_range_high ==
                        Configurations.SANS2D.wavelength_full_range_high)
        self.assertTrue(calculate_transmission.background_TOF_general_start == 3500)
        self.assertTrue(calculate_transmission.background_TOF_general_stop == 4500)
        self.assertTrue(calculate_transmission.background_TOF_monitor_start["1"] == 35000)
        self.assertTrue(calculate_transmission.background_TOF_monitor_stop["1"] == 65000)
        self.assertTrue(calculate_transmission.background_TOF_monitor_start["2"] == 85000)
        self.assertTrue(calculate_transmission.background_TOF_monitor_stop["2"] == 98000)
        self.assertTrue(calculate_transmission.background_TOF_roi_start == 123)
        self.assertTrue(calculate_transmission.background_TOF_roi_stop == 466)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Sample)].fit_type is FitType.Logarithmic)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Sample)].wavelength_low == 1.5)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Sample)].wavelength_high == 12.5)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Sample)].polynomial_order == 0)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Can)].fit_type is FitType.Logarithmic)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Can)].wavelength_low == 1.5)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Can)].wavelength_high == 12.5)
        self.assertTrue(calculate_transmission.fit[DataType.to_string(DataType.Can)].polynomial_order == 0)
        self.assertTrue(adjustment.show_transmission == False)

        # Wavelength and Pixel Adjustment
        wavelength_and_pixel_adjustment = adjustment.wavelength_and_pixel_adjustment
        self.assertTrue(wavelength_and_pixel_adjustment.wavelength_low == 1.5)
        self.assertTrue(wavelength_and_pixel_adjustment.wavelength_high == 12.5)
        self.assertTrue(wavelength_and_pixel_adjustment.wavelength_step == 0.125)
        self.assertTrue(wavelength_and_pixel_adjustment.wavelength_step_type is RangeStepType.Lin)
        self.assertTrue(wavelength_and_pixel_adjustment.adjustment_files[
                        DetectorType.to_string(DetectorType.LAB)].wavelength_adjustment_file ==
                        "DIRECTM1_15785_12m_31Oct12_v12.dat")
        self.assertTrue(wavelength_and_pixel_adjustment.adjustment_files[
                        DetectorType.to_string(DetectorType.HAB)].wavelength_adjustment_file ==
                        "DIRECTM1_15785_12m_31Oct12_v12.dat")

        # Assert wide angle correction
        self.assertTrue(state.adjustment.wide_angle_correction)
    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.Mandatory,
                                    direction=Direction.Input),
            doc=
            'The scatter workspace. This workspace does not contain monitors.')
        self.declareProperty(
            MatrixWorkspaceProperty('ScatterMonitorWorkspace',
                                    '',
                                    optional=PropertyMode.Mandatory,
                                    direction=Direction.Input),
            doc=
            'The scatter monitor workspace. This workspace only condtains 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')

        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.")

        self.declareProperty("CompatibilityMode",
                             False,
                             direction=Direction.Input)

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

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

        # ----------
        # OUTPUT
        # ----------
        self.declareProperty(MatrixWorkspaceProperty(
            "OutputWorkspaceLeft",
            'Left',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The left output workspace.')

        self.declareProperty(MatrixWorkspaceProperty(
            "OutputWorkspaceTop",
            'Top',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The top output workspace.')

        self.declareProperty(MatrixWorkspaceProperty(
            "OutputWorkspaceRight",
            'Right',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The right output workspace.')

        self.declareProperty(MatrixWorkspaceProperty(
            "OutputWorkspaceBottom",
            'Bottom',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The bottom output workspace.')
    def validate(self):  # noqa
        is_invalid = {}
        # -----------------
        # Incident monitor
        # -----------------
        if self.incident_monitor is None and self.default_incident_monitor is None:
            entry = validation_message("No incident monitor was specified.",
                                       "Make sure that incident monitor has been specified.",
                                       {"incident_monitor": self.incident_monitor,
                                        "default_incident_monitor": self.default_incident_monitor})
            is_invalid.update(entry)

        # --------------
        # Transmission, either we need some ROI (ie radius, roi files /mask files) or a transmission monitor
        # --------------
        has_no_transmission_monitor_setting = self.transmission_monitor is None and\
                                              self.default_transmission_monitor is None  # noqa
        has_no_transmission_roi_setting = self.transmission_radius_on_detector is None and\
                                          self.transmission_roi_files is None  # noqa
        if has_no_transmission_monitor_setting and has_no_transmission_roi_setting:
            entry = validation_message("No transmission settings were specified.",
                                       "Make sure that transmission settings are specified.",
                                       {"transmission_monitor": self.transmission_monitor,
                                        "default_transmission_monitor": self.default_transmission_monitor,
                                        "transmission_radius_on_detector": self.transmission_radius_on_detector,
                                        "transmission_roi_files": self.transmission_roi_files})
            is_invalid.update(entry)

        # -----------------
        # Prompt peak
        # -----------------
        if not is_pure_none_or_not_none([self.prompt_peak_correction_min, self.prompt_peak_correction_max]):
            entry = validation_message("Inconsistent prompt peak setting.",
                                       "Make sure that you have specified both prompt peak bounds (or none).",
                                       {"prompt_peak_correction_min": self.prompt_peak_correction_min,
                                        "prompt_peak_correction_max": self.prompt_peak_correction_max})
            is_invalid.update(entry)

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

        # -----------------
        # Wavelength rebin
        # -----------------
        if one_is_none([self.wavelength_low, self.wavelength_high, self.wavelength_step, self.wavelength_step_type,
                        self.wavelength_step_type, self.rebin_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,
                                        "rebin_type": self.rebin_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)

        if self.use_full_wavelength_range:
            if self.wavelength_full_range_low is None or self.wavelength_full_range_high is None:
                entry = validation_message("Incorrect full wavelength settings.",
                                           "Make sure that both full wavelength entries have been set.",
                                           {"wavelength_full_range_low": self.wavelength_full_range_low,
                                            "wavelength_full_range_high": self.wavelength_full_range_high})
                is_invalid.update(entry)
            if is_not_none_and_first_larger_than_second([self.wavelength_full_range_low,
                                                         self.wavelength_full_range_high]):
                entry = validation_message("Incorrect wavelength bounds.",
                                           "Make sure that lower full wavelength bound is smaller then upper bound.",
                                           {"wavelength_full_range_low": self.wavelength_full_range_low,
                                            "wavelength_full_range_high": self.wavelength_full_range_high})
                is_invalid.update(entry)

        # ----------------------
        # Background correction
        # ----------------------
        if not is_pure_none_or_not_none([self.background_TOF_general_start, self.background_TOF_general_stop]):
            entry = validation_message("A general background TOF entry has not been set.",
                                       "Make sure that either all general background TOF entries are set or none.",
                                       {"background_TOF_general_start": self.background_TOF_general_start,
                                        "background_TOF_general_stop": self.background_TOF_general_stop})
            is_invalid.update(entry)
        if is_not_none_and_first_larger_than_second([self.background_TOF_general_start,
                                                     self.background_TOF_general_stop]):
            entry = validation_message("Incorrect general background TOF bounds.",
                                       "Make sure that lower general background TOF bound is smaller then upper bound.",
                                       {"background_TOF_general_start": self.background_TOF_general_start,
                                        "background_TOF_general_stop": self.background_TOF_general_stop})
            is_invalid.update(entry)

        if not is_pure_none_or_not_none([self.background_TOF_roi_start, self.background_TOF_roi_stop]):
            entry = validation_message("A ROI background TOF entry has not been set.",
                                       "Make sure that either all ROI background TOF entries are set or none.",
                                       {"background_TOF_roi_start": self.background_TOF_roi_start,
                                        "background_TOF_roi_stop": self.background_TOF_roi_stop})
            is_invalid.update(entry)

        if is_not_none_and_first_larger_than_second([self.background_TOF_roi_start,
                                                     self.background_TOF_roi_stop]):
            entry = validation_message("Incorrect ROI background TOF bounds.",
                                       "Make sure that lower ROI background TOF bound is smaller then upper bound.",
                                       {"background_TOF_roi_start": self.background_TOF_roi_start,
                                        "background_TOF_roi_stop": self.background_TOF_roi_stop})
            is_invalid.update(entry)

        if not is_pure_none_or_not_none([self.background_TOF_monitor_start, self.background_TOF_monitor_stop]):
            entry = validation_message("A monitor background TOF entry has not been set.",
                                       "Make sure that either all monitor background TOF entries are set or none.",
                                       {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                        "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
            is_invalid.update(entry)

        if self.background_TOF_monitor_start is not None and self.background_TOF_monitor_stop is not None:
            if len(self.background_TOF_monitor_start) != len(self.background_TOF_monitor_stop):
                entry = validation_message("The monitor background TOF entries have a length mismatch.",
                                           "Make sure that all monitor background TOF entries have the same length.",
                                           {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                            "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
                is_invalid.update(entry)
            for key_start, value_start in list(self.background_TOF_monitor_start.items()):
                if key_start not in self.background_TOF_monitor_stop:
                    entry = validation_message("The monitor background TOF had spectrum number mismatch.",
                                               "Make sure that all monitors have entries for start and stop.",
                                               {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                                "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
                    is_invalid.update(entry)
                else:
                    value_stop = self.background_TOF_monitor_stop[key_start]
                    if value_start > value_stop:
                        entry = validation_message("Incorrect monitor background TOF bounds.",
                                                   "Make sure that lower monitor background TOF bound is"
                                                   " smaller then upper bound.",
                                                   {"background_TOF_monitor_start": self.background_TOF_monitor_start,
                                                    "background_TOF_monitor_stop": self.background_TOF_monitor_stop})
                        is_invalid.update(entry)

        # -----
        # Fit
        # -----
        self.fit[DataType.to_string(DataType.Sample)].validate()
        self.fit[DataType.to_string(DataType.Can)].validate()

        if is_invalid:
            raise ValueError("StateCalculateTransmission: The provided inputs are illegal. "
                             "Please see: {0}".format(json.dumps(is_invalid)))
Example #36
0
    def test_that_reduction_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_calculate_transmission_builder(data_info)
        self.assertTrue(builder)

        builder.set_prompt_peak_correction_min(12.0)
        builder.set_prompt_peak_correction_max(17.0)

        builder.set_incident_monitor(1)
        builder.set_default_incident_monitor(2)
        builder.set_transmission_monitor(3)
        builder.set_default_transmission_monitor(4)
        builder.set_transmission_radius_on_detector(1.)
        builder.set_transmission_roi_files(["sdfs", "sddfsdf"])
        builder.set_transmission_mask_files(["sdfs", "bbbbbb"])

        builder.set_rebin_type(RebinType.Rebin)
        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)
        builder.set_use_full_wavelength_range(True)
        builder.set_wavelength_full_range_low(12.)
        builder.set_wavelength_full_range_high(24.)

        builder.set_background_TOF_general_start(1.4)
        builder.set_background_TOF_general_stop(34.4)
        builder.set_background_TOF_monitor_start({"1": 123, "2": 123})
        builder.set_background_TOF_monitor_stop({"1": 234, "2": 2323})
        builder.set_background_TOF_roi_start(1.4)
        builder.set_background_TOF_roi_stop(34.4)

        builder.set_Sample_fit_type(FitType.Linear)
        builder.set_Sample_polynomial_order(0)
        builder.set_Sample_wavelength_low(10.0)
        builder.set_Sample_wavelength_high(20.0)

        builder.set_Can_fit_type(FitType.Polynomial)
        builder.set_Can_polynomial_order(3)
        builder.set_Can_wavelength_low(10.0)
        builder.set_Can_wavelength_high(20.0)

        state = builder.build()

        # Assert
        self.assertTrue(state.prompt_peak_correction_min == 12.0)
        self.assertTrue(state.prompt_peak_correction_max == 17.0)

        self.assertTrue(state.incident_monitor == 1)
        self.assertTrue(state.default_incident_monitor == 2)
        self.assertTrue(state.transmission_monitor == 3)
        self.assertTrue(state.default_transmission_monitor == 4)
        self.assertTrue(state.transmission_radius_on_detector == 1.)
        self.assertTrue(state.transmission_roi_files == ["sdfs", "sddfsdf"])
        self.assertTrue(state.transmission_mask_files == ["sdfs", "bbbbbb"])

        self.assertTrue(state.rebin_type is RebinType.Rebin)
        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)
        self.assertTrue(state.use_full_wavelength_range is True)
        self.assertTrue(state.wavelength_full_range_low == 12.)
        self.assertTrue(state.wavelength_full_range_high == 24.)

        self.assertTrue(state.background_TOF_general_start == 1.4)
        self.assertTrue(state.background_TOF_general_stop == 34.4)
        self.assertTrue(
            len(
                set(state.background_TOF_monitor_start.items()) & set({
                    "1": 123,
                    "2": 123
                }.items())) == 2)
        self.assertTrue(
            len(
                set(state.background_TOF_monitor_stop.items()) & set({
                    "1": 234,
                    "2": 2323
                }.items())) == 2)
        self.assertTrue(state.background_TOF_roi_start == 1.4)
        self.assertTrue(state.background_TOF_roi_stop == 34.4)

        self.assertTrue(state.fit[DataType.to_string(DataType.Sample)].fit_type
                        is FitType.Linear)
        self.assertTrue(state.fit[DataType.to_string(
            DataType.Sample)].polynomial_order == 0)
        self.assertTrue(state.fit[DataType.to_string(
            DataType.Sample)].wavelength_low == 10.)
        self.assertTrue(state.fit[DataType.to_string(
            DataType.Sample)].wavelength_high == 20.)

        self.assertTrue(state.fit[DataType.to_string(DataType.Can)].fit_type is
                        FitType.Polynomial)
        self.assertTrue(
            state.fit[DataType.to_string(DataType.Can)].polynomial_order == 3)
        self.assertTrue(
            state.fit[DataType.to_string(DataType.Can)].wavelength_low == 10.)
        self.assertTrue(
            state.fit[DataType.to_string(DataType.Can)].wavelength_high == 20.)
Example #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('DummyMaskWorkspace',
                                    '',
                                    optional=PropertyMode.Optional,
                                    direction=Direction.Input),
            doc=
            'The histogram workspace containing mask bins for the event workspace, to be copied '
            'over after event slicing.')
        self.declareProperty(
            MatrixWorkspaceProperty('ScatterMonitorWorkspace',
                                    '',
                                    optional=PropertyMode.Optional,
                                    direction=Direction.Input),
            doc=
            'The scatter monitor workspace. This workspace only contains monitors.'
        )
        # Direct Workspace
        self.declareProperty(MatrixWorkspaceProperty(
            'DirectWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Input),
                             doc='The direct workspace.')
        # Transmission Workspace
        self.declareProperty(MatrixWorkspaceProperty(
            'TransmissionWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Input),
                             doc='The transmission workspace')

        self.setPropertyGroup("ScatterWorkspace", 'Data')
        self.setPropertyGroup("ScatterMonitorWorkspace", 'Data')
        self.setPropertyGroup("DummyMaskWorkspace", 'Data')
        self.setPropertyGroup("DirectWorkspace", 'Data')
        self.setPropertyGroup("TransmissionWorkspace", '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
        # ----------
        # SANSReductionCoreEventSlice has the same outputs as SANSReductionCore
        self._pyinit_output()
Example #38
0
    def PyInit(self):
        # ---------------
        # INPUT
        # ---------------
        # State
        self.declareProperty(
            PropertyManagerProperty('SANSState'),
            doc='A property manager which fulfills the SANSState contract.')

        # Input workspaces
        self.declareProperty(MatrixWorkspaceProperty(
            'TransmissionWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Input),
                             doc='The transmission workspace.')
        self.declareProperty(MatrixWorkspaceProperty(
            'DirectWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Input),
                             doc='The direct workspace.')
        self.declareProperty(
            MatrixWorkspaceProperty('MonitorWorkspace',
                                    '',
                                    optional=PropertyMode.Optional,
                                    direction=Direction.Input),
            doc=
            'The scatter monitor workspace. This workspace only contains monitors.'
        )

        workspace_validator = CompositeValidator()
        workspace_validator.add(WorkspaceUnitValidator("Wavelength"))
        self.declareProperty(
            MatrixWorkspaceProperty('SampleData',
                                    '',
                                    optional=PropertyMode.Optional,
                                    direction=Direction.Input,
                                    validator=workspace_validator),
            doc=
            'A workspace cropped to the detector to be reduced (the SAME as the input to Q1D). '
            'This used to verify the solid angle. The workspace is not modified, just inspected.'
        )

        # The component
        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."
        )

        # 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.")

        # Slice factor for monitor
        self.declareProperty('SliceEventFactor',
                             1.0,
                             direction=Direction.Input,
                             doc='The slice factor for the monitor '
                             'normalization. This factor is the'
                             ' one obtained from event '
                             'slicing.')

        # ---------------
        # Output
        # ---------------
        self.declareProperty(
            MatrixWorkspaceProperty('OutputWorkspaceWavelengthAdjustment',
                                    '',
                                    direction=Direction.Output),
            doc='The workspace for wavelength-based adjustments.')

        self.declareProperty(
            MatrixWorkspaceProperty('OutputWorkspacePixelAdjustment',
                                    '',
                                    direction=Direction.Output),
            doc='The workspace for wavelength-based adjustments.')

        self.declareProperty(
            MatrixWorkspaceProperty(
                'OutputWorkspaceWavelengthAndPixelAdjustment',
                '',
                direction=Direction.Output),
            doc=
            'The workspace for, both, wavelength- and pixel-based adjustments.'
        )

        self.declareProperty(MatrixWorkspaceProperty(
            'CalculatedTransmissionWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The calculated transmission workspace')

        self.declareProperty(MatrixWorkspaceProperty(
            'UnfittedTransmissionWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The unfitted transmission workspace')
    def _perform_fit(self, transmission_workspace, direct_workspace,
                     transmission_roi_detector_ids, transmission_monitor_detector_id,
                     transmission_monitor_detector_id_default, incident_monitor_detector_id,
                     calculate_transmission_state, data_type):
        """
        This performs the actual transmission calculation.

        :param transmission_workspace: the corrected transmission workspace
        :param direct_workspace: the corrected direct workspace
        :param transmission_roi_detector_ids: the roi detector ids
        :param transmission_monitor_detector_id: the transmission monitor detector id
        :param transmission_monitor_detector_id_default: the default transmission monitor id
        :param incident_monitor_detector_id: the incident monitor id
        :param calculate_transmission_state: the state for the transmission calculation
        :param data_type: the data type which is currently being investigated, ie if it is a sample or a can run.
        :return: a fitted workspace and an unfitted workspace
        """

        wavelength_low = calculate_transmission_state.wavelength_low[0]
        wavelength_high = calculate_transmission_state.wavelength_high[0]
        wavelength_step = calculate_transmission_state.wavelength_step
        wavelength_step_type = calculate_transmission_state.wavelength_step_type
        prefix = 1.0 if wavelength_step_type is RangeStepType.Lin else -1.0
        wavelength_step *= prefix
        rebin_params = str(wavelength_low) + "," + str(wavelength_step) + "," + str(wavelength_high)

        trans_name = "CalculateTransmission"
        trans_options = {"SampleRunWorkspace": transmission_workspace,
                         "DirectRunWorkspace": direct_workspace,
                         "OutputWorkspace": EMPTY_NAME,
                         "IncidentBeamMonitor": incident_monitor_detector_id,
                         "RebinParams": rebin_params,
                         "OutputUnfittedData": True}

        # If we have a region of interest we use it else we use the transmission monitor

        if len(transmission_roi_detector_ids) > 0:
            trans_options.update({"TransmissionROI": transmission_roi_detector_ids})
        elif transmission_monitor_detector_id is not None:
            trans_options.update({"TransmissionMonitor": transmission_monitor_detector_id})
        elif transmission_monitor_detector_id_default:
            trans_options.update({"TransmissionMonitor": transmission_monitor_detector_id_default})
        else:
            raise RuntimeError("No transmission monitor has been provided.")

        # Get the fit setting for the correct data type, ie either for the Sample of the Can
        fit_type = calculate_transmission_state.fit[DataType.to_string(data_type)].fit_type
        if fit_type is FitType.Logarithmic:
            fit_string = "Log"
        elif fit_type is FitType.Polynomial:
            fit_string = "Polynomial"
        else:
            fit_string = "Linear"

        trans_options.update({"FitMethod": fit_string})
        if fit_type is FitType.Polynomial:
            polynomial_order = calculate_transmission_state.fit[DataType.to_string(data_type)].polynomial_order
            trans_options.update({"PolynomialOrder": polynomial_order})

        trans_alg = create_unmanaged_algorithm(trans_name, **trans_options)
        trans_alg.execute()

        fitted_transmission_workspace = trans_alg.getProperty("OutputWorkspace").value
        try:
            unfitted_transmission_workspace = trans_alg.getProperty("UnfittedData").value
        except RuntimeError:
            unfitted_transmission_workspace = None

        # Set the y label correctly for the fitted and unfitted transmission workspaces
        y_unit_label_transmission_ratio = "Transmission"
        if fitted_transmission_workspace:
            fitted_transmission_workspace.setYUnitLabel(y_unit_label_transmission_ratio)
        if unfitted_transmission_workspace:
            unfitted_transmission_workspace.setYUnitLabel(y_unit_label_transmission_ratio)

        if fit_type is FitType.NoFit:
            output_workspace = unfitted_transmission_workspace
        else:
            output_workspace = fitted_transmission_workspace
        return output_workspace, unfitted_transmission_workspace
Example #40
0
    def test_that_reduction_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_calculate_transmission_builder(data_info)
        self.assertTrue(builder)

        builder.set_prompt_peak_correction_min(12.0)
        builder.set_prompt_peak_correction_max(17.0)

        builder.set_incident_monitor(1)
        builder.set_default_incident_monitor(2)
        builder.set_transmission_monitor(3)
        builder.set_default_transmission_monitor(4)
        builder.set_transmission_radius_on_detector(1.)
        builder.set_transmission_roi_files(["sdfs", "sddfsdf"])
        builder.set_transmission_mask_files(["sdfs", "bbbbbb"])

        builder.set_rebin_type(RebinType.Rebin)
        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)
        builder.set_use_full_wavelength_range(True)
        builder.set_wavelength_full_range_low(12.)
        builder.set_wavelength_full_range_high(24.)

        builder.set_background_TOF_general_start(1.4)
        builder.set_background_TOF_general_stop(34.4)
        builder.set_background_TOF_monitor_start({"1": 123, "2": 123})
        builder.set_background_TOF_monitor_stop({"1": 234, "2": 2323})
        builder.set_background_TOF_roi_start(1.4)
        builder.set_background_TOF_roi_stop(34.4)

        builder.set_Sample_fit_type(FitType.Linear)
        builder.set_Sample_polynomial_order(0)
        builder.set_Sample_wavelength_low(10.0)
        builder.set_Sample_wavelength_high(20.0)

        builder.set_Can_fit_type(FitType.Polynomial)
        builder.set_Can_polynomial_order(3)
        builder.set_Can_wavelength_low(10.0)
        builder.set_Can_wavelength_high(20.0)

        state = builder.build()

        # Assert
        self.assertTrue(state.prompt_peak_correction_min == 12.0)
        self.assertTrue(state.prompt_peak_correction_max == 17.0)

        self.assertTrue(state.incident_monitor == 1)
        self.assertTrue(state.default_incident_monitor == 2)
        self.assertTrue(state.transmission_monitor == 3)
        self.assertTrue(state.default_transmission_monitor == 4)
        self.assertTrue(state.transmission_radius_on_detector == 1.)
        self.assertTrue(state.transmission_roi_files == ["sdfs", "sddfsdf"])
        self.assertTrue(state.transmission_mask_files == ["sdfs", "bbbbbb"])

        self.assertTrue(state.rebin_type is RebinType.Rebin)
        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)
        self.assertTrue(state.use_full_wavelength_range is True)
        self.assertTrue(state.wavelength_full_range_low == 12.)
        self.assertTrue(state.wavelength_full_range_high == 24.)

        self.assertTrue(state.background_TOF_general_start == 1.4)
        self.assertTrue(state.background_TOF_general_stop == 34.4)
        self.assertTrue(len(set(state.background_TOF_monitor_start.items()) & set({"1": 123, "2": 123}.items())) == 2)
        self.assertTrue(len(set(state.background_TOF_monitor_stop.items()) & set({"1": 234, "2": 2323}.items())) == 2)
        self.assertTrue(state.background_TOF_roi_start == 1.4)
        self.assertTrue(state.background_TOF_roi_stop == 34.4)

        self.assertTrue(state.fit[DataType.to_string(DataType.Sample)].fit_type is FitType.Linear)
        self.assertTrue(state.fit[DataType.to_string(DataType.Sample)].polynomial_order == 0)
        self.assertTrue(state.fit[DataType.to_string(DataType.Sample)].wavelength_low == 10.)
        self.assertTrue(state.fit[DataType.to_string(DataType.Sample)].wavelength_high == 20.)

        self.assertTrue(state.fit[DataType.to_string(DataType.Can)].fit_type is
                        FitType.Polynomial)
        self.assertTrue(state.fit[DataType.to_string(DataType.Can)].polynomial_order == 3)
        self.assertTrue(state.fit[DataType.to_string(DataType.Can)].wavelength_low == 10.)
        self.assertTrue(state.fit[DataType.to_string(DataType.Can)].wavelength_high == 20.)
    def PyInit(self):
        # ---------------
        # INPUT
        # ---------------
        # State
        self.declareProperty(PropertyManagerProperty('SANSState'),
                             doc='A property manager which fulfills the SANSState contract.')

        # Input workspaces
        self.declareProperty(MatrixWorkspaceProperty('TransmissionWorkspace', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The transmission workspace.')
        self.declareProperty(MatrixWorkspaceProperty('DirectWorkspace', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The direct workspace.')
        self.declareProperty(MatrixWorkspaceProperty('MonitorWorkspace', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input),
                             doc='The scatter monitor workspace. This workspace only contains monitors.')

        workspace_validator = CompositeValidator()
        workspace_validator.add(WorkspaceUnitValidator("Wavelength"))
        self.declareProperty(MatrixWorkspaceProperty('SampleData', '',
                                                     optional=PropertyMode.Optional, direction=Direction.Input,
                                                     validator=workspace_validator),
                             doc='A workspace cropped to the detector to be reduced (the SAME as the input to Q1D). '
                                 'This used to verify the solid angle. The workspace is not modified, just inspected.')

        # The component
        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.")

        # 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.")

        # Slice factor for monitor
        self.declareProperty('SliceEventFactor', 1.0, direction=Direction.Input, doc='The slice factor for the monitor '
                                                                                     'normalization. This factor is the'
                                                                                     ' one obtained from event '
                                                                                     'slicing.')

        # ---------------
        # Output
        # ---------------
        self.declareProperty(MatrixWorkspaceProperty('OutputWorkspaceWavelengthAdjustment', '',
                                                     direction=Direction.Output),
                             doc='The workspace for wavelength-based adjustments.')

        self.declareProperty(MatrixWorkspaceProperty('OutputWorkspacePixelAdjustment', '',
                                                     direction=Direction.Output),
                             doc='The workspace for wavelength-based adjustments.')

        self.declareProperty(MatrixWorkspaceProperty('OutputWorkspaceWavelengthAndPixelAdjustment', '',
                                                     direction=Direction.Output),
                             doc='The workspace for, both, wavelength- and pixel-based adjustments.')

        self.declareProperty(MatrixWorkspaceProperty('CalculatedTransmissionWorkspace', ''
                                                     ,optional=PropertyMode.Optional, direction=Direction.Output),
                             doc='The calculated transmission workspace')

        self.declareProperty(MatrixWorkspaceProperty('UnfittedTransmissionWorkspace', ''
                                                     ,optional=PropertyMode.Optional, direction=Direction.Output),
                             doc='The unfitted transmission workspace')
Example #42
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.')

        self.declareProperty(MatrixWorkspaceProperty(
            'CalculatedTransmissionWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The calculated transmission workspace')

        self.declareProperty(MatrixWorkspaceProperty(
            'UnfittedTransmissionWorkspace',
            '',
            optional=PropertyMode.Optional,
            direction=Direction.Output),
                             doc='The unfitted transmission workspace')
    def test_can_set_commands_without_exceptions(self):
        command_interface = CommandInterfaceStateDirector(SANSFacility.ISIS)

        # User file
        command = NParameterCommand(command_id=NParameterCommandId.user_file,
                                    values=["test_user_file_sans2d.txt"])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Mask
        command = NParameterCommand(command_id=NParameterCommandId.mask,
                                    values=["MASK/ FRONT H197>H199"])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Monitor spectrum (incident monitor for monitor normalization)
        command = NParameterCommand(
            command_id=NParameterCommandId.incident_spectrum,
            values=[1, True, False])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Transmission spectrum (incident monitor for transmission calculation)
        command = NParameterCommand(
            command_id=NParameterCommandId.incident_spectrum,
            values=[7, False, True])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Reduction Dimensionality One Dim
        command = NParameterCommand(
            command_id=NParameterCommandId.reduction_dimensionality,
            values=[ReductionDimensionality.OneDim])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Reduction Dimensionality Two Dim
        command = NParameterCommand(
            command_id=NParameterCommandId.reduction_dimensionality,
            values=[ReductionDimensionality.TwoDim])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Sample offset
        command = NParameterCommand(
            command_id=NParameterCommandId.sample_offset, values=[23.6])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Sample scatter data
        command = DataCommand(command_id=DataCommandId.sample_scatter,
                              file_name="SANS2D00022024",
                              period=3)
        self._assert_raises_nothing(command_interface.add_command, command)

        # Detector
        command = NParameterCommand(command_id=NParameterCommandId.detector,
                                    values=[ISISReductionMode.HAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Gravity
        command = NParameterCommand(command_id=NParameterCommandId.gravity,
                                    values=[True, 12.4])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Set centre
        command = NParameterCommand(command_id=NParameterCommandId.centre,
                                    values=[12.4, 23.54, DetectorType.HAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # # Trans fit
        command = NParameterCommand(
            command_id=NParameterCommandId.trans_fit,
            values=[FitData.Can, 10.4, 12.54, FitType.Logarithmic, 0])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Front detector rescale
        command = NParameterCommand(
            command_id=NParameterCommandId.front_detector_rescale,
            values=[1.2, 2.4, True, False, None, 7.2])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Event slices
        command = NParameterCommand(
            command_id=NParameterCommandId.event_slices, values="1-23,55:3:65")
        self._assert_raises_nothing(command_interface.add_command, command)

        # Flood file
        command = NParameterCommand(command_id=NParameterCommandId.flood_file,
                                    values=["test", DetectorType.LAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Phi limits
        command = NParameterCommand(command_id=NParameterCommandId.phi_limit,
                                    values=[12.5, 123.6, False])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Wavelength correction file
        command = NParameterCommand(
            command_id=NParameterCommandId.wavelength_correction_file,
            values=["test", DetectorType.HAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Radius mask
        command = NParameterCommand(command_id=NParameterCommandId.mask_radius,
                                    values=[23.5, 234.7])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Wavelength limits
        command = NParameterCommand(
            command_id=NParameterCommandId.wavelength_limit,
            values=[1.23, 23., 1.1, RangeStepType.Lin])
        self._assert_raises_nothing(command_interface.add_command, command)

        # QXY Limits
        command = NParameterCommand(command_id=NParameterCommandId.qxy_limit,
                                    values=[1.23, 23., 1.1, RangeStepType.Lin])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Process all commands
        state = command_interface.process_commands()

        # Assert
        # We check here that the elements we set up above (except for from the user file) are being applied
        self.assertTrue(state is not None)
        self.assertTrue(state.mask.detectors[DetectorType.to_string(
            DetectorType.HAB)].range_horizontal_strip_start[-1] == 197)
        self.assertTrue(state.mask.detectors[DetectorType.to_string(
            DetectorType.HAB)].range_horizontal_strip_stop[-1] == 199)
        self.assertTrue(
            state.adjustment.normalize_to_monitor.incident_monitor == 1)
        self.assertTrue(state.adjustment.normalize_to_monitor.rebin_type is
                        RebinType.InterpolatingRebin)
        self.assertTrue(
            state.adjustment.calculate_transmission.incident_monitor == 7)
        self.assertTrue(state.adjustment.calculate_transmission.rebin_type is
                        RebinType.Rebin)
        self.assertTrue(state.reduction.reduction_dimensionality is
                        ReductionDimensionality.TwoDim)
        self.assertTrue(state.convert_to_q.reduction_dimensionality is
                        ReductionDimensionality.TwoDim)
        self.assertTrue(state.move.sample_offset == 23.6 / 1000.)
        self.assertTrue(state.data.sample_scatter == "SANS2D00022024")
        self.assertTrue(state.data.sample_scatter_period == 3)
        self.assertTrue(
            state.reduction.reduction_mode is ISISReductionMode.HAB)
        self.assertTrue(state.convert_to_q.use_gravity)
        self.assertTrue(state.convert_to_q.gravity_extra_length == 12.4)
        self.assertTrue(state.move.detectors[DetectorType.to_string(
            DetectorType.HAB)].sample_centre_pos1 == 12.4 / 1000.)
        self.assertTrue(state.move.detectors[DetectorType.to_string(
            DetectorType.HAB)].sample_centre_pos2 == 23.54 / 1000.)
        self.assertTrue(state.adjustment.calculate_transmission.fit[
            DataType.to_string(DataType.Can)].fit_type is FitType.Logarithmic)
        self.assertTrue(state.adjustment.calculate_transmission.fit[
            DataType.to_string(DataType.Can)].polynomial_order == 0)

        self.assertTrue(state.adjustment.calculate_transmission.fit[
            DataType.to_string(DataType.Can)].wavelength_low == 10.4)
        self.assertTrue(state.adjustment.calculate_transmission.fit[
            DataType.to_string(DataType.Can)].wavelength_high == 12.54)

        self.assertTrue(state.reduction.merge_scale == 1.2)
        self.assertTrue(state.reduction.merge_shift == 2.4)
        self.assertTrue(
            state.reduction.merge_fit_mode is FitModeForMerge.ScaleOnly)
        self.assertTrue(state.reduction.merge_range_min is None)
        self.assertTrue(state.reduction.merge_range_max == 7.2)

        # Event slices
        start_values = state.slice.start_time
        end_values = state.slice.end_time
        expected_start_values = [1., 55., 58., 61., 64.]
        expected_end_values = [23., 58., 61., 64., 65.]
        for s1, e1, s2, e2 in zip(start_values, end_values,
                                  expected_start_values, expected_end_values):
            self.assertTrue(s1 == s2)
            self.assertTrue(e1 == e2)

        self.assertTrue(state.adjustment.wavelength_and_pixel_adjustment.
                        adjustment_files[DetectorType.to_string(
                            DetectorType.LAB)].pixel_adjustment_file == "test")
        self.assertTrue(state.mask.phi_min == 12.5)
        self.assertTrue(state.mask.phi_max == 123.6)
        self.assertFalse(state.mask.use_mask_phi_mirror)
        self.assertTrue(
            state.adjustment.wavelength_and_pixel_adjustment.adjustment_files[
                DetectorType.to_string(
                    DetectorType.HAB)].wavelength_adjustment_file == "test")
        self.assertTrue(state.mask.radius_min == 23.5 / 1000.)
        self.assertTrue(state.mask.radius_max == 234.7 / 1000.)
        self.assertTrue(state.wavelength.wavelength_low == [1.23])
        self.assertTrue(
            state.adjustment.normalize_to_monitor.wavelength_high == [23.])
        self.assertTrue(state.adjustment.wavelength_and_pixel_adjustment.
                        wavelength_step == 1.1)
        self.assertTrue(state.adjustment.calculate_transmission.
                        wavelength_step_type is RangeStepType.Lin)
        self.assertTrue(state.convert_to_q.q_xy_max == 23.)
        self.assertTrue(state.convert_to_q.q_xy_step == 1.1)
        self.assertTrue(state.convert_to_q.q_xy_step_type is RangeStepType.Lin)
    def test_can_set_commands_without_exceptions(self):
        command_interface = CommandInterfaceStateDirector(SANSFacility.ISIS)

        # User file
        command = NParameterCommand(command_id=NParameterCommandId.user_file,
                                    values=["test_user_file_sans2d.txt"])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Mask
        command = NParameterCommand(command_id=NParameterCommandId.mask,
                                    values=["MASK/ FRONT H197>H199"])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Monitor spectrum (incident monitor for monitor normalization)
        command = NParameterCommand(command_id=NParameterCommandId.incident_spectrum,
                                    values=[1, True, False])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Transmission spectrum (incident monitor for transmission calculation)
        command = NParameterCommand(command_id=NParameterCommandId.incident_spectrum, values=[7, False, True])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Reduction Dimensionality One Dim
        command = NParameterCommand(command_id=NParameterCommandId.reduction_dimensionality,
                                    values=[ReductionDimensionality.OneDim])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Reduction Dimensionality Two Dim
        command = NParameterCommand(command_id=NParameterCommandId.reduction_dimensionality,
                                    values=[ReductionDimensionality.TwoDim])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Sample offset
        command = NParameterCommand(command_id=NParameterCommandId.sample_offset, values=[23.6])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Sample scatter data
        command = DataCommand(command_id=DataCommandId.sample_scatter, file_name="SANS2D00022024", period=3)
        self._assert_raises_nothing(command_interface.add_command, command)

        # Detector
        command = NParameterCommand(command_id=NParameterCommandId.detector, values=[ISISReductionMode.HAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Gravity
        command = NParameterCommand(command_id=NParameterCommandId.gravity, values=[True, 12.4])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Set centre
        command = NParameterCommand(command_id=NParameterCommandId.centre, values=[12.4, 23.54, DetectorType.HAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # # Trans fit
        command = NParameterCommand(command_id=NParameterCommandId.trans_fit, values=[FitData.Can, 10.4, 12.54,
                                                                                      FitType.Logarithmic, 0])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Front detector rescale
        command = NParameterCommand(command_id=NParameterCommandId.front_detector_rescale, values=[1.2, 2.4, True,
                                                                                                   False, None, 7.2])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Event slices
        command = NParameterCommand(command_id=NParameterCommandId.event_slices, values="1-23,55:3:65")
        self._assert_raises_nothing(command_interface.add_command, command)

        # Flood file
        command = NParameterCommand(command_id=NParameterCommandId.flood_file, values=["test", DetectorType.LAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Phi limits
        command = NParameterCommand(command_id=NParameterCommandId.phi_limit, values=[12.5, 123.6, False])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Wavelength correction file
        command = NParameterCommand(command_id=NParameterCommandId.wavelength_correction_file,
                                    values=["test", DetectorType.HAB])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Radius mask
        command = NParameterCommand(command_id=NParameterCommandId.mask_radius,
                                    values=[23.5, 234.7])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Wavelength limits
        command = NParameterCommand(command_id=NParameterCommandId.wavelength_limit,
                                    values=[1.23, 23., 1.1, RangeStepType.Lin])
        self._assert_raises_nothing(command_interface.add_command, command)

        # QXY Limits
        command = NParameterCommand(command_id=NParameterCommandId.qxy_limit,
                                    values=[1.23, 23., 1.1, RangeStepType.Lin])
        self._assert_raises_nothing(command_interface.add_command, command)

        # Process all commands
        state = command_interface.process_commands()

        # Assert
        # We check here that the elements we set up above (except for from the user file) are being applied
        self.assertTrue(state is not None)
        self.assertTrue(state.mask.detectors[DetectorType.to_string(DetectorType.HAB)].range_horizontal_strip_start[-1]
                        == 197)
        self.assertTrue(state.mask.detectors[DetectorType.to_string(DetectorType.HAB)].range_horizontal_strip_stop[-1]
                        == 199)
        self.assertTrue(state.adjustment.normalize_to_monitor.incident_monitor == 1)
        self.assertTrue(state.adjustment.normalize_to_monitor.rebin_type is RebinType.InterpolatingRebin)
        self.assertTrue(state.adjustment.calculate_transmission.incident_monitor == 7)
        self.assertTrue(state.adjustment.calculate_transmission.rebin_type is RebinType.Rebin)
        self.assertTrue(state.reduction.reduction_dimensionality is ReductionDimensionality.TwoDim)
        self.assertTrue(state.convert_to_q.reduction_dimensionality is ReductionDimensionality.TwoDim)
        self.assertTrue(state.move.sample_offset == 23.6/1000.)
        self.assertTrue(state.data.sample_scatter == "SANS2D00022024")
        self.assertTrue(state.data.sample_scatter_period == 3)
        self.assertTrue(state.reduction.reduction_mode is ISISReductionMode.HAB)
        self.assertTrue(state.convert_to_q.use_gravity)
        self.assertTrue(state.convert_to_q.gravity_extra_length == 12.4)
        self.assertTrue(state.move.detectors[DetectorType.to_string(DetectorType.HAB)].sample_centre_pos1 == 12.4/1000.)
        self.assertTrue(state.move.detectors[DetectorType.to_string(DetectorType.HAB)].sample_centre_pos2
                        == 23.54/1000.)
        self.assertTrue(state.adjustment.calculate_transmission.fit[DataType.to_string(DataType.Can)].fit_type
                        is FitType.Logarithmic)
        self.assertTrue(state.adjustment.calculate_transmission.fit[DataType.to_string(DataType.Can)].polynomial_order
                        == 0)

        self.assertTrue(state.adjustment.calculate_transmission.fit[DataType.to_string(DataType.Can)].wavelength_low
                        == 10.4)
        self.assertTrue(state.adjustment.calculate_transmission.fit[DataType.to_string(DataType.Can)].wavelength_high
                        == 12.54)

        self.assertTrue(state.reduction.merge_scale == 1.2)
        self.assertTrue(state.reduction.merge_shift == 2.4)
        self.assertTrue(state.reduction.merge_fit_mode is FitModeForMerge.ScaleOnly)
        self.assertTrue(state.reduction.merge_range_min is None)
        self.assertTrue(state.reduction.merge_range_max == 7.2)

        # Event slices
        start_values = state.slice.start_time
        end_values = state.slice.end_time
        expected_start_values = [1., 55., 58., 61., 64.]
        expected_end_values = [23., 58., 61., 64., 65.]
        for s1, e1, s2, e2 in zip(start_values, end_values, expected_start_values, expected_end_values):
            self.assertTrue(s1 == s2)
            self.assertTrue(e1 == e2)

        self.assertTrue(state.adjustment.wavelength_and_pixel_adjustment.adjustment_files[
                            DetectorType.to_string(DetectorType.LAB)].pixel_adjustment_file == "test")
        self.assertTrue(state.mask.phi_min == 12.5)
        self.assertTrue(state.mask.phi_max == 123.6)
        self.assertFalse(state.mask.use_mask_phi_mirror)
        self.assertTrue(state.adjustment.wavelength_and_pixel_adjustment.adjustment_files[
                            DetectorType.to_string(DetectorType.HAB)].wavelength_adjustment_file == "test")
        self.assertTrue(state.mask.radius_min == 23.5 / 1000.)
        self.assertTrue(state.mask.radius_max == 234.7 / 1000.)
        self.assertTrue(state.wavelength.wavelength_low == [1.23])
        self.assertTrue(state.adjustment.normalize_to_monitor.wavelength_high == [23.])
        self.assertTrue(state.adjustment.wavelength_and_pixel_adjustment.wavelength_step == 1.1)
        self.assertTrue(state.adjustment.calculate_transmission.wavelength_step_type is RangeStepType.Lin)
        self.assertTrue(state.convert_to_q.q_xy_max == 23.)
        self.assertTrue(state.convert_to_q.q_xy_step == 1.1)
        self.assertTrue(state.convert_to_q.q_xy_step_type is RangeStepType.Lin)
    def _perform_fit(self, transmission_workspace, direct_workspace,
                     transmission_roi_detector_ids, transmission_monitor_detector_id,
                     transmission_monitor_detector_id_default, incident_monitor_detector_id,
                     calculate_transmission_state, data_type):
        """
        This performs the actual transmission calculation.

        :param transmission_workspace: the corrected transmission workspace
        :param direct_workspace: the corrected direct workspace
        :param transmission_roi_detector_ids: the roi detector ids
        :param transmission_monitor_detector_id: the transmission monitor detector id
        :param transmission_monitor_detector_id_default: the default transmission monitor id
        :param incident_monitor_detector_id: the incident monitor id
        :param calculate_transmission_state: the state for the transmission calculation
        :param data_type: the data type which is currently being investigated, ie if it is a sample or a can run.
        :return: a fitted workspace and an unfitted workspace
        """

        wavelength_low = calculate_transmission_state.wavelength_low[0]
        wavelength_high = calculate_transmission_state.wavelength_high[0]
        wavelength_step = calculate_transmission_state.wavelength_step
        wavelength_step_type = calculate_transmission_state.wavelength_step_type
        prefix = 1.0 if wavelength_step_type is RangeStepType.Lin else -1.0
        wavelength_step *= prefix
        rebin_params = str(wavelength_low) + "," + str(wavelength_step) + "," + str(wavelength_high)

        trans_name = "CalculateTransmission"
        trans_options = {"SampleRunWorkspace": transmission_workspace,
                         "DirectRunWorkspace": direct_workspace,
                         "OutputWorkspace": EMPTY_NAME,
                         "IncidentBeamMonitor": incident_monitor_detector_id,
                         "RebinParams": rebin_params,
                         "OutputUnfittedData": True}

        # If we have a region of interest we use it else we use the transmission monitor

        if len(transmission_roi_detector_ids) > 0:
            trans_options.update({"TransmissionROI": transmission_roi_detector_ids})
        elif transmission_monitor_detector_id is not None:
            trans_options.update({"TransmissionMonitor": transmission_monitor_detector_id})
        elif transmission_monitor_detector_id_default:
            trans_options.update({"TransmissionMonitor": transmission_monitor_detector_id_default})
        else:
            raise RuntimeError("No transmission monitor has been provided.")

        # Get the fit setting for the correct data type, ie either for the Sample of the Can
        fit_type = calculate_transmission_state.fit[DataType.to_string(data_type)].fit_type
        if fit_type is FitType.Logarithmic:
            fit_string = "Log"
        elif fit_type is FitType.Polynomial:
            fit_string = "Polynomial"
        else:
            fit_string = "Linear"

        trans_options.update({"FitMethod": fit_string})
        if fit_type is FitType.Polynomial:
            polynomial_order = calculate_transmission_state.fit[DataType.to_string(data_type)].polynomial_order
            trans_options.update({"PolynomialOrder": polynomial_order})

        trans_alg = create_unmanaged_algorithm(trans_name, **trans_options)
        trans_alg.execute()

        fitted_transmission_workspace = trans_alg.getProperty("OutputWorkspace").value
        try:
            unfitted_transmission_workspace = trans_alg.getProperty("UnfittedData").value
        except RuntimeError:
            unfitted_transmission_workspace = None

        # Set the y label correctly for the fitted and unfitted transmission workspaces
        y_unit_label_transmission_ratio = "Transmission"
        if fitted_transmission_workspace:
            fitted_transmission_workspace.setYUnitLabel(y_unit_label_transmission_ratio)
        if unfitted_transmission_workspace:
            unfitted_transmission_workspace.setYUnitLabel(y_unit_label_transmission_ratio)

        if fit_type is FitType.NoFit:
            output_workspace = unfitted_transmission_workspace
        else:
            output_workspace = fitted_transmission_workspace
        return output_workspace, unfitted_transmission_workspace
Example #46
0
def get_standard_output_workspace_name(state,
                                       reduction_data_type,
                                       data_type=DataType.to_string(
                                           DataType.Sample)):
    """
    Creates the name of the output workspace from a state object.

    The name of the output workspace is:
    1. The short run number
    2. If specific period is being reduced: 'p' + number
    3. Short detector name of the current reduction or "merged"
    4. The reduction dimensionality: "_" + dimensionality
    5. A wavelength range: wavelength_low + "_" + wavelength_high
    6. In case of a 1D reduction, then add phi limits
    7. If we are dealing with an actual slice limit, then specify it: "_tXX_TYY" Note that the time set to
       two decimals
    :param state: a SANSState object
    :param reduction_data_type: which reduced data type is being looked at, ie HAB, LAB or Merged
    :return: the name of the reduced workspace, and the base name fo the reduced workspace
    """
    # 1. Short run number
    data = state.data
    short_run_number = data.sample_scatter_run_number
    short_run_number_as_string = str(short_run_number)

    # 2. Multiperiod
    if state.data.sample_scatter_period != ALL_PERIODS:
        period = data.sample_scatter_period
        period_as_string = "p" + str(period)
    else:
        period_as_string = ""

    # 3. Detector name
    move = state.move
    detectors = move.detectors
    if reduction_data_type is ISISReductionMode.Merged:
        detector_name_short = "merged"
    elif reduction_data_type is ISISReductionMode.HAB:
        det_name = detectors[DetectorType.to_string(
            DetectorType.HAB)].detector_name_short
        detector_name_short = det_name if det_name is not None else "hab"
    elif reduction_data_type is ISISReductionMode.LAB:
        det_name = detectors[DetectorType.to_string(
            DetectorType.LAB)].detector_name_short
        detector_name_short = det_name if det_name is not None else "lab"
    else:
        raise RuntimeError(
            "SANSStateFunctions: Unknown reduction data type {0} cannot be used to "
            "create an output name".format(reduction_data_type))

    # 4. Dimensionality
    reduction = state.reduction
    if reduction.reduction_dimensionality is ReductionDimensionality.OneDim:
        dimensionality_as_string = "_1D"
    else:
        dimensionality_as_string = "_2D"

    # 5. Wavelength range
    wavelength = state.wavelength
    wavelength_range_string = "_" + str(
        wavelength.wavelength_low[0]) + "_" + str(
            wavelength.wavelength_high[0])

    # 6. Phi Limits
    mask = state.mask
    if reduction.reduction_dimensionality is ReductionDimensionality.OneDim:
        if mask.phi_min and mask.phi_max and (abs(mask.phi_max - mask.phi_min)
                                              != 180.0):
            phi_limits_as_string = 'Phi' + str(mask.phi_min) + '_' + str(
                mask.phi_max)
        else:
            phi_limits_as_string = ""
    else:
        phi_limits_as_string = ""

    # 7. Slice limits
    slice_state = state.slice
    start_time = slice_state.start_time
    end_time = slice_state.end_time
    if start_time and end_time:
        start_time_as_string = '_t%.2f' % start_time[0]
        end_time_as_string = '_T%.2f' % end_time[0]
    else:
        start_time_as_string = ""
        end_time_as_string = ""

    # Piece it all together
    output_workspace_name = (short_run_number_as_string + period_as_string +
                             detector_name_short + dimensionality_as_string +
                             wavelength_range_string + phi_limits_as_string +
                             start_time_as_string + end_time_as_string)
    output_workspace_base_name = (short_run_number_as_string +
                                  detector_name_short +
                                  dimensionality_as_string +
                                  phi_limits_as_string)

    return output_workspace_name, output_workspace_base_name
Example #47
0
def run_core_event_slice_reduction(reduction_alg, reduction_setting_bundle):
    """
    This function runs a core reduction for event slice data. This reduction slices by event time and converts to q.
    All other operations, such as moving and converting to histogram, have been performed before the event slicing.

    :param reduction_alg: a handle to the reduction algorithm.
    :param reduction_setting_bundle: a ReductionSettingBundle tuple
    :return: an OutputBundle and an OutputPartsBundle
    """

    # Get component to reduce
    component = get_component_to_reduce(reduction_setting_bundle)
    # Set the properties on the reduction algorithms
    serialized_state = reduction_setting_bundle.state.property_manager
    reduction_alg.setProperty("SANSState", serialized_state)
    reduction_alg.setProperty("Component", component)
    reduction_alg.setProperty("ScatterWorkspace",
                              reduction_setting_bundle.scatter_workspace)
    reduction_alg.setProperty("DirectWorkspace",
                              reduction_setting_bundle.direct_workspace)
    reduction_alg.setProperty("TransmissionWorkspace",
                              reduction_setting_bundle.transmission_workspace)
    reduction_alg.setProperty("DummyMaskWorkspace",
                              reduction_setting_bundle.dummy_mask_workspace)
    reduction_alg.setProperty(
        "ScatterMonitorWorkspace",
        reduction_setting_bundle.scatter_monitor_workspace)

    reduction_alg.setProperty(
        "DataType", DataType.to_string(reduction_setting_bundle.data_type))

    reduction_alg.setProperty("OutputWorkspace", EMPTY_NAME)
    reduction_alg.setProperty("SumOfCounts", EMPTY_NAME)
    reduction_alg.setProperty("SumOfNormFactors", EMPTY_NAME)

    # Run the reduction core
    reduction_alg.execute()

    # Get the results
    output_workspace = reduction_alg.getProperty("OutputWorkspace").value
    output_workspace_count = reduction_alg.getProperty("SumOfCounts").value
    output_workspace_norm = reduction_alg.getProperty("SumOfNormFactors").value
    output_calculated_transmission_workspace = reduction_alg.getProperty(
        "CalculatedTransmissionWorkspace").value
    output_unfitted_transmission_workspace = reduction_alg.getProperty(
        "UnfittedTransmissionWorkspace").value

    # Pull the result out of the workspace
    output_bundle = OutputBundle(
        state=reduction_setting_bundle.state,
        data_type=reduction_setting_bundle.data_type,
        reduction_mode=reduction_setting_bundle.reduction_mode,
        output_workspace=output_workspace)

    output_parts_bundle = OutputPartsBundle(
        state=reduction_setting_bundle.state,
        data_type=reduction_setting_bundle.data_type,
        reduction_mode=reduction_setting_bundle.reduction_mode,
        output_workspace_count=output_workspace_count,
        output_workspace_norm=output_workspace_norm)

    output_transmission_bundle = OutputTransmissionBundle(
        state=reduction_setting_bundle.state,
        data_type=reduction_setting_bundle.data_type,
        calculated_transmission_workspace=
        output_calculated_transmission_workspace,
        unfitted_transmission_workspace=output_unfitted_transmission_workspace,
    )
    return output_bundle, output_parts_bundle, output_transmission_bundle