Exemplo n.º 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))
def get_gui_algorithm_name(facility):
    if facility is SANSFacility.ISIS:
        algorithm_name = "SANSGuiDataProcessorAlgorithm"
        AlgorithmFactory.subscribe(SANSGuiDataProcessorAlgorithm)
    else:
        raise RuntimeError("The facility is currently not supported")
    return algorithm_name
Exemplo n.º 3
0
    def test_can_enable_and_disable_notifications(self):
        try:
            AlgorithmFactory.enableNotifications()
        except Exception:
            self.assertTrue(False, "Algorithm factory class is expected to have a method 'enableNotifications'")

        try:
            AlgorithmFactory.disableNotifications()
        except Exception:
            self.assertTrue(False, "Algorithm factory class is expected to have a method 'disableNotifications'")
Exemplo n.º 4
0
    def test_that_selector_is_refreshed_on_alg_load(self):
        widget = AlgorithmSelectorWidgetMock()
        widget.refresh = mock.MagicMock()
        widget.observeUpdate(True)
        AlgorithmFactory.subscribe(ToyAlgorithm)

        self.assertTrue(widget.refresh.call_count == 1,
                        "We expect the widget to be refreshed when the Algorithm Factory "
                        "subscribes to a new algorithm. refresh was called "
                        "{} times after subscription.".format(widget.refresh.call_count))
Exemplo n.º 5
0
    def test_can_toggle_algorithm_factory_notifications(self):
        widget = AlgorithmSelectorWidgetMock()
        widget.refresh = mock.MagicMock()
        widget.observeUpdate(True)
        widget.observeUpdate(False)

        AlgorithmFactory.subscribe(ToyAlgorithm)

        self.assertTrue(widget.refresh.call_count == 0,
                        "We expect the widget to be refreshed when the Algorithm Factory "
                        "subscribes to a new algorithm. refresh was called "
                        "{} times after subscription.".format(widget.refresh.call_count))
    def test_class_can_override_standard_algorithm_methods(self):
        class TestDataProcessor(DataProcessorAlgorithm):
            def version(self):
                return 2
            def PyInit(self):
                pass
            def PyExec(self):
                pass
        # end v2 alg

        AlgorithmFactory.subscribe(TestDataProcessor)
        assertRaisesNothing(self, AlgorithmManager.createUnmanaged, "TestDataProcessor", 2)
 def setUp(self):
     if self.__class__._registered is None:
         self.__class__._registered = True
         AlgorithmFactory.subscribe(TestPyAlgDefaultAttrs)
         AlgorithmFactory.subscribe(TestPyAlgOverriddenAttrs)
         AlgorithmFactory.subscribe(TestPyAlgIsRunningReturnsNonBool)
         AlgorithmFactory.subscribe(CancellableAlg)
Exemplo n.º 8
0
    def test_explicit_store_in_ADS(self):
        class SimpleAPIPythonAlgorithm5(PythonAlgorithm):
            def PyInit(self):
                pass

            def PyExec(self):
                from mantid.simpleapi import CreateSampleWorkspace
                workspaceInADS = CreateSampleWorkspace(StoreInADS=True)
                assert(workspaceInADS)
        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm5)

        alg = SimpleAPIPythonAlgorithm5()
        alg.initialize()
        alg.execute()
        self.assertTrue('workspaceInADS' in mtd)
Exemplo n.º 9
0
def genNewLinks(links, algNames, pageName):
    
    repLinks = []
    
    for link in links:

        link = link.replace('`', '')
        link = link.replace('<', '')
        link = link.replace('>', '')
        link = link.replace('__', '')
        link = link.split()

        #Check length of link
        if len(link) > 2:
            print 'Unlikely to be an algorithm link with multiple words in it'
            repLinks.append(None)
            links_todo[pageName].append(link)      
        else:            
            name = link[0]
            if "-v" in name:
                name = name[:-3]
            #Check if the link is a concept
            print "Checking for",name
            if (AlgorithmFactory.exists(name)):
                newLink = ':ref:`algm-'+ name +'`'
                repLinks.append(newLink)
            else:
                #These are links that aren't algorithms but are single words links, likely to be links to concepts or similar
                print 'Not found in algorithm list'
                repLinks.append(None)
                links_todo[pageName].append(link)
    
    return repLinks
Exemplo n.º 10
0
 def test_python_algorithms_are_loaded_recursively(self):
     """
     Test needs improving when the old API goes to just check that everything loads okay
     """
     all_algs = AlgorithmFactory.getRegisteredAlgorithms(True)
     self.assertTrue('SNSPowderReduction' in all_algs)
     self.assertTrue('Squares' in all_algs)
Exemplo n.º 11
0
 def test_get_registered_algs_returns_dictionary_of_known_algorithms(self):
     all_algs = AlgorithmFactory.getRegisteredAlgorithms(True)
     self.assertTrue( len(all_algs) > 0 )
     self.assertTrue( 'ConvertUnits' in all_algs )
     # 3 versions of LoadRaw
     self.assertEquals( len(all_algs['LoadRaw']), 3 )
     self.assertEquals( all_algs['LoadRaw'], [1,2,3] )
Exemplo n.º 12
0
    def _insert_pagetitle(self):
        """
        Outputs a reference to the top of the algorithm's rst
        of the form ".. _algm-AlgorithmName-vVersion:", so that
        the page can be referenced using
        :ref:`algm-AlgorithmName-version`. If this is the highest
        version then it outputs a reference ".. _algm-AlgorithmName: instead

        It then outputs a title for the page
        """
        from mantid.api import AlgorithmFactory

        alg_name = self.algorithm_name()
        version = self.algorithm_version()

        # page reference must come directly before the title if it wants
        # to be referenced without defining the link text. Here we put the
        # specific version one first so that it always must be referenced
        # using the full link text ":ref`LinkText <algm-AlgorithmName-vX>`:"
        self.add_rst(".. _algm-%s-v%d:\n\n" % (alg_name, version))
        if AlgorithmFactory.highestVersion(alg_name) == version:
            self.add_rst(".. _algm-%s:\n\n" % alg_name)

        # title
        title = "%s v%d" % (alg_name, version)
        self.add_rst(self.make_header(title, True))
        self.add_rst(u"\n.. index:: %s-v%d\n\n" % (alg_name, version))
Exemplo n.º 13
0
    def skip(self):
        """
        Override and return a string depending on whether the directive
        should be skipped. If empty then the directive should be processed
        otherwise the string should contain the error message
        The default is to skip (and warn) if the algorithm is not known.

        Returns:
          str: Return error mesage string if the directive should be skipped
        """
        from mantid.api import AlgorithmFactory, FunctionFactory

        name, version = self.algorithm_name(), self.algorithm_version()
        msg = ""
        if version is None: # it is a fit function
            if name in FunctionFactory.getFunctionNames():
                return ""
            else:
                msg = "No fit function '%s', skipping directive" % name
        else:
            if AlgorithmFactory.exists(name, version):
                return ""
            else:
                msg = "No algorithm '%s' version '%d', skipping directive" % (name, version)

        # warn the user
        if len(msg) > 0:
            env = self.state.document.settings.env
            env.app.verbose(msg)
        return msg
