Ejemplo n.º 1
0
def provide_workspace_with_proton_charge(is_event=True):
    sample_name = "CreateSampleWorkspace"
    sample_options = {"OutputWorkspace": "dummy",
                      "NumBanks": 1,
                      "BankPixelWidth": 2}
    if is_event:
        sample_options.update({"WorkspaceType": "Event"})
    else:
        sample_options.update({"WorkspaceType": "Histogram"})

    sample_alg = create_unmanaged_algorithm(sample_name, **sample_options)
    sample_alg.execute()
    workspace = sample_alg.getProperty("OutputWorkspace").value

    # Provide a proton charge
    log_name = "AddTimeSeriesLog"
    log_options = {"Workspace": workspace,
                   "Name": "proton_charge",
                   "Type": "double"}
    log_alg = create_unmanaged_algorithm(log_name, **log_options)
    time = DateAndTime("2010-01-01T00:10:00")
    for index in range(0, 10):
        time += 1000000000
        value = 1.0
        log_alg.setProperty("Time", str(time))
        log_alg.setProperty("Value", value)
        log_alg.execute()
    return workspace
Ejemplo n.º 2
0
    def _get_sample_workspace(with_zero_errors, convert_to_numeric_axis=False):
        create_name = "CreateSimulationWorkspace"
        create_options = {"Instrument": "LARMOR",
                          "BinParams": '1,10,1000',
                          "UnitX": 'MomentumTransfer',
                          "OutputWorkspace": EMPTY_NAME}
        create_alg = create_unmanaged_algorithm(create_name, **create_options)
        create_alg.execute()
        workspace = create_alg.getProperty("OutputWorkspace").value

        crop_name = "CropWorkspace"
        crop_options = {"InputWorkspace": workspace,
                        "OutputWorkspace": EMPTY_NAME,
                        "EndWorkspaceIndex": 0}
        crop_alg = create_unmanaged_algorithm(crop_name, **crop_options)
        crop_alg.execute()
        workspace = crop_alg.getProperty("OutputWorkspace").value

        if convert_to_numeric_axis:
            convert_name = "ConvertSpectrumAxis"
            convert_options = {"InputWorkspace": workspace,
                               "OutputWorkspace": EMPTY_NAME,
                               "Target": 'ElasticQ',
                               "EFixed": 1}
            convert_alg = create_unmanaged_algorithm(convert_name, **convert_options)
            convert_alg.execute()
            workspace = convert_alg.getProperty("OutputWorkspace").value

        if with_zero_errors:
            errors = workspace.dataE(0)
            errors[0] = 0.0
            errors[14] = 0.0
            errors[45] = 0.0
        return workspace
    def _compare_workspace(self, workspace, reference_file_name, check_spectra_map=True):
        # Load the reference file
        load_name = "LoadNexusProcessed"
        load_options = {"Filename": reference_file_name,
                        "OutputWorkspace": EMPTY_NAME}
        load_alg = create_unmanaged_algorithm(load_name, **load_options)
        load_alg.execute()
        reference_workspace = load_alg.getProperty("OutputWorkspace").value

        # Compare reference file with the output_workspace
        # We need to disable the instrument comparison, it takes way too long
        # We need to disable the sample -- Not clear why yet
        # operation how many entries can be found in the sample logs
        compare_name = "CompareWorkspaces"
        compare_options = {"Workspace1": workspace,
                           "Workspace2": reference_workspace,
                           "Tolerance": 1e-6,
                           "CheckInstrument": False,
                           "CheckSample": False,
                           "ToleranceRelErr": True,
                           "CheckAllData": True,
                           "CheckMasking": True,
                           "CheckType": True,
                           "CheckAxes": True,
                           "CheckSpectraMap": check_spectra_map}
        compare_alg = create_unmanaged_algorithm(compare_name, **compare_options)
        compare_alg.setChild(False)
        compare_alg.execute()
        result = compare_alg.getProperty("Result").value
        self.assertTrue(result)
Ejemplo n.º 4
0
def mask_with_mask_files(mask_info, workspace):
    """
    Apply mask files to the workspace

    Rolling our own MaskDetectors wrapper since masking is broken in a couple
    of places that affect us here.
    Calling MaskDetectors(Workspace=ws_name, MaskedWorkspace=mask_ws_name) is
    not something we can do because the algorithm masks by ws index rather than
    detector id, and unfortunately for SANS the detector table is not the same
    for MaskingWorkspaces as it is for the workspaces containing the data to be
    masked.  Basically, we get a mirror image of what we expect.  Instead, we
    have to extract the det IDs and use those via the DetectorList property.
    :param mask_info: a SANSStateMask object.
    :param workspace: the workspace to be masked.
    :return: the masked workspace.
    """
    mask_files = mask_info.mask_files
    if mask_files:
        idf_path = mask_info.idf_path

        # Mask loader
        load_name = "LoadMask"
        load_options = {"Instrument": idf_path,
                        "OutputWorkspace": EMPTY_NAME}
        load_alg = create_unmanaged_algorithm(load_name, **load_options)
        dummy_params = {"OutputWorkspace": EMPTY_NAME}
        mask_alg = create_unmanaged_algorithm("MaskInstrument", **dummy_params)
        clear_alg = create_unmanaged_algorithm("ClearMaskedSpectra", **dummy_params)

        # Masker
        for mask_file in mask_files:
            mask_file = find_full_file_path(mask_file)

            # Get the detector ids which need to be masked
            load_alg.setProperty("InputFile", mask_file)
            load_alg.execute()
            masking_workspace = load_alg.getProperty("OutputWorkspace").value
            # Could use MaskDetectors directly with masking_workspace but it does not
            # support MPI. Use a three step approach via a, b, and c instead.
            # a) Extract detectors to mask from MaskWorkspace
            det_ids = masking_workspace.getMaskedDetectors()
            # b) Mask the detector ids on the instrument
            mask_alg.setProperty("InputWorkspace", workspace)
            mask_alg.setProperty("OutputWorkspace", workspace)
            mask_alg.setProperty("DetectorIDs", det_ids)
            mask_alg.execute()
            workspace = mask_alg.getProperty("OutputWorkspace").value
        # c) Clear data in all spectra associated with masked detectors
        clear_alg.setProperty("InputWorkspace", workspace)
        clear_alg.setProperty("OutputWorkspace", workspace)
        clear_alg.execute()
        workspace = clear_alg.getProperty("OutputWorkspace").value
    return workspace
    def _get_wavelength_adjustment_workspace(self, wavelength_adjustment_file, transmission_workspace,
                                             monitor_normalization_workspace, rebin_string):
        """
        This creates a workspace with wavelength adjustments, ie this will be a correction for the bins, but it will
        be the same for all pixels. This is essentially the product of several workspaces.
        The participating workspaces are:
        1. A workspace loaded from a calibration file
        2.. The workspace resulting from the monitor normalization
        3. The workspace resulting from the transmission calculation (using SANSCalculateTransmission) if applicable

        :param wavelength_adjustment_file: the file path to the wavelength adjustment file
        :param transmission_workspace: the calculated transmission workspace (which can be None)
        :param monitor_normalization_workspace: the monitor normalization workspace
        :param rebin_string: the parameters for rebinning
        :return: a general wavelength adjustment workspace
        """
        # 1. Get the wavelength correction workspace from the file
        wavelength_adjustment_workspaces = []
        if wavelength_adjustment_file:
            wavelength_correction_workspace_from_file = \
                self._load_wavelength_correction_file(wavelength_adjustment_file)
            wavelength_adjustment_workspaces.append(wavelength_correction_workspace_from_file)

        # 2. Normalization
        wavelength_adjustment_workspaces.append(monitor_normalization_workspace)

        # 3. Transmission Calculation
        if transmission_workspace:
            wavelength_adjustment_workspaces.append(transmission_workspace)

        # Multiply all workspaces
        wavelength_adjustment_workspace = None
        for workspace in wavelength_adjustment_workspaces:
            # First we need to change the binning such that is matches the binning of the main data workspace
            rebin_name = "Rebin"
            rebin_options = {"InputWorkspace": workspace,
                             "Params": rebin_string,
                             "OutputWorkspace": EMPTY_NAME}
            rebin_alg = create_unmanaged_algorithm(rebin_name, **rebin_options)
            rebin_alg.execute()
            rebinned_workspace = rebin_alg.getProperty("OutputWorkspace").value
            if wavelength_adjustment_workspace is None:
                wavelength_adjustment_workspace = rebinned_workspace
            else:
                multiply_name = "Multiply"
                multiply_options = {"LHSWorkspace": rebinned_workspace,
                                    "RHSWorkspace": wavelength_adjustment_workspace,
                                    "OutputWorkspace": EMPTY_NAME}
                multiply_alg = create_unmanaged_algorithm(multiply_name, **multiply_options)
                multiply_alg.execute()
                wavelength_adjustment_workspace = multiply_alg.getProperty("OutputWorkspace").value
        return wavelength_adjustment_workspace
Ejemplo n.º 6
0
    def _compare_workspace(self, workspace, reference_file_name):
        # Load the reference file
        load_name = "LoadNexusProcessed"
        load_options = {"Filename": reference_file_name,
                        "OutputWorkspace": EMPTY_NAME}
        load_alg = create_unmanaged_algorithm(load_name, **load_options)
        load_alg.execute()
        reference_workspace = load_alg.getProperty("OutputWorkspace").value

        # Save the workspace out and reload it again. This equalizes it with the reference workspace
        f_name = os.path.join(mantid.config.getString('defaultsave.directory'),
                              'SANS_temp_single_core_reduction_testout.nxs')

        save_name = "SaveNexus"
        save_options = {"Filename": f_name,
                        "InputWorkspace": workspace}
        save_alg = create_unmanaged_algorithm(save_name, **save_options)
        save_alg.execute()
        load_alg.setProperty("Filename", f_name)
        load_alg.setProperty("OutputWorkspace", EMPTY_NAME)
        load_alg.execute()

        ws = load_alg.getProperty("OutputWorkspace").value

        # Compare reference file with the output_workspace
        # We need to disable the instrument comparison, it takes way too long
        # We need to disable the sample -- since the sample has been modified (more logs are being written)
        # operation how many entries can be found in the sample logs
        compare_name = "CompareWorkspaces"
        compare_options = {"Workspace1": ws,
                           "Workspace2": reference_workspace,
                           "Tolerance": 1e-6,
                           "CheckInstrument": False,
                           "CheckSample": False,
                           "ToleranceRelErr": True,
                           "CheckAllData": True,
                           "CheckMasking": True,
                           "CheckType": True,
                           "CheckAxes": True,
                           "CheckSpectraMap": True}
        compare_alg = create_unmanaged_algorithm(compare_name, **compare_options)
        compare_alg.setChild(False)
        compare_alg.execute()
        result = compare_alg.getProperty("Result").value
        message = compare_alg.getProperty("Messages").value
        self.assertTrue(result, message)

        # Remove file
        if os.path.exists(f_name):
            os.remove(f_name)
Ejemplo n.º 7
0
    def _apply_user_mask_ranges(self, cF, cR, nR, nF, merge_min, merge_max):
        merge_max = self._check_bins(merge_min, merge_max, cF, cR)

        mask_name = "MaskBins"
        mask_options = {"InputWorkspace": cF}
        mask_alg = create_unmanaged_algorithm(mask_name, **mask_options)

        mask_alg.setProperty("InputWorkspace", cF)
        mask_alg.setProperty("OutputWorkspace", EMPTY_NAME)
        mask_alg.setProperty("XMin", min(cF.dataX(0)))
        mask_alg.setProperty("XMax", merge_min)
        mask_alg.execute()
        cF = mask_alg.getProperty("OutputWorkspace").value

        mask_alg.setProperty("InputWorkspace", nF)
        mask_alg.setProperty("OutputWorkspace", EMPTY_NAME)
        mask_alg.setProperty("XMin", min(nF.dataX(0)))
        mask_alg.setProperty("XMax", merge_min)
        mask_alg.execute()
        nF = mask_alg.getProperty("OutputWorkspace").value

        mask_alg.setProperty("InputWorkspace", cR)
        mask_alg.setProperty("OutputWorkspace", EMPTY_NAME)
        mask_alg.setProperty("XMin", merge_max)
        mask_alg.setProperty("XMax", max(cR.dataX(0)))
        mask_alg.execute()
        cR = mask_alg.getProperty("OutputWorkspace").value

        mask_alg.setProperty("InputWorkspace", nR)
        mask_alg.setProperty("OutputWorkspace", EMPTY_NAME)
        mask_alg.setProperty("XMin", merge_max)
        mask_alg.setProperty("XMax", max(nR.dataX(0)))
        mask_alg.execute()
        nR = mask_alg.getProperty("OutputWorkspace").value
        return cR, cF, nR, nF
Ejemplo n.º 8
0
def mask_cylinder(mask_info, workspace):
    """
    Masks  a (hollow) cylinder around (0,0)

    Two radii can be specified for the cylinder mask. An inner radius (radius_min) and an outer radius(radius_max)
    which specify a hollow cylinder mask.
    :param mask_info: a SANSStateMask object.
    :param workspace: the workspace which is about to be masked
    :return: the masked workspace.
    """
    radius_min = mask_info.radius_min
    radius_max = mask_info.radius_max

    xml = []
    # Set up the inner radius of the cylinder
    if radius_min is not None and radius_min > 0.0:
        add_cylinder(xml, radius_min, 0, 0, 'beam_stop')

    # Set up the outer radius of the cylinder
    if radius_max is not None and radius_max > 0.0:
        add_outside_cylinder(xml, radius_max, 0, 0, 'beam_area')

    # Mask the cylinder shape if there is anything to mask, else don't do anything
    if xml:
        mask_name = "MaskDetectorsInShape"
        mask_options = {"Workspace": workspace}
        mask_alg = create_unmanaged_algorithm(mask_name, **mask_options)
        for shape in xml:
            mask_alg.setProperty("Workspace", workspace)
            mask_alg.setProperty("ShapeXML", shape)
            mask_alg.execute()
            workspace = mask_alg.getProperty("Workspace").value
    return workspace
    def _perform_prompt_peak_correction(self, workspace, prompt_peak_correction_min, prompt_peak_correction_max,
                                        prompt_peak_correction_enabled):
        """
        Prompt peak correction is performed if it is explicitly set by the user.

        :param workspace: the workspace to correct.
        :param prompt_peak_correction_min: the start time for the prompt peak correction.
        :param prompt_peak_correction_max: the stop time for the prompt peak correction.
        :prompt_peak_correction_enabled: flag if prompt peak correction should be enabled
        :return: a corrected workspace.
        """
        # We perform only a prompt peak correction if the start and stop values of the bins we want to remove,
        # were explicitly set. Some instruments require it, others don't.
        if prompt_peak_correction_enabled and prompt_peak_correction_min is not None and \
                        prompt_peak_correction_max is not None:  # noqa
            remove_name = "RemoveBins"
            remove_options = {"InputWorkspace": workspace,
                              "XMin": prompt_peak_correction_min,
                              "XMax": prompt_peak_correction_max,
                              "Interpolation": "Linear"}
            remove_alg = create_unmanaged_algorithm(remove_name, **remove_options)
            remove_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
            remove_alg.setProperty("OutputWorkspace", workspace)
            remove_alg.execute()
            workspace = remove_alg.getProperty("OutputWorkspace").value
        return workspace
Ejemplo n.º 10
0
def mask_beam_stop(mask_info, workspace, instrument, detector_names):
    """
    The beam stop is being masked here.

    :param mask_info: a SANSStateMask object.
    :param workspace: the workspace which is to be masked.
    :param instrument: the instrument associated with the current workspace.
    :return: a masked workspace
    """
    beam_stop_arm_width = mask_info.beam_stop_arm_width
    beam_stop_arm_angle = mask_info.beam_stop_arm_angle
    beam_stop_arm_pos1 = mask_info.beam_stop_arm_pos1
    beam_stop_arm_pos2 = mask_info.beam_stop_arm_pos2
    if beam_stop_arm_width is not None and beam_stop_arm_angle is not None:
        detector = workspace.getInstrument().getComponentByName(detector_names['LAB'])
        z_position = detector.getPos().getZ()
        start_point = [beam_stop_arm_pos1, beam_stop_arm_pos2, z_position]
        line_mask = create_line_mask(start_point, 100., beam_stop_arm_width, beam_stop_arm_angle)

        mask_name = "MaskDetectorsInShape"
        mask_options = {"Workspace": workspace,
                        "ShapeXML": line_mask}
        mask_alg = create_unmanaged_algorithm(mask_name, **mask_options)
        mask_alg.execute()
        workspace = mask_alg.getProperty("Workspace").value
    return workspace
Ejemplo n.º 11
0
    def test_that_workspace_can_be_saved_without_zero_error_free_option(self):
        # Arrange
        workspace = SANSSaveTest._get_sample_workspace(with_zero_errors=False, convert_to_numeric_axis=True)
        file_name = os.path.join(mantid.config.getString('defaultsave.directory'), 'sample_sans_save_file')
        use_zero_errors_free = False
        save_name = "SANSSave"
        save_options = {"InputWorkspace": workspace,
                        "Filename": file_name,
                        "UseZeroErrorFree": use_zero_errors_free,
                        "Nexus": True,
                        "CanSAS": True,
                        "NXCanSAS": True,
                        "NistQxy": True,
                        "RKH": True,
                        "CSV": True}
        save_alg = create_unmanaged_algorithm(save_name, **save_options)

        # Act
        save_alg.execute()
        self.assertTrue(save_alg.isExecuted())

        # Assert
        expected_files = ["sample_sans_save_file.xml", "sample_sans_save_file.txt", "sample_sans_save_file_nistqxy.dat",
                          "sample_sans_save_file.h5", "sample_sans_save_file.nxs",
                          "sample_sans_save_file.csv"]
        expected_full_file_names = [os.path.join(mantid.config.getString('defaultsave.directory'), elem)
                                    for elem in expected_files]
        for file_name in expected_full_file_names:
            self._assert_that_file_exists(file_name)

        # Clean up
        for file_name in expected_full_file_names:
            self._remove_file(file_name)
 def _load_workspace(file_name):
     load_name = "Load"
     load_options = {"OutputWorkspace": EMPTY_NAME,
                     "Filename": file_name}
     load_alg = create_unmanaged_algorithm(load_name, **load_options)
     load_alg.execute()
     return load_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 13
0
def rotate_component(workspace, angle, direction, component_to_rotate):
    """
    Rotate a component on a workspace.

    :param workspace: the workspace which contains the component which is to be rotated.
    :param angle: the angle by which it is to be rotated in degrees.
    :param direction: the rotation direction. This is a unit vector encoded as a Coordinate vs Value map.
    :param component_to_rotate: name of the component which is to be rotated
    :return:
    """
    rotate_name = "RotateInstrumentComponent"
    rotate_options = {"Workspace": workspace,
                      "ComponentName": component_to_rotate,
                      "RelativeRotation": "1"}
    for key, value in list(direction.items()):
        if key is CanonicalCoordinates.X:
            rotate_options.update({"X": value})
        elif key is CanonicalCoordinates.Y:
            rotate_options.update({"Y": value})
        elif key is CanonicalCoordinates.Z:
            rotate_options.update({"Z": value})
        else:
            raise RuntimeError("SANSMove: Trying to rotate the components along an unknown direction. "
                               "See here: {0}".format(str(component_to_rotate)))
    rotate_options.update({"Angle": angle})
    alg = create_unmanaged_algorithm(rotate_name, **rotate_options)
    alg.execute()
    def _get_calculated_transmission_workspace(self, state):
        """
        Creates the fitted transmission workspace.

        Note that this step is not mandatory. If no transmission and direct workspaces are provided, then we
        don't have to do anything here.
        :param state: a SANSState object.
        :return: a fitted transmission workspace and the unfitted data.
        """
        transmission_workspace = self.getProperty("TransmissionWorkspace").value
        direct_workspace = self.getProperty("DirectWorkspace").value
        if transmission_workspace and direct_workspace:
            data_type = self.getProperty("DataType").value
            transmission_name = "SANSCalculateTransmission"
            serialized_state = state.property_manager
            transmission_options = {"TransmissionWorkspace": transmission_workspace,
                                    "DirectWorkspace": direct_workspace,
                                    "SANSState": serialized_state,
                                    "DataType": data_type,
                                    "OutputWorkspace": EMPTY_NAME,
                                    "UnfittedData": EMPTY_NAME}
            transmission_alg = create_unmanaged_algorithm(transmission_name, **transmission_options)
            transmission_alg.execute()
            fitted_data = transmission_alg.getProperty("OutputWorkspace").value
            unfitted_data = transmission_alg.getProperty("UnfittedData").value
        else:
            fitted_data = None
            unfitted_data = None
        return fitted_data, unfitted_data
Ejemplo n.º 15
0
def move_component(workspace, offsets, component_to_move, is_relative=True):
    """
    Move an individual component on a workspace

    :param workspace: the workspace which the component which is to be moved.
    :param offsets: a Coordinate vs. Value map of offsets.
    :param component_to_move: the name of a component on the instrument. This component must be name which exist.
                              on the instrument.
    :param is_relative: if the move is relative of not.
    :return:
    """
    move_name = "MoveInstrumentComponent"
    move_options = {"Workspace": workspace,
                    "ComponentName": component_to_move,
                    "RelativePosition": is_relative}
    for key, value in list(offsets.items()):
        if key is CanonicalCoordinates.X:
            move_options.update({"X": value})
        elif key is CanonicalCoordinates.Y:
            move_options.update({"Y": value})
        elif key is CanonicalCoordinates.Z:
            move_options.update({"Z": value})
        else:
            raise RuntimeError("SANSMove: Trying to move the components along an unknown direction. "
                               "See here: {0}".format(str(component_to_move)))
    alg = create_unmanaged_algorithm(move_name, **move_options)
    alg.execute()
Ejemplo n.º 16
0
    def _convert_to_wavelength(self, workspace, normalize_to_monitor_state):
        """
        Converts the workspace from time-of-flight units to wavelength units

        :param workspace: a time-of-flight workspace.
        :param normalize_to_monitor_state: a SANSStateNormalizeToMonitor object.
        :return: a wavelength workspace.
        """
        wavelength_low = normalize_to_monitor_state.wavelength_low
        wavelength_high = normalize_to_monitor_state.wavelength_high
        wavelength_step = normalize_to_monitor_state.wavelength_step
        wavelength_step_type = normalize_to_monitor_state.wavelength_step_type
        wavelength_rebin_mode = normalize_to_monitor_state.rebin_type
        convert_name = "SANSConvertToWavelengthAndRebin"
        convert_options = {"InputWorkspace": workspace,
                           "WavelengthLow": wavelength_low,
                           "WavelengthHigh": wavelength_high,
                           "WavelengthStep": wavelength_step,
                           "WavelengthStepType": RangeStepType.to_string(wavelength_step_type),
                           "RebinMode": RebinType.to_string(wavelength_rebin_mode)}

        convert_alg = create_unmanaged_algorithm(convert_name, **convert_options)
        convert_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
        convert_alg.setProperty("OutputWorkspace", workspace)
        convert_alg.execute()
        return convert_alg.getProperty("OutputWorkspace").value
    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
 def _clone_workspace(workspace):
     clone_name = "CloneWorkspace"
     clone_options = {"InputWorkspace": workspace,
                      "OutputWorkspace": EMPTY_NAME}
     clone_alg = create_unmanaged_algorithm(clone_name, **clone_options)
     clone_alg.execute()
     return clone_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 19
