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

Python api.FunctionFactory类代码示例

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

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



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

示例1: initByName

    def initByName(self, name, *args, **kwargs):
        """
        intialise composite function of named type.
        E.g. "ProductFunction"
        This function would be protected in c++
        and should not be called directly except
        by :meth:`__init__` functions of this class
        and subclasses.

        :param name:   name of class calling this.
        :param args:   names of functions in composite function
        :param kwargs: any parameters or attributes that must be passed to the
                       composite function itself.
        """
        if len(args) == 1 and  not isinstance(args[0], FunctionWrapper):
            # We have a composite function to wrap
            self.fun = args[0]
        else:
            self.fun = FunctionFactory.createCompositeFunction(name)

            # Add the functions, checking for Composite & Product functions
            for a in args:
                if not isinstance(a, int):
                    if isinstance(a, CompositeFunctionWrapper):
                        if self.pureAddition:
                            self.pureAddition = a.pureAddition
                        if self.pureMultiplication:
                            self.pureMultiplication = a.pureMultiplication
                    functionToAdd = FunctionFactory.createInitialized(a.fun.__str__())
                    self.fun.add(functionToAdd)
        self.init_paramgeters_and_attributes(**kwargs)
开发者ID:mantidproject,项目名称:mantid,代码行数:31,代码来源:fitfunctions.py


示例2: isregistered

def isregistered(function):
    status, msg = True, ""
    try:
        FunctionFactory.createFunction(function)
    except RuntimeError as exc:
        status, msg = False, 'Could not create {} function: {}'.format(function, str(exc))
    return status, msg
开发者ID:mantidproject,项目名称:mantid,代码行数:7,代码来源:StretchedExpFTTestHelper.py


示例3: test_members_can_be_added

 def test_members_can_be_added(self):
     func = CompositeFunction()
     f1 = FunctionFactory.createInitialized('name=FlatBackground,A0=1')
     f2 = FunctionFactory.createInitialized('name=FlatBackground,A0=2')
     f3 = FunctionFactory.createInitialized('name=FlatBackground,A0=3')
     func.add(f1)
     func.add(f2)
     func.add(f3)
     self.assertEqual(len(func), 3)
     self.assertEqual(str(func[0]), 'name=FlatBackground,A0=1')
     self.assertEqual(str(func[1]), 'name=FlatBackground,A0=2')
     self.assertEqual(str(func[2]), 'name=FlatBackground,A0=3')
开发者ID:DanNixon,项目名称:mantid,代码行数:12,代码来源:CompositeFunctionTest.py


示例4: is_registered

def is_registered(function_name):
    """
    Check whether the function with the specified name has been registered.

    :param function_name: The name of the function to check for registration.
    :return:              A tuple of the status (True if function is registered,
                          false otherwise) and the error message (empty if the
                          function is registered).
    """
    try:
        FunctionFactory.createFunction(function_name)
    except RuntimeError as exc:
        return False, 'Could not create {} function: {}'.format(function_name,
                                                                str(exc))
    return True, ""
开发者ID:DanNixon,项目名称:mantid,代码行数:15,代码来源:MsdTestHelper.py


示例5: 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


示例6: test_parameters_can_be_get_and_set

 def test_parameters_can_be_get_and_set(self):
     func = FunctionFactory.createInitialized('name=FlatBackground,A0=1;name=FlatBackground,A0=2')
     self.assertEqual(func.getParameterValue('f0.A0'), 1.0)
     self.assertEqual(func.getParameterValue('f1.A0'), 2.0)
     func.setParameter('f0.A0', 10.0)
     self.assertEqual(func.getParameterValue('f0.A0'), 10.0)
     func.setParameter('f1.A0', 20.0)
     self.assertEqual(func.getParameterValue('f1.A0'), 20.0)
开发者ID:DanNixon,项目名称:mantid,代码行数:8,代码来源:CompositeFunctionTest.py


示例7: test_nested_functions

 def test_nested_functions(self):
     s = 'name=FlatBackground,A0=1;(name=FlatBackground,A0=2;name=FlatBackground,A0=3)'
     func = FunctionFactory.createInitialized(s)
     self.assertEqual(len(func), 2)
     self.assertFalse(isinstance(func[0], CompositeFunction))
     self.assertTrue(isinstance(func[1], CompositeFunction))
     self.assertEqual(len(func[1]), 2)
     self.assertEqual(func.getParameterValue('f0.A0'), 1.0)
     self.assertEqual(func.getParameterValue('f1.f0.A0'), 2.0)
     self.assertEqual(func.getParameterValue('f1.f1.A0'), 3.0)
     self.assertEqual(func.nParams(), 3)
开发者ID:DanNixon,项目名称:mantid,代码行数:11,代码来源:CompositeFunctionTest.py


示例8: create_mantid_ifunction

    def create_mantid_ifunction(self, function_name):
        """
        Create and initiializes a Mantid IFunction.

        Args:
          function_name (str): The name of the function to use.

        Returns:
          ifunction: An instance of a Mantid IFunction
        """
        from mantid.api import FunctionFactory
        return FunctionFactory.createFunction(function_name)
开发者ID:liyulun,项目名称:mantid,代码行数:12,代码来源:base.py


示例9: test_function_existing_function_can_be_unsubscribed

 def test_function_existing_function_can_be_unsubscribed(self):
     FunctionFactory.subscribe(TestFunctionCorrectForm)
     nfuncs_before = len(FunctionFactory.getFunctionNames())
     FunctionFactory.unsubscribe("TestFunctionCorrectForm")
     available_functions = FunctionFactory.getFunctionNames()
     self.assertEquals(nfuncs_before - 1, len(available_functions))
     self.assertTrue("TestFunctionCorrectForm" not in available_functions)
开发者ID:mantidproject,项目名称:mantid,代码行数:7,代码来源:FunctionFactoryTest.py


示例10: test_function_subscription

 def test_function_subscription(self):
     nfuncs_orig = len(FunctionFactory.getFunctionNames())
     FunctionFactory.subscribe(TestFunction)
     new_funcs = FunctionFactory.getFunctionNames()
     self.assertEquals(nfuncs_orig+1, len(new_funcs))
     self.assertTrue("TestFunction" in new_funcs)
     
     FunctionFactory.unsubscribe("TestFunction")
     new_funcs = FunctionFactory.getFunctionNames()
     self.assertEquals(nfuncs_orig, len(new_funcs))
     self.assertTrue("TestFunction" not in new_funcs)
开发者ID:AlistairMills,项目名称:mantid,代码行数:11,代码来源:FunctionFactoryTest.py


示例11: __init__

    def __init__(self, name, **kwargs):
        """
        Called when creating an instance

        :param name:   name of fitting function to create or
                       an Ifunction object to wrap.
        :param kwargs: standard argument for initializing fit
                       function
        """
        if not isinstance(name, str):
            self.fun = name
        else:
            self.fun = FunctionFactory.createFunction(name)
        self.init_paramgeters_and_attributes(**kwargs)
开发者ID:mantidproject,项目名称:mantid,代码行数:14,代码来源:fitfunctions.py


示例12: Dsf

                dsf = Dsf()
                dsf.SetIntensities( mtd[ self._InputWorkspaces[idsf] ].dataY(self._WorkspaceIndex) )
                dsf.errors = None # do not incorporate error data
                if self._LoadErrors:
                    dsf.SetErrors(mtd[ self._InputWorkspaces[idsf] ].dataE(self._WorkspaceIndex))
                dsf.SetFvalue( self._ParameterValues[idsf] )
                dsfgroup.InsertDsf(dsf)
            # Create the interpolator
            from dsfinterp.channelgroup import ChannelGroup
            self._channelgroup = ChannelGroup()
            self._channelgroup.InitFromDsfGroup(dsfgroup)
            if self._LocalRegression:
                self._channelgroup.InitializeInterpolator(running_regr_type=self._RegressionType, windowlength=self._RegressionWindow)
            else:
                self._channelgroup.InitializeInterpolator(windowlength=0)
        # channel group has been initialized, so evaluate the interpolator
        dsf = self._channelgroup(p['TargetParameter'])
        # Linear interpolation between the energies of the channels and the xvalues we require
        # NOTE: interpolator evaluates to zero for any of the xvals outside of the domain defined by self._xvalues
        intensities_interpolator = scipy.interpolate.interp1d(self._xvalues, p['Intensity']*dsf.intensities, kind='linear')
        return intensities_interpolator(xvals)  # can we pass by reference?

# Required to have Mantid recognize the new function
#pylint: disable=unused-import
try:
    import dsfinterp
    FunctionFactory.subscribe(DSFinterp1DFit)
except ImportError:
    logger.debug('Failed to subscribe fit function DSFinterp1DFit. '+\
                 'Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)')
开发者ID:mducle,项目名称:mantid,代码行数:30,代码来源:DSFinterp1DFit.py