Exemplo n.º 14
0
    def test_python_alg_can_use_other_python_alg_through_simple_api(self):
        """
        Runs a test in a separate process as it requires a reload of the
        whole mantid module 
        """
        src = """
from mantid.api import PythonAlgorithm, AlgorithmFactory
import mantid.simpleapi as api
from mantid.simpleapi import *

class %(name)s(PythonAlgorithm):

    def PyInit(self):
        pass
    def PyExec(self):
        %(execline1)s
        %(execline2)s
        
AlgorithmFactory.subscribe(%(name)s)
"""
        name1 = "SimpleAPIPythonAlgorithm1"
        name2 = "SimpleAPIPythonAlgorithm2"
        src1 = src % {"name":name1,"execline1":name2+"()","execline2":"api."+name2+"()"}
        src2 = src % {"name":name2,"execline1":"pass","execline2":"pass"}
        a = TemporaryPythonAlgorithm(name1,src1)
        b = TemporaryPythonAlgorithm(name2,src2)
        import subprocess
        # Try to use algorithm 1 to run algorithm 2
        cmd = sys.executable + ' -c "from mantid.simpleapi import %(name)s;%(name)s()"' % {'name':name1}
        try:
            subprocess.check_call(cmd,shell=True)
        except subprocess.CalledProcessError, exc:
            self.fail("Error occurred running one Python algorithm from another: %s" % str(exc))
Exemplo n.º 15
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)
Exemplo n.º 16
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
Exemplo n.º 17
0
def _mockup(plugins):
    """
        Creates fake, error-raising functions for all loaded algorithms plus
        any plugins given.
        The function name for the Python algorithms are taken from the filename
        so this mechanism requires the algorithm name to match the filename.

        This mechanism solves the "chicken-and-egg" problem with Python algorithms trying
        to use other Python algorithms through the simple API functions. The issue
        occurs when a python algorithm tries to import the simple API function of another
        Python algorithm that has not been loaded yet, usually when it is further along
        in the alphabet. The first algorithm stops with an import error as that function
        is not yet known. By having a pre-loading step all of the necessary functions
        on this module can be created and after the plugins are loaded the correct
        function definitions can overwrite the "fake" ones.

        :param plugins: A list of  modules that have been loaded
    """
    #--------------------------------------------------------------------------------------------------------
    def create_fake_function(name):
        """Create fake functions for the given name
        """
        #------------------------------------------------------------------------------------------------
        def fake_function(*args, **kwargs):
            raise RuntimeError("Mantid import error. The mock simple API functions have not been replaced!" +
                               " This is an error in the core setup logic of the mantid module, please contact the development team.")
        #------------------------------------------------------------------------------------------------
        if "." in name:
            name = name.rstrip('.py')
        if specialization_exists(name):
            return
        fake_function.__name__ = name
        f = fake_function.func_code
        c = f.__new__(f.__class__, f.co_argcount, f.co_nlocals, f.co_stacksize, f.co_flags, f.co_code, f.co_consts, f.co_names,\
                      ("", ""), f.co_filename, f.co_name, f.co_firstlineno, f.co_lnotab, f.co_freevars)
        # Replace the code object of the wrapper function
        fake_function.func_code = c
        globals()[name] = fake_function
    #--------------------------------------------------------
    def create_fake_functions(alg_names):
        """Create fake functions for all of the listed names
        """
        for alg_name in alg_names:
            create_fake_function(alg_name)
    #-------------------------------------

    # Start with the loaded C++ algorithms
    from mantid.api import AlgorithmFactory
    import os
    cppalgs = AlgorithmFactory.getRegisteredAlgorithms(True)
    create_fake_functions(cppalgs.keys())

    # Now the plugins
    for plugin in plugins:
        name = os.path.basename(plugin)
        name = os.path.splitext(name)[0]
        create_fake_function(name)
Exemplo n.º 18
0
    def test_getDescriptors(self):

        descriptors = AlgorithmFactory.getDescriptors(True)
        self.assertGreater(len(descriptors), 0)
        d = descriptors[0]
        self.assertTrue(hasattr(d, 'name'))
        self.assertTrue(hasattr(d, 'alias'))
        self.assertTrue(hasattr(d, 'category'))
        self.assertTrue(hasattr(d, 'version'))
Exemplo n.º 19
0
    def test_later_store_in_ADS(self):
        from mantid.api import MatrixWorkspaceProperty
        from mantid.kernel import Direction

        class SimpleAPIPythonAlgorithm6(PythonAlgorithm):
            def PyInit(self):
                self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output))

            def PyExec(self):
                from mantid.simpleapi import CreateSampleWorkspace
                workspaceNotInADS = CreateSampleWorkspace(StoreInADS=False)
                assert(workspaceNotInADS)
                self.setProperty("OutputWorkspace", workspaceNotInADS)
        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm6)

        alg = SimpleAPIPythonAlgorithm6()
        alg.initialize()
        alg.setPropertyValue("OutputWorkspace", "out")
        alg.execute()
        self.assertTrue('out' in mtd)
        mtd.remove('out')
Exemplo n.º 20
0
 def test_loading_python_algorithm_increases_registered_algs_by_one(self):
     loaded = plugins.load(self._testdir)
     self.assertTrue(len(loaded) > 0)
     expected_name = 'TestPyAlg'
     # Has the name appear in the module dictionary
     self.assertTrue(expected_name in sys.modules)
     # Do we have the registered algorithm
     algs = AlgorithmFactory.getRegisteredAlgorithms(True)
     self.assertTrue(expected_name in algs)
     # Can it be created?
     try:
         test_alg = AlgorithmManager.createUnmanaged(expected_name)
         self.assertEquals(expected_name, test_alg.name())
         self.assertEquals(1, test_alg.version())
     except RuntimeError as exc:
         self.fail("Failed to create plugin algorithm from the manager: '%s' " %s)
Exemplo n.º 21
0
def html_collect_pages(app):
    """
    Write out unversioned algorithm pages that redirect to the highest version of the algorithm
    """
    from mantid.api import AlgorithmFactory

    template = REDIRECT_TEMPLATE
    all_algs = AlgorithmFactory.getRegisteredAlgorithms(True)

    for name, versions in all_algs.iteritems():
        redirect_pagename = "algorithms/%s" % name
        versions.sort()
        highest_version = versions[-1]
        target = "%s-v%d.html" % (name, highest_version)
        context = {"name" : name, "target" : target}
        yield (redirect_pagename, context, template)
