• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python api.AlgorithmFactory类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mantid.api.AlgorithmFactory的典型用法代码示例。如果您正苦于以下问题:Python AlgorithmFactory类的具体用法?Python AlgorithmFactory怎么用?Python AlgorithmFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了AlgorithmFactory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_python_alg_can_use_other_python_alg_through_simple_api

    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))
开发者ID:rosswhitfield,项目名称:mantid,代码行数:28,代码来源:SimpleAPITest.py


示例2: get_gui_algorithm_name

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
开发者ID:DanNixon,项目名称:mantid,代码行数:7,代码来源:sans_data_processor_gui_algorithm.py


示例3: test_that_selector_is_refreshed_on_alg_load

    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))
开发者ID:mantidproject,项目名称:mantid,代码行数:10,代码来源:observer_test.py


示例4: test_can_enable_and_disable_notifications

    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'")
开发者ID:mantidproject,项目名称:mantid,代码行数:10,代码来源:AlgorithmFactoryTest.py


示例5: test_can_toggle_algorithm_factory_notifications

    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))
开发者ID:mantidproject,项目名称:mantid,代码行数:12,代码来源:observer_test.py


示例6: test_class_can_override_standard_algorithm_methods

    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)
开发者ID:AlistairMills,项目名称:mantid,代码行数:12,代码来源:DataProcessorAlgorithmTest.py


示例7: setUp

 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)
开发者ID:AlistairMills,项目名称:mantid,代码行数:7,代码来源:PythonAlgorithmTraitsTest.py


示例8: test_explicit_store_in_ADS

    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)
开发者ID:mantidproject,项目名称:mantid,代码行数:15,代码来源:SimpleAPITest.py


示例9: genNewLinks

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
开发者ID:martyngigg,项目名称:alg2rst,代码行数:33,代码来源:convertLinks.py


示例10: test_python_alg_can_use_other_python_alg_through_simple_api

    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))
开发者ID:BigShows,项目名称:mantid,代码行数:33,代码来源:SimpleAPITest.py


示例11: _insert_pagetitle

    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))
开发者ID:mkoennecke,项目名称:mantid,代码行数:27,代码来源:algorithm.py


示例12: test_python_algorithms_are_loaded_recursively

 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)
开发者ID:AlistairMills,项目名称:mantid,代码行数:7,代码来源:ImportModuleTest.py


示例13: skip

    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
开发者ID:liyulun,项目名称:mantid,代码行数:30,代码来源:base.py


示例14: test_get_registered_algs_returns_dictionary_of_known_algorithms

 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] )
开发者ID:trnielsen,项目名称:mantid,代码行数:7,代码来源:AlgorithmFactoryTest.py


示例15: test_optional_workspaces_are_ignored_if_not_present_in_output_even_if_given_as_input

    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
开发者ID:tyronerees,项目名称:mantid,代码行数:46,代码来源:SimpleAPITest.py


示例16: test_validate_inputs_with_errors_stops_algorithm

 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)
开发者ID:rosswhitfield,项目名称:mantid,代码行数:17,代码来源:SimpleAPITest.py


示例17: test_getDescriptors

    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'))
开发者ID:samueljackson92,项目名称:mantid,代码行数:9,代码来源:AlgorithmFactoryTest.py


示例18: _mockup

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)
开发者ID:mkoennecke,项目名称:mantid,代码行数:57,代码来源:simpleapi.py


示例19: test_later_store_in_ADS

    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')
开发者ID:mantidproject,项目名称:mantid,代码行数:21,代码来源:SimpleAPITest.py


示例20: test_loading_python_algorithm_increases_registered_algs_by_one

 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)
开发者ID:mantidproject,项目名称:mantid,代码行数:16,代码来源:PythonPluginsTest.py



注:本文中的mantid.api.AlgorithmFactory类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python api.AlgorithmManager类代码示例发布时间:2022-05-27
下一篇:
Python manipulate.Manipulate类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap