本文整理汇总了Python中sympy.Expr方法的典型用法代码示例。如果您正苦于以下问题:Python sympy.Expr方法的具体用法?Python sympy.Expr怎么用?Python sympy.Expr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sympy
的用法示例。
在下文中一共展示了sympy.Expr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sympy_to_grim
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def sympy_to_grim(expr, **kwargs):
import sympy
assert isinstance(expr, sympy.Expr)
if expr.is_Integer:
return Expr(int(expr))
if expr.is_Symbol:
return Expr(symbol_name=expr.name)
if expr is sympy.pi:
return Pi
if expr is sympy.E:
return ConstE
if expr is sympy.I:
return ConstI
if expr.is_Add:
args = [sympy_to_grim(x, **kwargs) for x in expr.args]
return Add(*args)
if expr.is_Mul:
args = [sympy_to_grim(x, **kwargs) for x in expr.args]
return Mul(*args)
if expr.is_Pow:
args = [sympy_to_grim(x, **kwargs) for x in expr.args]
b, e = args
return Pow(b, e)
raise NotImplementedError("converting %s to Grim", type(expr))
示例2: EvalExpr
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def EvalExpr(value_type, x):
"""Evaluates x with symbol_to_value_map within the current context.
Args:
value_type: the target value type (see VALUE_TYPE).
x: a sympy.Expr, an object, or a list/tuple of Exprs and objects.
Returns:
Evaluation result of 'x'.
"""
if isinstance(x, (list, tuple)):
return type(x)(EvalExpr(value_type, y) for y in x)
elif isinstance(x, sympy.Expr):
symbol_to_value_map = SymbolToValueMap.Get(value_type)
if not symbol_to_value_map:
return x
# In theory the below should be equivalent to:
# y = x.subs(symbol_to_value_map).
# In practice subs() doesn't work for when values are Tensors.
k, v = list(zip(*(list(symbol_to_value_map.items()))))
y = sympy.lambdify(k, x)(*v)
return y
else:
return x
示例3: basis_functions
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def basis_functions(d, x):
"""Symbolically evaluate the uniform B-spline basis functions.
Parameters
----------
d : int
The degree of the uniform B-spline.
x : sp.Symbol
Interpolation parameter.
Returns
-------
b : list of sp.Expr, len = d + 1
List of B-spline basis functions, where `b[i]` is the interpolating
expression over the unit interval.
"""
if d < 0:
raise ValueError('d < 0 (= {})'.format(d))
return [ib[1].subs({x : x + ib[0]}).expand()
for ib in enumerate(B(0, d + 1, x))][::-1]
# uniform_bspline_basis
示例4: canonical_shape
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def canonical_shape(shape):
""" Return shape as tuple of int or Symbol.
This utility function ensures the shape tuple
using a single integer type (to its best effort).
Args:
shape: tuple(int|long|np.int*|Symbol|SymbolExpr...)
"""
def try_cast(x):
try:
# In python2.7, long and int are different types.
# If we cast a long int whose value is out of the range of int,
# the result is still long, avoiding overflow:
#
# `type(2<<64) == long # true`
# `type(int(2<<64)) == long # true`
x = int(x)
except TypeError:
# ignore symbolic value (sm.Symbol or sm.Expr)
pass
return x
return tuple(try_cast(x) for x in shape)
示例5: __init__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def __init__(self, formula: str, expression: sp.Expr) -> None:
"""Parse the column name into a patsy term and replace any categorical variables in its SymPy expression with
the correct indicator variable symbols.
"""
self.expression = expression
self.names = {str(s) for s in expression.free_symbols}
# replace categorical variable symbols with their indicator counterparts
for factor in parse_terms(formula)[-1].factors:
name = factor.name()
base_symbol = CategoricalTreatment.parse_base_symbol(name)
if base_symbol is not None:
self.expression = self.expression.replace(base_symbol, CategoricalTreatment.parse_full_symbol(name))
# cache evaluated derivatives
self.derivatives: Dict[str, sp.Expr] = {}
示例6: output_equation
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
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()
示例7: __new__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def __new__(cls, lhs, rhs, params=None):
try:
rhs = Integer(rhs)
if rhs == 0:
raise ValueError("Cannot divide by 0")
elif rhs == 1:
return lhs
except TypeError:
# We must be sure the symbolic RHS is of type int
if not hasattr(rhs, 'dtype'):
raise ValueError("Symbolic RHS `%s` lacks dtype" % rhs)
if not issubclass(rhs.dtype, np.integer):
raise ValueError("Symbolic RHS `%s` must be of type `int`, found "
"`%s` instead" % (rhs, rhs.dtype))
obj = sympy.Expr.__new__(cls, lhs, rhs)
obj.lhs = lhs
obj.rhs = rhs
return obj
示例8: test_gaussian
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def test_gaussian():
"""
Make sure that symfit.distributions.Gaussians produces the expected
sympy expression.
"""
x0 = Parameter()
sig = Parameter(positive=True)
x = Variable()
new = sympy.exp(-(x - x0)**2/(2*sig**2))/sympy.sqrt((2*sympy.pi*sig**2))
assert isinstance(new, sympy.Expr)
g = Gaussian(x, x0, sig)
assert issubclass(g.__class__, sympy.Expr)
assert new == g
# A pdf should always integrate to 1 on its domain
assert sympy.integrate(g, (x, -sympy.oo, sympy.oo)) == 1
示例9: test_exp
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def test_exp():
"""
Make sure that symfit.distributions.Exp produces the expected
sympy expression.
"""
l = Parameter(positive=True)
x = Variable()
new = l * sympy.exp(- l * x)
assert isinstance(new, sympy.Expr)
e = Exp(x, l)
assert issubclass(e.__class__, sympy.Expr)
assert new == e
# A pdf should always integrate to 1 on its domain
assert sympy.integrate(e, (x, 0, sympy.oo)) == 1
示例10: Exp
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def Exp(x, l):
"""
.. math::
f(x) = l e^{- l x}
Exponential Distribution pdf.
:param x: free variable.
:param l: rate parameter.
:return: sympy.Expr for an Exponential Distribution pdf.
"""
return l * sympy.exp(- l * x)
# def Beta():
# sympy.stats.Beta()
示例11: __init__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def __init__(self, model):
"""
Initiate a Model from a dict::
a = Model({y: x**2})
Preferred way of initiating ``Model``, since now you know what the dependent variable is called.
:param model: dict of ``Expr``, where dependent variables are the keys.
"""
if not isinstance(model, Mapping):
try:
iter(model)
except TypeError:
# Model is still a scalar model
model = [model]
# TODO: this will break upon deprecating the auto-generation of
# names for Variables. At this time, a DummyVariable object
# should be introduced to fulfill the same role.
model = {Variable(): expr for expr in model}
self._init_from_dict(model)
示例12: sympify
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def sympify(expr: Union[str, Number, sympy.Expr, numpy.str_], **kwargs) -> sympy.Expr:
if isinstance(expr, numpy.str_):
# putting numpy.str_ in sympy.sympify behaves unexpected in version 1.1.1
# It seems to ignore the locals argument
expr = str(expr)
try:
return sympy.sympify(expr, **kwargs, locals=sympify_namespace)
except TypeError as err:
if True:#err.args[0] == "'Symbol' object is not subscriptable":
indexed_base = get_subscripted_symbols(expr)
return sympy.sympify(expr, **kwargs, locals={**{k: sympy.IndexedBase(k)
for k in indexed_base},
**sympify_namespace})
else:
raise
示例13: __init__
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def __init__(self, ex: Union[str, Number, sympy.Expr]) -> None:
"""Create an Expression object.
Receives the mathematical expression which shall be represented by the object as a string
which will be parsed using py_expression_eval. For available operators, functions and
constants see SymPy documentation
Args:
ex (string): The mathematical expression represented as a string
"""
super().__init__()
if isinstance(ex, sympy.Expr):
self._original_expression = str(ex)
self._sympified_expression = ex
else:
self._original_expression = ex
self._sympified_expression = sympify(ex)
self._variables = get_variables(self._sympified_expression)
示例14: grim_to_sympy
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def grim_to_sympy(expr, **kwargs):
import sympy
assert isinstance(expr, Expr)
if expr.is_integer():
return sympy.sympify(int(expr))
if expr.is_symbol():
if expr == Pi:
return sympy.pi
if expr == ConstI:
return sympy.I
if expr == ConstE:
return sympy.E
return sympy.Symbol(str(expr))
head = expr.head()
args = [grim_to_sympy(x, **kwargs) for x in expr.args()]
if head in (Pos, Parentheses, Brackets, Braces, AngleBrackets, Logic):
x, = args
return x
if expr.head() == Add:
return sympy.Add(*args)
if expr.head() == Mul:
return sympy.Mul(*args)
if expr.head() == Neg:
x, = args
return -x
if expr.head() == Sub:
a, b = args
return a - b
if expr.head() == Div:
p, q = args
return p / q
if expr.head() == Pow:
b, e = args
return b ** e
if expr.head() == Sqrt:
x, = args
return sympy.sqrt(x)
raise NotImplementedError("converting %s to SymPy", expr.head())
示例15: testGetSymbol
# 需要导入模块: import sympy [as 别名]
# 或者: from sympy import Expr [as 别名]
def testGetSymbol(self):
x = symbolic.Symbol('x')
self.assertIsInstance(x, sympy.Expr)