Exemplo n.º 22
0
def _translate():
    """
        Loop through the algorithms and register a function call
        for each of them
        :returns: a list of new function calls
    """
    from mantid.api import AlgorithmFactory, AlgorithmManager

    new_functions = []  # Names of new functions added to the global namespace
    new_methods = {}  # Method names mapped to their algorithm names. Used to detect multiple copies of same method name
    # on different algorithms, which is an error

    algs = AlgorithmFactory.getRegisteredAlgorithms(True)
    algorithm_mgr = AlgorithmManager
    for name, versions in iteritems(algs):
        if specialization_exists(name):
            continue
        try:
            # Create the algorithm object
            algm_object = algorithm_mgr.createUnmanaged(name, max(versions))
            algm_object.initialize()
        except Exception as exc:
            logger.warning("Error initializing {0} on registration: '{1}'".format(name, str(exc)))
            continue

        algorithm_wrapper = _create_algorithm_function(name, max(versions), algm_object)
        method_name = algm_object.workspaceMethodName()
        if len(method_name) > 0:
            if method_name in new_methods:
                other_alg = new_methods[method_name]
                raise RuntimeError(
                    "simpleapi: Trying to attach '%s' as method to point to '%s' algorithm but "
                    "it has already been attached to point to the '%s' algorithm.\n"
                    "Does one inherit from the other? "
                    "Please check and update one of the algorithms accordingly."
                    % (method_name, algm_object.name(), other_alg)
                )
            _attach_algorithm_func_as_method(method_name, algorithm_wrapper, algm_object)
            new_methods[method_name] = algm_object.name()

        # Dialog variant
        _create_algorithm_dialog(name, max(versions), algm_object)
        new_functions.append(name)

    return new_functions
Exemplo n.º 23
0
    def remote_resources_available(self):
        """
            Returns whether or not the application is cluster-enabled.
            The Remote algorithms have to be available and the
            cluster submission property has to be ON.
        """
        # Check whether Mantid is available
        try:
            from mantid.kernel import ConfigService
            from mantid.api import AlgorithmFactory

            if "SubmitRemoteJob" in AlgorithmFactory.getRegisteredAlgorithms(True):
                config = ConfigService.Instance()
                if config.hasProperty("cluster.submission") \
                and config.getString("cluster.submission").lower()=='on':
                    return True

            return False
        except:
            return False
Exemplo n.º 24
0
"""Wraps all Mantid algorithms so they use mslice's wrapped workspaces"""

from mantid.simpleapi import * # noqa: F401
from mslice.util.mantid.algorithm_wrapper import wrap_algorithm
from mantid.api import AlgorithmFactory

algorithms = AlgorithmFactory.getRegisteredAlgorithms(False)

for algorithm in algorithms.keys():
    globals()[algorithm] = wrap_algorithm(globals()[algorithm])
Exemplo n.º 25
0
                    )
            else:
                self.log().information("OMEGA_MAG read as " +
                                       str(parms_dict['phi']))
        else:
            parms_dict['phi'] = str(self.override_angle)
            self.log().warning(
                "OMEGA_MAG taken from user input, not from the file. Current value: "
                + str(parms_dict['phi']))
        return parms_dict, det_udet, det_count, det_tbc, data

    def struct_data_read(self, fin, nrows, data_type='i', byte_size=4):
        """
                helper function to read binary data_type
                requires the file handle, number of rows and data_type
                """
        self.log().debug("nrows %d" % nrows)
        tmp_lst = [
            struct.unpack(data_type, fin.read(byte_size))[0]
            for i in range(nrows)
        ]
        #for i in range(nrows):
        #    data = struct.unpack(data_type,fin.read(byte_size))[0]
        #    tmp_lst.append(data)
        #print(tmp_lst)
        return tmp_lst


# Register algorthm with Mantid.
AlgorithmFactory.subscribe(LoadEXED)
Exemplo n.º 26
0
        # check for required properties
        run = input_workspace.getRun()
        if not run.hasProperty('channel_width'):
            issues[
                'InputWorkspace'] = "Input workpsace must have sample log channel_width."
        if not run.hasProperty('full_channels'):
            issues[
                'InputWorkspace'] = "Input workpsace must have sample log full_channels."

        return issues

    def PyExec(self):
        """ Main execution body
        """
        inputws = self.getProperty("InputWorkspace").value
        outputws = self.getProperty("OutputWorkspace").value

        run = inputws.getRun()
        channel_width = float(run.getLogData('channel_width').value)
        full_channels = float(run.getLogData('full_channels').value)

        outputws = api.CropWorkspace(inputws,
                                     XMin=0.,
                                     XMax=full_channels * channel_width,
                                     OutputWorkspace=outputws)
        self.setProperty("OutputWorkspace", outputws)


# Register algorithm with Mantid.
AlgorithmFactory.subscribe(TOFTOFCropWorkspace)
Exemplo n.º 27
0
        return file_name

    def nominal_solid_angle(self, name):
        """
        Generate an isotropic solid angle
        :param name: Name of the output workspace
        :return: reference to solid angle workspace
        """
        ws = LoadNexus(Filename=self._solid_angle_ws_, OutputWorkspace=name)
        ClearMaskFlag(ws)
        MaskDetectors(ws, MaskedWorkspace=self._t_mask)
        for i in range(ws.getNumberHistograms()):
            ws.dataY(i)[0] = 0.0 if ws.getDetector(i).isMasked() else 1.0
            ws.setX(i, self._momentum_range)
        return ws

    def nominal_integrated_flux(self, name):
        """
        Generate a flux independent of momentum
        :param name: Name of the output workspace
        :return: reference to flux workspace
        """
        ws = LoadNexus(Filename=self._flux_ws_, OutputWorkspace=name)
        ClearMaskFlag(ws)
        MaskDetectors(ws, MaskedWorkspace=self._t_mask)
        return ws


# Register algorithm with Mantid.
AlgorithmFactory.subscribe(BASISDiffraction)
Exemplo n.º 28
0
    def create_indexed_peaksworkspace(self, fractional_peaks, qs, hklm):
        """Create a PeaksWorkspace that contains indexed peak data.

        :param fractional_peaks: the peaks workspace containing peaks with
            fractional HKL values.
        :param qs: The set of modulation vectors determined
        :param hklm: the new higher dimensional miller indices to add.
        :returns: a peaks workspace with the indexed peak data
        """
        # pad to 6 columns so we can assume a (hkl) (mnp) layout
        hklm = np.pad(hklm, pad_width=(0, 6 - hklm.shape[1]), mode='constant',
                      constant_values=0)
        indexed = api.CloneWorkspace(fractional_peaks, StoreInADS=False)
        # save modulation vectors. ensure qs has 3 rows
        qs = np.pad(qs, pad_width=((0, 3 - qs.shape[0]), (0, 0)), mode='constant',
                    constant_values=0)
        lattice = fractional_peaks.sample().getOrientedLattice()
        lattice.setModVec1(V3D(*qs[0]))
        lattice.setModVec2(V3D(*qs[1]))
        lattice.setModVec3(V3D(*qs[2]))
        # save indices
        for row, peak in enumerate(indexed):
            row_indices = hklm[row]
            peak.setHKL(*row_indices[:3])
            peak.setIntMNP(V3D(*row_indices[3:]))

        return indexed


AlgorithmFactory.subscribe(IndexSatellitePeaks)
Exemplo n.º 29
0
 def test_exists_returns_correct_value_for_given_args(self):
     self.assertTrue(AlgorithmFactory.exists('ConvertUnits'))  #any version
     self.assertTrue(AlgorithmFactory.exists('ConvertUnits',
                                             1))  #any version
     self.assertTrue(
         not AlgorithmFactory.exists('ConvertUnits', 100))  #any version