0
    def do_scale(workspace, scale_factor):
        single_valued_name = "CreateSingleValuedWorkspace"
        single_valued_options = {"OutputWorkspace": EMPTY_NAME,
                                 "DataValue": scale_factor}
        single_valued_alg = create_unmanaged_algorithm(single_valued_name, **single_valued_options)
        single_valued_alg.execute()
        single_valued_workspace = single_valued_alg.getProperty("OutputWorkspace").value

        multiply_name = "Multiply"
        multiply_options = {"LHSWorkspace": workspace,
                            "RHSWorkspace": single_valued_workspace}
        multiply_alg = create_unmanaged_algorithm(multiply_name, **multiply_options)
        multiply_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
        multiply_alg.setProperty("OutputWorkspace", workspace)
        multiply_alg.execute()
        return multiply_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 20
0
def mask_angle(mask_info, workspace):
    """
    Creates a pizza slice mask on the detector around (0,0)

    :param mask_info: a SANSStateMask object
    :param workspace: the workspace which is to be masked.
    :return: a masked workspace
    """
    phi_mirror = mask_info.use_mask_phi_mirror
    phi_min = mask_info.phi_min
    phi_max = mask_info.phi_max
    if phi_min is not None and phi_max is not None and phi_mirror is not None:
        # Check for edge cases for the mirror
        if phi_mirror:
            if phi_min > phi_max:
                phi_min, phi_max = phi_max, phi_min

            if phi_max - phi_min == 180.0:
                phi_min = -90.0
                phi_max = 90.0

        # Create the phi mask and apply it if anything was created
        phi_mask = create_phi_mask('unique phi', [0, 0, 0], phi_min, phi_max, phi_mirror)

        if phi_mask:
            mask_name = "MaskDetectorsInShape"
            mask_options = {"Workspace": workspace,
                            "ShapeXML": phi_mask}
            mask_alg = create_unmanaged_algorithm(mask_name, **mask_options)
            mask_alg.execute()
            workspace = mask_alg.getProperty("Workspace").value
    return workspace
 def _perform_rebin(self, rebin_type, rebin_options, workspace):
     rebin_name = "Rebin" if rebin_type is RebinType.Rebin else "InterpolatingRebin"
     rebin_alg = create_unmanaged_algorithm(rebin_name, **rebin_options)
     rebin_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
     rebin_alg.setProperty("OutputWorkspace", workspace)
     rebin_alg.execute()
     return rebin_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 22
0
    def test_that_scales_the_workspace_correctly(self):
        # Arrange
        workspace = self._get_workspace()
        width = 1.0
        height = 2.0
        scale = 7.2
        state = self._get_sample_state(width=width, height=height, thickness=3.0, scale=scale,
                                       shape=SampleShape.CylinderAxisUp)
        serialized_state = state.property_manager
        scale_name = "SANSScale"
        scale_options = {"SANSState": serialized_state,
                         "InputWorkspace": workspace,
                         "OutputWorkspace": EMPTY_NAME}
        scale_alg = create_unmanaged_algorithm(scale_name, **scale_options)

        # Act
        scale_alg.execute()
        output_workspace = scale_alg.getProperty("OutputWorkspace").value

        # Assert
        # We have a LOQ data set, hence we need to divide by pi
        expected_value = 0.3/(height * math.pi * math.pow(width, 2) / 4.0) * (scale / math.pi) * 100.
        data_y = output_workspace.dataY(0)
        tolerance = 1e-7
        self.assertTrue(abs(data_y[0] - expected_value) < tolerance)
Ejemplo n.º 23
0
    def _perform_prompt_peak_correction(self, workspace, normalize_to_monitor_state):
        """
        Performs a prompt peak correction.

        A prompt peak can occur when very fast neutrons shoot through the measurement. This can happen when working
        with two time regimes. Prompt peaks are prominent peaks which stand out from usual data. They occur frequently
        on LOQ, but are now also a possibility on other instruments. We deal with them, by removing the data and
        interpolating between the edge data points. If the user does not specify a start and stop time for the
        prompt peak, then this correction is not performed.
        :param workspace: the workspace which is to be corrected.
        :param normalize_to_monitor_state: a SANSStateNormalizeToMonitor object.
        :return: the corrected workspace.
        """
        prompt_peak_correction_start = normalize_to_monitor_state.prompt_peak_correction_min
        prompt_peak_correction_stop = normalize_to_monitor_state.prompt_peak_correction_max
        prompt_peak_correction_enabled = normalize_to_monitor_state.prompt_peak_correction_enabled
        # We perform only a prompt peak correction if the start and stop values of the bins we want to remove,
        # were explicitly set. Some instruments require it, others don't.
        if prompt_peak_correction_enabled and prompt_peak_correction_start is not None and prompt_peak_correction_stop is not None:
            remove_name = "RemoveBins"
            remove_options = {"InputWorkspace": workspace,
                              "OutputWorkspace": EMPTY_NAME,
                              "XMin": prompt_peak_correction_start,
                              "XMax": prompt_peak_correction_stop,
                              "Interpolation": "Linear"}
            remove_alg = create_unmanaged_algorithm(remove_name, **remove_options)
            remove_alg.execute()
            workspace = remove_alg.getProperty("OutputWorkspace").value
        return workspace
Ejemplo n.º 24
0
def perform_move(state, workspace):
    serialized_state = state.property_manager
    move_name = "SANSMove"
    move_options = {"SANSState": serialized_state,
                    "Workspace": workspace,
                    "MoveType": "InitialMove"}
    move_alg = create_unmanaged_algorithm(move_name, **move_options)
    move_alg.execute()
Ejemplo n.º 25
0
 def _save_output(self, workspace, mismatch_name):
     # Save the workspace out
     f_name = path.join(config.getString('defaultsave.directory'),
                        mismatch_name)
     save_name = "SaveNexus"
     save_options = {"Filename": f_name, "InputWorkspace": workspace}
     save_alg = create_unmanaged_algorithm(save_name, **save_options)
     save_alg.execute()
def perform_move(state, workspace):
    serialized_state = state.property_manager
    move_name = "SANSMove"
    move_options = {"SANSState": serialized_state,
                    "Workspace": workspace,
                    "MoveType": "InitialMove"}
    move_alg = create_unmanaged_algorithm(move_name, **move_options)
    move_alg.execute()
Ejemplo n.º 27
0
def perform_move(state, workspace):
    serialized_state = state.property_manager
    move_name = "SANSMove"

    zero_options = {"SANSState": serialized_state,
                    "Workspace": workspace,
                    "MoveType": "SetToZero",
                    "Component": ""}
    zero_alg = create_unmanaged_algorithm(move_name, **zero_options)
    zero_alg.execute()
    workspace = zero_alg.getProperty("Workspace").value

    move_options = {"SANSState": serialized_state,
                    "Workspace": workspace,
                    "MoveType": "InitialMove"}
    move_alg = create_unmanaged_algorithm(move_name, **move_options)
    move_alg.execute()
