Esempio n. 1
0
            def render(self, *args, **kwargs):
                ar = e.args  # just to shorten things
                settings = printer._settings if printer else {}
                if printer:
                    use_unicode = printer._use_unicode
                else:
                    from sympy.printing.pretty.pretty_symbology import (
                        pretty_use_unicode, )

                    use_unicode = pretty_use_unicode()
                mpp = printer if printer else VectorPrettyPrinter(settings)
                if len(ar) == 0:
                    return unicode(0)
                bar = u"\N{CIRCLED TIMES}" if use_unicode else "|"
                ol = []  # output list, to be concatenated to a string
                for i, v in enumerate(ar):
                    # if the coef of the dyadic is 1, we skip the 1
                    if ar[i][0] == 1:
                        ol.extend([
                            u" + ",
                            mpp.doprint(ar[i][1]), bar,
                            mpp.doprint(ar[i][2])
                        ])

                    # if the coef of the dyadic is -1, we skip the 1
                    elif ar[i][0] == -1:
                        ol.extend([
                            u" - ",
                            mpp.doprint(ar[i][1]), bar,
                            mpp.doprint(ar[i][2])
                        ])

                    # If the coefficient of the dyadic is not 1 or -1,
                    # we might wrap it in parentheses, for readability.
                    elif ar[i][0] != 0:
                        if isinstance(ar[i][0], Add):
                            arg_str = mpp._print(ar[i][0]).parens()[0]
                        else:
                            arg_str = mpp.doprint(ar[i][0])
                        if arg_str.startswith(u"-"):
                            arg_str = arg_str[1:]
                            str_start = u" - "
                        else:
                            str_start = u" + "
                        ol.extend([
                            str_start,
                            arg_str,
                            u" ",
                            mpp.doprint(ar[i][1]),
                            bar,
                            mpp.doprint(ar[i][2]),
                        ])

                outstr = u"".join(ol)
                if outstr.startswith(u" + "):
                    outstr = outstr[3:]
                elif outstr.startswith(" "):
                    outstr = outstr[1:]
                return outstr
Esempio n. 2
0
 def _pretty(self, printer, *args):
     controls = self._print_sequence_pretty(self.controls, ",", printer, *args)
     gate = printer._print(self.gate)
     gate_name = stringPict(unicode(self.gate_name))
     first = self._print_subscript_pretty(gate_name, controls)
     gate = self._print_parens_pretty(gate)
     final = prettyForm(*first.right((gate)))
     return final
Esempio n. 3
0
File: gate.py Progetto: B-Rich/sympy
 def _pretty(self, printer, *args):
     controls = self._print_sequence_pretty(self.controls, ",", printer, *args)
     gate = printer._print(self.gate)
     gate_name = stringPict(unicode(self.gate_name))
     first = self._print_subscript_pretty(gate_name, controls)
     gate = self._print_parens_pretty(gate)
     final = prettyForm(*first.right((gate)))
     return final
Esempio n. 4
0
            def render(self, *args, **kwargs):
                ar = e.args  # just to shorten things
                settings = printer._settings if printer else {}
                if printer:
                    use_unicode = printer._use_unicode
                else:
                    from sympy.printing.pretty.pretty_symbology import (
                        pretty_use_unicode)
                    use_unicode = pretty_use_unicode()
                mpp = printer if printer else VectorPrettyPrinter(settings)
                if len(ar) == 0:
                    return unicode(0)
                bar = u"\N{CIRCLED TIMES}" if use_unicode else "|"
                ol = []  # output list, to be concatenated to a string
                for i, v in enumerate(ar):
                    # if the coef of the dyadic is 1, we skip the 1
                    if ar[i][0] == 1:
                        ol.extend([u" + ",
                                  mpp.doprint(ar[i][1]),
                                  bar,
                                  mpp.doprint(ar[i][2])])

                    # if the coef of the dyadic is -1, we skip the 1
                    elif ar[i][0] == -1:
                        ol.extend([u" - ",
                                  mpp.doprint(ar[i][1]),
                                  bar,
                                  mpp.doprint(ar[i][2])])

                    # If the coefficient of the dyadic is not 1 or -1,
                    # we might wrap it in parentheses, for readability.
                    elif ar[i][0] != 0:
                        if isinstance(ar[i][0], Add):
                            arg_str = mpp._print(
                                ar[i][0]).parens()[0]
                        else:
                            arg_str = mpp.doprint(ar[i][0])
                        if arg_str.startswith(u"-"):
                            arg_str = arg_str[1:]
                            str_start = u" - "
                        else:
                            str_start = u" + "
                        ol.extend([str_start, arg_str, u" ",
                                  mpp.doprint(ar[i][1]),
                                  bar,
                                  mpp.doprint(ar[i][2])])

                outstr = u"".join(ol)
                if outstr.startswith(u" + "):
                    outstr = outstr[3:]
                elif outstr.startswith(" "):
                    outstr = outstr[1:]
                return outstr
Esempio n. 5
0
            def render(self, *args, **kwargs):
                ar = e.args  # just to shorten things
                if len(ar) == 0:
                    return unicode(0)
                settings = printer._settings if printer else {}
                vp = printer if printer else VectorPrettyPrinter(settings)
                pforms = []  # output list, to be concatenated to a string
                for i, v in enumerate(ar):
                    for j in 0, 1, 2:
                        # if the coef of the basis vector is 1, we skip the 1
                        if ar[i][0][j] == 1:
                            pform = vp._print(ar[i][1].pretty_vecs[j])
                        # if the coef of the basis vector is -1, we skip the 1
                        elif ar[i][0][j] == -1:
                            pform = vp._print(ar[i][1].pretty_vecs[j])
                            pform = prettyForm(*pform.left(" - "))
                            bin = prettyForm.NEG
                            pform = prettyForm(binding=bin, *pform)
                        elif ar[i][0][j] != 0:
                            # If the basis vector coeff is not 1 or -1,
                            # we might wrap it in parentheses, for readability.
                            pform = vp._print(ar[i][0][j])

                            if isinstance(ar[i][0][j], Add):
                                tmp = pform.parens()
                                pform = prettyForm(tmp[0], tmp[1])

                            pform = prettyForm(
                                *pform.right(" ", ar[i][1].pretty_vecs[j]))
                        else:
                            continue
                        pforms.append(pform)

                pform = prettyForm.__add__(*pforms)
                kwargs["wrap_line"] = kwargs.get("wrap_line")
                kwargs["num_columns"] = kwargs.get("num_columns")
                out_str = pform.render(*args, **kwargs)
                mlines = [line.rstrip() for line in out_str.split("\n")]
                return "\n".join(mlines)
Esempio n. 6
0
            def render(self, *args, **kwargs):
                ar = e.args  # just to shorten things
                if len(ar) == 0:
                    return unicode(0)
                settings = printer._settings if printer else {}
                vp = printer if printer else VectorPrettyPrinter(settings)
                pforms = []  # output list, to be concatenated to a string
                for i, v in enumerate(ar):
                    for j in 0, 1, 2:
                        # if the coef of the basis vector is 1, we skip the 1
                        if ar[i][0][j] == 1:
                            pform = vp._print(ar[i][1].pretty_vecs[j])
                        # if the coef of the basis vector is -1, we skip the 1
                        elif ar[i][0][j] == -1:
                            pform = vp._print(ar[i][1].pretty_vecs[j])
                            pform= prettyForm(*pform.left(" - "))
                            bin = prettyForm.NEG
                            pform = prettyForm(binding=bin, *pform)
                        elif ar[i][0][j] != 0:
                            # If the basis vector coeff is not 1 or -1,
                            # we might wrap it in parentheses, for readability.
                            if isinstance(ar[i][0][j], Add):
                                pform = vp._print(
                                    ar[i][0][j]).parens()
                            else:
                                pform = vp._print(
                                    ar[i][0][j])
                            pform = prettyForm(*pform.right(" ",
                                                ar[i][1].pretty_vecs[j]))
                        else:
                            continue
                        pforms.append(pform)

                pform = prettyForm.__add__(*pforms)
                kwargs["wrap_line"] = kwargs.get("wrap_line")
                kwargs["num_columns"] = kwargs.get("num_columns")
                out_str = pform.render(*args, **kwargs)
                mlines = [line.rstrip() for line in out_str.split("\n")]
                return "\n".join(mlines)
