本文整理汇总了Python中sympy.utilities.lambdify函数的典型用法代码示例。如果您正苦于以下问题:Python lambdify函数的具体用法?Python lambdify怎么用?Python lambdify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了lambdify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_transformation_function
def get_transformation_function(segments, fixed_endpoint=None, fixed_basepoint=None, use_dict=True):
if fixed_endpoint:
coordinate_labels = []
else:
coordinate_labels = ['x','y','z']
if fixed_basepoint:
inverse_coordinate_labels = []
else:
inverse_coordinate_labels = ['base_x','base_y','base_z']
trans_mat, inv_trans_mat, var_names = get_sympy_reduction(segments, fixed_endpoint, fixed_basepoint, coordinate_labels, inverse_coordinate_labels)
# Bake into a lambda func
base_func = lambdify(flatten((coordinate_labels, var_names)), trans_mat)
base_inv_func = lambdify(flatten((inverse_coordinate_labels, var_names)), inv_trans_mat)
if use_dict:
if fixed_endpoint:
func = lambda var_dict: base_func(*flatten([var_dict[var_name] for var_name in var_names])).A
else:
func = lambda coords, var_dict: base_func(*flatten((coords, [var_dict[var_name] for var_name in var_names]))).A
if fixed_basepoint:
inv_func = lambda var_dict: base_inv_func(*flatten([var_dict[var_name] for var_name in var_names])).A
else:
inv_func = lambda coords, var_dict: base_inv_func(*flatten((coords, [var_dict[var_name] for var_name in var_names]))).A
else:
if fixed_endpoint:
func = lambda var_vals: base_func(*flatten(var_vals)).A
else:
func = lambda coords, var_vals: base_func(*flatten((coords, var_vals))).A
if fixed_basepoint:
inv_func = lambda var_vals: base_inv_func(*flatten(var_vals)).A
else:
inv_func = lambda coords, var_vals: base_inv_func(*flatten((coords, var_vals))).A
return func, inv_func
示例2: eval_expr
def eval_expr(expr,variables,container,name):
vals={}
for k in container:
vals[k.name]=k.x
vals["S"+k.name]=k.Sx
#x = expr.evalf(subs=vals)
f=lambdify(tuple(vals.keys()),expr,"numpy")
x = f(**vals)
#little workaround
leer=sy.Symbol("leer")
f=0*leer
for k in variables:
f=f+ (sy.diff(expr,k))**2*sy.Symbol("S"+k.__str__())**2
f=sy.sqrt(f)
#print "Formel:"
#print ur"\begin*{equation}"
#print sy.latex(expr)
#print ur"\end{equation}"
#print "Fehler"
#print ur"\begin*{equation}"
#sy.pprint(f)
#print ur"\end{equation}"
gf = lambdify(tuple(vals.keys()),f,"numpy")
Sx = gf(**vals)
return (Groesse(name,x.dimensionality.string,x.magnitude,Sx.magnitude),expr,f)
示例3: _eval_evalf
def _eval_evalf(self, prec):
"""Evaluate this complex root to the given precision. """
with workprec(prec):
g = self.poly.gen
if not g.is_Symbol:
d = Dummy('x')
func = lambdify(d, self.expr.subs(g, d))
else:
func = lambdify(g, self.expr)
interval = self._get_interval()
if not self.is_real:
# For complex intervals, we need to keep refining until the
# imaginary interval is disjunct with other roots, that is,
# until both ends get refined.
ay = interval.ay
by = interval.by
while interval.ay == ay or interval.by == by:
interval = interval.refine()
while True:
if self.is_real:
x0 = mpf(str(interval.center))
else:
x0 = mpc(*map(str, interval.center))
try:
root = findroot(func, x0, verify=False)
# If the (real or complex) root is not in the 'interval',
# then keep refining the interval. This happens if findroot
# accidentally finds a different root outside of this
# interval because our initial estimate 'x0' was not close
# enough.
if self.is_real:
a = mpf(str(interval.a))
b = mpf(str(interval.b))
if a == b:
root = a
break
if not (a < root < b):
raise ValueError("Root not in the interval.")
else:
ax = mpf(str(interval.ax))
bx = mpf(str(interval.bx))
ay = mpf(str(interval.ay))
by = mpf(str(interval.by))
if ax == bx and ay == by:
root = ax + S.ImaginaryUnit*by
break
if not (ax < root.real < bx and ay < root.imag < by):
raise ValueError("Root not in the interval.")
except ValueError:
interval = interval.refine()
continue
else:
break
return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
示例4: accepted
def accepted(self):
expr = parse_expr(self.fEdit.text())
f = lambdify(x, expr)
df = lambdify(x, expr.diff(x))
N = 1
delta = float(self.deltaEdit.text())
x0 = float(self.xEdit.text())
x1 = x0-f(x0)/df(x0)
while not closeEnaught(x0, x1, delta):
x0 = x1
x1 = x0-f(x0)/df(x0)
N += 1
self.listWidget.addItem("x = " + str(x1) + ", N = " + str(N))
示例5: graphicalButtonClicked
def graphicalButtonClicked(self):
color1 = None
if self.f1colorBox.currentIndex() == 0:
color1 = 'r'
elif self.f1colorBox.currentIndex() == 1:
color1 = 'b'
elif self.f1colorBox.currentIndex() == 2:
color1 = 'g'
elif self.f1colorBox.currentIndex() == 3:
color1 = 'y'
elif self.f1colorBox.currentIndex() == 4:
color1 = 'm'
elif self.f1colorBox.currentIndex() == 5:
color1 = 'c'
color2 = None
if self.f2colorBox.currentIndex() == 0:
color2 = 'r'
elif self.f2colorBox.currentIndex() == 1:
color2 = 'b'
elif self.f2colorBox.currentIndex() == 2:
color2 = 'g'
elif self.f2colorBox.currentIndex() == 3:
color2 = 'y'
elif self.f2colorBox.currentIndex() == 4:
color2 = 'm'
elif self.f2colorBox.currentIndex() == 5:
color2 = 'c'
expr1 = parse_expr(self.f1Edit.text())
expr2 = parse_expr(self.f2Edit.text())
f1 = lambdify(x, expr1, 'numpy')
f2 = lambdify(x, expr2, 'numpy')
try:
minX = float(self.minxEdit.text())
maxX = float(self.maxxEdit.text())
except:
QMessageBox.warning(self, "Warning", "Min and max values error type.")
return
if minX <= maxX:
x1 = np.linspace(minX, maxX, (maxX-minX)*1000)
self.plotW.figure.clf()
self.plotW.plot(x1, f1(x1), color1)
self.plotW.plot(x1, f2(x1), color2)
else:
QMessageBox.warning(self, "Warning", "Min value must be smaller than max value")
示例6: SIMethod
def SIMethod(self):
self.x0 = float(self.x0EditSI.text())
self.eps = float(self.epsEditSI.text())
self.fexpr = parse_expr(self.fEditSI.text())
self.phiexpr = parse_expr(self.phiEditSI.text())
self.f = lambdify(x, self.fexpr)
self.phi = lambdify(x, self.phiexpr)
self.x1 = 0
self.N = 0
while True:
self.x1 = self.phi(self.x0)
self.N += 1
if closeEnaught(self.x1, self.x0, self.eps) or self.f(self.x1) == 0:
self.listWidget.addItem("x = "+str(self.x1)+", N = "+str(self.N))
break
self.x0 = self.x1
示例7: isolate
def isolate(alg, eps=None, fast=False):
"""Give a rational isolating interval for an algebraic number. """
alg = sympify(alg)
if alg.is_Rational:
return (alg, alg)
elif not ask(Q.real(alg)):
raise NotImplementedError(
"complex algebraic numbers are not supported")
func = lambdify((), alg, modules="mpmath", printer=IntervalPrinter())
poly = minpoly(alg, polys=True)
intervals = poly.intervals(sqf=True)
dps, done = mp.dps, False
try:
while not done:
alg = func()
for a, b in intervals:
if a <= alg.a and alg.b <= b:
done = True
break
else:
mp.dps *= 2
finally:
mp.dps = dps
if eps is not None:
a, b = poly.refine_root(a, b, eps=eps, fast=fast)
return (a, b)
示例8: _eval_evalf
def _eval_evalf(self, prec):
"""Evaluate this complex root to the given precision. """
_prec, mp.prec = mp.prec, prec
try:
func = lambdify(self.poly.gen, self.expr)
interval = self._get_interval()
refined = False
while True:
if self.is_real:
x0 = mpf(str(interval.center))
else:
x0 = mpc(*map(str, interval.center))
try:
root = findroot(func, x0)
except ValueError:
interval = interval.refine()
refined = True
continue
else:
if refined:
self._set_interval(interval)
break
finally:
mp.prec = _prec
return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
示例9: d2V_func
def d2V_func(lat, V, field_var):
"Calculate the masses of the fields in terms of the field values:"
field_list = lat.field_list
from sympy import diff, Symbol, var, simplify, sympify, S, evalf
from sympy.utilities import lambdify
from sympy.core.sympify import SympifyError
C_coeff = V.C_coeff
D_coeff = V.D_coeff
V_string = V.V
try:
d2V = diff(sympify(V_string),field_var,2)
except SympifyError:
print "Could not parse expression."
"Replacement list C_i->C_coeff[i], D_i->D_coeff[i]:"
rep_list = {}
for i in xrange(len(C_coeff)):
rep_list.update({'C'+str(i+1):C_coeff[i]})
for i in xrange(len(D_coeff)):
rep_list.update({'D'+str(i+1):D_coeff[i]})
d2V_func = lambdify(field_list,d2V.subs(rep_list))
return d2V_func
示例10: eval_rational
def eval_rational(self, tol):
"""
Return a Rational approximation to ``self`` with the tolerance ``tol``.
This method uses bisection, which is very robust and it will always
converge. The returned Rational instance will be at most 'tol' from the
exact root.
The following example first obtains Rational approximation to 1e-7
accuracy for all roots of the 4-th order Legendre polynomial, and then
evaluates it to 5 decimal digits (so all digits will be correct
including rounding):
>>> from sympy import S, legendre_poly, Symbol
>>> x = Symbol("x")
>>> p = legendre_poly(4, x, polys=True)
>>> roots = [r.eval_rational(S(1)/10**7) for r in p.real_roots()]
>>> roots = [str(r.n(5)) for r in roots]
>>> roots
['-0.86114', '-0.33998', '0.33998', '0.86114']
"""
if not self.is_real:
raise NotImplementedError(
"eval_rational() only works for real polynomials so far")
func = lambdify(self.poly.gen, self.expr)
interval = self._get_interval()
a = Rational(str(interval.a))
b = Rational(str(interval.b))
return bisect(func, a, b, tol)
示例11: f_min
def f_min(y,mi,mx,stp):
"""
y - form of analytical function
mi - plot and analyze in interval starting from this value
mx - plot and alalyze in interval ending with this value
stp- stepsize on the x axis. (with a little imagination it can be
considered as resolution
"""
fd=[];d={}
t=np.arange(mi,mx,stp)
ly=lambdify(x,y)
dy=y.diff()
ldy=lambdify(x,dy)
print 'Analitical function: ',y
print 'first derivative: ',dy
for i in np.arange(mi,mx,stp):
# searhing where the first derivative is zero OR NEAR ZERO!
# /technically the same way can be done with lambdify
if -0.01 < dy.subs(x,i).evalf() < 0.01:
yy=y.subs(x,i).evalf()
print 'local extreme at (x,y): (%s, %s)' %(i,yy)
d[yy]=i
ix=max(d.keys())
ixmin=min(d.keys())
iy=d.get(ix)
iymin=d.get(ixmin)
print ' '
print 'Global minimum at (x,y): (%s, %s) ' %(iymin,ixmin)
print 'Global maximum at (x,y): (%s, %s) ' %(iy,ix)
plt.figure('minimi')
o1=[];o2=[]
for ii in np.arange(mi,mx,stp):
o1.append(ly(ii))
o2.append(ldy(ii)) # the plot option below
# plt.plot(t,ly(np.arange(mi,mx,stp)))
plt.plot(t,o1)
# plt.plot(t,ldy(np.arange(mi,mx,stp)))
plt.plot(t,o2)
plt.plot(iy,ix,'ro',iymin,ixmin,'bo')
plt.legend(['y= %s'%y,'dy= %s' %dy, 'extreme point global max','extreme point global min'])
plt.show()
示例12: _eval_evalf
def _eval_evalf(self, prec):
"""Evaluate this complex root to the given precision. """
_prec, mp.prec = mp.prec, prec
try:
func = lambdify(self.poly.gen, self.expr)
interval = self._get_interval()
if not self.is_real:
# For complex intervals, we need to keep refining until the
# imaginary interval is disjunct with other roots, that is,
# until both ends get refined.
ay = interval.ay
by = interval.by
while interval.ay == ay or interval.by == by:
interval = interval.refine()
while True:
if self.is_real:
x0 = mpf(str(interval.center))
else:
x0 = mpc(*map(str, interval.center))
try:
root = findroot(func, x0)
# If the (real or complex) root is not in the 'interval',
# then keep refining the interval. This happens if findroot
# accidentally finds a different root outside of this
# interval because our initial estimate 'x0' was not close
# enough.
if self.is_real:
a = mpf(str(interval.a))
b = mpf(str(interval.b))
# This is needed due to the bug #3364:
a, b = min(a, b), max(a, b)
if not (a < root < b):
raise ValueError("Root not in the interval.")
else:
ax = mpf(str(interval.ax))
bx = mpf(str(interval.bx))
ay = mpf(str(interval.ay))
by = mpf(str(interval.by))
# This is needed due to the bug #3364:
ax, bx = min(ax, bx), max(ax, bx)
ay, by = min(ay, by), max(ay, by)
if not (ax < root.real < bx and ay < root.imag < by):
raise ValueError("Root not in the interval.")
except ValueError:
interval = interval.refine()
continue
else:
break
finally:
mp.prec = _prec
return Float._new(root.real._mpf_, prec) + I*Float._new(root.imag._mpf_, prec)
示例13: solve
def solve(self, iterations=10, until=None, threshold=0.001,
debuglist=None):
""" Runs the solver.
The solver will try to find a solution until one of the
conditions is reached:
(1) the iterations limit is reached
In this case a SolutionNotFoundError will be raised.
(2) the until condition returns True
Arguments:
iterations: The number of iterations to run until
a solution is reached. (Default: 10)
until: This is a function that determines whether or
not a solution is reached. (Default: residual error)
This takes two parameters, the previous solution
vector and the current solution vector.
threshold: If using the default end condition, this is the
threshold that the residuals must be less than.
Raises:
SolutionNotFoundError:
"""
# pylint: disable=invalid-name
self._validate_equations()
current = self._get_context()
if len(self.solutions) == 0:
self._update_solutions({k.name: v for k, v in current.items()})
# do we need to update the function lambdas? This is needed
# if the number of variables/parameters/equations change.
if self._need_function_update:
arg_list = [x for x in current.keys()]
for i in xrange(len(arg_list)):
if isinstance(arg_list[i], Symbol):
arg_list[i]._index = i
private_funcs = {x[2].__name__: x[1] for x in _RT_FUNCS}
for var in self.variables.values():
var.equation.func = lambdify(arg_list,
var.equation.expr,
private_funcs)
self._need_function_update = False
solution = _run_solver(self.equations,
self.variables,
current,
max_iterations=iterations,
until=until,
threshold=threshold,
debuglist=debuglist)
soln = {k.name: v for k, v in solution.items()}
self._update_solutions(soln)
示例14: makefunc
def makefunc(expr, mathmodule = "numpy", dummify=False, **kwargs):
symbols = list(expr.atoms(sp.Symbol))
symbols.sort(key=str)
func = lambdify(symbols, expr, mathmodule, dummify=dummify, **kwargs)
func.kw = symbols
func.expr = expr
func.kwstr = map(lambda x: x.name, symbols)
func.dictcall = types.MethodType(dictcall, func)
func.__doc__ = str(expr)
return func
示例15: _construct
def _construct(self, zet):
if not isinstance(zet, AbstractSet):
zet = as_abstract(zet)
var = zet.variables
expr = zet.expr
func = lambdify(var, expr)
if len(var) == 1:
return bitmap(func, self.voxels)
else:
return bitmap(lambda v: func(*v), self.voxels)