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

Python sympy_parser.parse_expr函数代码示例

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

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



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

示例1: test_symbol_splitting

def test_symbol_splitting():
    # By default Greek letter names should not be split (lambda is a keyword
    # so skip it)
    transformations = standard_transformations + (split_symbols,)
    greek_letters = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
                     'eta', 'theta', 'iota', 'kappa', 'mu', 'nu', 'xi',
                     'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
                     'phi', 'chi', 'psi', 'omega')

    for letter in greek_letters:
        assert(parse_expr(letter, transformations=transformations) ==
               parse_expr(letter))

    # Make sure custom splitting works
    def can_split(symbol):
        if symbol not in ('unsplittable', 'names'):
            return _token_splittable(symbol)
        return False
    transformations = standard_transformations
    transformations += (split_symbols_custom(can_split),
                        implicit_multiplication)

    assert(parse_expr('unsplittable', transformations=transformations) ==
           parse_expr('unsplittable'))
    assert(parse_expr('names', transformations=transformations) ==
           parse_expr('names'))
    assert(parse_expr('xy', transformations=transformations) ==
           parse_expr('x*y'))
    for letter in greek_letters:
        assert(parse_expr(letter, transformations=transformations) ==
               parse_expr(letter))
开发者ID:Acebulf,项目名称:sympy,代码行数:31,代码来源:test_implicit_multiplication_application.py


示例2: test_implicit_multiplication

def test_implicit_multiplication():
    cases = {
        "5x": "5*x",
        "abc": "a*b*c",
        "3sin(x)": "3*sin(x)",
        "(x+1)(x+2)": "(x+1)*(x+2)",
        "(5 x**2)sin(x)": "(5*x**2)*sin(x)",
        "2 sin(x) cos(x)": "2*sin(x)*cos(x)",
        "pi x": "pi*x",
        "x pi": "x*pi",
        "E x": "E*x",
        "EulerGamma y": "EulerGamma*y",
        "E pi": "E*pi",
        "pi (x + 2)": "pi*(x+2)",
        "(x + 2) pi": "(x+2)*pi",
        "pi sin(x)": "pi*sin(x)",
    }
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (split_symbols, implicit_multiplication)
    for case in cases:
        implicit = parse_expr(case, transformations=transformations2)
        normal = parse_expr(cases[case], transformations=transformations)
        assert implicit == normal

    application = ["sin x", "cos 2*x", "sin cos x"]
    for case in application:
        raises(SyntaxError, lambda: parse_expr(case, transformations=transformations2))
    raises(TypeError, lambda: parse_expr("sin**2(x)", transformations=transformations2))
开发者ID:plaes,项目名称:sympy,代码行数:28,代码来源:test_implicit_multiplication_application.py


示例3: test_implicit_multiplication

def test_implicit_multiplication():
    cases = {
        '5x': '5*x',
        'abc': 'a*b*c',
        '3sin(x)': '3*sin(x)',
        '(x+1)(x+2)': '(x+1)*(x+2)',
        '(5 x**2)sin(x)': '(5*x**2)*sin(x)',
        '2 sin(x) cos(x)': '2*sin(x)*cos(x)',
        'pi x': 'pi*x',
        'x pi': 'x*pi',
        'E x': 'E*x',
        'EulerGamma y': 'EulerGamma*y',
        'E pi': 'E*pi',
        'pi (x + 2)': 'pi*(x+2)',
        '(x + 2) pi': '(x+2)*pi',
        'pi sin(x)': 'pi*sin(x)',
    }
    transformations = standard_transformations + (convert_xor,)
    transformations2 = transformations + (split_symbols,
                                          implicit_multiplication)
    for case in cases:
        implicit = parse_expr(case, transformations=transformations2)
        normal = parse_expr(cases[case], transformations=transformations)
        assert(implicit == normal)

    application = ['sin x', 'cos 2*x', 'sin cos x']
    for case in application:
        raises(SyntaxError,
               lambda: parse_expr(case, transformations=transformations2))
    raises(TypeError,
           lambda: parse_expr('sin**2(x)', transformations=transformations2))
开发者ID:A-turing-machine,项目名称:sympy,代码行数:31,代码来源:test_implicit_multiplication_application.py


示例4: ode_is_lin_const_coeff

    def ode_is_lin_const_coeff(ode_symbol, ode_definition, shapes):
        """
        TODO: improve the original code: the function should take a list of shape names, not objects
        :param ode_symbol string encoding the LHS
        :param ode_definition string encoding RHS
        :param shapes A list with shape names
        :return true iff the ode definition is a linear and constant coefficient ODE
        """

        ode_symbol_sp = parse_expr(ode_symbol)
        ode_definition_sp = parse_expr(ode_definition)

        # Check linearity
        ddvar = diff(diff(ode_definition_sp, ode_symbol_sp), ode_symbol_sp)

        if simplify(ddvar) != 0:
            return False

        # Check coefficients
        dvar = diff(ode_definition_sp, ode_symbol_sp)

        for shape in shapes:
            for symbol in dvar.free_symbols:
                if shape == str(symbol):
                    return False
        return True
开发者ID:Silmathoron,项目名称:nestml,代码行数:26,代码来源:solution_transformers.py


示例5: test_local_dict_symbol_to_fcn

def test_local_dict_symbol_to_fcn():
    x = Symbol('x')
    d = {'foo': Function('bar')}
    assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
    # XXX: bit odd, but would be error if parser left the Symbol
    d = {'foo': Symbol('baz')}
    assert parse_expr('foo(x)', local_dict=d) == Function('baz')(x)
开发者ID:bjodah,项目名称:sympy,代码行数:7,代码来源:test_sympy_parser.py


示例6: test_issue_10560

def test_issue_10560():
    inputs = {
        '4*-3' : '(-3)*4',
        '-4*3' : '(-4)*3',
    }
    for text, result in inputs.items():
        assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
开发者ID:bjodah,项目名称:sympy,代码行数:7,代码来源:test_sympy_parser.py


示例7: test_issue_10773

def test_issue_10773():
    inputs = {
    '-10/5': '(-10)/5',
    '-10/-5' : '(-10)/(-5)',
    }
    for text, result in inputs.items():
        assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
开发者ID:bjodah,项目名称:sympy,代码行数:7,代码来源:test_sympy_parser.py


示例8: eq_sympy

    def eq_sympy(input_dim, output_dim, ARD=False):
        """
        Latent force model covariance, exponentiated quadratic with multiple outputs. Derived from a diffusion equation with the initial spatial condition layed down by a Gaussian process with lengthscale given by shared_lengthscale.

        See IEEE Trans Pattern Anal Mach Intell. 2013 Nov;35(11):2693-705. doi: 10.1109/TPAMI.2013.86. Linear latent force models using Gaussian processes. Alvarez MA, Luengo D, Lawrence ND.

        :param input_dim: Dimensionality of the kernel
        :type input_dim: int
        :param output_dim: number of outputs in the covariance function.
        :type output_dim: int
        :param ARD: whether or not to user ARD (default False).
        :type ARD: bool

        """
        real_input_dim = input_dim
        if output_dim>1:
            real_input_dim -= 1
        X = sp.symbols('x_:' + str(real_input_dim))
        Z = sp.symbols('z_:' + str(real_input_dim))
        scale = sp.var('scale_i scale_j',positive=True)
        if ARD:
            lengthscales = [sp.var('lengthscale%i_i lengthscale%i_j' % i, positive=True) for i in range(real_input_dim)]
            shared_lengthscales = [sp.var('shared_lengthscale%i' % i, positive=True) for i in range(real_input_dim)]
            dist_string = ' + '.join(['(x_%i-z_%i)**2/(shared_lengthscale%i**2 + lengthscale%i_i**2 + lengthscale%i_j**2)' % (i, i, i) for i in range(real_input_dim)])
            dist = parse_expr(dist_string)
            f =  variance*sp.exp(-dist/2.)
        else:
            lengthscales = sp.var('lengthscale_i lengthscale_j',positive=True)
            shared_lengthscale = sp.var('shared_lengthscale',positive=True)
            dist_string = ' + '.join(['(x_%i-z_%i)**2' % (i, i) for i in range(real_input_dim)])
            dist = parse_expr(dist_string)
            f =  scale_i*scale_j*sp.exp(-dist/(2*(lengthscale_i**2 + lengthscale_j**2 + shared_lengthscale**2)))
        return kern(input_dim, [spkern(input_dim, f, output_dim=output_dim, name='eq_sympy')])