Ejemplo n.º 28
0
 def _get_workspace(self, file_name):
     full_file_name = FileFinder.findRuns(file_name)[0]
     load_name = "Load"
     load_options = {"Filename": full_file_name,
                     "OutputWorkspace": EMPTY_NAME}
     load_alg = create_unmanaged_algorithm(load_name, **load_options)
     load_alg.execute()
     return load_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 29
0
 def _run_test(workspace, state):
     normalize_name = "SANSNormalizeToMonitor"
     normalize_options = {"InputWorkspace": workspace,
                          "OutputWorkspace": EMPTY_NAME,
                          "SANSState": state}
     normalize_alg = create_unmanaged_algorithm(normalize_name, **normalize_options)
     normalize_alg.execute()
     return normalize_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 30
0
    def _run_q_2d(self, state):
        """
        This method performs a 2D data reduction on our workspace.

        Note that it does not perform any q resolution calculation, nor any wavelength-and-pixel adjustment. The
        output workspace contains two numerical axes.
        :param state: a SANSState object
        :return: the reduced workspace, the sum of counts workspace, the sum of norms workspace or
                 the reduced workspace, None, None
        """
        data_workspace = self.getProperty("InputWorkspace").value
        wavelength_adjustment_workspace = self.getProperty(
            "InputWorkspaceWavelengthAdjustment").value
        pixel_adjustment_workspace = self.getProperty(
            "InputWorkspacePixelAdjustment").value

        output_parts = self.getProperty("OutputParts").value

        # Extract relevant settings
        convert_to_q = state.convert_to_q
        max_q_xy = convert_to_q.q_xy_max
        log_binning = True if convert_to_q.q_xy_step_type is RangeStepType.Log else False
        delta_q = convert_to_q.q_xy_step
        radius_cutoff = convert_to_q.radius_cutoff / 1000.  # Qxy expects the radius cutoff to be in mm
        wavelength_cutoff = convert_to_q.wavelength_cutoff
        use_gravity = convert_to_q.use_gravity
        gravity_extra_length = convert_to_q.gravity_extra_length

        qxy_name = "Qxy"
        qxy_options = {
            "InputWorkspace": data_workspace,
            "OutputWorkspace": EMPTY_NAME,
            "MaxQxy": max_q_xy,
            "DeltaQ": delta_q,
            "IQxQyLogBinning": log_binning,
            "AccountForGravity": use_gravity,
            "RadiusCut": radius_cutoff,
            "WaveCut": wavelength_cutoff,
            "OutputParts": output_parts,
            "ExtraLength": gravity_extra_length
        }
        if wavelength_adjustment_workspace:
            qxy_options.update(
                {"WavelengthAdj": wavelength_adjustment_workspace})
        if pixel_adjustment_workspace:
            qxy_options.update({"PixelAdj": pixel_adjustment_workspace})

        qxy_alg = create_unmanaged_algorithm(qxy_name, **qxy_options)
        qxy_alg.execute()

        reduced_workspace = qxy_alg.getProperty("OutputWorkspace").value
        reduced_workspace = self._replace_special_values(reduced_workspace)

        # Get the partial workspaces
        sum_of_counts_workspace, sum_of_norms_workspace = self._get_partial_output(
            output_parts, qxy_alg, do_clean=True)

        return reduced_workspace, sum_of_counts_workspace, sum_of_norms_workspace
Ejemplo n.º 31
0
    def _run_single_reduction(self,
                              state,
                              sample_scatter,
                              sample_monitor,
                              sample_transmission=None,
                              sample_direct=None,
                              can_scatter=None,
                              can_monitor=None,
                              can_transmission=None,
                              can_direct=None,
                              output_settings=None,
                              event_slice_optimisation=False,
                              save_can=False,
                              use_optimizations=False):
        single_reduction_name = "SANSSingleReduction"
        ver = 1 if not event_slice_optimisation else 2
        state_dict = Serializer.to_json(state)

        single_reduction_options = {
            "SANSState": state_dict,
            "SampleScatterWorkspace": sample_scatter,
            "SampleScatterMonitorWorkspace": sample_monitor,
            "UseOptimizations": use_optimizations,
            "SaveCan": save_can
        }
        if sample_transmission:
            single_reduction_options.update(
                {"SampleTransmissionWorkspace": sample_transmission})

        if sample_direct:
            single_reduction_options.update(
                {"SampleDirectWorkspace": sample_direct})

        if can_scatter:
            single_reduction_options.update(
                {"CanScatterWorkspace": can_scatter})

        if can_monitor:
            single_reduction_options.update(
                {"CanScatterMonitorWorkspace": can_monitor})

        if can_transmission:
            single_reduction_options.update(
                {"CanTransmissionWorkspace": can_transmission})

        if can_direct:
            single_reduction_options.update({"CanDirectWorkspace": can_direct})

        if output_settings:
            single_reduction_options.update(output_settings)

        single_reduction_alg = create_unmanaged_algorithm(
            single_reduction_name, version=ver, **single_reduction_options)

        # Act
        single_reduction_alg.execute()
        self.assertTrue(single_reduction_alg.isExecuted())
        return single_reduction_alg
Ejemplo n.º 32
0
 def _clone_workspace(workspace):
     clone_name = "CloneWorkspace"
     clone_options = {
         "InputWorkspace": workspace,
         "OutputWorkspace": EMPTY_NAME
     }
     clone_alg = create_unmanaged_algorithm(clone_name, **clone_options)
     clone_alg.execute()
     return clone_alg.getProperty("OutputWorkspace").value
 def _convert_units_to_wavelength(self, workspace):
     convert_name = "ConvertUnits"
     convert_options = {"InputWorkspace": workspace,
                        "Target": "Wavelength"}
     convert_alg = create_unmanaged_algorithm(convert_name, **convert_options)
     convert_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
     convert_alg.setProperty("OutputWorkspace", workspace)
     convert_alg.execute()
     return convert_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 34
0
 def _replace_special_values(self, workspace):
     replace_name = "ReplaceSpecialValues"
     replace_options = {"InputWorkspace": workspace,
                        "OutputWorkspace": EMPTY_NAME,
                        "NaNValue": 0.,
                        "InfinityValue": 0.}
     replace_alg = create_unmanaged_algorithm(replace_name, **replace_options)
     replace_alg.execute()
     return replace_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 35
