def test_function_exponentiation():
cases = {
'sin**2(x)': 'sin(x)**2',
'exp^y(z)': 'exp(z)^y',
'sin**2(E^(x))': 'sin(E^(x))**2'
}
transformations = standard_transformations + (convert_xor,)
transformations2 = transformations + (function_exponentiation,)
for case in cases:
implicit = parse_expr(case, transformations=transformations2)
normal = parse_expr(cases[case], transformations=transformations)
assert(implicit == normal)
other_implicit = ['x y', 'x sin x', '2x', 'sin x',
'cos 2*x', 'sin cos x']
for case in other_implicit:
raises(SyntaxError,
lambda: parse_expr(case, transformations=transformations2))
assert parse_expr('x**2', local_dict={ 'x': sympy.Symbol('x') },
transformations=transformations2) == parse_expr('x**2')
python类Symbol()的实例源码
test_implicit_multiplication_application.py 文件源码
项目:zippy
作者: securesystemslab
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def test_maxima_functions():
assert parse_maxima('expand( (x+1)^2)') == x**2 + 2*x + 1
assert parse_maxima('factor( x**2 + 2*x + 1)') == (x + 1)**2
assert parse_maxima('2*cos(x)^2 + sin(x)^2') == 2*cos(x)**2 + sin(x)**2
assert parse_maxima('trigexpand(sin(2*x)+cos(2*x))') == \
-1 + 2*cos(x)**2 + 2*cos(x)*sin(x)
assert parse_maxima('solve(x^2-4,x)') == [-2, 2]
assert parse_maxima('limit((1+1/x)^x,x,inf)') == E
assert parse_maxima('limit(sqrt(-x)/x,x,0,minus)') == -oo
assert parse_maxima('diff(x^x, x)') == x**x*(1 + log(x))
assert parse_maxima('sum(k, k, 1, n)', name_dict=dict(
n=Symbol('n', integer=True),
k=Symbol('k', integer=True)
)) == (n**2 + n)/2
assert parse_maxima('product(k, k, 1, n)', name_dict=dict(
n=Symbol('n', integer=True),
k=Symbol('k', integer=True)
)) == factorial(n)
assert parse_maxima('ratsimp((x^2-1)/(x+1))') == x - 1
assert Abs( parse_maxima(
'float(sec(%pi/3) + csc(%pi/3))') - 3.154700538379252) < 10**(-5)
def main():
a = sympy.Symbol('a')
b = sympy.Symbol('b')
e = (a + 2*b)**5
print("\nExpression : ")
print()
pprint(e)
print("\n\nDifferentiating w.r.t. a:")
print()
pprint(e.diff(a))
print("\n\nDifferentiating w.r.t. b:")
print()
pprint(e.diff(b))
print("\n\nSecond derivative of the above result w.r.t. a:")
print()
pprint(e.diff(b).diff(a, 2))
print("\n\nExpanding the above result:")
print()
pprint(e.expand().diff(b).diff(a, 2))
print()
def main():
x = Symbol("x")
a = Symbol("a")
h = Symbol("h")
show( limit(sqrt(x**2 - 5*x + 6) - x, x, oo), -Rational(5)/2 )
show( limit(x*(sqrt(x**2 + 1) - x), x, oo), Rational(1)/2 )
show( limit(x - sqrt3(x**3 - 1), x, oo), Rational(0) )
show( limit(log(1 + exp(x))/x, x, -oo), Rational(0) )
show( limit(log(1 + exp(x))/x, x, oo), Rational(1) )
show( limit(sin(3*x)/x, x, 0), Rational(3) )
show( limit(sin(5*x)/sin(2*x), x, 0), Rational(5)/2 )
show( limit(((x - 1)/(x + 1))**x, x, oo), exp(-2))
def main():
x = sympy.Symbol('x')
y = sympy.Symbol('y')
e = 1/sympy.cos(x)
print()
pprint(e)
print('\n')
pprint(e.subs(sympy.cos(x), y))
print('\n')
pprint(e.subs(sympy.cos(x), y).subs(y, x**2))
e = 1/sympy.log(x)
e = e.subs(x, sympy.Float("2.71828"))
print('\n')
pprint(e)
print('\n')
pprint(e.evalf())
print()
def state_update_equation(self, state_update_equation):
if state_update_equation is None:
if self.dim_state > 0:
state_update_equation = self.state
else:
state_update_equation = self.input
assert state_update_equation.atoms(sp.Symbol) <= set(
self.constants_values.keys()) | set([dynamicsymbols._t])
self._state_update_equation = state_update_equation
if self.dim_state:
assert find_dynamicsymbols(state_update_equation) <= \
set(self.state)
self.state_update_equation_function = self.code_generator(
[dynamicsymbols._t] + sp.flatten(self.state),
self._state_update_equation.subs(self.constants_values),
**self.code_generator_args
)
else:
assert find_dynamicsymbols(state_update_equation) <= \
set(self.input)
self.state_update_equation_function = self.code_generator(
[dynamicsymbols._t] + sp.flatten(self.input),
self._state_update_equation.subs(self.constants_values),
**self.code_generator_args
)
def event_variable_equation(self, event_variable_equation):
assert event_variable_equation.atoms(sp.Symbol) <= set(
self.constants_values.keys()) | set([dynamicsymbols._t])
self._event_variable_equation = event_variable_equation
if self.dim_state:
assert find_dynamicsymbols(event_variable_equation) <= \
set(self.state)
self.event_variable_equation_function = self.code_generator(
[dynamicsymbols._t] + sp.flatten(self.state),
self._event_variable_equation.subs(self.constants_values),
**self.code_generator_args
)
else:
assert find_dynamicsymbols(event_variable_equation) <= \
set(self.input)
self.event_variable_equation_function = self.code_generator(
[dynamicsymbols._t] + sp.flatten(self.input),
self._event_variable_equation.subs(self.constants_values),
**self.code_generator_args
)
def state_equation(self, state_equation):
if state_equation is None: # or other checks?
state_equation = empty_array()
else:
assert len(state_equation) == len(self.state)
assert find_dynamicsymbols(state_equation) <= (
set(self.state) | set(self.input)
)
assert state_equation.atoms(sp.Symbol) <= (
set(self.constants_values.keys())
| set([dynamicsymbols._t])
)
self._state_equation = state_equation
self.update_state_equation_function()
self.state_jacobian_equation = grad(self.state_equation, self.state)
self.update_state_jacobian_function()
self.input_jacobian_equation = grad(self.state_equation, self.input)
self.update_input_jacobian_function()
def output_equation(self, output_equation):
if isinstance(output_equation, sp.Expr):
output_equation = Array([output_equation])
if output_equation is None and self.dim_state == 0:
output_equation = empty_array()
else:
if output_equation is None:
output_equation = self.state
assert output_equation.atoms(sp.Symbol) <= (
set(self.constants_values.keys())
| set([dynamicsymbols._t])
)
if self.dim_state:
assert find_dynamicsymbols(output_equation) <= set(self.state)
else:
assert find_dynamicsymbols(output_equation) <= set(self.input)
self.dim_output = len(output_equation)
self._output_equation = output_equation
self.update_output_equation_function()
def _print_Symbol(self, sym):
"""Print a Symbol object.
:param sym: The expression.
:rtype : bce.dom.mathml.all.Base
:return: The printed MathML object.
"""
assert isinstance(sym, _sympy.Symbol)
if self.__ph_enabled and sym.name.startswith(self.__ph_prefix):
return _mathml.SubComponent(
_mathml.TextComponent(self.__ph_prefix.lower()),
_mathml.TextComponent(sym.name[len(self.__ph_prefix):])
)
else:
return _mathml.TextComponent(sym.name)
def free_parameters(expr):
"""
Returns the free parameters of a given expression. In general, this
corresponds to length of a For loop.
expr: sympy.Expr
any sympy expression or pyccel.ast.core object
"""
args = []
if isinstance(expr, For):
b = expr.iterable.args[0]
e = expr.iterable.args[1]
if isinstance(b, Symbol):
args.append(str(b))
if isinstance(e, Symbol):
args.append(str(e))
for i in expr.body:
args += free_parameters(i)
args = set(args)
args = list(args)
return args
# ...
# ...
def do_arg(a):
if isinstance(a, str):
arg = Symbol(a, integer=True)
elif isinstance(a, (Integer, Float)):
arg = a
elif isinstance(a, ArithmeticExpression):
arg = a.expr
if isinstance(arg, (Symbol, Variable)):
arg = Symbol(arg.name, integer=True)
else:
arg = convert_to_integer_expression(arg)
else:
raise Exception('Wrong instance in do_arg')
return arg
# ...
# ... TODO improve. this version is not working with function calls
def expr(self):
args = sp_symbols(self.args)
# ... we update the namespace
ls = args
if isinstance(args, Symbol):
ls = [args]
for i in ls:
namespace[str(i)] = i
# ...
# ... we do it here after the namespace has been updated
e = self.rhs.expr
# ...
# ... we clean the namespace
for i in ls:
namespace.pop(str(i))
# ...
return Lambda(args, e)
def expr(self):
"""
Process a Trailer by returning the approriate objects from
pyccel.ast.core
"""
self.update()
args = []
for a in self.args:
if isinstance(a, ArithmeticExpression):
arg = do_arg(a)
# TODO treat n correctly
n = Symbol('n', integer=True)
i = Idx(arg, n)
args.append(i)
elif isinstance(a, BasicSlice):
arg = a.expr
args.append(arg)
else:
raise Exception('Wrong instance')
return args
def __new__(cls, lhs, rhs, strict=False, status=None, like=None):
cls._strict = strict
if strict:
lhs = sympify(lhs)
rhs = sympify(rhs)
# Tuple of things that can be on the lhs of an assignment
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Idx)
#if not isinstance(lhs, assignable):
# raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
# Indexed types implement shape, but don't define it until later. This
# causes issues in assignment validation. For now, matrices are defined
# as anything with a shape that is not an Indexed
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
# If lhs and rhs have same structure, then this assignment is ok
if lhs_is_mat:
if not rhs_is_mat:
raise ValueError("Cannot assign a scalar to a matrix.")
elif lhs.shape != rhs.shape:
raise ValueError("Dimensions of lhs and rhs don't align.")
elif rhs_is_mat and not lhs_is_mat:
raise ValueError("Cannot assign a matrix to a scalar.")
return Basic.__new__(cls, lhs, rhs, status, like)
def wiener_attack(e, n):
pq = partial_quotiens(e, n)
c = convergents(pq)
x = Symbol('x')
print 'done'
for (k, d) in c:
if d != 196176397553781094149364022413702698618416570027142099596910222792686220199799634430113040703408219640551905602804050764120518037301734891772260502596755642106767631991390703026953707346708504142195119698789998222566587930259938572562702895638995035040020739921966671123993267592460124879940448923:
continue
if k != 0:
y = n - phiN(e, d, k) + 1
roots = solve(x**2 - y*x + n, x)
if len(roots) == 2:
p = roots[0]
q = roots[1]
if p * q == n:
break
return p, q
def __init__(self, n, e):
self.d = None
self.p = None
self.q = None
sys.setrecursionlimit(100000)
frac = self.rational_to_contfrac(e, n)
convergents = self.convergents_from_contfrac(frac)
for (k,d) in convergents:
if k!=0 and (e*d-1)%k == 0:
phi = (e*d-1)//k
s = n - phi + 1
discr = s*s - 4*n
if(discr>=0):
t = self.is_perfect_square(discr)
if t!=-1 and (s+t)%2==0:
self.d = d
x = Symbol('x')
roots = solve(x**2 - s*x + n, x)
if len(roots) == 2:
self.p = roots[0]
self.q = roots[1]
break
def __init__(self, n, e):
self.p = None
self.q = None
pq = self.partial_quotiens(e, n)
c = self.convergents(pq)
x = Symbol('x')
for (k, d) in c:
if k != 0:
y = n - self.phiN(e, d, k) + 1
roots = solve(x**2 - y*x + n, x)
if len(roots) == 2:
p = roots[0]
q = roots[1]
if p * q == n:
self.p = p
self.q = q
break
def dof_unknowns(control_volume_dimensions):
unknown_list = []
for path in control_volume_dimensions:
for equation_key, equation_value in path.items():
for variable in sp.sympify(equation_value).atoms(sp.Symbol):
if variable not in unknown_list:
unknown_list.append(variable)
unknowns = len(unknown_list)
return unknowns
# This function uses the dof_unknowns, along with the setup matrix from the first function
# to determine how many degrees of freedom exist in a given control volume
def get_S95(b0, sigma):
S95 = sy.Symbol('S95', positive = True, real = True)
b = sy.Symbol('b', positive = True)
chi21 = sy.Symbol('chi21')
chi22 = sy.Symbol('chi22')
chi2 = 3.84
N = b0
replacements = [(b, (b0 - S95 - sigma**2)/2 + 1./2*((b0 - S95 - sigma**2)**2 + 4*(sigma**2*N - S95*sigma**2 + S95*b0))**0.5)]
replacements2 = [(S95, 0.)]
chi21 = -2*( N*sy.log(S95 + b) - (S95 + b) - ((b-b0)/sigma)**2)
chi21 = chi21.subs(replacements)
chi22 = chi21.subs(replacements2)
eq = chi2 - chi21 + chi22
S95_new = sy.nsolve(eq, S95, 1)
return float(S95_new)