Ejemplo n.º 1
0
 def test_AlgorithmID_compares_by_value(self):
     alg = AlgorithmManager.createUnmanaged('Load')
     id = alg.getAlgorithmID()
     self.assertEquals(id, id) # equals itself
     alg2 = AlgorithmManager.createUnmanaged('Load')
     id2 = alg2.getAlgorithmID()
     self.assertNotEqual(id2, id)
Ejemplo n.º 2
0
 def test_AlgorithmID_compares_by_value(self):
     alg = AlgorithmManager.createUnmanaged('Load')
     id = alg.getAlgorithmID()
     self.assertEquals(id, id)  # equals itself
     alg2 = AlgorithmManager.createUnmanaged('Load')
     id2 = alg2.getAlgorithmID()
     self.assertNotEqual(id2, id)
Ejemplo n.º 3
0
 def setUp(self):
     if self._integration is None:
         self.__class__._integration = AlgorithmManager.createUnmanaged("Integration")
         self.__class__._integration.initialize()
     if self._mask_dets is None:
         self.__class__._mask_dets = AlgorithmManager.createUnmanaged("MaskDetectors")
         self.__class__._mask_dets.initialize()
Ejemplo n.º 4
0
 def setUp(self):
     if self._integration is None:
         self.__class__._integration = AlgorithmManager.createUnmanaged(
             "Integration")
         self.__class__._integration.initialize()
     if self._mask_dets is None:
         self.__class__._mask_dets = AlgorithmManager.createUnmanaged(
             "MaskDetectors")
         self.__class__._mask_dets.initialize()
Ejemplo n.º 5
0
 def validateInputs(self):
     issues = dict()
     loader = self.getPropertyValue('LoaderName')
     version = self.getProperty('LoaderVersion').value
     try:
         AlgorithmManager.createUnmanaged(loader, version)
     except RuntimeError:
         message = loader + '-v' + str(version) + ' is not registered with Mantid.'
         issues['LoaderName'] = message
         issues['LoaderVersion'] = message
     return issues
Ejemplo n.º 6
0
    def test_with_workspace_types(self):
        ws = CreateSampleWorkspace(
            Function="User Defined",
            UserDefinedFunction="name=LinearBackground, A0=0.3;name=Gaussian, "
            "PeakCentre=5, Height=10, Sigma=0.7",
            NumBanks=1,
            BankPixelWidth=1,
            XMin=0,
            XMax=10,
            BinWidth=0.1)

        # Setup the model, here a Gaussian, to fit to data
        tryCentre = '4'  # A start guess on peak centre
        sigma = '1'  # A start guess on peak width
        height = '8'  # A start guess on peak height
        myFunc = 'name=Gaussian, Height=' + height + ', PeakCentre=' + tryCentre + ', Sigma=' + sigma
        args = {"Function": myFunc, "InputWorkspace": ws, "Output": 'fit'}
        parent_alg = AlgorithmManager.createUnmanaged('Load')
        child_alg = parent_alg.createChildAlgorithm('Fit',
                                                    0,
                                                    0,
                                                    True,
                                                    version=1,
                                                    **args)
        child_alg.execute()
        out_ws = child_alg.getProperty("OutputWorkspace").value
        self.assertIsInstance(out_ws, Workspace)
Ejemplo n.º 7
0
    def _load_workspace(self, state):
        load_alg = AlgorithmManager.createUnmanaged("SANSLoad")
        load_alg.setChild(True)
        load_alg.initialize()

        state_dict = state.property_manager
        load_alg.setProperty("SANSState", state_dict)
        load_alg.setProperty("PublishToCache", False)
        load_alg.setProperty("UseCached", False)
        load_alg.setProperty("MoveWorkspace", False)
        load_alg.setProperty("SampleScatterWorkspace", EMPTY_NAME)
        load_alg.setProperty("SampleScatterMonitorWorkspace", EMPTY_NAME)
        if state.data.sample_transmission:
            load_alg.setProperty("SampleTransmissionWorkspace", EMPTY_NAME)
        if state.data.sample_direct:
            load_alg.setProperty("SampleDirectWorkspace", EMPTY_NAME)

        # Act
        load_alg.execute()
        self.assertTrue(load_alg.isExecuted())
        sample_scatter = load_alg.getProperty("SampleScatterWorkspace").value
        sample_scatter_monitor_workspace = load_alg.getProperty("SampleScatterMonitorWorkspace").value
        if state.data.sample_transmission:
            transmission_workspace = load_alg.getProperty("SampleTransmissionWorkspace").value
        else:
            transmission_workspace = None
        if state.data.sample_direct:
            direct_workspace = load_alg.getProperty("SampleDirectWorkspace").value
        else:
            direct_workspace = None
        return sample_scatter, sample_scatter_monitor_workspace, transmission_workspace, direct_workspace
Ejemplo n.º 8
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
Ejemplo n.º 9
0
def run_algorithm(name, **kwargs):
    """Run a named algorithm and return the
    algorithm handle

    Parameters:
        name - The name of the algorithm
        kwargs - A dictionary of property name:value pairs
    """
    alg = AlgorithmManager.createUnmanaged(name)
    alg.initialize()
    # Avoid problem that Load needs to set Filename first if it exists
    if name == 'Load' and 'Filename' in kwargs:
        alg.setPropertyValue('Filename', kwargs['Filename'])
        del kwargs['Filename']
    if 'child'in kwargs:
        alg.setChild(True)
        del kwargs['child']
        if 'OutputWorkspace' in alg:
            alg.setPropertyValue("OutputWorkspace","UNUSED_NAME_FOR_CHILD")
    if 'rethrow' in kwargs:
        alg.setRethrows(True)
        del kwargs['rethrow']
    for key, value in kwargs.iteritems():
        alg.setProperty(key, value)
    alg.execute()
    return alg
Ejemplo n.º 10
0
    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 test_alg_with_overridden_attrs(self):
     testhelpers.assertRaisesNothing(self,AlgorithmManager.createUnmanaged, "TestPyAlgOverriddenAttrs")
     alg = AlgorithmManager.createUnmanaged("TestPyAlgOverriddenAttrs")
     self.assertEquals(alg.name(), "TestPyAlgOverriddenAttrs")
     self.assertEquals(alg.version(), 2)
     self.assertEquals(alg.category(), "BestAlgorithms")
     self.assertEquals(alg.helpURL(), "Optional documentation URL")
Ejemplo n.º 12
0
 def test_alg_with_overridden_attrs(self):
     testhelpers.assertRaisesNothing(self,AlgorithmManager.createUnmanaged, "TestPyAlgOverriddenAttrs")
     alg = AlgorithmManager.createUnmanaged("TestPyAlgOverriddenAttrs")
     self.assertEqual(alg.name(), "TestPyAlgOverriddenAttrs")
     self.assertEqual(alg.version(), 2)
     self.assertEqual(alg.category(), "BestAlgorithms")
     self.assertEqual(alg.helpURL(), "Optional documentation URL")
Ejemplo n.º 13
0
 def setUp(self):
     FrameworkManagerImpl.Instance()
     self._alg_factory = AlgorithmFactory.Instance()
     self._alg_factory.subscribe(_ParamTester)
     if self._load is None:
         self.__class__._load = AlgorithmManager.createUnmanaged('Load')
         self._load.initialize()
Ejemplo n.º 14
0
    def _provide_workspace_with_x_errors(self, workspace_name, use_xerror = True, nspec = 1,
                                         x_in = [1,2,3,4,5,6,7,8,9,10], y_in = [2,2,2,2,2,2,2,2,2],
                                         e_in = [1,1,1,1,1,1,1,1,1],  x_error = [1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9, 10.1]):
        x = []
        y = []
        e = []
        for item in range(0, nspec):
            x = x + x_in
            y = y + y_in
            e = e + e_in
        ws_alg = AlgorithmManager.createUnmanaged("CreateWorkspace")
        ws_alg.initialize()
        ws_alg.setChild(True)
        ws_alg.setProperty("DataX", x)
        ws_alg.setProperty("DataY", y)
        ws_alg.setProperty("DataE", e)
        ws_alg.setProperty("NSpec", nspec)
        ws_alg.setProperty("UnitX", "MomentumTransfer")
        ws_alg.setProperty("OutputWorkspace", workspace_name)
        ws_alg.execute()

        ws = ws_alg.getProperty("OutputWorkspace").value
        if use_xerror:
            for hists in range(0, nspec):
                x_error_array = np.asarray(x_error)
                ws.setDx(hists, x_error_array)
        return ws
Ejemplo n.º 15
0
 def _validate_algorithm(self, lhs=None, rhs=None):
     """Validates the inputs for algorithm that is going to be called to process inputs."""
     valid_lhs = valid_rhs = True
     err_msg_lhs = err_msg_rhs = ""
     err_msg = ""
     alg_name = self._figure_out_algorithm()
     alg = AlgorithmManager.createUnmanaged(alg_name)
     alg.initialize()
     if lhs:
         try:
             if alg_name == 'WeightedMean':
                 alg.setProperty("InputWorkspace1", lhs)
             else:
                 alg.setProperty("LHSWorkspace", lhs)
         except (RuntimeError, ValueError) as err:
             valid_lhs = False
             err_msg_lhs = str(err)
             err_msg = err_msg_lhs
     if rhs:
         try:
             if alg_name == 'WeightedMean':
                 alg.setProperty("InputWorkspace2", rhs)
             else:
                 alg.setProperty("RHSWorkspace", rhs)
         except (RuntimeError, ValueError) as err:
             valid_rhs = False
             err_msg_rhs = str(err)
             err_msg = err_msg_rhs
     if lhs and rhs:
         err_msg = [err_msg_lhs, err_msg_rhs]
     return valid_lhs, valid_rhs, err_msg
Ejemplo n.º 16
0
    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
Ejemplo n.º 17
0
 def _provide_sample_workspace():
     alg = AlgorithmManager.createUnmanaged("CreateSampleWorkspace")
     alg.setChild(True)
     alg.initialize()
     alg.setProperty("OutputWorkspace", "dummy")
     alg.execute()
     return alg.getProperty("OutputWorkspace").value
