本文整理匯總了Python中sympy.lambdify方法的典型用法代碼示例。如果您正苦於以下問題:Python sympy.lambdify方法的具體用法?Python sympy.lambdify怎麽用?Python sympy.lambdify使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sympy
的用法示例。
在下文中一共展示了sympy.lambdify方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testSymbolicDims
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def testSymbolicDims(self):
p = builder.Base.Params()
b = p.Instantiate()
f1 = tshape.Shape(['kh', 'kw', 'idims', 'odims'])
kh, kw, idims, odims = f1
f2 = tshape.Shape([kh, kw, odims, odims])
p = b._Seq('test', b._Conv2D('conv', f1, (2, 2)),
b._Conv2D('conv', f2, (2, 2)), b._Bias('bias', odims))
inp = tshape.Shape(['b', 'h', 'w', idims])
b, h, w, _ = inp
meta = p.cls.FPropMeta(p, inp)
print('flops = ', meta.flops)
out = meta.out_shapes[0]
print('outputs = ', out)
# sympy.lambdify can help us to do faster numerical evaluation.
# Might be useful to build a "cost" model given a builder layer.
f = sympy.lambdify([b, h, w, kh, kw, idims, odims], meta.flops, 'numpy')
print('f.source = ', inspect.getsource(f))
self.assertEqual(f(8, 224, 224, 3, 3, 8, 32), 925646848)
self.assertEqual(f(8, 224, 224, 5, 5, 8, 32), 2569814016)
示例2: EvalExpr
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [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: get_equations
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def get_equations(self):
"""
:return: Functions to calculate A, B and f given state x and input u
"""
f = sp.zeros(3, 1)
x = sp.Matrix(sp.symbols('x y theta', real=True))
u = sp.Matrix(sp.symbols('v w', real=True))
f[0, 0] = u[0, 0] * sp.cos(x[2, 0])
f[1, 0] = u[0, 0] * sp.sin(x[2, 0])
f[2, 0] = u[1, 0]
f = sp.simplify(f)
A = sp.simplify(f.jacobian(x))
B = sp.simplify(f.jacobian(u))
f_func = sp.lambdify((x, u), f, 'numpy')
A_func = sp.lambdify((x, u), A, 'numpy')
B_func = sp.lambdify((x, u), B, 'numpy')
return f_func, A_func, B_func
示例4: get_equations
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def get_equations(self):
"""
:return: Functions to calculate A, B and f given state x and input u
"""
f = sp.zeros(6, 1)
x = sp.Matrix(sp.symbols('rx ry vx vy t w', real=True))
u = sp.Matrix(sp.symbols('gimbal T', real=True))
f[0, 0] = x[2, 0]
f[1, 0] = x[3, 0]
f[2, 0] = 1 / self.m * sp.sin(x[4, 0] + u[0, 0]) * u[1, 0]
f[3, 0] = 1 / self.m * (sp.cos(x[4, 0] + u[0, 0]) * u[1, 0] - self.m * self.g)
f[4, 0] = x[5, 0]
f[5, 0] = 1 / self.I * (-sp.sin(u[0, 0]) * u[1, 0] * self.r_T)
f = sp.simplify(f)
A = sp.simplify(f.jacobian(x))
B = sp.simplify(f.jacobian(u))
f_func = sp.lambdify((x, u), f, 'numpy')
A_func = sp.lambdify((x, u), A, 'numpy')
B_func = sp.lambdify((x, u), B, 'numpy')
return f_func, A_func, B_func
示例5: _is_non_decreasing
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def _is_non_decreasing(fn, q, bounds):
"""Verifies whether the function is non-decreasing within a range.
Args:
fn: Symbolic function of a single variable.
q: The name of f's variable.
bounds: Pair of (lower_bound, upper_bound) reals.
Returns:
True iff the function is non-decreasing in the range.
"""
diff_fn = sp.diff(fn, q) # Symbolically compute the derivative.
diff_fn_lambdified = sp.lambdify(
q,
diff_fn,
modules=[
"numpy", {
"erfc": scipy.special.erfc,
"erfcinv": scipy.special.erfcinv
}
])
r = scipy.optimize.minimize_scalar(
diff_fn_lambdified, bounds=bounds, method="bounded")
assert r.success, "Minimizer failed to converge."
return r.fun >= 0 # Check whether the derivative is non-negative.
示例6: test_more_than_255_args
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def test_more_than_255_args():
# SymPy's lambdify can handle at most 255 arguments
# this is a proof of concept that this limitation does
# not affect SymEngine's Lambdify class
n = 257
x = se.symarray('x', n)
p, q, r = 17, 42, 13
terms = [i*s for i, s in enumerate(x, p)]
exprs = [se.add(*terms), r + x[0], -99]
callback = se.Lambdify(x, exprs)
input_arr = np.arange(q, q + n*n).reshape((n, n))
out = callback(input_arr)
ref = np.empty((n, 3))
coeffs = np.arange(p, p + n, dtype=np.int64)
for i in range(n):
ref[i, 0] = coeffs.dot(np.arange(q + n*i, q + n*(i+1), dtype=np.int64))
ref[i, 1] = q + n*i + r
ref[:, 2] = -99
assert np.allclose(out, ref)
示例7: test_call_sim_with_args
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def test_call_sim_with_args():
a, a_unc, b, b_unc = 3.0, 0.1, 4.0, 0.1
c = f_hypotenuse(a, b)
m1 = PythagorasModel()
data = {'PythagorasData': {'a': a, 'b': b, 'a_unc': a_unc, 'b_unc': b_unc}}
m1.command('run', data=data)
assert m1.registries['outputs']['c'].m == c
assert m1.registries['outputs']['c'].u == UREG.cm
x, y = sympy.symbols('x, y')
z = sympy.sqrt(x * x + y * y)
fx = sympy.lambdify((x, y), z.diff(x))
fy = sympy.lambdify((x, y), z.diff(y))
dz = np.sqrt(fx(a, b) ** 2 * a_unc ** 2 + fy(a, b) ** 2 * b_unc ** 2)
c_unc = c * np.sqrt(m1.registries['outputs'].variance['c']['c'])
LOGGER.debug('uncertainty in c is %g', c_unc)
assert np.isclose(dz, c_unc.item())
c_unc = c * m1.registries['outputs'].uncertainty['c']['c'].to('fraction')
assert np.isclose(dz, c_unc.m.item())
return m1
示例8: vectors
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def vectors(self, mesh):
j, Sig = self.fcts()
f_jr = sympy.lambdify((r, t, z), j[0], 'numpy')
f_jt = sympy.lambdify((r, t, z), j[1], 'numpy')
f_jz = sympy.lambdify((r, t, z), j[2], 'numpy')
f_sig = sympy.lambdify((r, t, z), Sig[0], 'numpy')
jr = f_jr(mesh.gridFx[:, 0], mesh.gridFx[:, 1], mesh.gridFx[:, 2])
jt = f_jt(mesh.gridFy[:, 0], mesh.gridFy[:, 1], mesh.gridFy[:, 2])
jz = f_jz(mesh.gridFz[:, 0], mesh.gridFz[:, 1], mesh.gridFz[:, 2])
sig = f_sig(mesh.gridCC[:, 0], mesh.gridCC[:, 1], mesh.gridCC[:, 2])
return sig, np.r_[jr, jt, jz]
示例9: set_symbolic_to_numeric_method
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def set_symbolic_to_numeric_method(method):
'''
Sets the method that all RBF instances will use for converting sympy
expressions to numeric functions. This can be either "ufuncify" or
"lambdify". "ufuncify" will write and compile C code for a numpy universal
function, and "lambdify" will evaluate the sympy expression using
python-level numpy functions. Calling this function will cause all caches of
numeric functions to be cleared.
'''
global _SYMBOLIC_TO_NUMERIC_METHOD
if method not in {'lambdify', 'ufuncify'}:
raise ValueError(
'`method` must be either "lambdify" or "ufuncify"')
_SYMBOLIC_TO_NUMERIC_METHOD = method
clear_rbf_caches()
## Instantiate some common RBFs
#####################################################################
示例10: expression_lambda
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def expression_lambda(self) -> Callable:
if self._expression_lambda is None:
expression_lambda = sympy.lambdify(self.variables, self.underlying_expression,
[{'ceiling': ceiling}, 'numpy'])
@functools.wraps(expression_lambda)
def expression_wrapper(*args, **kwargs):
result = expression_lambda(*args, **kwargs)
if isinstance(result, sympy.NDimArray):
return numpy.array(result.tolist())
elif isinstance(result, list):
return numpy.array(result).reshape(self.underlying_expression.shape)
else:
return result.reshape(self.underlying_expression.shape)
self._expression_lambda = expression_wrapper
return self._expression_lambda
示例11: convert_to_function
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def convert_to_function(string: str, scale_by_k=False):
"""Using the sympy module, parse string input
into a mathematical expression.
Returns the original string, the latexified string,
the mathematical expression in terms of sympy symbols,
and a lambdified function
"""
string = string.replace("^", "**")
symbolic_function = parse_expr(string)
if scale_by_k:
latexstring = latex(symbolic_function*abc.k)
else:
latexstring = latex(symbolic_function)
lambda_function = lambdify(abc.x, symbolic_function,
modules=module_list)
string = string.replace('*', '')
latexstring = "$" + latexstring + "$"
return string, latexstring, \
symbolic_function, lambda_function
示例12: __init__
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def __init__(self, num_spherical, num_radial, cutoff=5.0,
envelope_exponent=5):
super(SphericalBasisLayer, self).__init__()
assert num_radial <= 64
self.num_spherical = num_spherical
self.num_radial = num_radial
self.cutoff = cutoff
self.envelope = Envelope(envelope_exponent)
bessel_forms = bessel_basis(num_spherical, num_radial)
sph_harm_forms = real_sph_harm(num_spherical)
self.sph_funcs = []
self.bessel_funcs = []
x, theta = sym.symbols('x theta')
modules = {'sin': torch.sin, 'cos': torch.cos}
for i in range(num_spherical):
if i == 0:
sph1 = sym.lambdify([theta], sph_harm_forms[i][0], modules)(0)
self.sph_funcs.append(lambda x: torch.zeros_like(x) + sph1)
else:
sph = sym.lambdify([theta], sph_harm_forms[i][0], modules)
self.sph_funcs.append(sph)
for j in range(num_radial):
bessel = sym.lambdify([x], bessel_forms[i][j], modules)
self.bessel_funcs.append(bessel)
示例13: _intensive_output
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def _intensive_output(self):
"""
:getter: Return vectorized symbolic intensive aggregate production.
:type: function
"""
if self.__intensive_output is None:
args = [k] + sym.symbols(list(self.params.keys()))
self.__intensive_output = sym.lambdify(args, self.intensive_output,
self._modules)
return self.__intensive_output
示例14: _mpk
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def _mpk(self):
"""
:getter: Return vectorized symbolic marginal product capital.
:type: function
"""
if self.__mpk is None:
args = [k] + sym.symbols(list(self.params.keys()))
self.__mpk = sym.lambdify(args, self.marginal_product_capital,
self._modules)
return self.__mpk
示例15: _numeric_jacobian
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import lambdify [as 別名]
def _numeric_jacobian(self):
"""
Vectorized, numpy-aware function defining the Jacobian matrix of
partial derivatives.
:getter: Return vectorized Jacobian matrix of partial derivatives.
:type: function
"""
if self.__numeric_jacobian is None:
self.__numeric_jacobian = sym.lambdify(self._symbolic_args,
self._symbolic_jacobian,
self._modules)
return self.__numeric_jacobian