开发者ID:Dalar,项目名称:GPy,代码行数:33,代码来源:constructors.py


示例9: __dot

	def __dot(self,vector2):
		product = 0.0
		for i in range(len(vector2)):
			try:
				product += (parse_expr(self.user_fn[i])*parse_expr(vector2[i]))
			except:
				product += (parse_expr(self.user_fn[i])*vector2[i])
		return product
开发者ID:daviddewhurst,项目名称:symbolic,代码行数:8,代码来源:functions.py


示例10: test_split_symbols

def test_split_symbols():
    transformations = standard_transformations + (split_symbols, implicit_multiplication)
    x = Symbol("x")
    y = Symbol("y")
    xy = Symbol("xy")

    assert parse_expr("xy") == xy
    assert parse_expr("xy", transformations=transformations) == x * y
开发者ID:brajeshvit,项目名称:virtual,代码行数:8,代码来源:test_sympy_parser.py


示例11: _check

 def _check(self, res, ref):
     if hasattr(res, "get_x"):
         x = res.get_x()
         for k in list(res.keys()):
             if np.all(res[k] == x):
                 continue
             elif np.any(np.iscomplex(res[k])) or np.any(np.iscomplex(ref[k])):
                 # Interpolate Re and Im of the results to compare.
                 x = x.reshape((-1,))
                 refx = ref[ref.x].reshape((-1,))
                 d1 = InterpolatedUnivariateSpline(x, np.real(res[k]).reshape((-1,)))
                 d2 = InterpolatedUnivariateSpline(refx, np.real(ref[k]).reshape((-1,)))
                 ok(d1(x), d2(x), rtol=self.er, atol=self.ea, msg=("Test %s FAILED (Re)" % self.test_id))
                 d1 = InterpolatedUnivariateSpline(x, np.imag(res[k]).reshape((-1,)))
                 d2 = InterpolatedUnivariateSpline(refx, np.imag(ref[k]).reshape((-1,)))
                 ok(d1(x), d2(x), rtol=self.er, atol=self.ea, msg=("Test %s FAILED (Im)" % self.test_id))
             else:
                 # Interpolate the results to compare.
                 x = x.reshape((-1,))
                 refx = ref[ref.x].reshape((-1,))
                 d1 = InterpolatedUnivariateSpline(x, np.real_if_close(res[k]).reshape((-1,)))
                 d2 = InterpolatedUnivariateSpline(refx, np.real_if_close(ref[k]).reshape((-1,)))
                 ok(d1(x), d2(x), rtol=self.er, atol=self.ea, msg=("Test %s FAILED" % self.test_id))
     elif isinstance(res, results.op_solution):
         for k in list(res.keys()):
             assert k in ref
             ok(res[k], ref[k], rtol=self.er, atol=self.ea, msg=("Test %s FAILED" % self.test_id))
     elif isinstance(res, results.pz_solution):
         # recover the reference signularities from Re/Im data
         ref_sing_keys = list(ref.keys())[:]
         ref_sing_keys.sort()
         assert len(ref_sing_keys) % 2 == 0
         ref_sing = [
             ref[ref_sing_keys[int(len(ref_sing_keys) / 2) + k]] + ref[ref_sing_keys[k]] * 1j
             for k in range(int(len(ref_sing_keys) / 2))
         ]
         ref_poles_num = len([k for k in ref.keys() if k[:4] == "Re(p"])
         poles_ref, zeros_ref = ref_sing[:ref_poles_num], ref_sing[ref_poles_num:]
         assert len(poles_ref) == len(res.poles)
         pz._check_singularities(res.poles, poles_ref)
         assert len(zeros_ref) == len(res.zeros)
         pz._check_singularities(res.zeros, zeros_ref)
     else:
         if isinstance(res, list) or isinstance(res, tuple):
             for i, j in zip(res, ref):
                 self._check(i, j)
         elif res is not None:
             for k in list(res.keys()):
                 assert k in ref
                 if isinstance(res[k], dict):  # hence ref[k] will be a dict too
                     self._check(res[k], ref[k])
                 elif isinstance(ref[k], sympy.Basic) and isinstance(res[k], sympy.Basic):
                     # get rid of assumptions. Evaluate only expression
                     rf = parse_expr(str(ref[k]))
                     rs = parse_expr(str(res[k]))
                     assert (rs == rf) or (sympy.simplify(rf / rs) == 1)
                 else:
                     assert res[k] == ref[k]