Ejemplo n.º 18
0
    def _run_load(state,
                  publish_to_cache,
                  use_cached,
                  move_workspace=False,
                  beam_coordinates=None,
                  component=None,
                  output_workspace_names=None):
        load_alg = AlgorithmManager.createUnmanaged("SANSLoad")
        load_alg.setChild(True)
        load_alg.setRethrows(True)
        load_alg.initialize()

        state_dict = Serializer.to_json(state)
        load_alg.setProperty("SANSState", state_dict)
        load_alg.setProperty("PublishToCache", publish_to_cache)
        load_alg.setProperty("UseCached", use_cached)
        if move_workspace:
            load_alg.setProperty("Component", component)
            load_alg.setProperty("BeamCoordinates", beam_coordinates)

        if output_workspace_names:
            for name, value in output_workspace_names.items():
                load_alg.setProperty(name, value)

        # Act
        load_alg.execute()
        # self.assertTrue(load_alg.isExecuted())
        return load_alg
Ejemplo n.º 19
0
 def _provide_sample_workspace():
     alg = AlgorithmManager.createUnmanaged("CreateSampleWorkspace")
     alg.setChild(True)
     alg.initialize()
     alg.setProperty("OutputWorkspace", "dummy")
     alg.execute()
     return alg.getProperty("OutputWorkspace").value
Ejemplo n.º 20
0
def get_geometry_information_raw(file_name):
    """
    Gets the geometry information form the table workspace with the spb information

    :param file_name: the full file name to an existing raw file.
    :return: height, width, thickness and shape
    """
    alg_info = AlgorithmManager.createUnmanaged("RawFileInfo")
    alg_info.initialize()
    alg_info.setChild(True)
    alg_info.setProperty("Filename", file_name)
    alg_info.setProperty("GetRunParameters", False)
    alg_info.setProperty("GetSampleParameters", True)
    alg_info.execute()

    sample_parameters = alg_info.getProperty("SampleParameterTable").value
    keys = sample_parameters.getColumnNames()

    height_id = E_HEIGHT
    width_id = E_WIDTH
    thickness_id = E_THICK
    shape_id = E_GEOM

    height = sample_parameters.column(keys.index(height_id))[0]
    width = sample_parameters.column(keys.index(width_id))[0]
    thickness = sample_parameters.column(keys.index(thickness_id))[0]
    shape_flag = sample_parameters.column(keys.index(shape_id))[0]
    shape = convert_to_shape(shape_flag)
    return height, width, thickness, shape
Ejemplo n.º 21
0
    def _save_workspaces(self, directory):
        """
        Save all workspaces present in the ADS to the given directory
        :param directory: String; Path to where to save the workspaces
        """
        # Get all present workspaces
        ws_list = ADS.getObjectNames()

        if len(ws_list) == 0:
            return

        start_time = UsageService.getStartTime().toISO8601String()

        alg_name = "GeneratePythonScript"
        alg = AlgorithmManager.createUnmanaged(alg_name, 1)
        alg.setChild(True)
        alg.setLogging(False)

        for index, ws in enumerate(ws_list):
            if self._empty_group_workspace(ws):
                continue

            filename = str(index) + ".py"
            filename = os.path.join(directory, filename)

            alg.initialize()
            alg.setProperty("AppendTimestamp", True)
            alg.setProperty("AppendExecCount", True)
            alg.setProperty("InputWorkspace", ws)
            alg.setPropertyValue("Filename", filename)
            alg.setPropertyValue("StartTimestamp", start_time)
            alg.setProperty("IgnoreTheseAlgs", ALGS_TO_IGNORE)
            alg.setProperty("IgnoreTheseAlgProperties", ALG_PROPERTIES_TO_IGNORE)

            alg.execute()
Ejemplo n.º 22
0
    def plot_guess(self):
        """
        Plot the guess curve.
        """
        from mantidqt.plotting.functions import plot
        fun = self.getFittingFunction()
        ws_name = self.workspaceName()
        if fun == '' or ws_name == '':
            return
        ws_index = self.workspaceIndex()
        out_ws_name = '{}_guess'.format(ws_name)

        alg = AlgorithmManager.createUnmanaged('EvaluateFunction')
        alg.setChild(True)
        alg.initialize()
        alg.setProperty('Function', fun)
        alg.setProperty('InputWorkspace', ws_name)
        alg.setProperty('WorkspaceIndex', ws_index)
        alg.setProperty('OutputWorkspace', out_ws_name)
        alg.execute()
        out_ws = alg.getProperty('OutputWorkspace').value

        plot([out_ws],
             wksp_indices=[1],
             fig=self.canvas.figure,
             overplot=True,
             plot_kwargs={'label': out_ws_name})
        for lin in self.get_lines():
            if lin.get_label().startswith(out_ws_name):
                self.guess_line = lin
                self.setTextPlotGuess('Remove Guess')
        self.canvas.draw()
Ejemplo n.º 23
0
    def plot_guess(self):
        """
        Plot the guess curve.
        """
        from mantidqt.plotting.functions import plot
        fun = self.getFittingFunction()
        ws_name = self.workspaceName()
        if fun == '' or ws_name == '':
            return
        ws_index = self.workspaceIndex()
        out_ws_name = '{}_guess'.format(ws_name)

        alg = AlgorithmManager.createUnmanaged('EvaluateFunction')
        alg.setChild(True)
        alg.initialize()
        alg.setProperty('Function', fun)
        alg.setProperty('InputWorkspace', ws_name)
        alg.setProperty('WorkspaceIndex', ws_index)
        alg.setProperty('OutputWorkspace', out_ws_name)
        alg.execute()
        out_ws = alg.getProperty('OutputWorkspace').value

        plot([out_ws], wksp_indices=[1], fig=self.canvas.figure, overplot=True, plot_kwargs={'label': out_ws_name})
        for lin in self.get_lines():
            if lin.get_label().startswith(out_ws_name):
                self.guess_line = lin
                self.setTextPlotGuess('Remove Guess')
        self.canvas.draw()