Exemplo n.º 30
0
from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory
from mantid.kernel import Direction

# Create an empty table workspace to be populated by a python script.
class CreateEmptyTableWorkspace(PythonAlgorithm):

    def summary(self):
        return "Creates an empty TableWorkspace which can be populated with various types of information."

    def PyInit(self):
        # Declare properties
        self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "The name of the table workspace that will be created.")
 
    def PyExec(self):
        tableWS = WorkspaceFactory.createTable()

        self.setProperty("OutputWorkspace", tableWS)
 
# Register algorithm with Mantid
AlgorithmFactory.subscribe(CreateEmptyTableWorkspace)
            ys = addeeWS.readY(0)
            foregroundYs += ys
            es = addeeWS.readE(0)
            foregroundEs += es**2
            self._cleanup.cleanup(addeeWS)
        self._cleanup.cleanup(ws)
        numpy.sqrt(foregroundEs, out=foregroundEs)
        return foregroundWS

    def _sumForegroundInQ(self, ws):
        """Sum the foreground region into a single histogram using the coherent method."""
        foreground = self._foregroundIndices(ws)
        sumIndices = [i for i in range(foreground[0], foreground[2] + 1)]
        beamPosIndex = foreground[1]
        isFlatSample = not ws.run().getProperty('beam_stats.bent_sample').value
        sumWSName = self._names.withSuffix('summed_in_Q')
        sumWS = ReflectometrySumInQ(InputWorkspace=ws,
                                    OutputWorkspace=sumWSName,
                                    InputWorkspaceIndexSet=sumIndices,
                                    BeamCentre=beamPosIndex,
                                    FlatSample=isFlatSample,
                                    EnableLogging=self._subalgLogging)
        self._cleanup.cleanup(ws)
        return sumWS

    def _sumType(self):
        return self.getProperty(Prop.SUM_TYPE).value


AlgorithmFactory.subscribe(ReflectometryILLSumForeground)
        out_ws.addColumn('str', 'statistic')

        stats = {
            'standard_deviation': dict(),
            'maximum': dict(),
            'minimum': dict(),
            'mean': dict(),
            'median': dict(),
        }

        for name in in_ws.getColumnNames():
            try:
                col_stats = _stats_to_dict(Stats.getStatistics(np.array([float(v) for v in in_ws.column(name)])))
                for statname in stats:
                    stats[statname][name] = col_stats[statname]
                out_ws.addColumn('float', name)
            except ValueError:
                logger.notice('Column \'%s\' is not numerical, skipping' % name)

        for name, stat in iteritems(stats):
            stat1 = dict(stat)
            stat1['statistic'] = name
            out_ws.addRow(stat1)

        self.setProperty('OutputWorkspace', out_ws)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(StatisticsOfTableWorkspace)
        """
        Correct for sample and container.
        """

        logger.information('Correcting sample and container')

        factor_workspaces_wavelength = {factor: self._convert_units_wavelength(workspace) for factor, workspace
                                        in factor_workspaces.items()}

        if self._rebin_container_ws:
            container_workspace = s_api.RebinToWorkspace(WorkspaceToRebin=container_workspace,
                                                         WorkspaceToMatch=factor_workspaces_wavelength['acc'],
                                                         OutputWorkspace="rebinned",
                                                         StoreInADS=False)
        return self._corrections_approximation(sample_workspace, container_workspace, factor_workspaces_wavelength)

    def _three_factor_corrections_approximation(self, sample_workspace, container_workspace, factor_workspaces):
        acc = factor_workspaces['acc']
        acsc = factor_workspaces['acsc']
        assc = factor_workspaces['assc']
        return (sample_workspace - container_workspace * (acsc / acc)) / assc

    def _two_factor_corrections_approximation(self, sample_workspace, container_workspace, factor_workspaces):
        acc = factor_workspaces['acc']
        ass = factor_workspaces['ass']
        return (sample_workspace / ass) - (container_workspace / acc)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(ApplyPaalmanPingsCorrection)
Exemplo n.º 34
0
    def getGonioAngles(self, aUB, zeroUB, omega):
        """
        Do the inverse of the rotation around the vertical axis between aUB and the zeroUB
        then use Rodrigues' rotation formula to find the single-axis rotation
        (i.e. the goniometer axis in the reference run).
        :param aUB: UB matrix at finite goniometer angles (omega and phi)
        :param zeroUB: UB matrix for omega = 0
        :param omega: omega rotation
        :return: chi: angle of gonio from +ve Z axis
        :return: phi: angle of rotation (ccw) around gonio axis to get between reference and aUB run
        :return: u: goniometer axis unit vector
        """

        # undo omega rotation between  (recall for a rotation matrix R^-1 = R.T)
        # rOmega rPhi U = U'
        rPhi = getR(omega, [0, 0, 1]).T @ aUB @ np.linalg.inv(zeroUB)
        phi, u = self.getSingleAxis(rPhi)
        # force z component to be positive (i.e. vertically upwards)
        if np.sign(u[-1]) < 0:
            u = u * np.sign(u[-1])
            phi = -phi
        # calculate chi [0,90]
        chi = np.arccos(np.dot(u, [0, 0, 1])) * (180 / np.pi)
        # force phi to be in range [0,360)
        phi = phi + np.ceil(-phi / 360) * 360
        return chi, phi, u


# register algorithm with mantid
AlgorithmFactory.subscribe(FindGoniometerFromUB)
Exemplo n.º 35
0
    def validateInputs(self):
        """
        Validates input ranges.
        """
        issues = dict()

        issues['PeakRange'] = self._validate_range('PeakRange')

        return issues

    def _validate_range(self, property_name):
        """
        Validates a range property.

        @param property_name Name of the property to validate
        @returns String detailing error, None if no error
        """

        prop_range = self.getProperty(property_name).value
        if len(prop_range) == 2:
            if prop_range[0] > prop_range[1]:
                return 'Invalid range'
        else:
            return 'Incorrect number of values (should be 2)'

        return None


# Register algorithm with Mantid
AlgorithmFactory.subscribe(ILLIN16BCalibration)
Exemplo n.º 36
0
            UnitX=ws.getAxis(0).getUnit().unitID(),
            ParentWorkspace=ws,
            EnableLogging=self._subalgLogging)
        groupedWS.setDx(0, groupedDxs)
        self._cleanup.cleanup(ws)
        return groupedWS

    def _inputWS(self):
        "Return the input workspace."
        ws = self.getProperty(Prop.INPUT_WS).value
        self._cleanup.protect(ws)
        return ws

    def _TOFChannelWidth(self, sampleLogs, instrumentName):
        """Return the time of flight bin width."""
        return sampleLogs.getProperty('PSD.time_of_flight_0').value

    def _toPointData(self, ws):
        """Convert ws from binned to point data."""
        pointWSName = self._names.withSuffix('as_points')
        pointWS = ConvertToPointData(
            InputWorkspace=ws,
            OutputWorkspace=pointWSName,
            EnableLogging=self._subalgLogging)
        pointWS.setDx(0, ws.readDx(0))
        self._cleanup.cleanup(ws)
        return pointWS


