def to_atset(value):
"""Convert an attribute value to AtSet object."""
if isinstance(value, str):
symset = safe_sympify(value)
# check that there are no symbols
return AtSet(convert(AtSymSet(symset)), AtEmptySet())
elif isinstance(value, list) or isinstance(value, set):
str_vals = []
num_vals = []
for val in value:
if test_number(val):
num_vals.append(val)
else:
str_vals.append(val)
res = AtSet(convert(AtFinSet(set(sympify(num_vals)))),
convert(AtPosStringSet(set(str_vals))))
return res
elif isinstance(value, dict):
return AtSet.from_json(value)
elif isinstance(value, AtSet):
return value
else:
raise ReGraphError("value {} should be a list, set, string or dict "
"representation of AtSet".format(value))
python类sympify()的实例源码
def tangent_vector_f(f, helpers, n, n_lyap, delays, zero_padding=0, simplify=True):
if f:
def f_lyap():
yield from f()
for i in range(n_lyap):
jacs = [_jac(f, helpers, delay, n) for delay in delays]
for _ in range(n):
expression = 0
for delay,jac in zip(delays,jacs):
for k,entry in enumerate(next(jac)):
expression += entry * y(k+(i+1)*n,t-delay)
if simplify:
expression = expression.simplify(ratio=1.0)
yield expression
for _ in range(zero_padding):
yield symengine.sympify(0)
else:
return []
return f_lyap
def __init__(
self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
**kwargs):
super(ParametricSurfaceSeries, self).__init__()
self.expr_x = sympify(expr_x)
self.expr_y = sympify(expr_y)
self.expr_z = sympify(expr_z)
self.var_u = sympify(var_start_end_u[0])
self.start_u = float(var_start_end_u[1])
self.end_u = float(var_start_end_u[2])
self.var_v = sympify(var_start_end_v[0])
self.start_v = float(var_start_end_v[1])
self.end_v = float(var_start_end_v[2])
self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
self.surface_color = kwargs.get('surface_color', None)
def __init__(self, expr, var_start_end_x, var_start_end_y,
has_equality, use_interval_math, depth, nb_of_points):
super(ImplicitSeries, self).__init__()
self.expr = sympify(expr)
self.var_x = sympify(var_start_end_x[0])
self.start_x = float(var_start_end_x[1])
self.end_x = float(var_start_end_x[2])
self.var_y = sympify(var_start_end_y[0])
self.start_y = float(var_start_end_y[1])
self.end_y = float(var_start_end_y[2])
self.get_points = self.get_raster
self.has_equality = has_equality # If the expression has equality, i.e.
#Eq, Greaterthan, LessThan.
self.nb_of_points = nb_of_points
self.use_interval_math = use_interval_math
self.depth = 4 + depth
def eval(cls, args):
new_args = args[0], sympify(args[1])
exp = new_args[1]
#simplify hs**1 -> hs
if exp == 1:
return args[0]
#simplify hs**0 -> 1
if exp == 0:
return sympify(1)
#check (and allow) for hs**(x+42+y...) case
if len(exp.atoms()) == 1:
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
raise ValueError('Hilbert spaces can only be raised to \
positive integers or Symbols: %r' % exp)
else:
for power in exp.atoms():
if not (power.is_Integer or power.is_Symbol):
raise ValueError('Tensor powers can only contain integers \
or Symbols: %r' % power)
return new_args
def set_potential_energy(self, scalar):
"""Used to set the potential energy of the Particle.
Parameters
==========
scalar : Sympifyable
The potential energy (a scalar) of the Particle.
Examples
========
>>> from sympy.physics.mechanics import Particle, Point
>>> from sympy import symbols
>>> m, g, h = symbols('m g h')
>>> O = Point('O')
>>> P = Particle('P', O, m)
>>> P.set_potential_energy(m * g * h)
"""
self._pe = sympify(scalar)
def __mul__(self, other):
"""Multiplies the Dyadic by a sympifyable expression.
Parameters
==========
other : Sympafiable
The scalar to multiply this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> 5 * d
5*(N.x|N.x)
"""
newlist = [v for v in self.args]
for i, v in enumerate(newlist):
newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1],
newlist[i][2])
return Dyadic(newlist)
def print_mathml(expr, **settings):
"""
Prints a pretty representation of the MathML code for expr
Examples
========
>>> ##
>>> from sympy.printing.mathml import print_mathml
>>> from sympy.abc import x
>>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE
<apply>
<plus/>
<ci>x</ci>
<cn>1</cn>
</apply>
"""
s = MathMLPrinter(settings)
xml = s._print(sympify(expr))
s.apply_patch()
pretty_xml = xml.toprettyxml()
s.restore_patch()
print(pretty_xml)
def test_function_series1():
"""Create our new "sin" function."""
class my_function(Function):
def fdiff(self, argindex=1):
return cos(self.args[0])
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg == 0:
return sympify(0)
#Test that the taylor series is correct
assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
assert limit(my_function(x)/x, x, 0) == 1
def test_function_series2():
"""Create our new "cos" function."""
class my_function2(Function):
def fdiff(self, argindex=1):
return -sin(self.args[0])
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg == 0:
return sympify(1)
#Test that the taylor series is correct
assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
def test_function_series3():
"""
Test our easy "tanh" function.
This test tests two things:
* that the Function interface works as expected and it's easy to use
* that the general algorithm for the series expansion works even when the
derivative is defined recursively in terms of the original function,
since tanh(x).diff(x) == 1-tanh(x)**2
"""
class mytanh(Function):
def fdiff(self, argindex=1):
return 1 - mytanh(self.args[0])**2
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg == 0:
return sympify(0)
e = tanh(x)
f = mytanh(x)
assert tanh(x).series(x, 0, 6) == mytanh(x).series(x, 0, 6)
def parse_maxima(str, globals=None, name_dict={}):
str = str.strip()
str = str.rstrip('; ')
for k, v in sub_dict.items():
str = v.sub(k, str)
assign_var = None
var_match = var_name.search(str)
if var_match:
assign_var = var_match.group(1)
str = str[var_match.end():].strip()
dct = MaximaHelpers.__dict__.copy()
dct.update(name_dict)
obj = sympify(str, locals=dct)
if assign_var and globals:
globals[assign_var] = obj
return obj
def test_mathematica():
d = {'Sin[x]^2': 'sin(x)**2',
'2(x-1)': '2*(x-1)',
'3y+8': '3*y+8',
'Arcsin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
'x+y': 'x+y',
'355/113': '355/113',
'2.718281828': '2.718281828',
'Sin[12]': 'sin(12)',
'Exp[Log[4]]': 'exp(log(4))',
'(x+1)(x+3)': '(x+1)*(x+3)',
'Cos[Arccos[3.6]]': 'cos(acos(3.6))',
'Cos[x]==Sin[y]': 'cos(x)==sin(y)',
'2*Sin[x+y]': '2*sin(x+y)',
'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
'Sin[Cos[x]]': 'sin(cos(x))',
'2*Sqrt[x+y]': '2*sqrt(x+y)'} # Test case from the issue 4259
for e in d:
assert mathematica(e) == sympify(d[e])
def print_mexp(expr, protected_header_enabled=False, protected_header_prefix="X", **settings):
"""Print an expression to a MathML object.
:type protected_header_enabled: bool
:type protected_header_prefix: str
:param expr: The expression.
:param protected_header_enabled: Whether the protected headers are enabled.
:param protected_header_prefix: The prefix of the protected headers.
:param settings: The settings.
:rtype : bce.dom.mathml.all.Base
:return: The printed MathML object.
"""
# noinspection PyProtectedMember
return _MathMLPrinter(
settings,
protected_header_enabled=protected_header_enabled,
protected_header_prefix=protected_header_prefix
).doprint(_sympy.sympify(expr))
def leading_term(expr, *args):
"""
Returns the leading term in a sympy Polynomial.
expr: sympy.Expr
any sympy expression
args: list
list of input symbols for univariate/multivariate polynomials
"""
expr = sympify(str(expr))
P = Poly(expr, *args)
return LT(P)
# ...
# ...
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 __new__(cls, base, *args, **kw_args):
from sympy.utilities.misc import filldedent
from sympy.tensor.array.ndim_array import NDimArray
from sympy.matrices.matrices import MatrixBase
if not args:
raise IndexException("Indexed needs at least one index.")
if isinstance(base, (string_types, Symbol)):
base = IndexedBase(base)
elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase):
raise TypeError(filldedent("""
Indexed expects string, Symbol, or IndexedBase as base."""))
args = list(map(sympify, args))
if isinstance(base, (NDimArray, collections.Iterable, Tuple, MatrixBase)) and all([i.is_number for i in args]):
if len(args) == 1:
return base[args[0]]
else:
return base[args]
return Expr.__new__(cls, base, *args, **kw_args)
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 __init__(
self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
**kwargs):
super(ParametricSurfaceSeries, self).__init__()
self.expr_x = sympify(expr_x)
self.expr_y = sympify(expr_y)
self.expr_z = sympify(expr_z)
self.var_u = sympify(var_start_end_u[0])
self.start_u = float(var_start_end_u[1])
self.end_u = float(var_start_end_u[2])
self.var_v = sympify(var_start_end_v[0])
self.start_v = float(var_start_end_v[1])
self.end_v = float(var_start_end_v[2])
self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
self.surface_color = kwargs.get('surface_color', None)
def __init__(self, expr, var_start_end_x, var_start_end_y,
has_equality, use_interval_math, depth, nb_of_points,
line_color):
super(ImplicitSeries, self).__init__()
self.expr = sympify(expr)
self.var_x = sympify(var_start_end_x[0])
self.start_x = float(var_start_end_x[1])
self.end_x = float(var_start_end_x[2])
self.var_y = sympify(var_start_end_y[0])
self.start_y = float(var_start_end_y[1])
self.end_y = float(var_start_end_y[2])
self.get_points = self.get_raster
self.has_equality = has_equality # If the expression has equality, i.e.
#Eq, Greaterthan, LessThan.
self.nb_of_points = nb_of_points
self.use_interval_math = use_interval_math
self.depth = 4 + depth
self.line_color = line_color
def __new__(cls, name, symbol=None):
if isinstance(name, string_types):
name = Symbol(name)
else:
name = sympify(name)
if not isinstance(name, Expr):
raise TypeError("Dimension name needs to be a valid math expression")
if isinstance(symbol, string_types):
symbol = Symbol(symbol)
elif symbol is not None:
assert isinstance(symbol, Symbol)
if symbol is not None:
obj = Expr.__new__(cls, name, symbol)
else:
obj = Expr.__new__(cls, name)
obj._name = name
obj._symbol = symbol
return obj
def __new__(cls, name, permittivity=None, permeability=None, n=None):
obj = super(Medium, cls).__new__(cls, name)
obj._permittivity = sympify(permittivity)
obj._permeability = sympify(permeability)
obj._n = sympify(n)
if n is not None:
if permittivity != None and permeability == None:
obj._permeability = n**2/(c**2*obj._permittivity)
if permeability != None and permittivity == None:
obj._permittivity = n**2/(c**2*obj._permeability)
if permittivity != None and permittivity != None:
if abs(n - c*sqrt(obj._permittivity*obj._permeability)) > 1e-6:
raise ValueError("Values are not consistent.")
elif permittivity is not None and permeability is not None:
obj._n = c*sqrt(permittivity*permeability)
elif permittivity is None and permeability is None:
obj._permittivity = _e0mksa
obj._permeability = _u0mksa
return obj
def eval(cls, args):
new_args = args[0], sympify(args[1])
exp = new_args[1]
#simplify hs**1 -> hs
if exp == 1:
return args[0]
#simplify hs**0 -> 1
if exp == 0:
return sympify(1)
#check (and allow) for hs**(x+42+y...) case
if len(exp.atoms()) == 1:
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
raise ValueError('Hilbert spaces can only be raised to \
positive integers or Symbols: %r' % exp)
else:
for power in exp.atoms():
if not (power.is_Integer or power.is_Symbol):
raise ValueError('Tensor powers can only contain integers \
or Symbols: %r' % power)
return new_args
def test_function_series1():
"""Create our new "sin" function."""
class my_function(Function):
def fdiff(self, argindex=1):
return cos(self.args[0])
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg == 0:
return sympify(0)
#Test that the taylor series is correct
assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
assert limit(my_function(x)/x, x, 0) == 1
def test_function_series2():
"""Create our new "cos" function."""
class my_function2(Function):
def fdiff(self, argindex=1):
return -sin(self.args[0])
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg == 0:
return sympify(1)
#Test that the taylor series is correct
assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
def test_function_series3():
"""
Test our easy "tanh" function.
This test tests two things:
* that the Function interface works as expected and it's easy to use
* that the general algorithm for the series expansion works even when the
derivative is defined recursively in terms of the original function,
since tanh(x).diff(x) == 1-tanh(x)**2
"""
class mytanh(Function):
def fdiff(self, argindex=1):
return 1 - mytanh(self.args[0])**2
@classmethod
def eval(cls, arg):
arg = sympify(arg)
if arg == 0:
return sympify(0)
e = tanh(x)
f = mytanh(x)
assert tanh(x).series(x, 0, 6) == mytanh(x).series(x, 0, 6)
def sdm_from_vector(vec, O, K, **opts):
"""
Create an sdm from an iterable of expressions.
Coefficients are created in the ground field ``K``, and terms are ordered
according to monomial order ``O``. Named arguments are passed on to the
polys conversion code and can be used to specify for example generators.
Examples
========
>>> from sympy.polys.distributedmodules import sdm_from_vector
>>> from sympy.abc import x, y, z
>>> from sympy.polys import QQ, lex
>>> sdm_from_vector([x**2+y**2, 2*z], lex, QQ)
[((1, 0, 0, 1), 2), ((0, 2, 0, 0), 1), ((0, 0, 2, 0), 1)]
"""
dics, gens = parallel_dict_from_expr(sympify(vec), **opts)
dic = {}
for i, d in enumerate(dics):
for k, v in d.items():
dic[(i,) + k] = K.convert(v)
return sdm_from_dict(dic, O)
def bench_R8():
"right(x^2,0,5,10^4)"
def right(f, a, b, n):
a = sympify(a)
b = sympify(b)
n = sympify(n)
x = f.atoms(Symbol).pop()
Deltax = (b - a)/n
c = a
est = 0
for i in range(n):
c += Deltax
est += f.subs(x, c)
return est*Deltax
a = right(x**2, 0, 5, 10**4)
def test_mathematica():
d = {
'- 6x': '-6*x',
'Sin[x]^2': 'sin(x)**2',
'2(x-1)': '2*(x-1)',
'3y+8': '3*y+8',
'Arcsin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x',
'x+y': 'x+y',
'355/113': '355/113',
'2.718281828': '2.718281828',
'Sin[12]': 'sin(12)',
'Exp[Log[4]]': 'exp(log(4))',
'(x+1)(x+3)': '(x+1)*(x+3)',
'Cos[Arccos[3.6]]': 'cos(acos(3.6))',
'Cos[x]==Sin[y]': 'cos(x)==sin(y)',
'2*Sin[x+y]': '2*sin(x+y)',
'Sin[x]+Cos[y]': 'sin(x)+cos(y)',
'Sin[Cos[x]]': 'sin(cos(x))',
'2*Sqrt[x+y]': '2*sqrt(x+y)'} # Test case from the issue 4259
for e in d:
assert mathematica(e) == sympify(d[e])
def to_atset(value):
"""Convert an attribute value to AtSet object."""
if isinstance(value, str):
symset = safe_sympify(value)
# check that there are no symbols
return AtSet(convert(AtSymSet(symset)), AtEmptySet())
elif isinstance(value, list) or isinstance(value, set):
str_vals = []
num_vals = []
for val in value:
if test_number(val):
num_vals.append(val)
else:
str_vals.append(val)
res = AtSet(convert(AtFinSet(set(sympify(num_vals)))),
convert(AtPosStringSet(set(str_vals))))
return res
elif isinstance(value, dict):
return AtSet.from_json(value)
elif isinstance(value, AtSet):
return value
else:
raise ReGraphError("value {} should be a list, set, string or dict "
"representation of AtSet".format(value))