本文整理匯總了Python中sympy.Function方法的典型用法代碼示例。如果您正苦於以下問題:Python sympy.Function方法的具體用法?Python sympy.Function怎麽用?Python sympy.Function使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類sympy
的用法示例。
在下文中一共展示了sympy.Function方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: testDiv
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def testDiv(self):
div = ops.Div(2, 3)
self.assertEqual(str(div), '2/3')
self.assertEqual(div.sympy(), sympy.Rational(2, 3))
div = ops.Div(2, sympy.Rational(4, 5))
self.assertEqual(str(div), '2/(4/5)')
self.assertEqual(div.sympy(), sympy.Rational(5, 2))
div = ops.Div(1, ops.Div(2, 3))
self.assertEqual(str(div), '1/(2/3)')
self.assertEqual(div.sympy(), sympy.Rational(3, 2))
div = ops.Div(ops.Div(2, 3), 4)
self.assertEqual(str(div), '(2/3)/4')
self.assertEqual(div.sympy(), sympy.Rational(1, 6))
div = ops.Div(2, ops.Mul(3, 4))
self.assertEqual(str(div), '2/(3*4)')
div = ops.Div(2, sympy.Function('f')(sympy.Symbol('x')))
self.assertEqual(str(div), '2/f(x)')
示例2: __init__
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def __init__(self, *function_entities):
"""Initialize a `FunctionHandle`.
Args:
*function_entities: List of function letters and `Entity`s representing
functions, to be composed.
"""
self._functions = []
for fn in function_entities:
if isinstance(fn, str):
functions = [sympy.Function(fn)]
else:
assert isinstance(fn, Entity)
assert isinstance(fn.handle, FunctionHandle)
functions = fn.handle.functions
self._functions += functions
示例3: test_conv10
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def test_conv10():
A = DenseMatrix(1, 4, [Integer(1), Integer(2), Integer(3), Integer(4)])
assert (A._sympy_() == sympy.Matrix(1, 4,
[sympy.Integer(1), sympy.Integer(2),
sympy.Integer(3), sympy.Integer(4)]))
B = DenseMatrix(4, 1, [Symbol("x"), Symbol("y"), Symbol("z"), Symbol("t")])
assert (B._sympy_() == sympy.Matrix(4, 1,
[sympy.Symbol("x"), sympy.Symbol("y"),
sympy.Symbol("z"), sympy.Symbol("t")])
)
C = DenseMatrix(2, 2,
[Integer(5), Symbol("x"),
function_symbol("f", Symbol("x")), 1 + I])
assert (C._sympy_() ==
sympy.Matrix([[5, sympy.Symbol("x")],
[sympy.Function("f")(sympy.Symbol("x")),
1 + sympy.I]]))
示例4: test_conv10b
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def test_conv10b():
A = sympy.Matrix([[sympy.Symbol("x"), sympy.Symbol("y")],
[sympy.Symbol("z"), sympy.Symbol("t")]])
assert sympify(A) == DenseMatrix(2, 2, [Symbol("x"), Symbol("y"),
Symbol("z"), Symbol("t")])
B = sympy.Matrix([[1, 2], [3, 4]])
assert sympify(B) == DenseMatrix(2, 2, [Integer(1), Integer(2), Integer(3),
Integer(4)])
C = sympy.Matrix([[7, sympy.Symbol("y")],
[sympy.Function("g")(sympy.Symbol("z")), 3 + 2*sympy.I]])
assert sympify(C) == DenseMatrix(2, 2, [Integer(7), Symbol("y"),
function_symbol("g",
Symbol("z")),
3 + 2*I])
示例5: test_conv11
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def test_conv11():
x = sympy.Symbol("x")
y = sympy.Symbol("y")
x1 = Symbol("x")
y1 = Symbol("y")
f = sympy.Function("f")
f1 = Function("f")
e1 = diff(f(2*x, y), x)
e2 = diff(f1(2*x1, y1), x1)
e3 = diff(f1(2*x1, y1), y1)
assert sympify(e1) == e2
assert sympify(e1) != e3
assert e2._sympy_() == e1
assert e3._sympy_() != e1
示例6: local_indices
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def local_indices(self):
"""
Tuple of slices representing the global indices that logically
belong to the calling MPI rank.
Notes
-----
Given a Function ``f(x, y)`` with shape ``(nx, ny)``, when *not* using
MPI this property will return ``(slice(0, nx-1), slice(0, ny-1))``. On
the other hand, when MPI is used, the local ranges depend on the domain
decomposition, which is carried by ``self.grid``.
"""
if self._distributor is None:
return tuple(slice(0, s) for s in self.shape)
else:
return tuple(self._distributor.glb_slices.get(d, slice(0, s))
for s, d in zip(self.shape, self.dimensions))
示例7: _arg_check
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def _arg_check(self, args, intervals):
"""
Check that ``args`` contains legal runtime values bound to ``self``.
Raises
------
InvalidArgument
If, given the runtime values ``args``, an out-of-bounds array
access would be performed, or if shape/dtype don't match with
self's shape/dtype.
"""
if self.name not in args:
raise InvalidArgument("No runtime value for `%s`" % self.name)
key = args[self.name]
if len(key.shape) != self.ndim:
raise InvalidArgument("Shape %s of runtime value `%s` does not match "
"dimensions %s" %
(key.shape, self.name, self.dimensions))
if key.dtype != self.dtype:
warning("Data type %s of runtime value `%s` does not match the "
"Function data type %s" % (key.dtype, self.name, self.dtype))
for i, s in zip(self.dimensions, key.shape):
i._arg_check(args, s, intervals[i])
示例8: __init_finalize__
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def __init_finalize__(self, *args, **kwargs):
super(SparseFunction, self).__init_finalize__(*args, **kwargs)
self.interpolator = LinearInterpolator(self)
# Set up sparse point coordinates
coordinates = kwargs.get('coordinates', kwargs.get('coordinates_data'))
if isinstance(coordinates, Function):
self._coordinates = coordinates
else:
dimensions = (self.indices[-1], Dimension(name='d'))
# Only retain the local data region
if coordinates is not None:
coordinates = np.array(coordinates)
self._coordinates = SubFunction(name='%s_coords' % self.name, parent=self,
dtype=self.dtype, dimensions=dimensions,
shape=(self.npoint, self.grid.dim),
space_order=0, initializer=coordinates,
distributor=self._distributor)
if self.npoint == 0:
# This is a corner case -- we might get here, for example, when
# running with MPI and some processes get 0-size arrays after
# domain decomposition. We "touch" the data anyway to avoid the
# case ``self._data is None``
self.coordinates.data
示例9: evaluate
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def evaluate(self):
# Average values if at a location not on the Function's grid
if self._is_on_grid:
return self
weight = 1.0
avg_list = [self]
is_averaged = False
for i, ir, d in zip(self.indices, self.indices_ref, self.dimensions):
off = (i - ir)/d.spacing
if not isinstance(off, sympy.Number) or int(off) == off:
pass
else:
weight *= 1/2
is_averaged = True
avg_list = [(a.xreplace({i: i - d.spacing/2}) +
a.xreplace({i: i + d.spacing/2})) for a in avg_list]
if not is_averaged:
return self
return weight * sum(avg_list)
示例10: as_tuple
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def as_tuple(item, type=None, length=None):
"""
Force item to a tuple.
Partly extracted from: https://github.com/OP2/PyOP2/.
"""
# Empty list if we get passed None
if item is None:
t = ()
elif isinstance(item, (str, sympy.Function)):
t = (item,)
else:
# Convert iterable to list...
try:
t = tuple(item)
# ... or create a list of a single item
except (TypeError, NotImplementedError):
t = (item,) * (length or 1)
if length and not len(t) == length:
raise ValueError("Tuple needs to be of length %d" % length)
if type and not all(isinstance(i, type) for i in t):
raise TypeError("Items need to be of type %s" % type)
return t
示例11: vars_as_functions
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def vars_as_functions(self):
"""
:return: Turn the keys of this model into
:class:`~sympy.core.function.Function`
objects. This is done recursively so the chain rule can be applied
correctly. This is done on the basis of `connectivity_mapping`.
Example: for ``{y: a * x, z: y**2 + a}`` this returns
``{y: y(x, a), z: z(y(x, a), a)}``.
"""
vars2functions = {}
key = lambda arg: [isinstance(arg, Parameter), str(arg)]
# Iterate over all symbols in this model in topological order, turning
# each one into a function object recursively.
for symbol in self.ordered_symbols:
if symbol in self.connectivity_mapping:
dependencies = self.connectivity_mapping[symbol]
# Replace the dependency by it's function if possible
dependencies = [vars2functions.get(dependency, dependency)
for dependency in dependencies]
# sort by vars first, then params, and alphabetically within
# each group
dependencies = sorted(dependencies, key=key)
vars2functions[symbol] = sympy.Function(symbol.name)(*dependencies)
return vars2functions
示例12: _is_simple
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def _is_simple(self):
"""Returns whether it's a simple number, rather than a division or neg."""
if isinstance(self._value, sympy.Symbol):
return True
elif (isinstance(self._value, int)
or isinstance(self._value, sympy.Integer)
or isinstance(self._value, display.Decimal)
or isinstance(self._value, np.int64)):
return self._value >= 0
elif isinstance(self._value, sympy.Rational):
return False
elif isinstance(self._value, sympy.Function):
return True
else:
raise ValueError('Unknown type {}'.format(type(self._value)))
示例13: _print_expint
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def _print_expint(self, e):
from sympy import Function
if e.args[0].is_Integer and self._use_unicode:
return self._print_Function(Function('E_%s' % e.args[0])(e.args[1]))
return self._print_Function(e)
示例14: python
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def python(expr, **settings):
"""Return Python interpretation of passed expression
(can be passed to the exec() function without any modifications)"""
printer = PythonPrinter(settings)
exprp = printer.doprint(expr)
result = ''
# Returning found symbols and functions
renamings = {}
for symbolname in printer.symbols:
newsymbolname = symbolname
# Escape symbol names that are reserved python keywords
if kw.iskeyword(newsymbolname):
while True:
newsymbolname += "_"
if (newsymbolname not in printer.symbols and
newsymbolname not in printer.functions):
renamings[sympy.Symbol(
symbolname)] = sympy.Symbol(newsymbolname)
break
result += newsymbolname + ' = Symbol(\'' + symbolname + '\')\n'
for functionname in printer.functions:
newfunctionname = functionname
# Escape function names that are reserved python keywords
if kw.iskeyword(newfunctionname):
while True:
newfunctionname += "_"
if (newfunctionname not in printer.symbols and
newfunctionname not in printer.functions):
renamings[sympy.Function(
functionname)] = sympy.Function(newfunctionname)
break
result += newfunctionname + ' = Function(\'' + functionname + '\')\n'
if not len(renamings) == 0:
exprp = expr.subs(renamings)
result += 'e = ' + printer._str(exprp)
return result
示例15: test_printmethod
# 需要導入模塊: import sympy [as 別名]
# 或者: from sympy import Function [as 別名]
def test_printmethod():
x = symbols('x')
class nint(Function):
def _fcode(self, printer):
return "nint(%s)" % printer._print(self.args[0])
assert fcode(nint(x)) == " nint(x)"