Ejemplo n.º 24
0
    def _provide_workspace_with_x_errors(
            self,
            workspace_name,
            use_xerror=True,
            nspec=1,
            x_in=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            y_in=[2, 2, 2, 2, 2, 2, 2, 2, 2],
            e_in=[1, 1, 1, 1, 1, 1, 1, 1, 1],
            x_error=[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]):
        x = []
        y = []
        e = []
        for item in range(0, nspec):
            x = x + x_in
            y = y + y_in
            e = e + e_in
        ws_alg = AlgorithmManager.createUnmanaged("CreateWorkspace")
        ws_alg.initialize()
        ws_alg.setChild(True)
        ws_alg.setProperty("DataX", x)
        ws_alg.setProperty("DataY", y)
        ws_alg.setProperty("DataE", e)
        ws_alg.setProperty("NSpec", nspec)
        ws_alg.setProperty("UnitX", "MomentumTransfer")
        ws_alg.setProperty("OutputWorkspace", workspace_name)
        ws_alg.execute()

        ws = ws_alg.getProperty("OutputWorkspace").value
        if use_xerror:
            for hists in range(0, nspec):
                x_error_array = np.asarray(x_error)
                ws.setDx(hists, x_error_array)
        return ws
Ejemplo n.º 25
0
def get_geometry_information_raw(file_name):
    """
    Gets the geometry information form the table workspace with the spb information

    :param file_name: the full file name to an existing raw file.
    :return: height, width, thickness and shape
    """
    alg_info = AlgorithmManager.createUnmanaged("RawFileInfo")
    alg_info.initialize()
    alg_info.setChild(True)
    alg_info.setProperty("Filename", file_name)
    alg_info.setProperty("GetRunParameters", False)
    alg_info.setProperty("GetSampleParameters", True)
    alg_info.execute()

    sample_parameters = alg_info.getProperty("SampleParameterTable").value
    keys = sample_parameters.getColumnNames()

    height_id = E_HEIGHT
    width_id = E_WIDTH
    thickness_id = E_THICK
    shape_id = E_GEOM

    height = sample_parameters.column(keys.index(height_id))[0]
    width = sample_parameters.column(keys.index(width_id))[0]
    thickness = sample_parameters.column(keys.index(thickness_id))[0]
    shape_flag = sample_parameters.column(keys.index(shape_id))[0]
    shape = convert_to_shape(shape_flag)
    return height, width, thickness, shape
Ejemplo n.º 26
0
    def _run_move(self,
                  state,
                  workspace,
                  move_type,
                  beam_coordinates=None,
                  component=None):
        move_alg = AlgorithmManager.createUnmanaged("SANSMove")
        move_alg.setChild(True)
        move_alg.initialize()
        state_dict = state.property_manager

        move_alg.setProperty("SANSState", state_dict)
        move_alg.setProperty("Workspace", workspace)
        move_alg.setProperty("MoveType", move_type)

        if beam_coordinates is not None:
            move_alg.setProperty("BeamCoordinates", beam_coordinates)

        if component is not None:
            move_alg.setProperty("Component", component)

        # Act
        move_alg.execute()
        self.assertTrue(move_alg.isExecuted())
        return move_alg
Ejemplo n.º 27
0
    def evaluate_function(self, ws_name, fun, out_ws_name):
        """
        Evaluates the guess workspace for the input workspace and function
        :param ws_name: Name of the workspace in the ADS
        :param fun: Function to be evaluated
        :param out_ws_name: Output workspace name
        :return: Output guess workspace
        """
        workspace = AnalysisDataService.retrieve(ws_name)
        alg = AlgorithmManager.createUnmanaged('EvaluateFunction')
        alg.setChild(True)
        alg.initialize()
        alg.setProperty('Function', fun)
        alg.setProperty('InputWorkspace', ws_name)
        if isinstance(workspace, ITableWorkspace):
            alg.setProperty('XColumn', self.fit_browser.getXColumnName())
            alg.setProperty('YColumn', self.fit_browser.getYColumnName())
            if self.fit_browser.getErrColumnName():
                alg.setProperty('ErrColumn',
                                self.fit_browser.getErrColumnName())
        else:
            alg.setProperty('WorkspaceIndex',
                            self.fit_browser.workspaceIndex())
        alg.setProperty('StartX', self.fit_browser.startX())
        alg.setProperty('EndX', self.fit_browser.endX())
        alg.setProperty('IgnoreInvalidData',
                        self.fit_browser.ignoreInvalidData())
        alg.setProperty('OutputWorkspace', out_ws_name)
        alg.execute()

        return alg.getProperty('OutputWorkspace').value