0
    def _run_q_1d(self, state):
        data_workspace = self.getProperty("InputWorkspace").value
        wavelength_adjustment_workspace = self.getProperty(
            "InputWorkspaceWavelengthAdjustment").value
        pixel_adjustment_workspace = self.getProperty(
            "InputWorkspacePixelAdjustment").value
        wavelength_and_pixel_adjustment_workspace = self.getProperty(
            "InputWorkspaceWavelengthAndPixelAdjustment").value

        # Get QResolution
        convert_to_q = state.convert_to_q
        q_resolution_factory = QResolutionCalculatorFactory()
        q_resolution_calculator = q_resolution_factory.create_q_resolution_calculator(
            state)
        q_resolution_workspace = q_resolution_calculator.get_q_resolution_workspace(
            convert_to_q, data_workspace)

        output_parts = self.getProperty("OutputParts").value

        # Extract relevant settings
        q_binning = convert_to_q.q_1d_rebin_string
        use_gravity = convert_to_q.use_gravity
        gravity_extra_length = convert_to_q.gravity_extra_length
        radius_cutoff = convert_to_q.radius_cutoff * 1000.  # Q1D2 expects the radius cutoff to be in mm
        wavelength_cutoff = convert_to_q.wavelength_cutoff

        q1d_name = "Q1D"
        q1d_options = {
            "DetBankWorkspace": data_workspace,
            "OutputWorkspace": EMPTY_NAME,
            "OutputBinning": q_binning,
            "AccountForGravity": use_gravity,
            "RadiusCut": radius_cutoff,
            "WaveCut": wavelength_cutoff,
            "OutputParts": output_parts,
            "ExtraLength": gravity_extra_length
        }
        if wavelength_adjustment_workspace:
            q1d_options.update(
                {"WavelengthAdj": wavelength_adjustment_workspace})
        if pixel_adjustment_workspace:
            q1d_options.update({"PixelAdj": pixel_adjustment_workspace})
        if wavelength_and_pixel_adjustment_workspace:
            q1d_options.update(
                {"WavePixelAdj": wavelength_and_pixel_adjustment_workspace})
        if q_resolution_workspace:
            q1d_options.update({"QResolution": q_resolution_workspace})

        q1d_alg = create_unmanaged_algorithm(q1d_name, **q1d_options)
        q1d_alg.execute()
        reduced_workspace = q1d_alg.getProperty("OutputWorkspace").value

        # Get the partial workspaces
        sum_of_counts_workspace, sum_of_norms_workspace = self._get_partial_output(
            output_parts, q1d_alg, do_clean=False)

        return reduced_workspace, sum_of_counts_workspace, sum_of_norms_workspace
 def _convert_units_to_wavelength(self, workspace):
     convert_name = "ConvertUnits"
     convert_options = {"InputWorkspace": workspace, "Target": "Wavelength"}
     convert_alg = create_unmanaged_algorithm(convert_name,
                                              **convert_options)
     convert_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
     convert_alg.setProperty("OutputWorkspace", workspace)
     convert_alg.execute()
     return convert_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 37
0
    def divide_by_volume(self, workspace, scale_info):
        volume = self._get_volume(scale_info)

        single_valued_name = "CreateSingleValuedWorkspace"
        single_valued_options = {"OutputWorkspace": EMPTY_NAME,
                                 "DataValue": volume}
        single_valued_alg = create_unmanaged_algorithm(single_valued_name, **single_valued_options)
        single_valued_alg.execute()
        single_valued_workspace = single_valued_alg.getProperty("OutputWorkspace").value

        divide_name = "Divide"
        divide_options = {"LHSWorkspace": workspace,
                          "RHSWorkspace": single_valued_workspace}
        divide_alg = create_unmanaged_algorithm(divide_name, **divide_options)
        divide_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
        divide_alg.setProperty("OutputWorkspace", workspace)
        divide_alg.execute()
        return divide_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 38
0
 def _replace_special_values(self, workspace):
     replace_name = "ReplaceSpecialValues"
     replace_options = {"InputWorkspace": workspace,
                        "OutputWorkspace": EMPTY_NAME,
                        "NaNValue": 0.,
                        "InfinityValue": 0.}
     replace_alg = create_unmanaged_algorithm(replace_name, **replace_options)
     replace_alg.execute()
     return replace_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 39
0
def mask_with_mask_files(mask_info, workspace):
    """
    Apply mask files to the workspace

    Rolling our own MaskDetectors wrapper since masking is broken in a couple
    of places that affect us here.
    Calling MaskDetectors(Workspace=ws_name, MaskedWorkspace=mask_ws_name) is
    not something we can do because the algorithm masks by ws index rather than
    detector id, and unfortunately for SANS the detector table is not the same
    for MaskingWorkspaces as it is for the workspaces containing the data to be
    masked.  Basically, we get a mirror image of what we expect.  Instead, we
    have to extract the det IDs and use those via the DetectorList property.
    :param mask_info: a SANSStateMask object.
    :param workspace: the workspace to be masked.
    :return: the masked workspace.
    """
    mask_files = mask_info.mask_files
    if mask_files:
        idf_path = mask_info.idf_path

        # Mask loader
        load_name = "LoadMask"
        load_options = {"Instrument": idf_path, "OutputWorkspace": EMPTY_NAME}
        load_alg = create_unmanaged_algorithm(load_name, **load_options)
        mask_alg = create_unmanaged_algorithm("MaskDetectors")

        # Masker
        for mask_file in mask_files:
            mask_file = find_full_file_path(mask_file)

            # Get the detector ids which need to be masked
            load_alg.setProperty("InputFile", mask_file)
            load_alg.execute()
            masking_workspace = load_alg.getProperty("OutputWorkspace").value
            # Could use MaskDetectors directly with masking_workspace but it does not
            # support MPI. Use a two step approach via a and b instead.
            # a) Extract detectors to mask from MaskWorkspace
            det_ids = masking_workspace.getMaskedDetectors()
            # b) Mask the detector ids on the instrument
            mask_alg.setProperty("Workspace", workspace)
            mask_alg.setProperty("DetectorList", det_ids)
            mask_alg.execute()
            workspace = mask_alg.getProperty("Workspace").value
    return workspace
Ejemplo n.º 40
0
    def _get_pixel_adjustment_workspace(pixel_adjustment_file, component, idf_path):
        """
        This get the pixel-by-pixel adjustment of the workspace

        :param pixel_adjustment_file: full file path to the pixel adjustment file
        :param component: the component which is currently being investigated
        :param idf_path: the idf path
        :return: the pixel adjustment workspace
        """
        if pixel_adjustment_file:
            load_name = "LoadRKH"
            load_options = {"Filename": pixel_adjustment_file,
                            "OutputWorkspace": EMPTY_NAME,
                            "FirstColumnValue": "SpectrumNumber"}
            load_alg = create_unmanaged_algorithm(load_name, **load_options)
            load_alg.execute()
            output_workspace = load_alg.getProperty("OutputWorkspace").value

            if not idf_path:
                raise ValueError("No IDF path was found in the provided state")

            # Add an instrument to the workspace
            instrument_name = "LoadInstrument"
            instrument_options = {"Workspace": output_workspace,
                                  "Filename": idf_path,
                                  "RewriteSpectraMap": False}
            instrument_alg = create_unmanaged_algorithm(instrument_name, **instrument_options)
            instrument_alg.execute()

            # Crop to the required detector
            crop_name = "CropToComponent"
            component_to_crop = DetectorType(component)
            component_to_crop = get_component_name(output_workspace, component_to_crop)
            crop_options = {"InputWorkspace": output_workspace,
                            "OutputWorkspace": EMPTY_NAME,
                            "ComponentNames": component_to_crop}

            crop_alg = create_unmanaged_algorithm(crop_name, **crop_options)
            crop_alg.execute()
            pixel_adjustment_workspace = crop_alg.getProperty("OutputWorkspace").value
        else:
            pixel_adjustment_workspace = None
        return pixel_adjustment_workspace
Ejemplo n.º 41
0
 def _get_workspace():
     sample_name = "CreateSampleWorkspace"
     sample_options = {"WorkspaceType": "Histogram",
                       "NumBanks": 1,
                       "BankPixelWidth": 1,
                       "OutputWorkspace": "test"}
     sample_alg = create_unmanaged_algorithm(sample_name, **sample_options)
     sample_alg.execute()
     workspace = sample_alg.getProperty("OutputWorkspace").value
     return workspace
Ejemplo n.º 42
0
 def _rebin_workspace(workspace):
     rebin_name = "Rebin"
     rebin_options = {"InputWorkspace": workspace,
                      "OutputWorkspace": EMPTY_NAME,
                      "Params": "{0}, {1}, {2}".format(SANSCreateAdjustmentWorkspacesTest.test_tof_min,
                                                       SANSCreateAdjustmentWorkspacesTest.test_tof_width,
                                                       SANSCreateAdjustmentWorkspacesTest.test_tof_max)}
     rebin_alg = create_unmanaged_algorithm(rebin_name, **rebin_options)
     rebin_alg.execute()
     return rebin_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 43
