本文整理汇总了Python中sympy.parsing.sympy_parser.parse_expr函数的典型用法代码示例。如果您正苦于以下问题:Python parse_expr函数的具体用法?Python parse_expr怎么用?Python parse_expr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_expr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
示例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))
示例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))
示例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
示例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)
示例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)
示例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)
示例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')])
示例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
示例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
示例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]
示例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)
示例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)
示例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)
示例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