Ejemplo n.º 28
0
 def test_createChildAlgorithm_without_name(self):
     parent_alg = AlgorithmManager.createUnmanaged('Load')
     with self.assertRaisesRegex(ValueError, "algorithm name"):
         parent_alg.createChildAlgorithm(startProgress=0.0,
                                         endProgress=1.0,
                                         enableLogging=False,
                                         version=1,
                                         **{"XUnit": "Wavelength"})
Ejemplo n.º 29
0
 def test_alg_with_default_attrs(self):
     testhelpers.assertRaisesNothing(self,AlgorithmManager.createUnmanaged, "TestPyAlgDefaultAttrs")
     alg = AlgorithmManager.createUnmanaged("TestPyAlgDefaultAttrs")
     testhelpers.assertRaisesNothing(self,alg.initialize)
    
     self.assertEquals(alg.name(), "TestPyAlgDefaultAttrs")
     self.assertEquals(alg.version(), 1)
     self.assertEquals(alg.category(), "PythonAlgorithms")
 def test_isRunning_returning_non_bool_raises_error(self):
     alg = AlgorithmManager.createUnmanaged("TestPyAlgIsRunningReturnsNonBool")
     # boost.python automatically downcasts to the most available type
     # meaning that type(alg)=TestPyAlgIsRunningReturnsNonBool and not the interface
     # so that any method lookup doesn't go through the base class automatically.
     # Here we simulate how it would be called on C++ framework side
     base_running_attr = getattr(IAlgorithm, "isRunning")
     self.assertRaises(RuntimeError, base_running_attr, alg)
Ejemplo n.º 31
0
def load_workspace(file_name):
    alg = AlgorithmManager.createUnmanaged("Load")
    alg.initialize()
    alg.setChild(True)
    alg.setProperty("Filename", file_name)
    alg.setProperty("OutputWorkspace", "dummy")
    alg.execute()
    return alg.getProperty("OutputWorkspace").value
Ejemplo n.º 32
0
 def test_isRunning_returning_non_bool_raises_error(self):
     alg = AlgorithmManager.createUnmanaged("TestPyAlgIsRunningReturnsNonBool")
     # boost.python automatically downcasts to the most available type
     # meaning that type(alg)=TestPyAlgIsRunningReturnsNonBool and not the interface
     # so that any method lookup doesn't go through the base class automatically.
     # Here we simulate how it would be called on C++ framework side
     base_running_attr = getattr(IAlgorithm, "isRunning")
     self.assertRaises(RuntimeError, base_running_attr, alg)
Ejemplo n.º 33
0
 def _create_algorithm(self, **kwargs):
     alg = AlgorithmManager.createUnmanaged("VesuvioPreFit")
     alg.initialize()
     alg.setChild(True)
     alg.setProperty("OutputWorkspace", "__unused")
     for key, value in kwargs.iteritems():
         alg.setProperty(key, value)
     return alg
Ejemplo n.º 34
0
 def _create_algorithm(self, **kwargs):
     alg = AlgorithmManager.createUnmanaged("VesuvioPreFit")
     alg.initialize()
     alg.setChild(True)
     alg.setProperty("OutputWorkspace", "__unused")
     for key, value in kwargs.iteritems():
         alg.setProperty(key, value)
     return alg
Ejemplo n.º 35
0
 def test_createChildAlgorithm_with_incorrect_types(self):
     parent_alg = AlgorithmManager.createUnmanaged('Load')
     with self.assertRaises(TypeError):
         parent_alg.createChildAlgorithm("CreateSampleWorkspace",
                                         startProgress="0.0",
                                         endProgress=1.0,
                                         enableLogging=False,
                                         version=1,
                                         **{"XUnit": "Wavelength"})
Ejemplo n.º 36
0
def save_reduction(worksspace_names, formats, x_units='DeltaE'):
    """
    Saves the workspaces to the default save directory.

    @param worksspace_names List of workspace names to save
    @param formats List of formats to save in
    @param Output X units
    """
    from mantid.simpleapi import (SaveSPE, SaveNexusProcessed, SaveNXSPE,
                                  SaveAscii, Rebin, DeleteWorkspace,
                                  ConvertSpectrumAxis, SaveDaveGrp)

    for workspace_name in worksspace_names:
        if 'spe' in formats:
            SaveSPE(InputWorkspace=workspace_name,
                    Filename=workspace_name + '.spe')

        if 'nxs' in formats:
            SaveNexusProcessed(InputWorkspace=workspace_name,
                               Filename=workspace_name + '.nxs')

        if 'nxspe' in formats:
            SaveNXSPE(InputWorkspace=workspace_name,
                      Filename=workspace_name + '.nxspe')

        if 'ascii' in formats:
            # Version 1 of SaveAscii produces output that works better with excel/origin
            # For some reason this has to be done with an algorithm object, using the function
            # wrapper with Version did not change the version that was run
            saveAsciiAlg = AlgorithmManager.createUnmanaged('SaveAscii', 1)
            saveAsciiAlg.initialize()
            saveAsciiAlg.setProperty('InputWorkspace', workspace_name)
            saveAsciiAlg.setProperty('Filename', workspace_name + '.dat')
            saveAsciiAlg.execute()

        if 'aclimax' in formats:
            if x_units == 'DeltaE_inWavenumber':
                bins = '24, -0.005, 4000' #cm-1
            else:
                bins = '3, -0.005, 500' #meV

            Rebin(InputWorkspace=workspace_name,
                  OutputWorkspace=workspace_name + '_aclimax_save_temp',
                  Params=bins)
            SaveAscii(InputWorkspace=workspace_name + '_aclimax_save_temp',
                      Filename=workspace_name + '_aclimax.dat',
                      Separator='Tab')
            DeleteWorkspace(Workspace=workspace_name + '_aclimax_save_temp')

        if 'davegrp' in formats:
            ConvertSpectrumAxis(InputWorkspace=workspace_name,
                                OutputWorkspace=workspace_name + '_davegrp_save_temp',
                                Target='ElasticQ',
                                EMode='Indirect')
            SaveDaveGrp(InputWorkspace=workspace_name + '_davegrp_save_temp',
                        Filename=workspace_name + '.grp')
            DeleteWorkspace(Workspace=workspace_name + '_davegrp_save_temp')