0
 def _get_workspace(self, file_name):
     full_file_name = FileFinder.findRuns(file_name)[0]
     load_name = "Load"
     load_options = {
         "Filename": full_file_name,
         "OutputWorkspace": EMPTY_NAME
     }
     load_alg = create_unmanaged_algorithm(load_name, **load_options)
     load_alg.execute()
     return load_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 44
0
 def create_1D_workspace(data_x, data_y):
     create_name = "CreateWorkspace"
     create_options = {'DataX': data_x,
                       'DataY': data_y,
                       'NSpec': 1,
                       'UnitX': 'MomentumTransfer',
                       "OutputWorkspace": EMPTY_NAME}
     create_alg = create_unmanaged_algorithm(create_name, **create_options)
     create_alg.execute()
     return create_alg.getProperty('OutputWorkspace').value
Ejemplo n.º 45
0
    def test_that_zero_error_is_removed(self):
        # Arrange
        workspace = SANSSaveTest._get_sample_workspace(
            with_zero_errors=True, convert_to_numeric_axis=True)
        file_name = os.path.join(
            mantid.config.getString('defaultsave.directory'),
            'sample_sans_save_file')
        use_zero_errors_free = True
        save_name = "SANSSave"
        save_options = {
            "InputWorkspace": workspace,
            "Filename": file_name,
            "UseZeroErrorFree": use_zero_errors_free,
            "Nexus": True,
            "CanSAS": False,
            "NXCanSAS": False,
            "NistQxy": False,
            "RKH": False,
            "CSV": False
        }
        save_alg = create_unmanaged_algorithm(save_name, **save_options)

        # Act
        save_alg.execute()
        self.assertTrue(save_alg.isExecuted())
        file_name = os.path.join(
            mantid.config.getString('defaultsave.directory'),
            "sample_sans_save_file.nxs")

        load_name = "LoadNexusProcessed"
        load_options = {"Filename": file_name, "OutputWorkspace": EMPTY_NAME}
        load_alg = create_unmanaged_algorithm(load_name, **load_options)
        load_alg.execute()
        reloaded_workspace = load_alg.getProperty("OutputWorkspace").value
        errors = reloaded_workspace.dataE(0)
        # Make sure that the errors are not zero
        self.assertGreater(errors[0], 1.0)
        self.assertGreater(errors[14], 1.0)
        self.assertGreater(errors[45], 1.0)

        # Clean up
        self._remove_file(file_name)
Ejemplo n.º 46
0
    def _compare_to_reference(self, workspace, reference_file_name, check_spectra_map=True):
        # Load the reference file
        load_name = "LoadNexusProcessed"
        load_options = {"Filename": reference_file_name,
                        "OutputWorkspace": EMPTY_NAME}
        load_alg = create_unmanaged_algorithm(load_name, **load_options)
        load_alg.execute()
        reference_workspace = load_alg.getProperty("OutputWorkspace").value

        # Compare reference file with the output_workspace
        self._compare_workspace(workspace, reference_workspace, check_spectra_map=check_spectra_map)
Ejemplo n.º 47
0
 def _load_wavelength_correction_file(file_name):
     correction_workspace = None
     if file_name:
         load_name = "LoadRKH"
         load_option = {"Filename": file_name,
                        "OutputWorkspace": EMPTY_NAME,
                        "FirstColumnValue": "Wavelength"}
         load_alg = create_unmanaged_algorithm(load_name, **load_option)
         load_alg.execute()
         output_workspace = load_alg.getProperty("OutputWorkspace").value
         # We require HistogramData and not PointData
         if not output_workspace.isHistogramData():
             convert_name = "ConvertToHistogram"
             convert_options = {"InputWorkspace": output_workspace,
                                "OutputWorkspace": EMPTY_NAME}
             convert_alg = create_unmanaged_algorithm(convert_name, **convert_options)
             convert_alg.execute()
             output_workspace = convert_alg.getProperty("OutputWorkspace").value
         correction_workspace = output_workspace
     return correction_workspace
Ejemplo n.º 48
0
def _load_sigma_moderator_workspace(file_name):
    """
    Gets the sigma moderator workspace.
    :param file_name: the file name of the sigma moderator
    :returns the sigma moderator workspace
    """
    load_name = "LoadRKH"
    load_option = {"Filename": file_name,
                   "OutputWorkspace": EMPTY_NAME,
                   "FirstColumnValue": "Wavelength"}
    load_alg = create_unmanaged_algorithm(load_name, **load_option)
    load_alg.execute()
    moderator_workspace = load_alg.getProperty("OutputWorkspace").value

    convert_name = "ConvertToHistogram"
    convert_options = {"InputWorkspace": moderator_workspace,
                       "OutputWorkspace": EMPTY_NAME}
    convert_alg = create_unmanaged_algorithm(convert_name, **convert_options)
    convert_alg.execute()
    return convert_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 49
0
 def _get_monitor_workspace(data=None):
     create_name = "CreateSampleWorkspace"
     name = "test_workspace"
     create_options = {"OutputWorkspace": name,
                       "NumBanks": 0,
                       "NumMonitors": 8}
     create_alg = create_unmanaged_algorithm(create_name, **create_options)
     create_alg.execute()
     ws = create_alg.getProperty("OutputWorkspace").value
     ws = SANSNormalizeToMonitorTest._prepare_workspace(ws, data=data)
     return ws
Ejemplo n.º 50
0
 def _run_test(workspace, state):
     normalize_name = "SANSNormalizeToMonitor"
     normalize_options = {
         "InputWorkspace": workspace,
         "OutputWorkspace": EMPTY_NAME,
         "SANSState": state
     }
     normalize_alg = create_unmanaged_algorithm(normalize_name,
                                                **normalize_options)
     normalize_alg.execute()
     return normalize_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 51
0
    def _get_sample_workspace(with_zero_errors, convert_to_numeric_axis=False):
        create_name = "CreateSimulationWorkspace"
        create_options = {
            "Instrument": "LARMOR",
            "BinParams": '1,10,1000',
            "UnitX": 'MomentumTransfer',
            "OutputWorkspace": EMPTY_NAME
        }
        create_alg = create_unmanaged_algorithm(create_name, **create_options)
        create_alg.execute()
        workspace = create_alg.getProperty("OutputWorkspace").value

        crop_name = "CropWorkspace"
        crop_options = {
            "InputWorkspace": workspace,
            "OutputWorkspace": EMPTY_NAME,
            "EndWorkspaceIndex": 0
        }
        crop_alg = create_unmanaged_algorithm(crop_name, **crop_options)
        crop_alg.execute()
        workspace = crop_alg.getProperty("OutputWorkspace").value

        if convert_to_numeric_axis:
            convert_name = "ConvertSpectrumAxis"
            convert_options = {
                "InputWorkspace": workspace,
                "OutputWorkspace": EMPTY_NAME,
                "Target": 'ElasticQ',
                "EFixed": 1
            }
            convert_alg = create_unmanaged_algorithm(convert_name,
                                                     **convert_options)
            convert_alg.execute()
            workspace = convert_alg.getProperty("OutputWorkspace").value

        if with_zero_errors:
            errors = workspace.dataE(0)
            errors[0] = 0.0
            errors[14] = 0.0
            errors[45] = 0.0
        return workspace
Ejemplo n.º 52
0
def perform_move(state, workspace):
    serialized_state = state.property_manager
    move_name = "SANSMove"

    zero_options = {
        "SANSState": serialized_state,
        "Workspace": workspace,
        "MoveType": "SetToZero",
        "Component": ""
    }
    zero_alg = create_unmanaged_algorithm(move_name, **zero_options)
    zero_alg.execute()
    workspace = zero_alg.getProperty("Workspace").value

    move_options = {
        "SANSState": serialized_state,
        "Workspace": workspace,
        "MoveType": "InitialMove"
    }
    move_alg = create_unmanaged_algorithm(move_name, **move_options)
    move_alg.execute()