AlgorithmFactory.subscribe(ReflectometryILLConvertToQ)
Exemplo n.º 37
0
        self.setPropertySettings('ResetValue', EnabledWhenProperty('AddMinimum', PropertyCriterion.IsNotDefault))

    def getInputs(self):
        self.data = mtd[self.getPropertyValue('Workspace')]
        self._addMin = self.getProperty('AddMinimum').value
        self._resetValue = self.getProperty('ResetValue').value

    def PyExec(self):
        self.getInputs()

        xData = self.data.extractX()
        yData = self.data.extractY()

        eData = self.data.extractE()
        if self._addMin:
            intMin = np.min(yData)
            # Check if minimal Intensity is negative. If it is, add -1*intMin to all intensities
            if intMin < 0:
                Scale(InputWorkspace=self.data, OutputWorkspace=self.data, Factor=-intMin, Operation="Add")
        else:
            yDataNew = np.where(yData < 0, self._resetValue, yData)
            CreateWorkspace(OutputWorkspace=self.data,
                            DataX=xData,
                            DataY=yDataNew,
                            DataE=eData,
                            NSpec=self.data.getNumberHistograms(),
                            ParentWorkspace=self.data)


AlgorithmFactory.subscribe(ResetNegatives2D)
Exemplo n.º 38
0
            grain_end = min((i // grain_size + 1) * grain_size,
                            numberFilesToProcess)
            grain = files[grain_start:grain_end]
            partialsum_wkspname = '__' + self.__getGroupWkspName(grain)
            if finalunfocusname:
                partialsum_unfocusname = partialsum_wkspname + '_unfocused'
            else:
                partialsum_unfocusname = ''
            self.__accumulate(wkspname, partialsum_wkspname, unfocusname,
                              partialsum_unfocusname, (not hasAccumulated)
                              or i == 0)
            hasAccumulated = True
            if i == grain_end - 1:
                if self.useCaching and len(grain) > 1:
                    # save partial cache
                    self.__saveSummedGroupToCache(grain, partialsum_wkspname)
                # accumulate into final sum
                self.__accumulate(partialsum_wkspname, finalname,
                                  partialsum_unfocusname, finalunfocusname,
                                  (not hasAccumulated) or i == 0)

    def __saveSummedGroupToCache(self, group, wkspname):
        cache_file = self.__getGroupCacheName(group)
        if not os.path.exists(cache_file):
            SaveNexusProcessed(InputWorkspace=wkspname, Filename=cache_file)
        return


# Register algorithm with Mantid.
AlgorithmFactory.subscribe(AlignAndFocusPowderFromFiles)
Exemplo n.º 39
0
                name=self._instrument_name)
        else:
            raise ValueError("Unknown instrument %s" % instrument_name)

        self._atoms = self.getProperty("Atoms").value
        self._sum_contributions = self.getProperty("SumContributions").value

        # conversion from str to int
        self._num_quantum_order_events = int(
            self.getProperty("QuantumOrderEventsNumber").value)

        self._scale_by_cross_section = self.getPropertyValue(
            'ScaleByCrossSection')
        self._out_ws_name = self.getPropertyValue('OutputWorkspace')
        self._calc_partial = (len(self._atoms) > 0)

        # user defined interval is exclusive with respect to
        # AbinsModules.AbinsParameters.min_wavenumber
        # AbinsModules.AbinsParameters.max_wavenumber
        # with bin width AbinsModules.AbinsParameters.bin_width
        step = self._bin_width
        start = AbinsModules.AbinsParameters.min_wavenumber + step / 2.0
        stop = AbinsModules.AbinsParameters.max_wavenumber + step / 2.0
        self._bins = np.arange(start=start,
                               stop=stop,
                               step=step,
                               dtype=AbinsModules.AbinsConstants.FLOAT_TYPE)


AlgorithmFactory.subscribe(Abins)
Exemplo n.º 40
0
                    unfitted_transmission_workspace = CloneWorkspace(
                        unfitted_transmission_workspace, StoreInADS=False)
                if fit_performed:
                    self.setProperty(
                        "OutputWorkspaceCalculatedTransmissionCan",
                        calculated_transmission_workspace)
                self.setProperty("OutputWorkspaceUnfittedTransmissionCan",
                                 unfitted_transmission_workspace)
            elif transmission_bundle.data_type is DataType.Sample:
                if fit_performed:
                    self.setProperty("OutputWorkspaceCalculatedTransmission",
                                     calculated_transmission_workspace)
                self.setProperty("OutputWorkspaceUnfittedTransmission",
                                 unfitted_transmission_workspace)
            else:
                raise RuntimeError(
                    "SANSSingleReduction: The data type {0} should be"
                    " sample or can.".format(transmission_bundle.data_type))

    def _get_progress(self, number_of_reductions, overall_reduction_mode):
        number_from_merge = 1 if overall_reduction_mode is ReductionMode.Merged else 0
        number_of_progress_reports = number_of_reductions + number_from_merge + 1
        return Progress(self,
                        start=0.0,
                        end=1.0,
                        nreports=number_of_progress_reports)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSSingleReduction)
Exemplo n.º 41
0
        JRAND = 12345
        MRAND = 67890
        neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)]

        HEIGHT = 3.0
        alfa = self.getPropertyValue('DetAngle')
        THICK = self.getPropertyValue('Thick')
        WIDTH = self.getPropertyValue('Width')
        HEIGHT = self.getPropertyValue('Height')
        if geom == 'Flat':
            beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)]
        if geom == 'Cyl':
            beam = [float(THICK),
                    float(WIDTH),
                    float(HEIGHT), 0.0]  #beam = [WIDTH, WIDTH2, HEIGHT, 0.0]
        dens = self.getPropertyValue('Density')
        sigb = self.getPropertyValue('SigScat')
        siga = self.getPropertyValue('SigAbs')
        temp = self.getPropertyValue('Temperature')
        sam = [float(temp), float(dens), float(siga), float(sigb)]

        kr1 = 1
        verbOp = self.getProperty('Verbose').value
        plotOp = self.getPropertyValue('Plot')
        saveOp = self.getProperty('Save').value
        Main.MuscatDataStart(sname, geom, neut, beam, sam, sqw, kr1, verbOp,
                             plotOp, saveOp)


AlgorithmFactory.subscribe(MuscatData)  # Register algorithm with Mantid
Exemplo n.º 42
0
    print("%s, %i, %s, %s" % (alg, algVersion, description, notes))


rstdir = r"C:\Mantid\Code\Mantid\docs\source\algorithms"
ticketList = [9582,9586,9607,9610,9704,9804,9726]

ticketHash = {}
for ticket in ticketList:
    ticketHash[ticket] = readWebPage( r"http://trac.mantidproject.org/mantid/ticket/" + str(ticket))

usagePattern = re.compile('Usage', re.IGNORECASE)
excusesPattern = re.compile('(rarely called directly|designed to work with other algorithms|only used for testing|deprecated)',
                            re.IGNORECASE)