Ejemplo n.º 37
0
    def test_createChildAlgorithm_respects_keyword_arguments(self):
        parent_alg = AlgorithmManager.createUnmanaged('Load')
        try:
            child_alg = parent_alg.createChildAlgorithm(name='Rebin',version=1,startProgress=0.5,endProgress=0.9,enableLogging=True)
        except Exception as exc:
            self.fail("Expected createChildAlgorithm not to throw but it did: %s" % (str(exc)))

        # Unknown keyword
        self.assertRaises(Exception, parent_alg.createChildAlgorithm, name='Rebin',version=1,startProgress=0.5,endProgress=0.9,enableLogging=True, unknownKW=1)
Ejemplo n.º 38
0
 def test_createChildAlgorithm_with_list(self):
     parent_alg = AlgorithmManager.createUnmanaged('Load')
     args = {
         'FloatInput': [2.3, 4.5],
         'IntInput': [1, 2, 3],
         'StringInput': ['test1', 'test2']
     }
     child_alg = parent_alg.createChildAlgorithm("_ParamTester", **args)
     self.assertIsNotNone(child_alg)
Ejemplo n.º 39
0
def save_reduction(workspace_names, formats, x_units='DeltaE'):
    """
    Saves the workspaces to the default save directory.

    @param workspace_names List of workspace names to save
    @param formats List of formats to save in
    @param x_units X units
    """
    from mantid.simpleapi import (SaveSPE, SaveNexusProcessed, SaveNXSPE,
                                  SaveAscii, Rebin, DeleteWorkspace,
                                  ConvertSpectrumAxis, SaveDaveGrp)

    for workspace_name in workspace_names:
        if 'spe' in formats:
            SaveSPE(InputWorkspace=workspace_name,
                    Filename=workspace_name + '.spe')

        if 'nxs' in formats:
            SaveNexusProcessed(InputWorkspace=workspace_name,
                               Filename=workspace_name + '.nxs')

        if 'nxspe' in formats:
            SaveNXSPE(InputWorkspace=workspace_name,
                      Filename=workspace_name + '.nxspe')

        if 'ascii' in formats:

            # Changed to version 2 to enable re-loading of files into mantid
            saveAsciiAlg = AlgorithmManager.createUnmanaged('SaveAscii', 2)
            saveAsciiAlg.initialize()
            saveAsciiAlg.setProperty('InputWorkspace', workspace_name)
            saveAsciiAlg.setProperty('Filename', workspace_name + '.dat')
            saveAsciiAlg.execute()

        if 'aclimax' in formats:
            if x_units == 'DeltaE_inWavenumber':
                bins = '24, -0.005, 4000'  #cm-1
            else:
                bins = '3, -0.005, 500'  #meV

            Rebin(InputWorkspace=workspace_name,
                  OutputWorkspace=workspace_name + '_aclimax_save_temp',
                  Params=bins)
            SaveAscii(InputWorkspace=workspace_name + '_aclimax_save_temp',
                      Filename=workspace_name + '_aclimax.dat',
                      Separator='Tab')
            DeleteWorkspace(Workspace=workspace_name + '_aclimax_save_temp')

        if 'davegrp' in formats:
            ConvertSpectrumAxis(InputWorkspace=workspace_name,
                                OutputWorkspace=workspace_name +
                                '_davegrp_save_temp',
                                Target='ElasticQ',
                                EMode='Indirect')
            SaveDaveGrp(InputWorkspace=workspace_name + '_davegrp_save_temp',
                        Filename=workspace_name + '.grp')
            DeleteWorkspace(Workspace=workspace_name + '_davegrp_save_temp')