开发者ID:ReynaldoBelfortUPRM,项目名称:ahkab,代码行数:58,代码来源:testing.py


示例12: test_split_symbols_function

def test_split_symbols_function():
    transformations = standard_transformations + (split_symbols, implicit_multiplication)
    x = Symbol("x")
    y = Symbol("y")
    a = Symbol("a")
    f = Function("f")

    assert parse_expr("ay(x+1)", transformations=transformations) == a * y * (x + 1)
    assert parse_expr("af(x+1)", transformations=transformations, local_dict={"f": f}) == a * f(x + 1)
开发者ID:brajeshvit,项目名称:virtual,代码行数:9,代码来源:test_sympy_parser.py


示例13: test_fixedpoints

 def test_fixedpoints(self):
     # Module B1 Page 26
     points = fixed_points(parse_expr('x**2 + 1/8'))
     self.assertEqual(points[0], parse_expr('1/2 - 1/4 * sqrt(2)'))
     self.assertEqual(points[1], parse_expr('1/2 + 1/4 * sqrt(2)'))
     # Module B1 Page 28
     points = fixed_points(parse_expr('-1/8*x**2+5/8*x+7/2'))
     self.assertEqual(points[0], -7)
     self.assertEqual(points[1], 4)
开发者ID:jaymzcd,项目名称:oucode,代码行数:9,代码来源:ms221_tests.py


示例14: parse_using_sympy_simplify

def parse_using_sympy_simplify(s):
    transformations = standard_transformations + (convert_xor, implicit_multiplication_application,)
    print(s)
    s = s.split('==')
    new_s = []
    for x in s:
        new_s.append(str(simplify(parse_expr(x, transformations=transformations, global_dict=None, evaluate=True))))
    new_s = '=='.join(new_s)
    return parse_expr(new_s, transformations=transformations, global_dict=None, evaluate=True)
开发者ID:ampled,项目名称:oppgavegenerator,代码行数:9,代码来源:answer_checker.py


示例15: test_split_symbols

def test_split_symbols():
    transformations = standard_transformations + \
                      (split_symbols, implicit_multiplication,)
    x = Symbol('x')
    y = Symbol('y')
    xy = Symbol('xy')

    assert parse_expr("xy") == xy
    assert parse_expr("xy", transformations=transformations) == x*y
开发者ID:Lenqth,项目名称:sympy,代码行数:9,代码来源:test_sympy_parser.py


示例16: test_convert_equals_signs

def test_convert_equals_signs():
    transformations = standard_transformations + \
                        (convert_equals_signs, )
    x = Symbol('x')
    y = Symbol('y')
    assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x)
    assert parse_expr("y = x", transformations=transformations) == Eq(y, x)
    assert parse_expr("(2*y = x) = False",
        transformations=transformations) == Eq(Eq(2*y, x), False)
开发者ID:bjodah,项目名称:sympy,代码行数:9,代码来源:test_sympy_parser.py


示例17: test_factorial_fail

def test_factorial_fail():
    inputs = ['x!!!', 'x!!!!', '(!)']

    for text in inputs:
        try:
            parse_expr(text)
            assert False
        except TokenError:
            assert True
开发者ID:Bercio,项目名称:sympy,代码行数:9,代码来源:test_sympy_parser.py