algs = AlgorithmFactory.getRegisteredAlgorithms(True)
for alg in algs:
    algVersion = algs[alg][0]
    fileFound = False
    filename = os.path.join(rstdir,alg + "-v" + str(algVersion) + ".rst")
    if os.path.exists(filename):
        with open (filename, "r") as algRst:
            fileFound = True
            algText = algRst.read()
            if (usagePattern.search(algText) is None) and (excusesPattern.search(algText) is None):
                #check if already in a ticket
                usageTicket = ticketExists(alg,ticketHash)
                outputError(alg, algVersion, "No usage section", usageTicket)
    if not fileFound:
        outputError(alg, algVersion, "File not found")
Exemplo n.º 43
0
    def test_getDescriptorsWithAlias(self):

        descriptors = AlgorithmFactory.getDescriptors(True, True)
        result = [d for d in descriptors if (d.name == 'Subtract')]
        self.assertEqual(1, len(result))
Exemplo n.º 44
0
            logger.debug(
                'choosing TIB just before leading edge before elastic-3')
            TIB_high_us = pre_lead_us - MinTIB_us / 2.0 * slop_frac / 2.0
            TIB_low_us = TIB_high_us - MinTIB_us / 2.0
        # elif (pre_tail_us > frame_start_us) and (t_focEle_us - pre_tail_us > MinTIB_us * (slop_frac + 1.0)):
        #   logger.debug('choosing TIB just before focus element')
        # TIB_low_us = pre_tail_us + MinTIB_us * slop_frac / 2.0
        # TIB_high_us = TIB_low_us + MinTIB_us
        elif post_lead_us > frame_end_us:
            logger.debug('choosing TIB at end of frame')
            TIB_high_us = frame_end_us - MinTIB_us * slop_frac / 2.0
            TIB_low_us = TIB_high_us - MinTIB_us
        elif post_lead_us - t_det_us > MinTIB_us * (slop_frac + 1.0):
            logger.debug(
                'choosing TIB between elastic peak and later prompt pulse leading edge'
            )
            TIB_high_us = post_lead_us - MinTIB_us * slop_frac / 2.0
            TIB_low_us = TIB_high_us - MinTIB_us
        else:
            logger.debug('I cannot find a good TIB range')
            TIB_low_us = 0.0
            TIB_high_us = 0.0

        #return the result
        self.setProperty("TibMin", TIB_low_us)
        self.setProperty("TibMax", TIB_high_us)
        return


AlgorithmFactory.subscribe(HYSPECSuggestTIB)
Exemplo n.º 45
0
        if num_hist == 0:
            raise ValueError('Workspace %s has NO histograms' % ws)
        x_in = mtd[ws].readX(0)
        ntc = len(x_in) - 1  # no. points from length of x array
        if ntc == 0:
            raise ValueError('Workspace %s has NO points' % ws)
        return num_hist, ntc

    def _CheckElimits(self, erange, ws):
        import math
        x_data = np.asarray(mtd[ws].readX(0))
        len_x = len(x_data) - 1

        if math.fabs(erange[0]) < 1e-5:
            raise ValueError('Elimits - input emin (%f) is Zero' % (erange[0]))
        if erange[0] < x_data[0]:
            raise ValueError('Elimits - input emin (%f) < data emin (%f)' %
                             (erange[0], x_data[0]))
        if math.fabs(erange[1]) < 1e-5:
            raise ValueError('Elimits - input emax (%f) is Zero' % (erange[1]))
        if erange[1] > x_data[len_x]:
            raise ValueError('Elimits - input emax (%f) > data emax (%f)' %
                             (erange[1], x_data[len_x]))
        if erange[1] < erange[0]:
            raise ValueError('Elimits - input emax (%f) < emin (%f)' %
                             (erange[1], erange[0]))


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SofQWMoments)
Exemplo n.º 46
0
            ('StandardDev', collections.OrderedDict()),
            ('Minimum', collections.OrderedDict()),
            ('Median', collections.OrderedDict()),
            ('Maximum', collections.OrderedDict()),
            ('Mean', collections.OrderedDict()),
        ])

        for index in indices_list:
            column_name = column_names[index]
            try:
                column_data = np.array([float(v) for v in in_ws.column(index)])
                col_stats = _stats_to_dict(Stats.getStatistics(column_data))
                for stat_name in stats:
                    stats[stat_name][column_name] = col_stats[stat_name]
                out_ws.addColumn('float', column_name)
            except RuntimeError:
                logger.notice('Column \'%s\' is not numerical, skipping' % column_name)
            except:
                logger.notice('Column \'%s\' is not numerical, skipping' % column_name)

        for index, stat_name in iteritems(stats):
            stat = collections.OrderedDict(stat_name)
            stat['Statistic'] = index
            out_ws.addRow(stat)

        self.setProperty('OutputWorkspace', out_ws)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(StatisticsOfTableWorkspace)
Exemplo n.º 47
0
            params = self.getProperty(common.PROP_BINNING_PARAMS_Q).value
            if len(params) == 1:
                qMin, qMax = _minMaxQ(mainWS)
                params = [qMin, params[0], qMax]
        Ei = mainWS.run().getLogData('Ei').value
        sOfQWWS = SofQWNormalisedPolygon(InputWorkspace=mainWS,
                                         OutputWorkspace=sOfQWWSName,
                                         QAxisBinning=params,
                                         EMode='Direct',
                                         EFixed=Ei,
                                         ReplaceNaNs=False,
                                         EnableLogging=self._subalgLogging)
        self._cleanup.cleanup(mainWS)
        return sOfQWWS

    def _transpose(self, mainWS):
        """Transpose the final output workspace."""
        transposing = self.getProperty(
            common.PROP_TRANSPOSE_SAMPLE_OUTPUT).value
        if transposing == common.TRANSPOSING_OFF:
            return mainWS
        transposedWSName = self._names.withSuffix('transposed')
        transposedWS = Transpose(InputWorkspace=mainWS,
                                 OutputWorkspace=transposedWSName,
                                 EnableLogging=self._subalgLogging)
        self._cleanup.cleanup(mainWS)
        return transposedWS


AlgorithmFactory.subscribe(DirectILLReduction)
Exemplo n.º 48
0
        return state

    def _calculate_residuals(self, quartile1, quartile2):
        yvalsAX = quartile1.readY(0)
        yvalsBX = quartile2.readY(0)
        qvalsAX = quartile1.readX(0)
        qvalsBX = quartile2.readX(0)
        A_vals_dict = dict(zip(qvalsAX, yvalsAX))
        B_vals_dict = dict(zip(qvalsBX, yvalsBX))

        residue = 0.0
        for key in B_vals_dict:
            if key not in A_vals_dict:
                A_vals_dict[key] = 0.0

        for key in A_vals_dict:
            if key not in B_vals_dict:
                B_vals_dict[key] = 0.0

        for key in A_vals_dict and B_vals_dict:
            residue += pow(A_vals_dict[key] - B_vals_dict[key], 2)

        return residue

    def _get_progress(self):
        return Progress(self, start=0.0, end=1.0, nreports=10)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSBeamCentreFinder)