Ejemplo n.º 40
0
def save_reduction(worksspace_names, formats, x_units='DeltaE'):
    """
    Saves the workspaces to the default save directory.

    @param worksspace_names List of workspace names to save
    @param formats List of formats to save in
    @param Output X units
    """
    from mantid.simpleapi import (SaveSPE, SaveNexusProcessed, SaveNXSPE,
                                  SaveAscii, Rebin, DeleteWorkspace,
                                  ConvertSpectrumAxis, SaveDaveGrp)

    for workspace_name in worksspace_names:
        if 'spe' in formats:
            SaveSPE(InputWorkspace=workspace_name,
                    Filename=workspace_name + '.spe')

        if 'nxs' in formats:
            SaveNexusProcessed(InputWorkspace=workspace_name,
                               Filename=workspace_name + '.nxs')

        if 'nxspe' in formats:
            SaveNXSPE(InputWorkspace=workspace_name,
                      Filename=workspace_name + '.nxspe')

        if 'ascii' in formats:
            # Version 1 of SaveAscii produces output that works better with excel/origin
            # For some reason this has to be done with an algorithm object, using the function
            # wrapper with Version did not change the version that was run
            saveAsciiAlg = AlgorithmManager.createUnmanaged('SaveAscii', 1)
            saveAsciiAlg.initialize()
            saveAsciiAlg.setProperty('InputWorkspace', workspace_name)
            saveAsciiAlg.setProperty('Filename', workspace_name + '.dat')
            saveAsciiAlg.execute()

        if 'aclimax' in formats:
            if x_units == 'DeltaE_inWavenumber':
                bins = '24, -0.005, 4000' #cm-1
            else:
                bins = '3, -0.005, 500' #meV

            Rebin(InputWorkspace=workspace_name,
                  OutputWorkspace=workspace_name + '_aclimax_save_temp',
                  Params=bins)
            SaveAscii(InputWorkspace=workspace_name + '_aclimax_save_temp',
                      Filename=workspace_name + '_aclimax.dat',
                      Separator='Tab')
            DeleteWorkspace(Workspace=workspace_name + '_aclimax_save_temp')

        if 'davegrp' in formats:
            ConvertSpectrumAxis(InputWorkspace=workspace_name,
                                OutputWorkspace=workspace_name + '_davegrp_save_temp',
                                Target='ElasticQ',
                                EMode='Indirect')
            SaveDaveGrp(InputWorkspace=workspace_name + '_davegrp_save_temp',
                        Filename=workspace_name + '.grp')
            DeleteWorkspace(Workspace=workspace_name + '_davegrp_save_temp')
Ejemplo n.º 41
0
    def test_createChildAlgorithm_respects_keyword_arguments(self):
        parent_alg = AlgorithmManager.createUnmanaged('Load')
        try:
            child_alg = parent_alg.createChildAlgorithm(name='Rebin',version=1,startProgress=0.5,endProgress=0.9,enableLogging=True)
        except Exception as exc:
            self.fail("Expected createChildAlgorithm not to throw but it did: %s" % (str(exc)))

        # Unknown keyword
        self.assertRaises(Exception, parent_alg.createChildAlgorithm, name='Rebin',version=1,startProgress=0.5,endProgress=0.9,enableLogging=True, unknownKW=1)
Ejemplo n.º 42
0
 def test_set_property_succeeds_with_python_float_lists(self):
     rebin = AlgorithmManager.createUnmanaged("Rebin")
     rebin.initialize()
     input = [0.5,1.0,5.5]
     rebin.setProperty('Params',input)
     params = rebin.getProperty('Params').value
     self.assertEquals(len(params), 3)
     for i in range(3):
         self.assertEquals(params[i], input[i])
Ejemplo n.º 43
0
 def test_set_property_succeeds_with_python_float_lists(self):
     rebin = AlgorithmManager.createUnmanaged("Rebin")
     rebin.initialize()
     input = [0.5, 1.0, 5.5]
     rebin.setProperty('Params', input)
     params = rebin.getProperty('Params').value
     self.assertEquals(len(params), 3)
     for i in range(3):
         self.assertEquals(params[i], input[i])
Ejemplo n.º 44
0
def guarantee_unique_lines(script):
    alg_name = "OrderWorkspaceHistory"
    alg = AlgorithmManager.createUnmanaged(alg_name, 1)
    alg.setChild(True)
    alg.setLogging(False)
    alg.initialize()
    alg.setPropertyValue("InputString", script)
    alg.execute()
    script = alg.getPropertyValue("OutputString")
    return script
Ejemplo n.º 45
0
def create_unmanaged_algorithm(name, version=None, **kwargs):
    """
    Creates an unmanaged child algorithm and initializes it.

    :param name: the name of the algorithm
    :param version: optional int. The version of the algorithm to use.
    :param kwargs: settings for the algorithm
    :return: an initialized algorithm instance.
    """
    if version is not None:
        alg = AlgorithmManager.createUnmanaged(name, version)
    else:
        alg = AlgorithmManager.createUnmanaged(name)
    alg.initialize()
    alg.setChild(True)
    alg.setRethrows(True)
    for key, value in kwargs.items():
        alg.setProperty(key, value)
    return alg
Ejemplo n.º 46
0
    def test_alg_with_default_attrs(self):
        testhelpers.assertRaisesNothing(self,AlgorithmManager.createUnmanaged, "TestPyAlgDefaultAttrs")
        alg = AlgorithmManager.createUnmanaged("TestPyAlgDefaultAttrs")
        testhelpers.assertRaisesNothing(self,alg.initialize)

        self.assertEqual(alg.name(), "TestPyAlgDefaultAttrs")
        self.assertEqual(alg.version(), 1)
        self.assertEqual(alg.category(), "PythonAlgorithms")
        self.assertEqual(alg.isRunning(), False)
        testhelpers.assertRaisesNothing(self, alg.cancel)
Ejemplo n.º 47
0
def makeWorkspace(xArray, yArray):
    """Create a workspace that doesn't appear in the ADS"""
    from mantid.api import AlgorithmManager
    alg = AlgorithmManager.createUnmanaged('CreateWorkspace')
    alg.initialize()
    alg.setChild(True)
    alg.setProperty('DataX', xArray)
    alg.setProperty('DataY', yArray)
    alg.setProperty('OutputWorkspace', 'dummy')
    alg.execute()
    return alg.getProperty('OutputWorkspace').value
Ejemplo n.º 48
0
def get_from_raw_header(file_name, index):
    alg_info = AlgorithmManager.createUnmanaged("RawFileInfo")
    alg_info.initialize()
    alg_info.setChild(True)
    alg_info.setProperty("Filename", file_name)
    alg_info.setProperty("GetRunParameters", True)
    alg_info.execute()

    header = alg_info.getProperty("RunHeader").value
    element = header.split()[index]
    return element
Ejemplo n.º 49
0
 def _calcPeaksList(self, i):
     """Calculate a peak list for spectrum i"""
     if self._dirty_peaks:
         from mantid.api import AlgorithmManager
         alg = AlgorithmManager.createUnmanaged('EvaluateFunction')
         alg.initialize()
         alg.setChild(True)
         alg.setProperty('Function', self.makePeaksFunction(i))
         del alg['InputWorkspace']
         alg.setProperty('OutputWorkspace', 'dummy')
         alg.execute()
         self._peakList = alg.getProperty('OutputWorkspace').value
Ejemplo n.º 50
0
 def _do_vector_double_numpy_test(self, int_type=False):
     create_ws = AlgorithmManager.createUnmanaged('CreateWorkspace')
     create_ws.initialize()
     if int_type:
         datax = np.arange(10)
     else:
         datax = np.arange(10.0)
     create_ws.setProperty('DataX', datax)
     x_values = create_ws.getProperty('DataX').value
     self.assertEquals(len(x_values), 10)
     for i in range(10):
         self.assertEquals(x_values[i], i)
Ejemplo n.º 51
0
 def _monte_carlo_single(self, **kwargs):
     from mantid.api import AlgorithmManager
     fun = self.model.makeSpectrumFunction()
     alg = AlgorithmManager.createUnmanaged('EstimateFitParameters')
     alg.initialize()
     alg.setProperty('Function', fun)
     alg.setProperty('InputWorkspace', self._input_workspace)
     for param in kwargs:
         alg.setProperty(param, kwargs[param])
     alg.execute()
     function = alg.getProperty('Function').value
     self.model.update(function)
     self._function = function
Ejemplo n.º 52
0
    def _run_mask(self, state, workspace, component):
        mask_alg = AlgorithmManager.createUnmanaged("SANSMaskWorkspace")
        mask_alg.setChild(True)
        mask_alg.initialize()

        state_dict = state.property_manager
        mask_alg.setProperty("SANSState", state_dict)
        mask_alg.setProperty("Workspace", workspace)
        mask_alg.setProperty("Component", component)

        mask_alg.execute()
        self.assertTrue(mask_alg.isExecuted())
        return mask_alg.getProperty("Workspace").value
Ejemplo n.º 53
0
def _mask_detectors(workspace, masked_indices):
    """
    Masks the detectors at the specified indices in the specified
    workspace.

    :param workspace:       The workspace whose detectors to mask.
    :param masked_indices:  The indices of the detectors to mask.
    """
    mask_detectors = AlgorithmManager.createUnmanaged("MaskDetectors")
    mask_detectors.setChild(True)
    mask_detectors.initialize()
    mask_detectors.setProperty("Workspace", workspace)
    mask_detectors.setProperty("WorkspaceIndexList", masked_indices)
    mask_detectors.execute()
Ejemplo n.º 54
0
    def create_mantid_algorithm_by_name(self, algorithm_name):
        """
        Create and initializes a Mantid algorithm using the latest version.

        Args:
          algorithm_name (str): The name of the algorithm to use for the title.

        Returns:
          algorithm: An instance of a Mantid algorithm.
        """
        from mantid.api import AlgorithmManager
        alg = AlgorithmManager.createUnmanaged(algorithm_name)
        alg.initialize()
        return alg
Ejemplo n.º 55
0
def create_unmanaged_algorithm(name, **kwargs):
    """
    Creates an unmanaged child algorithm and initializes it.

    :param name: the name of the algorithm
    :param kwargs: settings for the algorithm
    :return: an initialized algorithm instance.
    """
    alg = AlgorithmManager.createUnmanaged(name)
    alg.initialize()
    alg.setChild(True)
    for key, value in kwargs.items():
        alg.setProperty(key, value)
    return alg
Ejemplo n.º 56
0
def compare_workspaces(workspace1, workspace2):
    try:
        alg = AlgorithmManager.createUnmanaged("CompareWorkspaces")
        alg.initialize()
        alg.setChild(True)
        alg.setRethrows(True)
        alg.setProperty("Workspace1", workspace1)
        alg.setProperty("Workspace2", workspace2)
        alg.setProperty("Tolerance", 1e-6)
        alg.setProperty("ToleranceRelErr", True)
        alg.setProperty("CheckAllData", True)
        alg.execute()
    except RuntimeError:
        raise RuntimeError("Comparison was wrong.")