• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sympy.pretty函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sympy.pretty函数的典型用法代码示例。如果您正苦于以下问题:Python pretty函数的具体用法?Python pretty怎么用?Python pretty使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了pretty函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
                              )
开发者ID:bgraille,项目名称:pylbm,代码行数:34,代码来源:equivalent_equation.py


示例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)
开发者ID:jisqyv,项目名称:ipython,代码行数:8,代码来源:sympyprinting.py


示例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
                              )
开发者ID:bgraille,项目名称:pylbm,代码行数:33,代码来源:scheme.py


示例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)'
开发者ID:mrshu,项目名称:sympy,代码行数:10,代码来源:test_logic.py


示例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)
开发者ID:schlamar,项目名称:sitforc,代码行数:10,代码来源:fitting.py


示例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')
开发者ID:heartvalve,项目名称:mapy,代码行数:10,代码来源:doperator.py


示例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)
开发者ID:fabiommendes,项目名称:pytex,代码行数:21,代码来源:examples.py


示例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)
开发者ID:davidshepherd7,项目名称:Landau-Lifshitz-Gilbert-ODE-model,代码行数:21,代码来源:sym-bdf3.py


示例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)
开发者ID:schlamar,项目名称:sitforc,代码行数:13,代码来源:fitting.py


示例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
开发者ID:ELZo3,项目名称:symoro,代码行数:15,代码来源:transform.py


示例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)
开发者ID:davidshepherd7,项目名称:Landau-Lifshitz-Gilbert-ODE-model,代码行数:24,代码来源:sym-bdf3.py


示例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))
开发者ID:davidshepherd7,项目名称:generate-bdf-method,代码行数:43,代码来源:generate-bdf-method.py


示例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()
开发者ID:abhik137,项目名称:sympy,代码行数:15,代码来源:hydrogen.py


示例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
开发者ID:danilobellini,项目名称:audiolazy,代码行数:31,代码来源:lowpass_highpass_bilinear.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

#.........这里部分代码省略.........
开发者ID:bgraille,项目名称:pylbm,代码行数:101,代码来源:stability.py


示例16: print_basic_unicode

def print_basic_unicode(obj, printer, cycle):
    out = pretty(obj, use_unicode=True)
    printer.text(out)
开发者ID:gabtremblay,项目名称:scipy-2011-tutorial,代码行数:3,代码来源:pretty.py


示例17: test_printing

def test_printing():
    psi = Ket('psi')
    assert pretty(psi, use_unicode=True) == u'\u2758\u03c8\u27e9'
    assert pretty(Dagger(psi), use_unicode=True) == u'\u27e8\u03c8\u2758'
    assert latex(psi) == r"{\left|\psi\right\rangle }"
    assert latex(Dagger(psi)) == r"{\left\langle \psi\right|}"
开发者ID:Jerryy,项目名称:sympy,代码行数:6,代码来源:test_state.py


示例18: pretty

def pretty(expr):

    if hasattr(expr, 'pretty'):
        return expr.pretty()
    else:
        return sym.pretty(expr)
开发者ID:bcbnz,项目名称:lcapy,代码行数:6,代码来源:core.py


示例19: test_printing

def test_printing():
    psi = Ket('psi')
    ip = Dagger(psi)*psi
    assert pretty(ip, use_unicode=True) == u'\u27e8\u03c8\u2758\u03c8\u27e9'
    assert latex(ip) == r"\left\langle \psi \right. {\left|\psi\right\rangle }"
开发者ID:101man,项目名称:sympy,代码行数:5,代码来源:test_innerproduct.py


示例20: autogen_functions

def autogen_functions(L, where):
    for d in L:
        f = d['name']
        fname = '%s/@sym/%s.m' % (where,f)
        print fname

        fd = open(fname, "w")

        fd.write(make_copyright_line(d['firstyear']))
        fd.write("%%\n")

        fd.write(license_boilerplate)

        # Build and out example block for doctest
        xstr = d['docexpr']
        x = sp.S(xstr)
        y = eval("sp.%s(x)" % d['spname'])
        ystr = sp.pretty(y, use_unicode=True)
        lines = ystr.splitlines()
        if len(lines) > 1:
            # indent multiline output
            lines = [("%%       " + a).strip() for a in lines]
            ystr = "\n" + "\n".join(lines)
        else:
            ystr = " " + ystr
        yutf8 = ystr.encode('utf-8')

        body = \
"""
%% -*- texinfo -*-
%% @documentencoding UTF-8
%% @defmethod @@sym {NAME} (@var{{x}})
%% Symbolic {NAME} function.
%%
%% Example:
%% @example
%% @group
%% syms x
%% y = {NAME} ({XSTR})
%%   @result{{}} y = (sym){YUTF8}
%% @end group
%% @end example
%%
%% Note: this file is autogenerated: if you want to edit it, you might
%% want to make changes to 'generate_functions.py' instead.
%%
%% @end defmethod


function y = {NAME}(x)
  if (nargin ~= 1)
    print_usage ();
  end
  y = elementwise_op ('{SPNAME}', x);
end


%!error <Invalid> {NAME} (sym(1), 2)
%!assert (isequaln ({NAME} (sym(nan)), sym(nan)))

""".format(NAME=f, SPNAME=d['spname'], XSTR=xstr, YUTF8=yutf8)

        fd.write(body)

        # tests
        fd.write("%!shared x, d\n")
        fd.write("%%! d = %s;\n" % d['test_in_val'])
        fd.write("%%! x = sym('%s');\n\n" % d['test_in_val'])
        fd.write("%!test\n")
        fd.write("%%! f1 = %s(x);\n" % f)
        if d['out_val_from_oct']:
            fd.write("%%! f2 = %s(d);\n" % f)
        else:
            fd.write("%%! f2 = %s;\n" % d['test_out_val'])
        fd.write("%! assert( abs(double(f1) - f2) < 1e-15 )\n\n")

        fd.write("%!test\n")
        fd.write("%! D = [d d; d d];\n")
        fd.write("%! A = [x x; x x];\n")
        fd.write("%%! f1 = %s(A);\n" % f)
        if d['out_val_from_oct']:
            fd.write("%%! f2 = %s(D);\n" % f)
        else:
            fd.write("%%! f2 = %s;\n" % d['test_out_val'])
            fd.write("%! f2 = [f2 f2; f2 f2];\n")
        fd.write("%! assert( all(all( abs(double(f1) - f2) < 1e-15 )))\n")

        fd.write( \
"""
%!test
%! % round trip
%! y = sym('y');
%! A = {NAME} (d);
%! f = {NAME} (y);
%! h = function_handle (f);
%! B = h (d);
%! assert (A, B, -eps)
""".format(NAME=f))

        fd.close()
开发者ID:genuinelucifer,项目名称:octsympy,代码行数:100,代码来源:generate_functions.py



注:本文中的sympy.pretty函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sympy.principal_branch函数代码示例发布时间:2022-05-27
下一篇:
Python sympy.pprint函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap