Beispiel #1
0
    def test_python_alg_can_use_other_python_alg_through_simple_api(self):
        class SimpleAPIPythonAlgorithm1(PythonAlgorithm):
            def PyInit(self):
                pass
            def PyExec(self):
                from mantid.simpleapi import SimpleAPIPythonAlgorithm2
                SimpleAPIPythonAlgorithm2()
        class SimpleAPIPythonAlgorithm2(PythonAlgorithm):
            def PyInit(self):
                pass
            def PyExec(self):
                pass

        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm1)
        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm2)
        # ---------------------------------------------------------
        alg1 = SimpleAPIPythonAlgorithm1()
        alg1.initialize()
        # Puts function in simpleapi globals
        simpleapi_alg1_func = simpleapi._create_algorithm_function("SimpleAPIPythonAlgorithm1", 1, alg1)
        alg2 = SimpleAPIPythonAlgorithm1()
        alg2.initialize()
        # Puts function in simpleapi globals
        simpleapi._create_algorithm_function("SimpleAPIPythonAlgorithm2", 1, alg2)
        try:
            simpleapi_alg1_func()
        except RuntimeError as exc:
            self.fail("Running algorithm 2 from 1 failed: " + str(exc))
Beispiel #2
0
    def test_python_alg_can_use_other_python_alg_through_simple_api(self):
        class SimpleAPIPythonAlgorithm1(PythonAlgorithm):
            def PyInit(self):
                pass

            def PyExec(self):
                from mantid.simpleapi import SimpleAPIPythonAlgorithm2
                SimpleAPIPythonAlgorithm2()

        class SimpleAPIPythonAlgorithm2(PythonAlgorithm):
            def PyInit(self):
                pass

            def PyExec(self):
                pass

        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm1)
        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm2)
        # ---------------------------------------------------------
        alg1 = SimpleAPIPythonAlgorithm1()
        alg1.initialize()
        # Puts function in simpleapi globals
        simpleapi_alg1_func = simpleapi._create_algorithm_function(
            "SimpleAPIPythonAlgorithm1", 1, alg1)
        alg2 = SimpleAPIPythonAlgorithm1()
        alg2.initialize()
        # Puts function in simpleapi globals
        simpleapi._create_algorithm_function("SimpleAPIPythonAlgorithm2", 1,
                                             alg2)
        try:
            simpleapi_alg1_func()
        except RuntimeError as exc:
            self.fail("Running algorithm 2 from 1 failed: " + str(exc))
Beispiel #3
0
    def test_optional_workspaces_are_ignored_if_not_present_in_output_even_if_given_as_input(
            self):
        # Test algorithm
        from mantid.api import AlgorithmManager, PropertyMode, PythonAlgorithm, MatrixWorkspaceProperty, WorkspaceFactory
        from mantid.kernel import Direction

        class OptionalWorkspace(PythonAlgorithm):
            def PyInit(self):
                self.declareProperty(
                    MatrixWorkspaceProperty("RequiredWorkspace", "",
                                            Direction.Output))
                self.declareProperty(
                    MatrixWorkspaceProperty("OptionalWorkspace", "",
                                            Direction.Output,
                                            PropertyMode.Optional))

            def PyExec(self):
                ws = WorkspaceFactory.create("Workspace2D",
                                             NVectors=1,
                                             YLength=1,
                                             XLength=1)
                ws.dataY(0)[0] = 5
                self.setProperty("RequiredWorkspace", ws)
                self.getLogger().notice("done!")

        AlgorithmFactory.subscribe(OptionalWorkspace)

        # temporarily attach it to simpleapi module
        name = "OptionalWorkspace"
        algm_object = AlgorithmManager.createUnmanaged(name, 1)
        algm_object.initialize()
        simpleapi._create_algorithm_function(name, 1,
                                             algm_object)  # Create the wrapper

        # Call with no optional output specified
        result = simpleapi.OptionalWorkspace(RequiredWorkspace="required")
        self.assertTrue(isinstance(result, MatrixWorkspace))
        self.assertAlmostEqual(5, result.readY(0)[0], places=12)
        mtd.remove("required")

        # Call with both outputs specified
        result = simpleapi.OptionalWorkspace(RequiredWorkspace="required",
                                             OptionalWorkspace="optional")
        self.assertTrue(isinstance(result, MatrixWorkspace))
        self.assertAlmostEqual(5, result.readY(0)[0], places=12)
        mtd.remove("required")

        # Tidy up simple api function
        del simpleapi.OptionalWorkspace
 def test_slice(self, alg_mock):
     # set up slice algorithm
     AlgorithmFactory.subscribe(Slice)
     alg_mock.Slice = wrap_algorithm(
         _create_algorithm_function('Slice', 1, Slice()))
     plot = compute_slice('test_ws', self.q_axis, self.e_axis, False)
     self.assertEqual(plot.get_signal().shape, (30, 25))
Beispiel #5
0
    def test_optional_workspaces_are_ignored_if_not_present_in_output_even_if_given_as_input(self):
        # Test algorithm
        from mantid.api import (
            AlgorithmManager,
            PropertyMode,
            PythonAlgorithm,
            MatrixWorkspaceProperty,
            WorkspaceFactory,
        )
        from mantid.kernel import Direction

        class OptionalWorkspace(PythonAlgorithm):
            def PyInit(self):
                self.declareProperty(MatrixWorkspaceProperty("RequiredWorkspace", "", Direction.Output))
                self.declareProperty(
                    MatrixWorkspaceProperty("OptionalWorkspace", "", Direction.Output, PropertyMode.Optional)
                )

            def PyExec(self):
                ws = WorkspaceFactory.create("Workspace2D", NVectors=1, YLength=1, XLength=1)
                ws.dataY(0)[0] = 5
                self.setProperty("RequiredWorkspace", ws)
                self.getLogger().notice("done!")

        AlgorithmFactory.subscribe(OptionalWorkspace)

        # temporarily attach it to simpleapi module
        name = "OptionalWorkspace"
        algm_object = AlgorithmManager.createUnmanaged(name, 1)
        algm_object.initialize()
        simpleapi._create_algorithm_function(name, 1, algm_object)  # Create the wrapper

        # Call with no optional output specified
        result = simpleapi.OptionalWorkspace(RequiredWorkspace="required")
        self.assertTrue(isinstance(result, MatrixWorkspace))
        self.assertAlmostEqual(5, result.readY(0)[0], places=12)
        mtd.remove("required")

        # Call with both outputs specified
        result = simpleapi.OptionalWorkspace(RequiredWorkspace="required", OptionalWorkspace="optional")
        self.assertTrue(isinstance(result, MatrixWorkspace))
        self.assertAlmostEqual(5, result.readY(0)[0], places=12)
        mtd.remove("required")

        # Tidy up simple api function
        del simpleapi.OptionalWorkspace
Beispiel #6
0
 def test_validate_inputs_with_errors_stops_algorithm(self):
     class ValidateInputsTest(PythonAlgorithm):
         def PyInit(self):
             self.declareProperty("Prop1", 1.0)
             self.declareProperty("Prop2", 2.0)
         def validateInputs(self):
             return {"Prop1":"Value is less than Prop2"}
         def PyExec(self):
             pass
     AlgorithmFactory.subscribe(ValidateInputsTest)
     # ---------------------------------------------------------
     alg_obj = ValidateInputsTest()
     alg_obj.initialize()
     
     simpleapi_func = simpleapi._create_algorithm_function("ValidateInputsTest", 1, alg_obj)
     # call
     self.assertRaises(RuntimeError, simpleapi_func, Prop1=2.5, Prop2=3.5)
    def test_validate_inputs_with_errors_stops_algorithm(self):
        class ValidateInputsTest(PythonAlgorithm):
            def PyInit(self):
                self.declareProperty("Prop1", 1.0)
                self.declareProperty("Prop2", 2.0)

            def validateInputs(self):
                return {"Prop1":"Value is less than Prop2"}

            def PyExec(self):
                pass
        AlgorithmFactory.subscribe(ValidateInputsTest)
        # ---------------------------------------------------------
        alg_obj = ValidateInputsTest()
        alg_obj.initialize()

        simpleapi_func = simpleapi._create_algorithm_function("ValidateInputsTest", 1, alg_obj)
        # call
        self.assertRaises(RuntimeError, simpleapi_func, Prop1=2.5, Prop2=3.5)
Beispiel #8
0
"""
Sets up mslice specific algorithms. This code executes when the module is imported (and should be imported first) as
it can affect other imports.
"""

from mantid.api import AlgorithmFactory
import mantid.simpleapi as s_api
from mslice.models.cut.cut_algorithm import Cut
from mslice.models.projection.powder.make_projection import MakeProjection
from mslice.models.slice.slice_algorithm import Slice

AlgorithmFactory.subscribe(MakeProjection)
AlgorithmFactory.subscribe(Slice)
AlgorithmFactory.subscribe(Cut)
s_api._create_algorithm_function('MakeProjection', 1, MakeProjection())
s_api._create_algorithm_function('Slice', 1, Slice())
s_api._create_algorithm_function('Cut', 1, Cut())
 def test_slice(self, alg_mock):
     # set up slice algorithm
     AlgorithmFactory.subscribe(Slice)
     alg_mock.Slice = wrap_algorithm(_create_algorithm_function('Slice', 1, Slice()))
     plot = compute_slice('test_ws', self.q_axis, self.e_axis, False)
     self.assertEqual(plot.get_signal().shape, (30, 25))
Beispiel #10
0
def fit_tof_iteration(sample_data, container_data, runs, flags):
    """
    Performs a single iterations of the time of flight corrections and fitting
    workflow.

    :param sample_data: Loaded sample data workspaces
    :param container_data: Loaded container data workspaces
    :param runs: A string specifying the runs to process
    :param flags: A dictionary of flags to control the processing
    :return: Tuple of (workspace group name, pre correction fit parameters,
             final fit parameters, chi^2 values)
    """
    # Transform inputs into something the algorithm can understand
    if isinstance(flags['masses'][0], list):
        mass_values = _create_profile_strs_and_mass_list(copy.deepcopy(flags['masses'][0]))[0]
        profiles_strs = []
        for mass_spec in flags['masses']:
            profiles_strs.append(_create_profile_strs_and_mass_list(mass_spec)[1])
    else:
        mass_values, profiles_strs = _create_profile_strs_and_mass_list(flags['masses'])
    background_str = _create_background_str(flags.get('background', None))
    intensity_constraints = _create_intensity_constraint_str(flags['intensity_constraints'])

    # The simpleapi function won't have been created so do it by hand
    VesuvioTOFFit = _create_algorithm_function("VesuvioTOFFit", 1,
                                               AlgorithmManager.createUnmanaged("VesuvioTOFFit"))
    VesuvioCorrections = _create_algorithm_function("VesuvioCorrections", 1,
                                                    AlgorithmManager.createUnmanaged("VesuvioCorrections"))

    num_spec = sample_data.getNumberHistograms()
    pre_correct_pars_workspace = None
    pars_workspace = None
    max_fit_iterations = flags.get('max_fit_iterations', 5000)

    output_groups = []
    chi2_values = []
    for index in range(num_spec):
        if isinstance(profiles_strs, list):
            profiles = profiles_strs[index]
        else:
            profiles = profiles_strs

        suffix = _create_fit_workspace_suffix(index,
                                              sample_data,
                                              flags['fit_mode'],
                                              flags['spectra'],
                                              flags.get('iteration', None))

        # Corrections
        corrections_args = dict()

        # Need to do a fit first to obtain the parameter table
        pre_correction_pars_name = runs + "_params_pre_correction" + suffix
        corrections_fit_name = "__vesuvio_corrections_fit"
        VesuvioTOFFit(InputWorkspace=sample_data,
                      WorkspaceIndex=index,
                      Masses=mass_values,
                      MassProfiles=profiles,
                      Background=background_str,
                      IntensityConstraints=intensity_constraints,
                      OutputWorkspace=corrections_fit_name,
                      FitParameters=pre_correction_pars_name,
                      MaxIterations=max_fit_iterations,
                      Minimizer=flags['fit_minimizer'])
        DeleteWorkspace(corrections_fit_name)
        corrections_args['FitParameters'] = pre_correction_pars_name

        # Add the mutiple scattering arguments
        corrections_args.update(flags['ms_flags'])

        corrected_data_name = runs + "_tof_corrected" + suffix
        linear_correction_fit_params_name = runs + "_correction_fit_scale" + suffix

        if flags.get('output_verbose_corrections', False):
            corrections_args["CorrectionWorkspaces"] = runs + "_correction" + suffix
            corrections_args["CorrectedWorkspaces"] = runs + "_corrected" + suffix

        if container_data is not None:
            corrections_args["ContainerWorkspace"] = container_data

        VesuvioCorrections(InputWorkspace=sample_data,
                           OutputWorkspace=corrected_data_name,
                           LinearFitResult=linear_correction_fit_params_name,
                           WorkspaceIndex=index,
                           GammaBackground=flags.get('gamma_correct', False),
                           Masses=mass_values,
                           MassProfiles=profiles,
                           IntensityConstraints=intensity_constraints,
                           MultipleScattering=True,
                           GammaBackgroundScale=flags.get('fixed_gamma_scaling', 0.0),
                           ContainerScale=flags.get('fixed_container_scaling', 0.0),
                           **corrections_args)

        # Final fit
        fit_ws_name = runs + "_data" + suffix
        pars_name = runs + "_params" + suffix
        fit_result = VesuvioTOFFit(InputWorkspace=corrected_data_name,
                                   WorkspaceIndex=0, # Corrected data always has a single histogram
                                   Masses=mass_values,
                                   MassProfiles=profiles,
                                   Background=background_str,
                                   IntensityConstraints=intensity_constraints,
                                   OutputWorkspace=fit_ws_name,
                                   FitParameters=pars_name,
                                   MaxIterations=max_fit_iterations,
                                   Minimizer=flags['fit_minimizer'])
        chi2_values.append(fit_result[-1])
        DeleteWorkspace(corrected_data_name)

        # Process parameter tables
        if pre_correct_pars_workspace is None:
            pre_correct_pars_workspace = _create_param_workspace(num_spec, mtd[pre_correction_pars_name])

        if pars_workspace is None:
            pars_workspace = _create_param_workspace(num_spec, mtd[pars_name])

        _update_fit_params(pre_correct_pars_workspace, index, mtd[pre_correction_pars_name], suffix[1:])
        _update_fit_params(pars_workspace, index, mtd[pars_name], suffix[1:])

        DeleteWorkspace(pre_correction_pars_name)
        DeleteWorkspace(pars_name)

        # Process spectrum group
        # Note the ordering of operations here gives the order in the WorkspaceGroup
        group_name = runs + suffix
        output_workspaces = [fit_ws_name, linear_correction_fit_params_name]
        if flags.get('output_verbose_corrections', False):
            output_workspaces += mtd[corrections_args["CorrectionWorkspaces"]].getNames()
            output_workspaces += mtd[corrections_args["CorrectedWorkspaces"]].getNames()
            UnGroupWorkspace(corrections_args["CorrectionWorkspaces"])
            UnGroupWorkspace(corrections_args["CorrectedWorkspaces"])

        output_groups.append(GroupWorkspaces(InputWorkspaces=output_workspaces, OutputWorkspace=group_name))

        # Output the parameter workspaces
        AnalysisDataService.Instance().addOrReplace(runs + "_params_pre_correction" + suffix, pre_correct_pars_workspace)
        AnalysisDataService.Instance().addOrReplace(runs + "_params" + suffix, pars_workspace)

    if len(output_groups) > 1:
        result_ws = output_groups
    else:
        result_ws = output_groups[0]

    return (result_ws, pre_correct_pars_workspace, pars_workspace, chi2_values)