示例18: __init__

    def __init__(self,config,sec) :
        for it in config.options(sec) :
            # chaque it est la liste des variables 
            if config.get(sec,it) == '' :  # on teste si c'est vide
                vars(self)[it] = None
            elif config.get(sec,it).count(',')>=1 : # on teste si c'est une liste de param
                if config.get(sec,it).count('pi')==0 : # pas de pi
                    try :
                        vars(self)[it] = map(float,config.get(sec,it).split(','))
                    except ValueError :
                        vars(self)[it] = config.get(sec,it).split(',') # une liste de chaines
                        
                elif config.get(sec,it).count('pi')>=1 : # au moins un pi
                    vars(self)[it] = [float(parse_expr(el).n()) for el in config.get(sec,it).split(',')]
            
            # on teste si c'est une chaine
            elif config.get(sec,it).isalpha() and config.get(sec,it).count('pi')==0: 
                    vars(self)[it]=config.get(sec,it)
            elif config.get(sec,it).count('pi')>=1 :
                    vars(self)[it]=float(parse_expr(config.get(sec,it)).n())
            else : # dans les autre cas c'est un float
                try :
                    vars(self)[it] = config.getfloat(sec,it)
                except ValueError : # a-priori on a un mélange float + str
                    vars(self)[it] = config.get(sec,it)
        
        for k in vars(self).keys() : 
            if k[-5:]=='param' and vars(self).get(k)!=None :
                param=vars(self).get(k)
                if type(param)==str :
                    # afin de conserver le nom du fichier d'entrée 
                    # on crée un dict avec l'extension _filename
                    Dict_filename={k[:-6]+'_filename':param}
                    vars(self).update(Dict_filename)
                    
                    # si param est une chaine c'est un fichier à charger
                    # on doit avoir un fichier csv avec :
                    # le delimiter= tab ou espace 
                    # les nombres au format GB
                    # la colonne 1 = abscisses
                    # la colonne 2 = ordonnées
                    param=np.loadtxt(param)
                    # afin d'eviter de lire le fichier n fois on change 
                    # la variable param en un array issu du loadtxt
                    vars(self)[k]=param

                typeDyn=vars(self).get(k[:-6]+'_type')
                # on crée la fonction qui renvoie la propriété
                # la fonction partial est indispensable
                vars(self)[k[:-6]]=partial(self._dynamicProp,param=param,typeDyn=typeDyn)

            if k[-4:]=='expr' :
                expr=vars(self).get(k)
                vars(self)[k[:-5]]= parse_expr(expr)
                delattr(self, k)
开发者ID:Ticonderoga,项目名称:Routines,代码行数:55,代码来源:ImportData.py


示例19: quadratic_find_roots

def quadratic_find_roots(quad_val):
    x = sympy.Symbol("x")
    solution_ls = sympy.solve(sympy.Eq(parse_expr(quad_val), parse_expr("0")), x)
    solution_str = ""
    for sol_ind in range(0, len(solution_ls)):
        if (len(solution_ls) - 1) != sol_ind:
            solution_str += "x = " + str(solution_ls[sol_ind]) + "\n"
        else:
            solution_str += "x = " + str(solution_ls[sol_ind])

    return solution_str
开发者ID:TheTekUnion,项目名称:Software,代码行数:11,代码来源:quadratic.py


示例20: CheckAnswerType5

def CheckAnswerType5 (problem, answer):
    facN = parse_expr('factorial('+problem.vars['n']+')')
    str = answer.split("/")[0]
    fac_ans = parse_expr(str)
    if (facN == fac_ans):
        return '5'
    facTop = parse_expr('factorial('+problem.vars['n']+'+'+problem.vars['k']+'-1)')
    if(facTop == fac_ans):
        return '4'
    else:
        return '-1'
开发者ID:SoukainaChrifiAlaoui,项目名称:Capstone_IDTS,代码行数:11,代码来源:Evaluator.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python beam.Beam类代码示例发布时间:2022-05-27
下一篇:
Python oo.evalf函数代码示例发布时间: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