Exemplo n.º 49
0
        return fitted_data, unfitted_data

    def _get_wide_angle_correction_workspace(self, state, calculated_transmission_workspace):
        wide_angle_correction = state.adjustment.wide_angle_correction
        sample_data = self.getProperty("SampleData").value
        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

    def validateInputs(self):
        errors = dict()
        # Check that the input can be converted into the right state object
        state_property_manager = self.getProperty("SANSState").value
        try:
            state = Serializer.from_json(state_property_manager)
            state.validate()
        except ValueError as err:
            errors.update({"SANSCreateAdjustmentWorkspaces": str(err)})
        return errors


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSCreateAdjustmentWorkspaces)
Exemplo n.º 50
0
    def _append_to(self, initial_workspace, to_append):
        append_alg = self.createChildAlgorithm("AppendSpectra",
                                               enableLogging=False)
        append_alg.setProperty("InputWorkspace1", initial_workspace)
        append_alg.setProperty("InputWorkspace2", to_append)
        append_alg.setProperty("OutputWorkspace", initial_workspace)
        append_alg.execute()
        mtd.addOrReplace(initial_workspace,
                         append_alg.getProperty("OutputWorkspace").value)

    def _copy_log(self, input_name, output_name):
        copy_log_alg = self.createChildAlgorithm("CopyLogs",
                                                 enableLogging=False)
        copy_log_alg.setProperty("InputWorkspace", input_name)
        copy_log_alg.setProperty("OutputWorkspace", output_name)
        copy_log_alg.execute()
        mtd.addOrReplace(output_name,
                         copy_log_alg.getProperty("OutputWorkspace").value)

    def _add_sample_log_multiple(self, input_name, log_names, log_values):
        sample_log_mult_alg = self.createChildAlgorithm("AddSampleLogMultiple",
                                                        enableLogging=False)
        sample_log_mult_alg.setProperty("Workspace", input_name)
        sample_log_mult_alg.setProperty("LogNames", log_names)
        sample_log_mult_alg.setProperty("LogValues", log_values)
        sample_log_mult_alg.execute()


# Register algorithm with Mantid
AlgorithmFactory.subscribe(IndirectTwoPeakFit)
Exemplo n.º 51
0
            block_FWHM_e = []
            block_amplitude_e = []
            for _ in range(nl):
                # Amplitude error,FWHM error for each peak
                # SIGIK
                line = next(line_pointer)
                amp = AMAX * math.sqrt(math.fabs(line[0]) + 1.0e-20)
                block_amplitude_e.append(amp)

                # SIGFK
                line = next(line_pointer)
                FWHM = 2.0 * HWHM * math.sqrt(math.fabs(line[0]) + 1.0e-20)
                block_FWHM_e.append(FWHM)

            # append data from block
            amp_data.append(block_amplitude)
            FWHM_data.append(block_FWHM)
            height_data.append(block_height)

            # append error values from block
            amp_error.append(block_amplitude_e)
            FWHM_error.append(block_FWHM_e)
            height_error.append(block_height_e)

        return q_data, (amp_data, FWHM_data,
                        height_data), (amp_error, FWHM_error, height_error)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(BayesQuasi)
Exemplo n.º 52
0
        #
        dict_repr = json.loads(str(self)).get(
            'properties'
        )  # representation of the algorithm's properties in a dict
        # Remove not wanted properties
        for not_wanted in ('RunNumbers', 'OutputDirectory',
                           'EnableConfigurator', 'ConfigSaveDir'):
            if not_wanted in dict_repr:
                del dict_repr[not_wanted]
        """
        hack to fix the entry for the default JSON represenation of property DetCalFilename, which is saved as a list of lists
        Example: "DetCalFilename": [ ["/SNS/SNAP/IPTS-26217/shared/E76p2_W65p3.detcal"],
                                     ["/SNS/SNAP/IPTS-26217/shared/E76p2_W65p5.detcal"]]
                 must become:
                 "DetCalFilename": "/SNS/SNAP/IPTS-26217/shared/E76p2_W65p3.detcal,/SNS/SNAP/IPTS-26217/shared/E76p2_W65p5.detcal"
        """
        if 'DetCalFilename' in dict_repr:
            dict_repr['DetCalFilename'] = ','.join(
                [entry[0] for entry in dict_repr.get('DetCalFilename')])
        #
        # Save to file in JSON format
        #
        formatted_pretty = json.dumps(dict_repr, sort_keys=True, indent=4)
        with open(filename, 'w') as f:
            f.write(formatted_pretty)
            logger.information(f'Saving configuration to {filename}')
            logger.debug(f'Configuration contents:\n{formatted_pretty}')


AlgorithmFactory.subscribe(SNAPReduce)
Exemplo n.º 53
0
#pylint: disable=invalid-name
"""
    Main window for reduction UIs
"""
import sys, os
import traceback

# Check whether Mantid is available
IS_IN_MANTIDPLOT = False
try:
    import mantidplot
    IS_IN_MANTIDPLOT = True
    from mantid.kernel import ConfigService
    from mantid.api import AlgorithmFactory
    CLUSTER_ENABLED = "SubmitRemoteJob" in AlgorithmFactory.getRegisteredAlgorithms(True)
except:
    import sip
    sip.setapi('QString',2)
    sip.setapi('QVariant',2)

from PyQt4 import QtGui, QtCore

REDUCTION_WARNING = False
WARNING_MESSAGE = ""

if IS_IN_MANTIDPLOT:
    try:
        import reduction
        if os.path.splitext(os.path.basename(reduction.__file__))[0] == "reduction":
            REDUCTION_WARNING = True
            home_dir = os.path.expanduser('~')
Exemplo n.º 54
0
            "SeedValue": self._seed
        }
        for key, value in args.items():
            calculateiqt_alg.setProperty(key, value)
        calculateiqt_alg.execute()

        iqt = calculateiqt_alg.getProperty("OutputWorkspace").value

        # Set Y axis unit and label
        iqt.setYUnit('')
        iqt.setYUnitLabel('Intensity')
        return iqt

    def _check_analysers_and_reflection(self):
        from IndirectCommon import CheckAnalysersOrEFixed

        try:
            CheckAnalysersOrEFixed(self._sample, self._resolution)
        except ValueError:
            # A genuine error the shows that the two runs are incompatible
            raise
        except BaseException:
            # Checking could not be performed due to incomplete or no
            # instrument
            logger.warning(
                'Could not check for matching analyser and reflection')


# Register algorithm with Mantid
AlgorithmFactory.subscribe(TransformToIqt)
Exemplo n.º 55
0
            if selected_detector is None:
                selected_detector = detectors[DetectorType.to_string(DetectorType.LAB)]
            pos1 = selected_detector.sample_centre_pos1
            pos2 = selected_detector.sample_centre_pos2
            coordinates = [pos1, pos2]
        return coordinates

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

        # Check that if the MoveType is either InitialMove or ElementaryDisplacement, then there are beam coordinates
        # supplied. In the case of SetToZero these coordinates are ignored if they are supplied
        coordinates = self.getProperty("BeamCoordinates").value
        selected_move_type = self._get_move_type()
        if len(coordinates) == 0 and (selected_move_type is MoveType.ElementaryDisplacement):
            errors.update({"BeamCoordinates": "Beam coordinates were not specified. An elementary displacement "
                                              "requires beam coordinates."})
        return errors


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSMove)
Exemplo n.º 56
0
            instrument = mainWS.getInstrument()
            if instrument.hasParameter('enable_elastic_peak_diagnostics'):
                enabled = instrument.getBoolParameter(
                    'enable_elastic_peak_diagnostics')[0]
                if not enabled:
                    report.notice(
                        'Elastic peak diagnostics disabled by the IPF.')
                    return False
            report.notice('Elastic peak diagnostics enabled.')
            return True
        return peakDiagnostics == common.ELASTIC_PEAK_DIAGNOSTICS_ON

    def _userMask(self, mainWS, wsNames, wsCleanup, algorithmLogging):
        """Return combined masked spectra and components."""
        userMask = self.getProperty(common.PROP_USER_MASK).value
        maskComponents = self.getProperty(
            common.PROP_USER_MASK_COMPONENTS).value
        maskWSName = wsNames.withSuffix('user_mask')
        maskWS = _createMaskWS(mainWS, maskWSName, algorithmLogging)
        MaskDetectors(Workspace=maskWS,
                      DetectorList=userMask,
                      ComponentList=maskComponents,
                      EnableLogging=algorithmLogging)
        maskWS, detectorLsit = ExtractMask(InputWorkspace=maskWS,
                                           OutputWorkspace=maskWSName,
                                           EnableLogging=algorithmLogging)
        return maskWS


AlgorithmFactory.subscribe(DirectILLDiagnostics)
Exemplo n.º 57
0
                              "C_a", "C_b", "C_c", "C_z", "polarisation", "polarisation_comment"])
        logs["values"].extend([metadata.flipper_precession_current,
                               metadata.flipper_z_compensation_current, flipper_status,
                               metadata.a_coil_current, metadata.b_coil_current,
                               metadata.c_coil_current, metadata.z_coil_current,
                               str(pol[0]), str(pol[1])])
        logs["units"].extend(["A", "A", "", "A", "A", "A", "A", "", ""])

        # slits
        logs["names"].extend(["slit_i_upper_blade_position", "slit_i_lower_blade_position",
                              "slit_i_left_blade_position", "slit_i_right_blade_position"])
        logs["values"].extend([metadata.slit_i_upper_blade_position, metadata.slit_i_lower_blade_position,
                               metadata.slit_i_left_blade_position, metadata.slit_i_right_blade_position])
        logs["units"].extend(["mm", "mm", "mm", "mm"])

        # add information whether the data are normalized (duration/monitor/no):
        api.AddSampleLog(outws, LogName='normalized', LogText=norm, LogType='String')
        api.AddSampleLogMultiple(outws, LogNames=logs["names"], LogValues=logs["values"], LogUnits=logs["units"])

        outws.setYUnit(yunit)
        outws.setYUnitLabel(ylabel)

        self.setProperty("OutputWorkspace", outws)
        self.log().debug('LoadDNSLegacy: data are loaded to the workspace ' + outws_name)

        return


# Register algorithm with Mantid
AlgorithmFactory.subscribe(LoadDNSLegacy)
Exemplo n.º 58
0
        gs2.PatternTree.SetItemPyData(
            gs2.PatternTree.AppendItem(tree_id, text='Reflection Lists'),
            {})

    def _save_gsas2_project(self, gsas2, gs2_rd, proj_filename):
        """
        Saves all the information loaded into a GSAS-II project file that can be loaded
        in the GSAS-II GUI (.gpx files).

        @param gsas2 :: the main GSAS-II object
        @param gs2_rd :: the GSAS-II "rd" object with powder data
        @param proj_filename :: name of the output project file
        """
        self.log().notice("Preparing GSAS-II project tree to save into: {0}".format(proj_filename))
        self._prepare_save_gsas2_project(gsas2, gs2_rd)

        import GSASIIIO
        self.log().debug("Saving GSAS-II project: {0}".format(gsas2))
        gsas2.GSASprojectfile = proj_filename
        gsas2.CheckNotebook()
        GSASIIIO.ProjFileSave(gsas2)

# Need GSAS-II _init_Imports()
#pylint: disable=protected-access
    def _init_histo_data_readers(self, gs2):
        gs2._init_Imports()
        readers_list = gs2.ImportPowderReaderlist
        return readers_list

AlgorithmFactory.subscribe(GSASIIRefineFitPeaks)
Exemplo n.º 59
0
        # Outputs the calculated density of states to another workspace
        dos2d = CloneWorkspace(inws)
        if iqq == 1:
            dos2d = Transpose(dos2d)
        for i in range(len(y)):
            dos2d.setY(i, y[i,:])
            dos2d.setE(i, e[i,:])
        dos2d.setYUnitLabel(ylabel)

        # Make a 1D (energy dependent) cut
        dos1d = Rebin2D(dos2d, [dq[0], dq[1]-dq[0], dq[1]], dosebin, True, True)
        if cm and input_en_in_meV:
            dos1d.getAxis(0).setUnit('DeltaE_inWavenumber')
            dos1d = ScaleX(dos1d, mev2cm)
        elif not cm and not input_en_in_meV:
            dos1d.getAxis(0).setUnit('DeltaE')
            dos1d = ScaleX(dos1d, 1/mev2cm)

        if absunits:
            print("Converting to states/energy")
            # cross-section information is given in barns, but data is in milibarns.
            sigma = atoms[0].neutron()['tot_scatt_xs'] * 1000
            mass = atoms[0].mass
            dos1d = dos1d * (mass/sigma) * 4 * np.pi

        self.setProperty("OutputWorkspace", dos1d)
        DeleteWorkspace(dos2d)
        DeleteWorkspace(dos1d)

AlgorithmFactory.subscribe(ComputeIncoherentDOS)
Exemplo n.º 60
0
                OutputWorkspace=correctionWSName,
                SparseInstrument=False,
                Interpolation='CSpline',
                EnableLogging=self._subalgLogging,
                EventsPerPoint=eventsPerPoint,
                SeedValue=common.SIMULATION_SEED)
        else:
            rows = self.getProperty(common.PROP_SPARSE_INSTRUMENT_ROWS).value
            columns = self.getProperty(
                common.PROP_SPARSE_INSTRUMENT_COLUMNS).value
            correctionWS = MonteCarloAbsorption(
                InputWorkspace=wavelengthWS,
                OutputWorkspace=correctionWSName,
                SparseInstrument=True,
                NumberOfDetectorRows=rows,
                NumberOfDetectorColumns=columns,
                Interpolation='CSpline',
                EnableLogging=self._subalgLogging,
                EventsPerPoint=eventsPerPoint,
                SeedValue=common.SIMULATION_SEED)
        self._cleanup.cleanup(wavelengthWS)
        correctionWS = ConvertUnits(InputWorkspace=correctionWS,
                                    OutputWorkspace=correctionWSName,
                                    Target='TOF',
                                    EMode='Direct',
                                    EnableLogging=self._subalgLogging)
        return correctionWS


AlgorithmFactory.subscribe(DirectILLSelfShielding)