本文整理汇总了Python中sympy.pretty函数的典型用法代码示例。如果您正苦于以下问题:Python pretty函数的具体用法?Python pretty怎么用?Python pretty使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pretty函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __str__
def __str__(self):
from ..utils import header_string
from ..jinja_env import env
template = env.get_template('equivalent_equation.tpl')
t, x, y, z, U, Fx, Fy, Fz, Delta = sp.symbols('t, x, y, z, U, Fx, Fy, Fz, Delta_t')
Bxx, Bxy, Bxz = sp.symbols('Bxx, Bxy, Bxz')
Byx, Byy, Byz = sp.symbols('Byx, Byy, Byz')
Bzx, Bzy, Bzz = sp.symbols('Bzx, Bzy, Bzz')
phys_equation = sp.Derivative(U, t) + sp.Derivative(Fx, x)
if self.dim > 1:
phys_equation += sp.Derivative(Fy, y)
if self.dim == 3:
phys_equation += sp.Derivative(Fz, z)
order2 = []
space = [x, y, z]
B = [[Bxx, Bxy, Bxz],
[Byx, Byy, Byz],
[Bzx, Bzy, Bzz],
]
phys_equation_rhs = 0
for i in range(self.dim):
for j in range(self.dim):
order2.append(sp.pretty(sp.Eq(B[i][j], -Delta*self.coeff_order2[i][j], evaluate=False)))
phys_equation_rhs += sp.Derivative(B[i][j]*sp.Derivative(U, space[j]), space[i])
return template.render(header=header_string('Equivalent Equations'),
dim=self.dim,
phys_equation=sp.pretty(sp.Eq(phys_equation, phys_equation_rhs)),
conserved_moments=sp.pretty(sp.Eq(U, self.consm, evaluate=False)),
order1=[sp.pretty(sp.Eq(F, coeff, evaluate=False)) for F, coeff in zip([Fx, Fy, Fz][:self.dim], self.coeff_order1)],
order2=order2
)
示例2: print_basic_unicode
def print_basic_unicode(o, p, cycle):
"""A function to pretty print sympy Basic objects."""
if cycle:
return p.text('Basic(...)')
out = pretty(o, use_unicode=True)
if '\n' in out:
p.text(u'\n')
p.text(out)
示例3: __str__
def __str__(self):
from .utils import header_string
from .jinja_env import env
template = env.get_template('scheme.tpl')
P = []
EQ = []
s = []
header_scheme = []
for k in range(self.nschemes):
myslice = slice(self.stencil.nv_ptr[k], self.stencil.nv_ptr[k+1])
header_scheme.append(header_string("Scheme %d"%k))
P.append(sp.pretty(sp.Matrix(self.P[myslice])))
EQ.append(sp.pretty(sp.Matrix(self.EQ_no_swap[myslice])))
s.append(sp.pretty(sp.Matrix(self.s_no_swap[myslice])))
if self.rel_vel:
addons = {'rel_vel': self.rel_vel,
'Tu': sp.pretty(self.Tu_no_swap)
}
else:
addons = {}
return template.render(header=header_string("Scheme information"),
scheme=self,
consm=sp.pretty(list(self.consm.keys())),
header_scheme=header_scheme,
P=P,
EQ=EQ,
s=s,
M=sp.pretty(self.M_no_swap),
invM=sp.pretty(self.invM_no_swap),
**addons
)
示例4: test_logic_printing
def test_logic_printing():
from sympy import symbols, pretty
from sympy.printing import latex
syms = symbols('a:f')
expr = And(*syms)
assert latex(expr) == 'a \\wedge b \\wedge c \\wedge d \\wedge e \\wedge f'
assert pretty(expr) == 'And(a, b, c, d, e, f)'
assert str(expr) == 'And(a, b, c, d, e, f)'
示例5: _derivate
def _derivate(self, n):
if n not in self.data_cache:
m = max((d for d in self.data_cache if d < n))
sym_func = self.data_cache[m]['obj']
derivate = symlib.diff_func(sym_func, n - m)
repr_str = sympy.pretty(derivate)
func = numlib.generate_func(derivate)
values = func(self.x, None)
self._fill_cache(n, derivate, values, repr_str)
示例6: print_to_file
def print_to_file(guy, append=False,
software=r"C:\Program Files (x86)\Notepad++\notepad++.exe"):
flag = 'w'
if append: flag = 'a'
outfile = open(r'print.txt', flag)
outfile.write('\n')
outfile.write(sympy.pretty(guy, wrap_line=False))
outfile.write('\n')
outfile.close()
subprocess.Popen(software + ' print.txt')
示例7: pretty
def pretty(self, view='question'):
'''Return a pretty print representation of example. By default,
it pretty prints the question.
``view`` can be any of "question", "answer", "responses", "full" or an
integer that refers to a specific response. '''
if view == 'question':
return sp.pretty(self.question)
elif view == 'answer':
return sp.pretty(self.answer)
elif view == 'responses':
raise NotImplementedError
elif view == 'full':
out = ['Question', '--------', self.pretty('question')]
out.extend(['Responses', '---------', self.pretty('responses')])
return '\n'.join(out)
elif isinstance(view, int):
return sp.pretty(self.alternatives[view])
else:
raise ValueError('unrecognized value: view=%r' % view)
示例8: main
def main():
print sympy.pretty(sympy.collect(bdf_method(2, 0).expand(), ys).simplify())
print "code for ibdf2 step:"
print my_bdf_code_gen(2, 0, True)
# print "\n\n code for eBDF3 step:"
# print my_bdf_code_gen(3, 1, False)
# print "\n\n code for iBDF3 dydt approximation:"
# print my_bdf_code_gen(3, 0, True)
print "\n\n code for iBDF3 step:"
print my_bdf_code_gen(3, 0, True)
# print "\n\n code for iBDF4 dydt approximation:"
# print my_bdf_code_gen(4, 0, True)
print "\n\n code for eBDF3 step w/ derivative at n-1:"
print my_bdf_code_gen(3, 2, True)
示例9: __init__
def __init__(self, x, y, model, **params):
Fitter.__init__(self, x, y)
self.model = model
self.params = dict(self.model.default_params)
self.params.update(params)
numlib.modelfit(self.model, self.params, x, y)
sym_func = symlib.generate_sym_func(self.model.funcstring,
self.params)
repr_str = sympy.pretty(sym_func)
values = self.model(self.x, self.params)
self._fill_cache(0, sym_func, values, repr_str)
示例10: __str__
def __str__(self):
str_format = (
"T matrix of frame %d wrt frame %d:\n"
"----------------------------------\n"
"gamma=%s, b=%s, alpha=%s, d=%s, theta=%s, r=%s\n"
"%s\n"
"**********************************\n"
) % (
self._frame_j, self._frame_i,
str(self._gamma), str(self._b),
str(self._alpha), str(self._d),
str(self._theta), str(self._r),
sympy.pretty(self._tmat)
)
return str_format
示例11: assert_sym_eq
def assert_sym_eq(a, b):
"""Compare symbolic expressions. Note that the simplification algorithm
is not completely robust: might give false negatives (but never false
positives).
Try adding extra simplifications if needed, e.g. add .trigsimplify() to
the end of my_simp.
"""
def my_simp(expr):
# Can't .expand() ints, so catch the zero case separately.
try:
return expr.expand().simplify()
except AttributeError:
return expr
print
print sympy.pretty(my_simp(a))
print "equals"
print sympy.pretty(my_simp(b))
print
# Try to simplify the difference to zero
assert (my_simp(a - b) == 0)
示例12: main
def main():
"""Construct implicit or explicit bdf methods.
\nCode notation:
dtn = size of nth time step
yn = value of y at nth step
Dyn = derivative at nth step (i.e. f(t_n, y_n))
nm1 = n-1, np1 = n+1, etc.
** is the power operator
"""
# Parse arguments
parser = argparse.ArgumentParser(description=main.__doc__,
# Don't mess up my formating in the help message
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--order', action = "store",
type=int,
help="order of the method to generate",
required=True)
parser.add_argument('--explicit', action = "store",
type=bool,
help="Generate explicit bdf method? (true/false)",
required=True)
args = parser.parse_args()
print("I'm computing the",
"explicit" if args.explicit else "implicit",
"BDF methd of order", args.order, ".\n\n")
our_bdf_method = derive_full_method(args.order,
1 if args.explicit else 0)
print("The symbolic representation is [may require a unicode-enabled terminal]:\n")
print(sympy.pretty(our_bdf_method))
print("\n\nThe code is:")
print(code_gen(our_bdf_method))
示例13: main
def main():
print "Hydrogen radial wavefunctions:"
var("r a")
print "R_{21}:"
pprint(R_nl(2, 1, a, r))
print "R_{60}:"
pprint(R_nl(6, 0, a, r))
print "Normalization:"
i = Integral(R_nl(1, 0, 1, r)**2 * r**2, (r, 0, oo))
print pretty(i), " = ", i.doit()
i = Integral(R_nl(2, 0, 1, r)**2 * r**2, (r, 0, oo))
print pretty(i), " = ", i.doit()
i = Integral(R_nl(2, 1, 1, r)**2 * r**2, (r, 0, oo))
print pretty(i), " = ", i.doit()
示例14: print_header
print_header("Bilinear transformation method")
print("\nLaplace and Z Transforms are related by:")
pprint(Eq(z, exp(s / rate)))
print("\nBilinear transform approximation (no prewarping):")
z_num = exp(s / (2 * rate))
z_den = exp(-s / (2 * rate))
assert z_num / z_den == exp(s / rate)
z_bilinear = together(taylor(z_num, x=s, x0=0) / taylor(z_den, x=s, x0=0))
pprint(Eq(z, z_bilinear))
print("\nWhich also means:")
s_bilinear = solve(Eq(z, z_bilinear), s)[0]
pprint(Eq(s, radsimp(s_bilinear.subs(z, 1 / zinv))))
print("\nPrewarping H(z) = H(s) at a frequency " + pretty(w) + " (rad/sample) to " + pretty(f) + " (rad/s):")
pprint(Eq(z, exp(I * w)))
pprint(Eq(s, I * f))
f_prewarped = (s_bilinear / I).subs(z, exp(I * w)).rewrite(sin).rewrite(tan).cancel()
pprint(Eq(f, f_prewarped))
# Lowpass/highpass filters with prewarped bilinear transform equation
T = tan(w / 2)
for name, afilt_str in [("high", "s / (s - p)"), ("low", "-p / (s - p)")]:
print()
print_header("Laplace {0}pass filter (matches {0}pass.z)".format(name))
print("\nFilter equations:")
print("H(s) = " + afilt_str)
afilt = sympify(afilt_str, dict(p=-f, s=s))
pprint(Eq(p, -f)) # Proof is given in lowpass_highpass_matched_z.py
示例15: visualize
def visualize(self, dico=None, viewer_app=viewer.matplotlib_viewer):
"""
visualize the stability
"""
if dico is None:
dico = {}
consm0 = [0.] * len(self.consm)
dicolin = dico.get('linearization', None)
if dicolin is not None:
for k, moment in enumerate(self.consm):
consm0[k] = dicolin.get(moment, 0.)
n_wv = dico.get('number_of_wave_vectors', 1024)
v_xi, eigs = self.eigenvalues(consm0, n_wv)
nx = v_xi.shape[1]
fig = viewer_app.Fig(1, 2, figsize=(12.8, 6.4)) # , figsize=(12, 6))
if self.dim == 1:
color = 'orange'
elif self.dim == 2:
color = .5 + .5/np.pi*np.arctan2(v_xi[0, :], v_xi[1, :])
color = np.repeat(
color[np.newaxis, :], self.nvtot, axis=0
).flatten()
# real and imaginary part
view0 = fig[0]
view0.title = "Stability: {}".format(self.is_stable_l2)
view0.axis(-1.1, 1.1, -1.1, 1.1, aspect='equal')
view0.grid(visible=False)
view0.set_label('real part', 'imaginary part')
view0.ax.set_xticks([-1, 0, 1])
view0.ax.set_xticklabels([r"$-1$", r"$0$", r"$1$"])
view0.ax.set_yticks([-1, 0, 1])
view0.ax.set_yticklabels([r"$-1$", r"$0$", r"$1$"])
theta = np.linspace(0, 2*np.pi, 1000)
view0.plot(
np.cos(theta), np.sin(theta),
alpha=0.5, color='navy', width=0.5,
)
pos0 = np.empty((nx*self.nvtot, 2))
for k in range(self.nvtot):
pos0[nx*k:nx*(k+1), 0] = np.real(eigs[:, k])
pos0[nx*k:nx*(k+1), 1] = np.imag(eigs[:, k])
markers0 = view0.markers(pos0, 5, color=color, alpha=0.5)
# modulus
view1 = fig[1]
view1.title = "Stability: {}".format(self.is_stable_l2)
view1.axis(0, 2*np.pi, -.1, 1.1)
view1.grid(visible=True)
view1.set_label('wave vector modulus', 'modulus')
view1.ax.set_xticks([k*np.pi/4 for k in range(0, 9)])
view1.ax.set_xticklabels(
[
r"$0$", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$",
r"$\frac{3\pi}{4}$", r"$\pi$",
r"$\frac{5\pi}{4}$", r"$\frac{3\pi}{2}$",
r"$\frac{7\pi}{4}$", r"$2\pi$"
]
)
view1.plot(
[0, 2*np.pi], [1., 1.],
alpha=0.5, color='navy', width=0.5,
)
pos1 = np.empty((nx*self.nvtot, 2))
for k in range(self.nvtot):
# pos1[nx*k:nx*(k+1), 0] = np.sqrt(np.sum(v_xi**2, axis=0))
pos1[nx*k:nx*(k+1), 0] = np.max(v_xi, axis=0)
pos1[nx*k:nx*(k+1), 1] = np.abs(eigs[:, k])
markers1 = view1.markers(pos1, 5, color=color, alpha=0.5)
dicosliders = dico.get('parameters', None)
if dicosliders is not None:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
axcolor = 'lightgoldenrodyellow'
viewer_app.Fig(figsize=(6, 2))
sliders = {}
item = 0
length = 0.8/len(dicosliders)
for k, v in dicosliders.items():
axe = plt.axes(
[0.2, 0.1+item*length, 0.65, 0.8*length],
facecolor=axcolor,
)
sliders[k] = Slider(
axe,
v.get('name', sp.pretty(k)),
*v['range'],
valinit=v['init'],
valstep=v['step']
)
item += 1
#.........这里部分代码省略.........