Esempio n. 7
0
            def render(self, *args, **kwargs):
                self = e
                ar = self.args  # just to shorten things
                if len(ar) == 0:
                    return unicode(0)
                settings = printer._settings if printer else {}
                vp = printer if printer else VectorPrettyPrinter(settings)
                ol = []  # output list, to be concatenated to a string
                for i, v in enumerate(ar):
                    for j in 0, 1, 2:
                        # if the coef of the basis vector is 1, we skip the 1
                        if ar[i][0][j] == 1:
                            ol.append(u(" + ") + ar[i][1].pretty_vecs[j])
                        # if the coef of the basis vector is -1, we skip the 1
                        elif ar[i][0][j] == -1:
                            ol.append(u(" - ") + ar[i][1].pretty_vecs[j])
                        elif ar[i][0][j] != 0:
                            # If the basis vector coeff is not 1 or -1,
                            # we might wrap it in parentheses, for readability.
                            if isinstance(ar[i][0][j], Add):
                                arg_str = vp._print(
                                    ar[i][0][j]).parens()[0]
                            else:
                                arg_str = (vp.doprint(
                                    ar[i][0][j]))

                            if arg_str[0] == u("-"):
                                arg_str = arg_str[1:]
                                str_start = u(" - ")
                            else:
                                str_start = u(" + ")
                            ol.append(str_start + arg_str + ' ' +
                                      ar[i][1].pretty_vecs[j])
                outstr = u("").join(ol)
                if outstr.startswith(u(" + ")):
                    outstr = outstr[3:]
                elif outstr.startswith(" "):
                    outstr = outstr[1:]
                return outstr
Esempio n. 8
0
            def render(self, *args, **kwargs):
                ar = e.args  # just to shorten things
                if len(ar) == 0:
                    return unicode(0)
                settings = printer._settings if printer else {}
                vp = printer if printer else VectorPrettyPrinter(settings)
                ol = []  # output list, to be concatenated to a string
                for i, v in enumerate(ar):
                    for j in 0, 1, 2:
                        # if the coef of the basis vector is 1, we skip the 1
                        if ar[i][0][j] == 1:
                            ol.append(u(" + ") + ar[i][1].pretty_vecs[j])
                        # if the coef of the basis vector is -1, we skip the 1
                        elif ar[i][0][j] == -1:
                            ol.append(u(" - ") + ar[i][1].pretty_vecs[j])
                        elif ar[i][0][j] != 0:
                            # If the basis vector coeff is not 1 or -1,
                            # we might wrap it in parentheses, for readability.
                            if isinstance(ar[i][0][j], Add):
                                arg_str = vp._print(
                                    ar[i][0][j]).parens()[0]
                            else:
                                arg_str = (vp.doprint(
                                    ar[i][0][j]))

                            if arg_str[0] == u("-"):
                                arg_str = arg_str[1:]
                                str_start = u(" - ")
                            else:
                                str_start = u(" + ")
                            ol.append(str_start + arg_str + ' ' +
                                      ar[i][1].pretty_vecs[j])
                outstr = u("").join(ol)
                if outstr.startswith(u(" + ")):
                    outstr = outstr[3:]
                elif outstr.startswith(" "):
                    outstr = outstr[1:]
                return outstr
Esempio n. 9
0
 def _pretty(self, printer, *args):
     targets = self._print_sequence_pretty(
         self.targets, ',', printer, *args)
     gate_name = stringPict(unicode(self.gate_name))
     return self._print_subscript_pretty(gate_name, targets)
Esempio n. 10
0
 def _pretty(self, printer, *args):
     a = stringPict(unicode(self.gate_name))
     b = self._print_label_pretty(printer, *args)
     return self._print_subscript_pretty(a, b)
Esempio n. 11
0
def preview(expr,
            output='png',
            viewer=None,
            euler=True,
            packages=(),
            filename=None,
            outputbuffer=None,
            preamble=None,
            dvioptions=None,
            outputTexFile=None,
            **latex_settings):
    r"""
    View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.

    If the expr argument is an expression, it will be exported to LaTeX and
    then compiled using the available TeX distribution.  The first argument,
    'expr', may also be a LaTeX string.  The function will then run the
    appropriate viewer for the given output format or use the user defined
    one. By default png output is generated.

    By default pretty Euler fonts are used for typesetting (they were used to
    typeset the well known "Concrete Mathematics" book). For that to work, you
    need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the
    texlive-fonts-extra package). If you prefer default AMS fonts or your
    system lacks 'eulervm' LaTeX package then unset the 'euler' keyword
    argument.

    To use viewer auto-detection, lets say for 'png' output, issue

    >>> from sympy import symbols, preview, Symbol
    >>> x, y = symbols("x,y")

    >>> preview(x + y, output='png')

    This will choose 'pyglet' by default. To select a different one, do

    >>> preview(x + y, output='png', viewer='gimp')

    The 'png' format is considered special. For all other formats the rules
    are slightly different. As an example we will take 'dvi' output format. If
    you would run

    >>> preview(x + y, output='dvi')

    then 'view' will look for available 'dvi' viewers on your system
    (predefined in the function, so it will try evince, first, then kdvi and
    xdvi). If nothing is found you will need to set the viewer explicitly.

    >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')

    This will skip auto-detection and will run user specified
    'superior-dvi-viewer'. If 'view' fails to find it on your system it will
    gracefully raise an exception.

    You may also enter 'file' for the viewer argument. Doing so will cause
    this function to return a file object in read-only mode, if 'filename'
    is unset. However, if it was set, then 'preview' writes the genereted
    file to this filename instead.

    There is also support for writing to a BytesIO like object, which needs
    to be passed to the 'outputbuffer' argument.

    >>> from io import BytesIO
    >>> obj = BytesIO()
    >>> preview(x + y, output='png', viewer='BytesIO',
    ...         outputbuffer=obj)

    The LaTeX preamble can be customized by setting the 'preamble' keyword
    argument. This can be used, e.g., to set a different font size, use a
    custom documentclass or import certain set of LaTeX packages.

    >>> preamble = "\\documentclass[10pt]{article}\n" \
    ...            "\\usepackage{amsmath,amsfonts}\\begin{document}"
    >>> preview(x + y, output='png', preamble=preamble)

    If the value of 'output' is different from 'dvi' then command line
    options can be set ('dvioptions' argument) for the execution of the
    'dvi'+output conversion tool. These options have to be in the form of a
    list of strings (see subprocess.Popen).

    Additional keyword args will be passed to the latex call, e.g., the
    symbol_names flag.

    >>> phidd = Symbol('phidd')
    >>> preview(phidd, symbol_names={phidd:r'\ddot{\varphi}'})

    For post-processing the generated TeX File can be written to a file by
    passing the desired filename to the 'outputTexFile' keyword
    argument. To write the TeX code to a file named
    "sample.tex" and run the default png viewer to display the resulting
    bitmap, do

    >>> preview(x + y, outputTexFile="sample.tex")


    """
    special = ['pyglet']

    if viewer is None:
        if output == "png":
            viewer = "pyglet"
        else:
            # sorted in order from most pretty to most ugly
            # very discussable, but indeed 'gv' looks awful :)
            # TODO add candidates for windows to list
            candidates = {
                "dvi": ["evince", "okular", "kdvi", "xdvi"],
                "ps": ["evince", "okular", "gsview", "gv"],
                "pdf": ["evince", "okular", "kpdf", "acroread", "xpdf", "gv"],
            }

            try:
                for candidate in candidates[output]:
                    path = find_executable(candidate)
                    if path is not None:
                        viewer = path
                        break
                else:
                    raise SystemError(
                        "No viewers found for '%s' output format." % output)
            except KeyError:
                raise SystemError("Invalid output format: %s" % output)
    else:
        if viewer == "file":
            if filename is None:
                SymPyDeprecationWarning(
                    feature="Using viewer=\"file\" without a "
                    "specified filename",
                    deprecated_since_version="0.7.3",
                    useinstead="viewer=\"file\" and filename=\"desiredname\"",
                    issue=7018).warn()
        elif viewer == "StringIO":
            SymPyDeprecationWarning(feature="The preview() viewer StringIO",
                                    useinstead="BytesIO",
                                    deprecated_since_version="0.7.4",
                                    issue=7083).warn()
            viewer = "BytesIO"
            if outputbuffer is None:
                raise ValueError("outputbuffer has to be a BytesIO "
                                 "compatible object if viewer=\"StringIO\"")
        elif viewer == "BytesIO":
            if outputbuffer is None:
                raise ValueError("outputbuffer has to be a BytesIO "
                                 "compatible object if viewer=\"BytesIO\"")
        elif viewer not in special and not find_executable(viewer):
            raise SystemError("Unrecognized viewer: %s" % viewer)

    if preamble is None:
        actual_packages = packages + ("amsmath", "amsfonts")
        if euler:
            actual_packages += ("euler", )
        package_includes = "\n" + "\n".join(
            ["\\usepackage{%s}" % p for p in actual_packages])

        preamble = r"""\documentclass[12pt]{article}
\pagestyle{empty}
%s

\begin{document}
""" % (package_includes)
    else:
        if len(packages) > 0:
            raise ValueError("The \"packages\" keyword must not be set if a "
                             "custom LaTeX preamble was specified")
    latex_main = preamble + '\n%s\n\n' + r"\end{document}"

    if isinstance(expr, str):
        latex_string = expr
    else:
        latex_string = latex(expr, mode='inline', **latex_settings)

    try:
        workdir = tempfile.mkdtemp()

        with io.open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:
            fh.write(unicode(latex_main) % u_decode(latex_string))

        if outputTexFile is not None:
            shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)

        if not find_executable('latex'):
            raise RuntimeError("latex program is not installed")

        try:
            # Avoid showing a cmd.exe window when running this
            # on Windows
            if os.name == 'nt':
                creation_flag = 0x08000000  # CREATE_NO_WINDOW
            else:
                creation_flag = 0  # Default value
            check_output([
                'latex', '-halt-on-error', '-interaction=nonstopmode',
                'texput.tex'
            ],
                         cwd=workdir,
                         stderr=STDOUT,
                         creationflags=creation_flag)
        except CalledProcessError as e:
            raise RuntimeError(
                "'latex' exited abnormally with the following output:\n%s" %
                e.output)

        if output != "dvi":
            defaultoptions = {
                "ps": [],
                "pdf": [],
                "png": ["-T", "tight", "-z", "9", "--truecolor"],
                "svg": ["--no-fonts"],
            }

            commandend = {
                "ps": ["-o", "texput.ps", "texput.dvi"],
                "pdf": ["texput.dvi", "texput.pdf"],
                "png": ["-o", "texput.png", "texput.dvi"],
                "svg": ["-o", "texput.svg", "texput.dvi"],
            }

            if output == "svg":
                cmd = ["dvisvgm"]
            else:
                cmd = ["dvi" + output]
            if not find_executable(cmd[0]):
                raise RuntimeError("%s is not installed" % cmd[0])
            try:
                if dvioptions is not None:
                    cmd.extend(dvioptions)
                else:
                    cmd.extend(defaultoptions[output])
                cmd.extend(commandend[output])
            except KeyError:
                raise SystemError("Invalid output format: %s" % output)

            try:
                # Avoid showing a cmd.exe window when running this
                # on Windows
                if os.name == 'nt':
                    creation_flag = 0x08000000  # CREATE_NO_WINDOW
                else:
                    creation_flag = 0  # Default value
                check_output(cmd,
                             cwd=workdir,
                             stderr=STDOUT,
                             creationflags=creation_flag)
            except CalledProcessError as e:
                raise RuntimeError(
                    "'%s' exited abnormally with the following output:\n%s" %
                    (' '.join(cmd), e.output))

        src = "texput.%s" % (output)

        if viewer == "file":
            if filename is None:
                buffer = BytesIO()
                with open(join(workdir, src), 'rb') as fh:
                    buffer.write(fh.read())
                return buffer
            else:
                shutil.move(join(workdir, src), filename)
        elif viewer == "BytesIO":
            with open(join(workdir, src), 'rb') as fh:
                outputbuffer.write(fh.read())
        elif viewer == "pyglet":
            try:
                from pyglet import window, image, gl
                from pyglet.window import key
            except ImportError:
                raise ImportError(
                    "pyglet is required for preview.\n visit http://www.pyglet.org/"
                )

            if output == "png":
                from pyglet.image.codecs.png import PNGImageDecoder
                img = image.load(join(workdir, src), decoder=PNGImageDecoder())
            else:
                raise SystemError("pyglet preview works only for 'png' files.")

            offset = 25

            config = gl.Config(double_buffer=False)
            win = window.Window(width=img.width + 2 * offset,
                                height=img.height + 2 * offset,
                                caption="sympy",
                                resizable=False,
                                config=config)

            win.set_vsync(False)

            try:

                def on_close():
                    win.has_exit = True

                win.on_close = on_close

                def on_key_press(symbol, modifiers):
                    if symbol in [key.Q, key.ESCAPE]:
                        on_close()

                win.on_key_press = on_key_press

                def on_expose():
                    gl.glClearColor(1.0, 1.0, 1.0, 1.0)
                    gl.glClear(gl.GL_COLOR_BUFFER_BIT)

                    img.blit((win.width - img.width) / 2,
                             (win.height - img.height) / 2)

                win.on_expose = on_expose

                while not win.has_exit:
                    win.dispatch_events()
                    win.flip()
            except KeyboardInterrupt:
                pass

            win.close()
        else:
            try:
                # Avoid showing a cmd.exe window when running this
                # on Windows
                if os.name == 'nt':
                    creation_flag = 0x08000000  # CREATE_NO_WINDOW
                else:
                    creation_flag = 0  # Default value
                check_output([viewer, src],
                             cwd=workdir,
                             stderr=STDOUT,
                             creationflags=creation_flag)
            except CalledProcessError as e:
                raise RuntimeError(
                    "'%s %s' exited abnormally with the following output:\n%s"
                    % (viewer, src, e.output))
    finally:
        try:
            shutil.rmtree(workdir)  # delete directory
        except OSError as e:
            if e.errno != 2:  # code 2 - no such file or directory
                raise
Esempio n. 12
0
def xstr(*args):
    """call str or unicode depending on current mode"""
    if _use_unicode:
        return unicode(*args)
    else:
        return str(*args)
Esempio n. 13
0
def xstr(*args):
    """call str or unicode depending on current mode"""
    if _use_unicode:
        return unicode(*args)
    else:
        return str(*args)
Esempio n. 14
0
def preview(expr, output='png', viewer=None, euler=True, packages=(),
            filename=None, outputbuffer=None, preamble=None, dvioptions=None,
            outputTexFile=None, **latex_settings):
    r"""
    View expression or LaTeX markup in PNG, DVI, PostScript or PDF form.

    If the expr argument is an expression, it will be exported to LaTeX and
    then compiled using the available TeX distribution.  The first argument,
    'expr', may also be a LaTeX string.  The function will then run the
    appropriate viewer for the given output format or use the user defined
    one. By default png output is generated.

    By default pretty Euler fonts are used for typesetting (they were used to
    typeset the well known "Concrete Mathematics" book). For that to work, you
    need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the
    texlive-fonts-extra package). If you prefer default AMS fonts or your
    system lacks 'eulervm' LaTeX package then unset the 'euler' keyword
    argument.

    To use viewer auto-detection, lets say for 'png' output, issue

    >>> from sympy import symbols, preview, Symbol
    >>> x, y = symbols("x,y")

    >>> preview(x + y, output='png')

    This will choose 'pyglet' by default. To select a different one, do

    >>> preview(x + y, output='png', viewer='gimp')

    The 'png' format is considered special. For all other formats the rules
    are slightly different. As an example we will take 'dvi' output format. If
    you would run

    >>> preview(x + y, output='dvi')

    then 'view' will look for available 'dvi' viewers on your system
    (predefined in the function, so it will try evince, first, then kdvi and
    xdvi). If nothing is found you will need to set the viewer explicitly.

    >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer')

    This will skip auto-detection and will run user specified
    'superior-dvi-viewer'. If 'view' fails to find it on your system it will
    gracefully raise an exception.

    You may also enter 'file' for the viewer argument. Doing so will cause
    this function to return a file object in read-only mode, if 'filename'
    is unset. However, if it was set, then 'preview' writes the genereted
    file to this filename instead.

    There is also support for writing to a BytesIO like object, which needs
    to be passed to the 'outputbuffer' argument.

    >>> from io import BytesIO
    >>> obj = BytesIO()
    >>> preview(x + y, output='png', viewer='BytesIO',
    ...         outputbuffer=obj)

    The LaTeX preamble can be customized by setting the 'preamble' keyword
    argument. This can be used, e.g., to set a different font size, use a
    custom documentclass or import certain set of LaTeX packages.

    >>> preamble = "\\documentclass[10pt]{article}\n" \
    ...            "\\usepackage{amsmath,amsfonts}\\begin{document}"
    >>> preview(x + y, output='png', preamble=preamble)

    If the value of 'output' is different from 'dvi' then command line
    options can be set ('dvioptions' argument) for the execution of the
    'dvi'+output conversion tool. These options have to be in the form of a
    list of strings (see subprocess.Popen).

    Additional keyword args will be passed to the latex call, e.g., the
    symbol_names flag.

    >>> phidd = Symbol('phidd')
    >>> preview(phidd, symbol_names={phidd:r'\ddot{\varphi}'})

    For post-processing the generated TeX File can be written to a file by
    passing the desired filename to the 'outputTexFile' keyword
    argument. To write the TeX code to a file named
    "sample.tex" and run the default png viewer to display the resulting
    bitmap, do

    >>> preview(x + y, outputTexFile="sample.tex")


    """
    special = [ 'pyglet' ]

    if viewer is None:
        if output == "png":
            viewer = "pyglet"
        else:
            # sorted in order from most pretty to most ugly
            # very discussable, but indeed 'gv' looks awful :)
            # TODO add candidates for windows to list
            candidates = {
                "dvi": [ "evince", "okular", "kdvi", "xdvi" ],
                "ps": [ "evince", "okular", "gsview", "gv" ],
                "pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ],
            }

            try:
                for candidate in candidates[output]:
                    path = find_executable(candidate)
                    if path is not None:
                        viewer = path
                        break
                else:
                    raise SystemError(
                        "No viewers found for '%s' output format." % output)
            except KeyError:
                raise SystemError("Invalid output format: %s" % output)
    else:
        if viewer == "file":
            if filename is None:
                SymPyDeprecationWarning(feature="Using viewer=\"file\" without a "
                    "specified filename", deprecated_since_version="0.7.3",
                    useinstead="viewer=\"file\" and filename=\"desiredname\"",
                    issue=7018).warn()
        elif viewer == "StringIO":
            SymPyDeprecationWarning(feature="The preview() viewer StringIO",
                useinstead="BytesIO", deprecated_since_version="0.7.4",
                issue=7083).warn()
            viewer = "BytesIO"
            if outputbuffer is None:
                raise ValueError("outputbuffer has to be a BytesIO "
                                 "compatible object if viewer=\"StringIO\"")
        elif viewer == "BytesIO":
            if outputbuffer is None:
                raise ValueError("outputbuffer has to be a BytesIO "
                                 "compatible object if viewer=\"BytesIO\"")
        elif viewer not in special and not find_executable(viewer):
            raise SystemError("Unrecognized viewer: %s" % viewer)


    if preamble is None:
        actual_packages = packages + ("amsmath", "amsfonts")
        if euler:
            actual_packages += ("euler",)
        package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p
                                             for p in actual_packages])

        preamble = r"""\documentclass[12pt]{article}
\pagestyle{empty}
%s

\begin{document}
""" % (package_includes)
    else:
        if len(packages) > 0:
            raise ValueError("The \"packages\" keyword must not be set if a "
                             "custom LaTeX preamble was specified")
    latex_main = preamble + '\n%s\n\n' + r"\end{document}"

    if isinstance(expr, str):
        latex_string = expr
    else:
        latex_string = latex(expr, mode='inline', **latex_settings)

    try:
        workdir = tempfile.mkdtemp()

        with io.open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh:
            fh.write(unicode(latex_main) % u_decode(latex_string))

        if outputTexFile is not None:
            shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile)

        if not find_executable('latex'):
            raise RuntimeError("latex program is not installed")

        try:
            check_output(['latex', '-halt-on-error', '-interaction=nonstopmode',
                          'texput.tex'], cwd=workdir, stderr=STDOUT)
        except CalledProcessError as e:
            raise RuntimeError(
                "'latex' exited abnormally with the following output:\n%s" %
                e.output)

        if output != "dvi":
            defaultoptions = {
                "ps": [],
                "pdf": [],
                "png": ["-T", "tight", "-z", "9", "--truecolor"],
                "svg": ["--no-fonts"],
            }

            commandend = {
                "ps": ["-o", "texput.ps", "texput.dvi"],
                "pdf": ["texput.dvi", "texput.pdf"],
                "png": ["-o", "texput.png", "texput.dvi"],
                "svg": ["-o", "texput.svg", "texput.dvi"],
            }

            if output == "svg":
                cmd = ["dvisvgm"]
            else:
                cmd = ["dvi" + output]
            if not find_executable(cmd[0]):
                raise RuntimeError("%s is not installed" % cmd[0])
            try:
                if dvioptions is not None:
                    cmd.extend(dvioptions)
                else:
                    cmd.extend(defaultoptions[output])
                cmd.extend(commandend[output])
            except KeyError:
                raise SystemError("Invalid output format: %s" % output)

            try:
                check_output(cmd, cwd=workdir, stderr=STDOUT)
            except CalledProcessError as e:
                raise RuntimeError(
                    "'%s' exited abnormally with the following output:\n%s" %
                    (' '.join(cmd), e.output))

        src = "texput.%s" % (output)

        if viewer == "file":
            if filename is None:
                buffer = BytesIO()
                with open(join(workdir, src), 'rb') as fh:
                    buffer.write(fh.read())
                return buffer
            else:
                shutil.move(join(workdir,src), filename)
        elif viewer == "BytesIO":
            with open(join(workdir, src), 'rb') as fh:
                outputbuffer.write(fh.read())
        elif viewer == "pyglet":
            try:
                from pyglet import window, image, gl
                from pyglet.window import key
            except ImportError:
                raise ImportError("pyglet is required for preview.\n visit http://www.pyglet.org/")

            if output == "png":
                from pyglet.image.codecs.png import PNGImageDecoder
                img = image.load(join(workdir, src), decoder=PNGImageDecoder())
            else:
                raise SystemError("pyglet preview works only for 'png' files.")

            offset = 25

            config = gl.Config(double_buffer=False)
            win = window.Window(
                width=img.width + 2*offset,
                height=img.height + 2*offset,
                caption="sympy",
                resizable=False,
                config=config
            )

            win.set_vsync(False)

            try:
                def on_close():
                    win.has_exit = True

                win.on_close = on_close

                def on_key_press(symbol, modifiers):
                    if symbol in [key.Q, key.ESCAPE]:
                        on_close()

                win.on_key_press = on_key_press

                def on_expose():
                    gl.glClearColor(1.0, 1.0, 1.0, 1.0)
                    gl.glClear(gl.GL_COLOR_BUFFER_BIT)

                    img.blit(
                        (win.width - img.width) / 2,
                        (win.height - img.height) / 2
                    )

                win.on_expose = on_expose

                while not win.has_exit:
                    win.dispatch_events()
                    win.flip()
            except KeyboardInterrupt:
                pass

            win.close()
        else:
            try:
                check_output([viewer, src], cwd=workdir, stderr=STDOUT)
            except CalledProcessError as e:
                raise RuntimeError(
                    "'%s %s' exited abnormally with the following output:\n%s" %
                    (viewer, src, e.output))
    finally:
        try:
            shutil.rmtree(workdir) # delete directory
        except OSError as e:
            if e.errno != 2: # code 2 - no such file or directory
                raise
Esempio n. 15
0
 def _pretty(self, printer, *args):
     targets = self._print_sequence_pretty(self.targets, ",", printer, *args)
     gate_name = stringPict(unicode(self.gate_name))
     return self._print_subscript_pretty(gate_name, targets)
Esempio n. 16
0
 def _pretty(self, printer, *args):
     a = stringPict(unicode(self.gate_name))
     b = self._print_label_pretty(printer, *args)
     return self._print_subscript_pretty(a, b)