Ejemplo n.º 53
0
def get_region_of_interest(workspace, radius=None, roi_files=None, mask_files=None):
    """
    Calculate the various contributions to the "region of interest", used in the
    transmission calculation.

    The region of interest can be made up of a circle of detectors (with a given radius)
    around the beam centre, and/or one or more mask files, and/or the main detector bank.
    Note that the mask files wont actually be used for masking, we're just piggy-backing
    on the functionality that they provide. Note that in the case of a radius, we have
    to ensure that we do not use a workspace which already has masked detectors, since
    they would contribute to the ROI.
    :param workspace: the workspace which is used for the transmission calculation
    :param radius: the radius of the region of interest
    :param roi_files: a list of roi files. Spectra in the ROI contribute to the
                      transmission calculation.
    :param mask_files: a list of mask files. Spectra in the Mask explicitly do not
                       contribute to the transmission calculation.
    :return: a list of spectrum numbers
    """
    trans_roi = []

    if radius is not None:
        # Mask out a cylinder with the given radius in a copy of the workspace.
        # The centre position of the Cylinder does not require a shift, as all
        # components have been shifted already, when the workspaces were loaded
        clone_name = "CloneWorkspace"
        clone_options = {"InputWorkspace": workspace,
                         "OutputWorkspace": EMPTY_NAME}
        clone_alg = create_unmanaged_algorithm(clone_name, **clone_options)
        clone_alg.execute()
        cloned_workspace = clone_alg.getProperty("OutputWorkspace").value

        # Mask the cylinder around a centre of (0, 0)
        mask_with_cylinder(cloned_workspace, radius, 0.0, 0.0, "")

        # Extract the masked detector ID's.
        trans_roi += get_masked_det_ids(cloned_workspace)

    idf_path = get_idf_path_from_workspace(workspace)

    if roi_files is not None and idf_path is not None:
        for roi_file in roi_files:
            trans_roi += get_masked_det_ids_from_mask_file(roi_file, idf_path)

    masked_ids = []
    if mask_files is not None and idf_path is not None:
        for mask_file in mask_files:
            masked_ids += get_masked_det_ids_from_mask_file(mask_file, idf_path)

    # Detector ids which are not allowed and specified by "masked_ids" need to
    # be removed from the trans_roi list
    # Remove duplicates and sort.
    return sorted(set(trans_roi) - set(masked_ids))
Ejemplo n.º 54
0
    def _run_single_reduction(self,
                              state,
                              sample_scatter,
                              sample_monitor,
                              sample_transmission=None,
                              sample_direct=None,
                              can_scatter=None,
                              can_monitor=None,
                              can_transmission=None,
                              can_direct=None,
                              output_settings=None):
        single_reduction_name = "SANSSingleReduction"
        state_dict = state.property_manager

        single_reduction_options = {
            "SANSState": state_dict,
            "SampleScatterWorkspace": sample_scatter,
            "SampleScatterMonitorWorkspace": sample_monitor,
            "UseOptimizations": False
        }
        if sample_transmission:
            single_reduction_options.update(
                {"SampleTransmissionWorkspace": sample_transmission})

        if sample_direct:
            single_reduction_options.update(
                {"SampleDirectWorkspace": sample_direct})

        if can_scatter:
            single_reduction_options.update(
                {"CanScatterWorkspace": can_scatter})

        if can_monitor:
            single_reduction_options.update(
                {"CanScatterMonitorWorkspace": can_monitor})

        if can_transmission:
            single_reduction_options.update(
                {"CanTransmissionWorkspace": can_transmission})

        if can_direct:
            single_reduction_options.update({"CanDirectWorkspace": can_direct})

        if output_settings:
            single_reduction_options.update(output_settings)

        single_reduction_alg = create_unmanaged_algorithm(
            single_reduction_name, **single_reduction_options)

        # Act
        single_reduction_alg.execute()
        self.assertTrue(single_reduction_alg.isExecuted())
        return single_reduction_alg
Ejemplo n.º 55
0
 def _get_sample_data():
     create_name = "CreateSampleWorkspace"
     name = "test_workspace"
     create_options = {"OutputWorkspace": name,
                       "NumBanks": 1,
                       "NumMonitors": 1,
                       "XMin": SANSCreateAdjustmentWorkspacesTest.test_wav_min,
                       "XMax": SANSCreateAdjustmentWorkspacesTest.test_wav_max,
                       "BinWidth": SANSCreateAdjustmentWorkspacesTest.test_wav_width,
                       "XUnit": "Wavelength"}
     create_alg = create_unmanaged_algorithm(create_name, **create_options)
     create_alg.execute()
     return create_alg.getProperty("OutputWorkspace").value
    def _get_wide_angle_correction_workspace(self, sample_data, calculated_transmission_workspace):
        wide_angle_correction = self._state.wide_angle_correction

        workspace = None
        if wide_angle_correction and sample_data and calculated_transmission_workspace:
            wide_angle_name = "SANSWideAngleCorrection"
            wide_angle_options = {"SampleData": sample_data,
                                  "TransmissionData": calculated_transmission_workspace,
                                  "OutputWorkspace": EMPTY_NAME}
            wide_angle_alg = create_unmanaged_algorithm(wide_angle_name, **wide_angle_options)
            wide_angle_alg.execute()
            workspace = wide_angle_alg.getProperty("OutputWorkspace").value
        return workspace
Ejemplo n.º 57
0
def _replace_special_values(workspace):
    replace_name = "ReplaceSpecialValues"
    replace_options = {"InputWorkspace": workspace,
                       "OutputWorkspace": EMPTY_NAME,
                       "NaNValue": 0.,
                       "InfinityValue": 0.,
                       "UseAbsolute": False,
                       "SmallNumberThreshold": 0.0,
                       "SmallNumberValue": 0.0,
                       "SmallNumberError": 0.0}
    replace_alg = create_unmanaged_algorithm(replace_name, **replace_options)
    replace_alg.execute()
    return replace_alg.getProperty("OutputWorkspace").value
Ejemplo n.º 58
0
 def test_that_run_number_properties_can_be_set(self):
     # Arrange
     workspace = SANSSaveTest._get_sample_workspace(with_zero_errors=False, convert_to_numeric_axis=True)
     file_name = os.path.join(mantid.config.getString('defaultsave.directory'), 'sample_sans_save_file')
     save_name = "SANSSave"
     save_options = {"InputWorkspace": workspace,
                     "Filename": file_name,
                     "UseZeroErrorFree": False,
                     "Nexus": False,
                     "CanSAS": False,
                     "NXCanSAS": True,
                     "NistQxy": False,
                     "RKH": False,
                     "CSV": False,
                     "SampleTransmissionRunNumber": "5",
                     "SampleDirectRunNumber": "6",
                     "CanScatterRunNumber": "7",
                     "CanDirectRunNumber": "8"}
     try:
         create_unmanaged_algorithm(save_name, **save_options)
     except RuntimeError:
         self.fail("Unable to set properties for SANSSave.")
Ejemplo n.º 59
0
 def test_single_nested_json_raises(self):
     convert_options = {
         "InputWorkspace": provide_workspace(),
         "OutputWorkspace": EMPTY_NAME,
         "RebinMode": "InterpolatingRebin",
         self.WAV_PAIRS: json.dumps([1.0, 2.0]),
         "WavelengthStep": 1.5,
         "WavelengthStepType": RangeStepType.LIN.value
     }
     convert_alg = create_unmanaged_algorithm(
         "SANSConvertToWavelengthAndRebin", **convert_options)
     with self.assertRaisesRegex(RuntimeError, "WavelengthPairs"):
         convert_alg.execute()