本文整理汇总了Python中sympy.printing.lambdarepr.lambdarepr函数的典型用法代码示例。如果您正苦于以下问题:Python lambdarepr函数的具体用法?Python lambdarepr怎么用?Python lambdarepr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了lambdarepr函数的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_matrix
def test_matrix():
A = Matrix([[x, y], [y*x, z**2]])
assert lambdarepr(A) == "ImmutableDenseMatrix([[x, y], [x*y, z**2]])"
# Test printing a Matrix that has an element that is printed differently
# with the LambdaPrinter than in the StrPrinter.
p = Piecewise((x, True), evaluate=False)
A = Matrix([p])
assert lambdarepr(A) == "ImmutableDenseMatrix([[((x) if (True) else None)]])"
开发者ID:baoqchau,项目名称:sympy,代码行数:9,代码来源:test_lambdarepr.py
示例2: lambdastr
def lambdastr(args, expr):
"""
Returns a string that can be evaluated to a lambda function.
>>> from sympy import symbols
>>> x,y,z = symbols('xyz')
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
"""
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
# Transform everything to strings.
expr = lambdarepr(expr)
if isinstance(args, str):
pass
elif hasattr(args, "__iter__"):
args = ",".join(str(a) for a in args)
else:
args = str(args)
return "lambda %s: (%s)" % (args, expr)
开发者ID:cran,项目名称:rSymPy,代码行数:25,代码来源:lambdify.py
示例3: test_piecewise
def test_piecewise():
p = Piecewise(
(x, x < 1),
(x**2, Interval(3, 4, True, False)),
(0, True)
)
assert lambdarepr(p) == 'iff(x < 1,x,iff(((x <= 4) and (3 < x)),x**2,iff(True,0,0)))'
开发者ID:Aang,项目名称:sympy,代码行数:7,代码来源:test_lambdarepr.py
示例4: lambdarepr
def lambdarepr(self):
"""
"""
from sympy.printing.lambdarepr import lambdarepr
temp_arr=numpy.empty(self.getShape(), dtype=object)
for idx,el in numpy.ndenumerate(self._arr):
atoms=el.atoms(sympy.Symbol) if isinstance(el,sympy.Basic) else []
# create a dictionary to convert names like [x]_0_0 to x[0,0]
symdict={}
for a in atoms:
n,c=Symbol._symComp(a)
if len(c)>0:
c=[str(i) for i in c]
symstr=n+'['+','.join(c)+']'
else:
symstr=n
symdict[a.name]=symstr
s=lambdarepr(el)
for key in symdict:
s=s.replace(key, symdict[key])
temp_arr[idx]=s
if self.getRank()==0:
return temp_arr.item()
else:
return 'combineData(%s,%s)'%(str(temp_arr.tolist()).replace("'",""),str(self.getShape()))
开发者ID:svn2github,项目名称:Escript,代码行数:25,代码来源:symbol.py
示例5: lambdastr
def lambdastr(args, expr, printer=None):
"""
Returns a string that can be evaluated to a lambda function.
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
"""
if printer is not None:
if inspect.isfunction(printer):
lambdarepr = printer
else:
if inspect.isclass(printer):
lambdarepr = lambda expr: printer().doprint(expr)
else:
lambdarepr = lambda expr: printer.doprint(expr)
else:
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
# Transform everything to strings.
expr = lambdarepr(expr)
if isinstance(args, str):
pass
elif hasattr(args, "__iter__"):
args = ",".join(str(a) for a in args)
else:
args = str(args)
return "lambda %s: (%s)" % (args, expr)
开发者ID:Ingwar,项目名称:sympy,代码行数:34,代码来源:lambdify.py
示例6: test_multiple_sums
def test_multiple_sums():
s = Sum(i * x + j, (i, a, b), (j, c, d))
l = lambdarepr(s)
assert l == "(builtins.sum(i*x + j for i in range(a, b+1) for j in range(c, d+1)))"
assert (lambdify((x, a, b, c, d), s)(2, 3, 4, 5, 6) ==
s.subs([(x, 2), (a, 3), (b, 4), (c, 5), (d, 6)]).doit())
开发者ID:A-turing-machine,项目名称:sympy,代码行数:8,代码来源:test_lambdarepr.py
示例7: test_sum__2
def test_sum__2():
s = Sum(i * x, (i, a, b))
l = lambdarepr(s)
assert l == "(builtins.sum(i*x for i in range(a, b+1)))"
args = x, a, b
f = lambdify(args, s)
v = 2, 3, 8
assert f(*v) == s.subs(zip(args, v)).doit()
开发者ID:baoqchau,项目名称:sympy,代码行数:9,代码来源:test_lambdarepr.py
示例8: test_piecewise
def test_piecewise():
# In each case, test eval() the lambdarepr() to make sure there are a
# correct number of parentheses. It will give a SyntaxError if there aren't.
h = "lambda x: "
p = Piecewise((x, True), evaluate=False)
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (True) else None)"
p = Piecewise((x, x < 0))
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (x < 0) else None)"
p = Piecewise((1, x < 1), (2, x < 2), (0, True))
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x < 1) else (((2) if (x < 2) else (((0) if (True) " "else None)))))"
p = Piecewise((1, x < 1), (2, x < 2))
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x < 1) else (((2) if (x < 2) else None)))"
p = Piecewise((x, x < 1), (x ** 2, Interval(3, 4, True, False)), (0, True))
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (x < 1) else (((x**2) if (((x <= 4) " "and (3 < x))) else (((0) if (True) else None)))))"
p = Piecewise((x ** 2, x < 0), (x, Interval(0, 1, False, True)), (2 - x, x >= 1), (0, True))
l = lambdarepr(p)
eval(h + l)
assert (
l == "((x**2) if (x < 0) else (((x) if (((x < 1) and (0 <= x))) "
"else (((-x + 2) if (1 <= x) else (((0) if (True) else None)))))))"
)
p = Piecewise((x ** 2, x < 0), (x, Interval(0, 1, False, True)), (2 - x, x >= 1))
l = lambdarepr(p)
eval(h + l)
assert (
l == "((x**2) if (x < 0) else (((x) if (((x < 1) and " "(0 <= x))) else (((-x + 2) if (1 <= x) else None)))))"
)
p = Piecewise((1, x < 1), (2, x < 2), (3, x < 3), (4, x < 4), (5, x < 5), (6, True))
l = lambdarepr(p)
eval(h + l)
assert (
l == "((1) if (x < 1) else (((2) if (x < 2) else (((3) if "
"(x < 3) else (((4) if (x < 4) else (((5) if (x < 5) else (((6) if "
"(True) else None)))))))))))"
)
开发者ID:hitej,项目名称:meta-core,代码行数:54,代码来源:test_lambdarepr.py
示例9: test_sum
def test_sum():
# In each case, test eval() the lambdarepr() to make sure that
# it evaluates to the same results as the symbolic expression
s = Sum(x ** i, (i, a, b))
l = lambdarepr(s)
assert l == "(builtins.sum(x**i for i in range(a, b+1)))"
assert (lambdify((x, a, b), s)(2, 3, 8) ==
s.subs([(x, 2), (a, 3), (b, 8)]).doit())
s = Sum(i * x, (i, a, b))
l = lambdarepr(s)
assert l == "(builtins.sum(i*x for i in range(a, b+1)))"
assert (lambdify((x, a, b), s)(2, 3, 8) ==
s.subs([(x, 2), (a, 3), (b, 8)]).doit())
开发者ID:A-turing-machine,项目名称:sympy,代码行数:19,代码来源:test_lambdarepr.py
示例10: test_sum__1
def test_sum__1():
# In each case, test eval() the lambdarepr() to make sure that
# it evaluates to the same results as the symbolic expression
s = Sum(x ** i, (i, a, b))
l = lambdarepr(s)
assert l == "(builtins.sum(x**i for i in range(a, b+1)))"
args = x, a, b
f = lambdify(args, s)
v = 2, 3, 8
assert f(*v) == s.subs(zip(args, v)).doit()
开发者ID:baoqchau,项目名称:sympy,代码行数:11,代码来源:test_lambdarepr.py
示例11: test_multiple_sums
def test_multiple_sums():
s = Sum(i * x + j, (i, a, b), (j, c, d))
l = lambdarepr(s)
assert l == "(builtins.sum(i*x + j for i in range(a, b+1) for j in range(c, d+1)))"
args = x, a, b, c, d
f = lambdify(args, s)
vals = 2, 3, 4, 5, 6
f_ref = s.subs(zip(args, vals)).doit()
f_res = f(*vals)
assert f_res == f_ref
开发者ID:baoqchau,项目名称:sympy,代码行数:12,代码来源:test_lambdarepr.py
示例12: callback_factory
def callback_factory(args, expr, module, use_numba=False):
if module == 'numpy':
from sympy.utilities.lambdify import NUMPY_TRANSLATIONS as TRANSLATIONS
from sympy.printing.lambdarepr import NumPyPrinter as Printer
def lambdarepr(_x):
return Printer().doprint(_x)
else:
from sympy.printing.lambdarepr import lambdarepr
if module == 'mpmath':
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS as TRANSLATIONS
elif module == 'sympy':
TRANSLATIONS = {}
else:
raise NotImplementedError("Lambdify does not yet support %s" % module)
mod = __import__(module)
from sympy import IndexedBase, Symbol
x = IndexedBase('x')
indices = [Symbol('..., %d' % i) for i in range(len(args))]
dummy_subs = dict(zip(args, [x[i] for i in indices]))
dummified = expr.xreplace(dummy_subs)
estr = lambdarepr(dummified)
namespace = mod.__dict__.copy()
# e.g. NumPyPrinter incomplete: https://github.com/sympy/sympy/issues/11023
# we need to read translations from lambdify
for k, v in TRANSLATIONS.items():
namespace[k] = namespace[v]
if module != 'mpmath':
namespace['Abs'] = abs
func = eval('lambda x: %s' % estr, namespace)
if use_numba:
from numba import njit
func = njit(func)
if module == 'numpy':
def wrapper(x):
return func(mod.asarray(x, dtype=mod.float64))
else:
wrapper = func
wrapper.__doc__ = estr
return wrapper
开发者ID:bjodah,项目名称:sym,代码行数:46,代码来源:_sympy_Lambdify.py
示例13: lambdastr
def lambdastr(args, expr, printer=None, dummify=False):
"""
Returns a string that can be evaluated to a lambda function.
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
"""
# Transforming everything to strings.
from sympy.matrices import DeferredVector
from sympy import Dummy, sympify, Symbol, Function
if printer is not None:
if inspect.isfunction(printer):
lambdarepr = printer
else:
if inspect.isclass(printer):
lambdarepr = lambda expr: printer().doprint(expr)
else:
lambdarepr = lambda expr: printer.doprint(expr)
else:
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
def sub_args(args, dummies_dict):
if isinstance(args, str):
return args
elif isinstance(args, DeferredVector):
return str(args)
elif iterable(args):
flatten = lambda *n: (e for a in n for e in
(flatten(*a) if iterable(a) else (a,)))
dummies = flatten([sub_args(a, dummies_dict) for a in args])
return ",".join(str(a) for a in dummies)
else:
if isinstance(args, Function):
dummies = Dummy()
dummies_dict.update({args : dummies})
return str(dummies)
else:
return str(args)
def sub_expr(expr, dummies_dict):
try:
expr = sympify(expr).xreplace(dummies_dict)
except:
if isinstance(expr, DeferredVector):
pass
elif isinstance(expr, dict):
k = [sub_expr(sympify(a), dummies_dict) for a in expr.keys()]
v = [sub_expr(sympify(a), dummies_dict) for a in expr.values()]
expr = dict(zip(k, v))
elif isinstance(expr, tuple):
expr = tuple(sub_expr(sympify(a), dummies_dict) for a in expr)
elif isinstance(expr, list):
expr = [sub_expr(sympify(a), dummies_dict) for a in expr]
return expr
# Transform args
dummies_dict = {}
if dummify:
args = sub_args(args, dummies_dict)
else:
if isinstance(args, str):
pass
elif iterable(args, exclude=DeferredVector):
args = ",".join(str(a) for a in args)
# Transform expr
if dummify:
if isinstance(expr, str):
pass
else:
expr = sub_expr(expr, dummies_dict)
expr = lambdarepr(expr)
return "lambda %s: (%s)" % (args, expr)
开发者ID:Frifon,项目名称:sympy,代码行数:81,代码来源:lambdify.py
示例14: test_basic
def test_basic():
assert lambdarepr(x*y) == "x*y"
assert lambdarepr(x + y) in ["y + x", "x + y"]
assert lambdarepr(x**y) == "x**y"
开发者ID:baoqchau,项目名称:sympy,代码行数:4,代码来源:test_lambdarepr.py
示例15: test_piecewise
def test_piecewise():
# In each case, test eval() the lambdarepr() to make sure there are a
# correct number of parentheses. It will give a SyntaxError if there aren't.
h = "lambda x: "
p = Piecewise((x, True), evaluate=False)
l = lambdarepr(p)
eval(h + l)
assert l == "((x))"
p = Piecewise((x, x < 0))
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (x < 0) else None)"
p = Piecewise(
(1, x < 1),
(2, x < 2),
(0, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x < 1) else (2) if (x < 2) else (0))"
p = Piecewise(
(1, x < 1),
(2, x < 2),
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x < 1) else (2) if (x < 2) else None)"
p = Piecewise(
(x, x < 1),
(x**2, Interval(3, 4, True, False).contains(x)),
(0, True),
)
l = lambdarepr(p)
eval(h + l)
assert l == "((x) if (x < 1) else (x**2) if (((x <= 4)) and ((x > 3))) else (0))"
p = Piecewise(
(x**2, x < 0),
(x, x < 1),
(2 - x, x >= 1),
(0, True), evaluate=False
)
l = lambdarepr(p)
eval(h + l)
assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
" else (-x + 2) if (x >= 1) else (0))"
p = Piecewise(
(x**2, x < 0),
(x, x < 1),
(2 - x, x >= 1), evaluate=False
)
l = lambdarepr(p)
eval(h + l)
assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
" else (-x + 2) if (x >= 1) else None)"
p = Piecewise(
(1, x >= 1),
(2, x >= 2),
(3, x >= 3),
(4, x >= 4),
(5, x >= 5),
(6, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x >= 1) else (2) if (x >= 2) else (3) if (x >= 3)"\
" else (4) if (x >= 4) else (5) if (x >= 5) else (6))"
p = Piecewise(
(1, x <= 1),
(2, x <= 2),
(3, x <= 3),
(4, x <= 4),
(5, x <= 5),
(6, True)
)
l = lambdarepr(p)
eval(h + l)
assert l == "((1) if (x <= 1) else (2) if (x <= 2) else (3) if (x <= 3)"\
" else (4) if (x <= 4) else (5) if (x <= 5) else (6))"
p = Piecewise(
(1, x > 1),
(2, x > 2),
(3, x > 3),
(4, x > 4),
(5, x > 5),
(6, True)
)
l = lambdarepr(p)
eval(h + l)
assert l =="((1) if (x > 1) else (2) if (x > 2) else (3) if (x > 3)"\
#.........这里部分代码省略.........
开发者ID:KonstantinTogoi,项目名称:sympy,代码行数:101,代码来源:test_lambdarepr.py
示例16: lambdastr
def lambdastr(args, expr, printer=None, dummify=None):
"""
Returns a string that can be evaluated to a lambda function.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
Although tuples may not appear as arguments to lambda in Python 3,
lambdastr will create a lambda function that will unpack the original
arguments so that nested arguments can be handled:
>>> lambdastr((x, (y, z)), x + y)
'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])'
"""
# Transforming everything to strings.
from sympy.matrices import DeferredVector
from sympy import Dummy, sympify, Symbol, Function, flatten, Derivative, Basic
if printer is not None:
if inspect.isfunction(printer):
lambdarepr = printer
else:
if inspect.isclass(printer):
lambdarepr = lambda expr: printer().doprint(expr)
else:
lambdarepr = lambda expr: printer.doprint(expr)
else:
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
def sub_args(args, dummies_dict):
if isinstance(args, str):
return args
elif isinstance(args, DeferredVector):
return str(args)
elif iterable(args):
dummies = flatten([sub_args(a, dummies_dict) for a in args])
return ",".join(str(a) for a in dummies)
else:
# replace these with Dummy symbols
if isinstance(args, (Function, Symbol, Derivative)):
dummies = Dummy()
dummies_dict.update({args : dummies})
return str(dummies)
else:
return str(args)
def sub_expr(expr, dummies_dict):
try:
expr = sympify(expr).xreplace(dummies_dict)
except Exception:
if isinstance(expr, DeferredVector):
pass
elif isinstance(expr, dict):
k = [sub_expr(sympify(a), dummies_dict) for a in expr.keys()]
v = [sub_expr(sympify(a), dummies_dict) for a in expr.values()]
expr = dict(zip(k, v))
elif isinstance(expr, tuple):
expr = tuple(sub_expr(sympify(a), dummies_dict) for a in expr)
elif isinstance(expr, list):
expr = [sub_expr(sympify(a), dummies_dict) for a in expr]
return expr
# Transform args
def isiter(l):
return iterable(l, exclude=(str, DeferredVector, NotIterable))
def flat_indexes(iterable):
n = 0
for el in iterable:
if isiter(el):
for ndeep in flat_indexes(el):
yield (n,) + ndeep
else:
yield (n,)
n += 1
if dummify is None:
dummify = any(isinstance(a, Basic) and
a.atoms(Function, Derivative) for a in (
args if isiter(args) else [args]))
if isiter(args) and any(isiter(i) for i in args):
dum_args = [str(Dummy(str(i))) for i in range(len(args))]
indexed_args = ','.join([
dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]])
for ind in flat_indexes(args)])
lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)
#.........这里部分代码省略.........
开发者ID:cmarqu,项目名称:sympy,代码行数:101,代码来源:lambdify.py
示例17: test_settings
def test_settings():
raises(TypeError, lambda: lambdarepr(sin(x), method="garbage"))
开发者ID:baoqchau,项目名称:sympy,代码行数:2,代码来源:test_lambdarepr.py
示例18: lambdastr
def lambdastr(args, expr, printer=None, dummify=False):
"""
Returns a string that can be evaluated to a lambda function.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'
Although tuples may not appear as arguments to lambda in Python 3,
lambdastr will create a lambda function that will unpack the original
arguments so that nested arguments can be handled:
>>> lambdastr((x, (y, z)), x + y)
'lambda _0,_1: (lambda x,y,z: (x + y))(*list(__flatten_args__([_0,_1])))'
"""
# Transforming everything to strings.
from sympy.matrices import DeferredVector
from sympy import Dummy, sympify, Symbol, Function, flatten
if printer is not None:
if inspect.isfunction(printer):
lambdarepr = printer
else:
if inspect.isclass(printer):
lambdarepr = lambda expr: printer().doprint(expr)
else:
lambdarepr = lambda expr: printer.doprint(expr)
else:
#XXX: This has to be done here because of circular imports
from sympy.printing.lambdarepr import lambdarepr
def sub_args(args, dummies_dict):
if isinstance(args, str):
return args
elif isinstance(args, DeferredVector):
return str(args)
elif iterable(args):
dummies = flatten([sub_args(a, dummies_dict) for a in args])
return ",".join(str(a) for a in dummies)
else:
#Sub in dummy variables for functions or symbols
if isinstance(args, (Function, Symbol)):
dummies = Dummy()
dummies_dict.update({args : dummies})
return str(dummies)
else:
return str(args)
def sub_expr(expr, dummies_dict):
try:
expr = sympify(expr).xreplace(dummies_dict)
except Exception:
if isinstance(expr, DeferredVector):
pass
elif isinstance(expr, dict):
k = [sub_expr(sympify(a), dummies_dict) for a in expr.keys()]
v = [sub_expr(sympify(a), dummies_dict) for a in expr.values()]
expr = dict(zip(k, v))
elif isinstance(expr, tuple):
expr = tuple(sub_expr(sympify(a), dummies_dict) for a in expr)
elif isinstance(expr, list):
expr = [sub_expr(sympify(a), dummies_dict) for a in expr]
return expr
# Transform args
def isiter(l):
return iterable(l, exclude=(str, DeferredVector))
if isiter(args) and any(isiter(i) for i in args):
from sympy.utilities.iterables import flatten
import re
dum_args = [str(Dummy(str(i))) for i in range(len(args))]
iter_args = ','.join([i if isiter(a) else i
for i, a in zip(dum_args, args)])
lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)
flat = '__flatten_args__'
rv = 'lambda %s: (%s)(*list(%s([%s])))' % (
','.join(dum_args), lstr, flat, iter_args)
if len(re.findall(r'\b%s\b' % flat, rv)) > 1:
raise ValueError('the name %s is reserved by lambdastr' % flat)
return rv
dummies_dict = {}
if dummify:
args = sub_args(args, dummies_dict)
else:
if isinstance(args, str):
pass
elif iterable(args, exclude=DeferredVector):
args = ",".join(str(a) for a in args)
# Transform expr
if dummify:
if isinstance(expr, str):
#.........这里部分代码省略.........
开发者ID:MCGallaspy,项目名称:sympy,代码行数:101,代码来源:lambdify.py
示例19: test_matrix
def test_matrix():
A = Matrix([[x,y],[y*x,z**2]])
assert lambdarepr(A)=="Matrix([[ x, y],[x*y, z**2]])"
开发者ID:StefenYin,项目名称:sympy,代码行数:3,代码来源:test_lambdarepr.py
注:本文中的sympy.printing.lambdarepr.lambdarepr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论