示例13: fwhm

    def fwhm(self):
        """
        Return what should be considered the 'fwhm' of this function.
        """
        return 2.0*math.sqrt(2.0*math.log(2.0))*self.getParameterValue("Sigma")

    def setCentre(self, new_centre):
        """
        Called by an external entity, probably a GUI, in response to a mouse click
        that gives a guess at the centre.
        """
        self.setParameter("PeakCentre",new_centre)

    def setHeight(self, new_height):
        """
        Called by an external entity, probably a GUI, in response to a user guessing
        the height.
        """
        self.setParameter("Height", new_height)

    def setFwhm(self, new_fwhm):
        """
        Called by an external entity, probably a GUI, in response to a user guessing
        the height.
        """
        sigma = new_fwhm/(2.0*math.sqrt(2.0*math.log(2.0)))
        self.setParameter("Sigma",sigma)

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(ExamplePeakFunction)
开发者ID:dezed,项目名称:mantid,代码行数:30,代码来源:ExamplePeakFunction.py


示例14: functionDeriv1D

        -------
        numpy.ndarray
            Function values
        """
        zs = self.getParameterValue('R') * np.asarray(xvals)
        return self.getParameterValue('A') * np.square(3 * self.vecbessel(zs))

    def functionDeriv1D(self, xvals, jacobian):
        r"""Calculate the partial derivatives

        Parameters
        ----------
        xvals : sequence of floats
          The domain where to evaluate the function
        jacobian: 2D array
          partial derivatives of the function with respect to the fitting
          parameters, evaluated at the domain.
        """
        amplitude = self.getParameterValue('A')
        radius = self.getParameterValue('R')
        i = 0
        for x in xvals:
            z = radius * x
            j = j1(z)/z
            jacobian.set(i, 0, np.square(3 * j))
            jacobian.set(i,1, amplitude * 2 * 9 * j * (j1d(z) - j) / radius)
            i += 1

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(EISFDiffSphere)
开发者ID:mantidproject,项目名称:mantid,代码行数:30,代码来源:EISFDiffSphere.py


示例15: import

along with this program.  If not, see <http://www.gnu.org/licenses/>.

File change history is stored at: <https://github.com/mantidproject/mantid>
Code Documentation is available at: <http://doxygen.mantidproject.org>
'''

from __future__ import (absolute_import, division, print_function)
from mantid.api import IFunction1D, FunctionFactory


class FickDiffusion(IFunction1D):

    def category(self):
        return "QuasiElastic"

    def init(self):
        # Active fitting parameters
        self.declareParameter("D", 1.0, 'Diffusion constant')

    def function1D(self, xvals):
        return self.getParameterValue("D")*xvals*xvals

    def functionDeriv1D(self, xvals, jacobian):
        i = 0
        for x in xvals:
            jacobian.set(i,0,2.0*x)
            i += 1

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(FickDiffusion)
开发者ID:rosswhitfield,项目名称:mantid,代码行数:30,代码来源:FickDiffusion.py


示例16: init

    def init(self):
        # Active fitting parameters
        self.declareParameter("Scale", 1.0, 'Scale')
        self.declareParameter("Length", 50.0, 'Length')
        self.declareParameter("Background", 0.0, 'Background')

    def function1D(self, xvals):
        """
            Evaluate the model
            @param xvals: numpy array of q-values
        """
        return self.getParameterValue("Scale") / (1.0 + np.power(xvals*self.getParameterValue('Length'), 2)) + self.getParameterValue('Background')

    def functionDeriv1D(self, xvals, jacobian):
        """
            Evaluate the first derivatives
            @param xvals: numpy array of q-values
            @param jacobian: Jacobian object
        """
        i = 0
        for x in xvals:
            jacobian.set(i,0, 1.0 / (1.0 + np.power(x*self.getParameterValue('Length'), 2)))
            denom = math.pow(1.0 + math.pow(x*self.getParameterValue('Length'), 2), -2)
            jacobian.set(i,1, -2.0 * self.getParameterValue("Scale") * x * x * self.getParameterValue('Length') * denom)
            jacobian.set(i,2, 1.0)
            i += 1

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(Lorentz)

开发者ID:mkoennecke,项目名称:mantid,代码行数:29,代码来源:Lorentz.py


示例17: init

        return "QuasiElastic"

    def init(self):
        # Active fitting parameters
        self.declareParameter("Tau", 1.0, 'Residence time')
        self.declareParameter("L", 0.2, 'Jump length')
       
    def function1D(self, xvals):
        tau = self.getParameterValue("Tau")
        l = self.getParameterValue("L")

        xvals = np.array(xvals)
        hwhm = (1.0 - np.exp( -l * xvals * xvals )) / tau

        return hwhm
    
    def functionDeriv1D(self, xvals, jacobian):
        tau = self.getParameterValue("Tau")
        l = self.getParameterValue("L")

        i = 0
        for x in xvals:
            ex = math.exp(-l*x*x)
            h = (1.0-ex)/tau
            jacobian.set(i,0,-h/tau);
            jacobian.set(i,1,x*x*ex/tau);
            i += 1

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(SingwiSjolander)
开发者ID:AlistairMills,项目名称:mantid,代码行数:30,代码来源:SingwiSjolander.py


示例18: while

        Nmax = 16000 # increase short-times resolution, increase the resolution of the structure factor tail
        while ( emax / de ) < Nmax:
            emax = 2 * emax
        N = int( emax / de )
        dt = ( float(N) / ( 2 * N + 1 ) ) * (self._h / emax)  # extent to negative times and t==0
        sampled_times = dt * np.arange(-N, N+1) # len( sampled_times ) < 64000
        exponent = -(np.abs(sampled_times)/p['tau'])**p['beta']
        freqs = de * np.arange(-N, N+1)
        fourier = p['height']*np.abs( scipy.fftpack.fft( np.exp(exponent) ).real )
        fourier = np.concatenate( (fourier[N+1:],fourier[0:N+1]) )
        interpolator = scipy.interpolate.interp1d(freqs, fourier)
        fourier = interpolator(xvals)
        return fourier
    
    def functionDeriv1D(self, xvals, jacobian):
        '''Numerical derivative'''
        p = self.validateParams()
        f0 = self.function1D(xvals)
        dp = {}
        for (key,val) in p.items(): dp[key] = 0.1 * val #modify by ten percent
        for name in self._parmset:
            pp = copy.copy(p)
            pp[name] += dp[name]
            df = (self.function1D(xvals, **pp) - f0) / dp[name]
            ip = self._parm2index[name]
            for ix in range(len(xvals)):
                jacobian.set(ix, ip, df[ix])  

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(StretchedExpFT)
开发者ID:jkrueger1,项目名称:mantid,代码行数:30,代码来源:StretchedExpFT.py


示例19: category

    def category(self):
        return "QuasiElastic"

    def init(self):
        # Active fitting parameters
        self.declareParameter("Tau", 1.0, 'Residence time')
        self.declareParameter("L", 1.5, 'Jump length')

    def function1D(self, xvals):
        tau = self.getParameterValue("Tau")
        length = self.getParameterValue("L")

        xvals = np.array(xvals)
        hwhm = (1.0 - np.sin(xvals * length) / (xvals * length)) / tau

        return hwhm

    def functionDeriv1D(self, xvals, jacobian):
        tau = self.getParameterValue("Tau")
        length = self.getParameterValue("L")
        i = 0
        for x in xvals:
            s = math.sin(x*length)/(x*length)
            h = (1.0-s)/tau
            jacobian.set(i,0,-h/tau);
            jacobian.set(i,1,(math.cos(x*length)-s)/(length*tau));
            i += 1

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(ChudleyElliot)
开发者ID:BigShows,项目名称:mantid,代码行数:30,代码来源:ChudleyElliot.py


示例20: function1D

        See ExamplePeakFunction for more on attributes
        """
        # Active fitting parameters
        self.declareParameter("A0")
        self.declareParameter("A1")

    def function1D(self, xvals):
        """
        Computes the function on the set of values given and returns
        the answer as a numpy array of floats
        """
        return self.getParameterValue("A0") +  self.getParameterValue("A1")*xvals

    def functionDeriv1D(self, xvals, jacobian):
        """
        Computes the partial derivatives of the function on the set of values given
        and the sets these values in the given jacobian. The Jacobian is essentially
        a matrix where jacobian.set(iy,ip,value) takes 3 parameters:
            iy = The index of the data value whose partial derivative this corresponds to
            ip = The index of the parameter value whose partial derivative this corresponds to
            value = The value of the derivative
        """
        i = 0
        for x in xvals:
            jacobian.set(i,0,1);
            jacobian.set(i,1,x);
            i += 1

# Required to have Mantid recognise the new function
FunctionFactory.subscribe(Example1DFunction)
开发者ID:BigShows,项目名称:mantid,代码行数:30,代码来源:Example1DFunction.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python api.Progress类代码示例发布时间:2022-05-27
下一篇:
Python api.FileFinder类代码示例发布时间: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