예제 #1
0
    def pretty_print(self):
        """
        Actually do the pretty print.

        EXAMPLES::

            sage: from sage.repl.rich_output.pretty_print import SequencePrettyPrinter
            sage: SequencePrettyPrinter(1, 2, 3).pretty_print()
            1 2 3

        The keyword arguments are only used the first time graphics
        output is generated::

            sage: seq = SequencePrettyPrinter(Graph(), Graph(), edge_labels=True)
            sage: seq.pretty_print()   # does not pass edge_labels to graphics object
            sage: seq._concatenate_graphs().show(edge_labels=True)
            Traceback (most recent call last):
            ...
            TypeError: matplotlib() got an unexpected keyword argument 'edge_labels'
        """
        from sage.plot.plot import Graphics
        from sage.graphs.graph import GenericGraph
        if self.is_homogeneous(GenericGraph):
            args = self._concatenate_graphs()
            kwds = dict()
        elif self.is_homogeneous(Graphics):
            args = self._concatenate_graphics()
            kwds = dict()
        else:
            args = self.args
            kwds = dict(self.kwds)
            kwds['concatenate'] = True
        get_display_manager().display_immediately(args, **kwds)
예제 #2
0
    def pretty_print(self):
        """
        Actually do the pretty print.

        EXAMPLES::

            sage: from sage.repl.rich_output.pretty_print import SequencePrettyPrinter
            sage: SequencePrettyPrinter(1, 2, 3).pretty_print()
            1 2 3

        The keyword arguments are only used the first time graphics
        output is generated::

            sage: seq = SequencePrettyPrinter(Graph(), Graph(), edge_labels=True)
            sage: seq.pretty_print()   # does not pass edge_labels to graphics object
            sage: seq._concatenate_graphs().show(edge_labels=True)
            Traceback (most recent call last):
            ...
            TypeError: matplotlib() got an unexpected keyword argument 'edge_labels'
        """
        from sage.plot.plot import Graphics
        from sage.graphs.graph import GenericGraph
        if self.is_homogeneous(GenericGraph):
            args = self._concatenate_graphs()
            kwds = dict()
        elif self.is_homogeneous(Graphics):
            args = self._concatenate_graphics()
            kwds = dict()
        else:
            args = self.args
            kwds = dict(self.kwds)
            kwds['concatenate'] = True
        get_display_manager().display_immediately(args, **kwds)
예제 #3
0
def mathics_console():
    r"""
    Spawn a new Mathics command-line session.

    EXAMPLES::

        sage: mathics_console()  # not tested

        Mathics 2.1.1.dev0
        on CPython 3.9.2 (default, Mar 19 2021, 22:23:28)
        using SymPy 1.7, mpmath 1.2.1, numpy 1.19.5, cython 0.29.21

        Copyright (C) 2011-2021 The Mathics Team.
        This program comes with ABSOLUTELY NO WARRANTY.
        This is free software, and you are welcome to redistribute it
        under certain conditions.
        See the documentation for the full license.

        Quit by evaluating Quit[] or by pressing CONTROL-D.

        In[1]:= Sin[0.5]
        Out[1]= 0.479426

        Goodbye!
    """
    from sage.repl.rich_output.display_manager import get_display_manager
    if not get_display_manager().is_in_terminal():
        raise RuntimeError('Can use the console only in the terminal. Try %%mathics magics instead.')
    from mathics import main
    main.main()
예제 #4
0
    def show(self, ImageSize=600):
        r"""
        Show a mathics expression immediately.

        This method attempts to display the graphics immediately,
        without waiting for the currently running code (if any) to
        return to the command line. Be careful, calling it from within
        a loop will potentially launch a large number of external
        viewer programs.

        INPUT:

        - ``ImageSize`` -- integer. The size of the resulting image.

        OUTPUT:

        This method does not return anything. Use :meth:`save` if you
        want to save the figure as an image.

        EXAMPLES::

            sage: Q = mathics('Sin[x Cos[y]]/Sqrt[1-x^2]')   # optional - mathics
            sage: show(Q)                                    # optional - mathics
            Sin[x Cos[y]] / Sqrt[1 - x ^ 2]

            sage: P = mathics('Plot[Sin[x],{x,-2Pi,4Pi}]')   # optional - mathics
            sage: show(P)                                    # optional - mathics
            sage: P.show(ImageSize=800)                      # optional - mathics
        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        dm.display_immediately(self, ImageSize=ImageSize)
예제 #5
0
    def threejs_offline_scripts(self):
        """
        Three.js scripts for the IPython notebook

        OUTPUT:

        String containing script tags

        EXAMPLES::

            sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
            sage: backend = BackendIPythonNotebook()
            sage: backend.threejs_offline_scripts()
            '...<script src="/nbextensions/threejs/build/three.min...<\\/script>...'
        """
        from sage.repl.rich_output import get_display_manager
        CDN_scripts = get_display_manager().threejs_scripts(online=True)
        return """
<script src="/nbextensions/threejs/build/three.min.js"></script>
<script src="/nbextensions/threejs/examples/js/controls/OrbitControls.js"></script>
<script>
  if ( !window.THREE ) document.write('{}');
</script>
        """.format(
            CDN_scripts.replace('</script>',
                                r'<\/script>').replace('\n', ' \\\n'))
예제 #6
0
def pretty_print_default(enable=True):
    r"""
    Enable or disable default pretty printing.

    Pretty printing means rendering things in HTML and by MathJax so that a
    browser-based frontend can render real math.

    This function is pretty useless without the notebook, it should not
    be in the global namespace.

    INPUT:

    -  ``enable`` -- bool (optional, default ``True``).  If ``True``, turn on
       pretty printing; if ``False``, turn it off.

    EXAMPLES::

        sage: pretty_print_default(True)
        sage: 'foo'  # the doctest backend does not support html
        'foo'
        sage: pretty_print_default(False)
        sage: 'foo'
        'foo'
    """
    from sage.repl.rich_output import get_display_manager
    dm = get_display_manager()
    dm.preferences.text = 'latex' if enable else None
예제 #7
0
파일: mathematica.py 프로젝트: Babyll/sage
    def show(self, ImageSize=600):
        r"""
        Show a mathematica expression immediately.

        This method attempts to display the graphics immediately,
        without waiting for the currently running code (if any) to
        return to the command line. Be careful, calling it from within
        a loop will potentially launch a large number of external
        viewer programs.

        INPUT:

        - ``ImageSize`` -- integer. The size of the resulting image.

        OUTPUT:

        This method does not return anything. Use :meth:`save` if you
        want to save the figure as an image.

        EXAMPLES::

            sage: P = mathematica('Plot[Sin[x],{x,-2Pi,4Pi}]')   # optional - mathematica
            sage: show(P)                                        # optional - mathematica
            sage: P.show(ImageSize=800)                          # optional - mathematica
            sage: Q = mathematica('Sin[x Cos[y]]/Sqrt[1-x^2]')   # optional - mathematica
            sage: show(Q)                                        # optional - mathematica
            <html><script type="math/tex">\frac{\sin (x \cos (y))}{\sqrt{1-x^2}}</script></html>
        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        dm.display_immediately(self, ImageSize=ImageSize)
예제 #8
0
파일: mathematica.py 프로젝트: yjjcc/sage
    def show(self, ImageSize=600):
        r"""
        Show a mathematica expression immediately.

        This method attempts to display the graphics immediately,
        without waiting for the currently running code (if any) to
        return to the command line. Be careful, calling it from within
        a loop will potentially launch a large number of external
        viewer programs.

        INPUT:

        - ``ImageSize`` -- integer. The size of the resulting image.

        OUTPUT:

        This method does not return anything. Use :meth:`save` if you
        want to save the figure as an image.

        EXAMPLES::

            sage: Q = mathematica('Sin[x Cos[y]]/Sqrt[1-x^2]')   # optional - mathematica
            sage: show(Q)                                        # optional - mathematica
            <html><script type="math/tex">\frac{\sin (x \cos (y))}{\sqrt{1-x^2}}</script></html>

        The following example starts a Mathematica frontend to do the rendering
        (:trac:`28819`)::

            sage: P = mathematica('Plot[Sin[x],{x,-2Pi,4Pi}]')   # optional - mathematica
            sage: show(P)                                        # optional - mathematica mathematicafrontend
            sage: P.show(ImageSize=800)                          # optional - mathematica mathematicafrontend
        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        dm.display_immediately(self, ImageSize=ImageSize)
예제 #9
0
def DisplayHook():
    """
    This function is called by SageNB to set up its displayhook.

    OUTPUT:

    The new displayhook that will be used by SageNB

    EXAMPLES::

        sage: from sage.misc.displayhook import DisplayHook
        sage: d = DisplayHook()
        sage: d
        <bound method DisplayManager.displayhook of The 
        Sage display manager using the SageNB backend>

        sage: d(set([1, 2, 3]))       # Sage commandline output
        {1, 2, 3}

        sage: from sage.repl.rich_output import get_display_manager
        sage: get_display_manager()
        The Sage display manager using the SageNB backend
    """
    display_manager = get_display_manager()
    backend = BackendSageNB()
    display_manager.switch_backend(backend)
    return display_manager.displayhook
예제 #10
0
    def threejs_offline_scripts(self):
        """
        Three.js script for the IPython notebook

        OUTPUT:

        String containing script tag

        EXAMPLES::

            sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
            sage: backend = BackendIPythonNotebook()
            sage: backend.threejs_offline_scripts()
            '...<script src="/nbextensions/threejs-sage/r.../three.min.js...<\\/script>...'
        """
        from sage.repl.rich_output import get_display_manager
        from sage.repl.rich_output.display_manager import _required_threejs_version
        CDN_script = get_display_manager().threejs_scripts(online=True)
        CDN_script = CDN_script.replace('</script>',
                                        r'<\/script>').replace('\n', ' \\\n')
        return """
<script src="/nbextensions/threejs-sage/{}/three.min.js"></script>
<script>
  if ( !window.THREE ) document.write('{}');
</script>
        """.format(_required_threejs_version(), CDN_script)
예제 #11
0
파일: mathematica.py 프로젝트: Babyll/sage
def mathematica_console(readline=True):
    from sage.repl.rich_output.display_manager import get_display_manager
    if not get_display_manager().is_in_terminal():
        raise RuntimeError('Can use the console only in the terminal. Try %%mathematica magics instead.')
    if not readline:
        os.system('math')
        return
    else:
        os.system('math-readline')
        return
예제 #12
0
def mathematica_console(readline=True):
    from sage.repl.rich_output.display_manager import get_display_manager
    if not get_display_manager().is_in_terminal():
        raise RuntimeError('Can use the console only in the terminal. Try %%mathematica magics instead.')
    if not readline:
        os.system('math')
        return
    else:
        os.system('math-readline')
        return
예제 #13
0
    def threejs_offline_scripts(self):
        """
        Three.js scripts for the Sage notebook

        OUTPUT:

        String containing script tags

        EXAMPLES::

            sage: from sage.repl.rich_output.backend_sagenb import BackendSageNB
            sage: backend = BackendSageNB()
            sage: backend.threejs_offline_scripts()
            '...<script ...</script>...'
        """
        from sage.repl.rich_output import get_display_manager
        return get_display_manager().threejs_scripts(online=True)
예제 #14
0
    def get_display_manager(self):
        """
        Return the display manager singleton

        This is a convenience method to access the display manager
        singleton.

        OUTPUT:

        The unique
        :class:`~sage.repl.rich_output.display_manager.DisplayManager`
        instance.

        EXAMPLES::

            sage: from sage.repl.rich_output.backend_base import BackendBase
            sage: backend = BackendBase()
            sage: backend.get_display_manager()
            The Sage display manager using the doctest backend
        """
        from sage.repl.rich_output import get_display_manager
        return get_display_manager()
예제 #15
0
    def get_display_manager(self):
        """
        Return the display manager singleton

        This is a convenience method to access the display manager
        singleton.

        OUTPUT:

        The unique
        :class:`~sage.repl.rich_output.display_manager.DisplayManager`
        instance.

        EXAMPLES::

            sage: from sage.repl.rich_output.backend_base import BackendBase
            sage: backend = BackendBase()
            sage: backend.get_display_manager()
            The Sage display manager using the doctest backend
        """
        from sage.repl.rich_output import get_display_manager
        return get_display_manager()
예제 #16
0
    def threejs_offline_scripts(self):
        """
        Three.js scripts for the IPython notebook

        OUTPUT:

        String containing script tags

        EXAMPLES::

            sage: from sage.repl.rich_output.backend_ipython import BackendIPythonNotebook
            sage: backend = BackendIPythonNotebook()
            sage: backend.threejs_offline_scripts()
            '...<script src="/nbextensions/threejs/three.min...<\\/script>...'
        """
        from sage.repl.rich_output import get_display_manager
        CDN_scripts = get_display_manager().threejs_scripts(online=True)
        return """
<script src="/nbextensions/threejs/three.min.js"></script>
<script src="/nbextensions/threejs/OrbitControls.js"></script>
<script>
  if ( !window.THREE ) document.write('{}');
</script>
        """.format(CDN_scripts.replace('</script>', r'<\/script>'))
예제 #17
0
파일: image.py 프로젝트: manguluka/sage
    def show(self):
        r"""
        Show this image immediately.

        This method attempts to display the graphics immediately,
        without waiting for the currently running code (if any) to
        return to the command line. Be careful, calling it from within
        a loop will potentially launch a large number of external
        viewer programs.

        OUTPUT:

        This method does not return anything. Use :meth:`save` if you
        want to save the figure as an image.

        EXAMPLES::

            sage: from sage.repl.image import Image
            sage: img = Image('1', (12, 34), 'white')
            sage: img.show()
        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        dm.display_immediately(self)
예제 #18
0
파일: image.py 프로젝트: mcognetta/sage
    def show(self):
        r"""
        Show this image immediately.

        This method attempts to display the graphics immediately,
        without waiting for the currently running code (if any) to
        return to the command line. Be careful, calling it from within
        a loop will potentially launch a large number of external
        viewer programs.

        OUTPUT:

        This method does not return anything. Use :meth:`save` if you
        want to save the figure as an image.

        EXAMPLES::

            sage: from sage.repl.image import Image
            sage: img = Image('1', (12, 34), 'white')
            sage: img.show()
        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        dm.display_immediately(self)
예제 #19
0
def pretty_print(*args, **kwds):
    r"""
    Pretty print the arguments in an intelligent way.

    For a single positional argument, this function chooses the
    highest-quality output supported by the user interface.

    For certain homogeneous multiple positional arguments a suitable
    combined graphical output is generated. In particular, graphs and
    plots are treated special.

    Otherwise this function will concatenate the textual
    representations. Latex output is preferred if none is specified
    via
    :meth:`~sage.repl.rich_output.display_manager.DisplayManager.preferences`.

    INPUT:

    - ``*args`` -- any number of positional arguments. The objects to
      pretty print. If the single argument is an iterator/generator
      then it is expanded.

    - ``**kwds`` -- optional keyword arguments that are passed to the
      rich representation. Examples include:

        - ``dpi`` - dots per inch

        - ``figsize``- [width, height] (same for square aspect)

        - ``axes`` - (default: True)

        - ``fontsize`` - positive integer

        - ``frame`` - (default: False) draw a MATLAB-like frame around
          the image

    EXAMPLES::

        sage: pretty_print(ZZ)
        Integer Ring

        sage: pretty_print("Integers = ", ZZ) # trac 11775
        'Integers = ' Integer Ring

    To typeset LaTeX code as-is, use :class:`LatexExpr`::

        sage: pretty_print(LatexExpr(r"\frac{x^2 + 1}{x - 2}"))
        \frac{x^2 + 1}{x - 2}

    TESTS::

        sage: plt = plot(sin)
        sage: pretty_print(plt)             # graphics output
        sage: pretty_print(ZZ, 123, plt)    # optional - latex
        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z} 123 %% Creator: Matplotlib, PGF backend...</script></html>
        sage: pretty_print(plt, plt)        # graphics output
    """
    dm = get_display_manager()
    old_preferences_text = dm.preferences.text
    try:
        if dm.preferences.text is None:
            dm.preferences.text = 'latex'
        if len(args) == 0:
            pass
        elif len(args) == 1:
            dm.display_immediately(*args, **kwds)
        else:
            SequencePrettyPrinter(*args, **kwds).pretty_print()
    finally:
        dm.preferences.text = old_preferences_text
예제 #20
0
def pretty_print(*args, **kwds):
    r"""
    Pretty print the arguments using rich output if available.

    This function is similar to ``print()``, except that a rich output
    representation such as ``ascii_art`` or Latex is printed instead of the
    string representation.

    Note that the output depends on the global display preferences specified
    via
    :meth:`~sage.repl.rich_output.display_manager.DisplayManager.preferences`.
    If the display preference for ``text`` is not specified, Latex output is
    preferred.

    For graphical objects, a graphical output is used.

    For certain homogeneous multiple positional arguments, a suitable
    combined graphical output is generated. In particular, graphs and
    plots are treated special. Otherwise this function concatenates the
    textual representations.

    INPUT:

    - ``*args`` -- any number of positional arguments. The objects to
      pretty print.

    - ``**kwds`` -- optional keyword arguments that are passed to the
      rich representation. Examples include:

        - ``dpi`` - dots per inch

        - ``figsize``- [width, height] (same for square aspect)

        - ``axes`` - (default: True)

        - ``fontsize`` - positive integer

        - ``frame`` - (default: False) draw a MATLAB-like frame around
          the image

    EXAMPLES::

        sage: pretty_print(ZZ)
        Integer Ring

        sage: pretty_print("Integers = ", ZZ) # trac 11775
        'Integers = ' Integer Ring

    To typeset LaTeX code as-is, use :class:`LatexExpr`::

        sage: pretty_print(LatexExpr(r"\frac{x^2 + 1}{x - 2}"))
        \frac{x^2 + 1}{x - 2}

    For text-based backends, the default text display preference is to output
    plain text which is usually the same as using ``print()``::

        sage: pretty_print(x^2 / (x + 1))
        x^2/(x + 1)

        sage: t = BinaryTrees(3).first()
        sage: pretty_print(t)
        [., [., [., .]]]
        sage: print(t)
        [., [., [., .]]]

    TESTS::

        sage: dm = get_display_manager()
        sage: dm.preferences.text = 'ascii_art'

    EXAMPLES:

    Changing the text display preference affects the output of this function.
    The following illustrates a possible use-case::

        sage: %display ascii_art  # not tested
        sage: for t in BinaryTrees(3)[:3]:
        ....:     pretty_print(t)
        o
         \
          o
           \
            o
        o
         \
          o
         /
        o
          o
         / \
        o   o

        sage: pretty_print(x^2 / (x + 1))
           2
          x
        -----
        x + 1

    TESTS:

    After the previous example, we need to reset the text display preferences::

        sage: dm.preferences.text = None

    ::

        sage: plt = plot(sin)
        sage: pretty_print(plt)             # graphics output
        sage: pretty_print(plt, plt)        # graphics output
        sage: pretty_print(ZZ, 123, plt)
        Integer Ring 123 Graphics object consisting of 1 graphics primitive
    """
    dm = get_display_manager()
    old_preferences_text = dm.preferences.text
    try:
        if dm.preferences.text is None:
            dm.preferences.text = 'latex'
        if len(args) == 0:
            pass
        elif len(args) == 1:
            dm.display_immediately(*args, **kwds)
        else:
            SequencePrettyPrinter(*args, **kwds).pretty_print()
    finally:
        dm.preferences.text = old_preferences_text
예제 #21
0
def pretty_print(*args, **kwds):
    r"""
    Pretty print the arguments in an intelligent way.
    
    For a single positional argument, this function chooses the
    highest-quality output supported by the user interface.
    
    For certain homogeneous multiple positional arguments a suitable
    combined graphical output is generated. In particular, graphs and
    plots are treated special.

    Otherwise this function will concatenate the textual
    representations. Latex output is preferred if none is specified
    via
    :meth:`~sage.repl.rich_output.display_manager.DisplayManager.preferences`.

    INPUT:

    - ``*args`` -- any number of positional arguments. The objects to
      pretty print. If the single argument is an iterator/generator
      then it is expanded.

    - ``**kwds`` -- optional keyword arguments that are passed to the
      rich representation. Examples include:

        - ``dpi`` - dots per inch

        - ``figsize``- [width, height] (same for square aspect)

        - ``axes`` - (default: True)

        - ``fontsize`` - positive integer

        - ``frame`` - (default: False) draw a MATLAB-like frame around
          the image

    EXAMPLES::

        sage: pretty_print(ZZ)
        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z}</script></html>

        sage: pretty_print("Integers = ", ZZ) # trac 11775
        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\verb|Integers|\phantom{\verb!x!}\verb|=| \Bold{Z}</script></html>

    To typeset LaTeX code as-is, use :class:`LatexExpr`::

        sage: pretty_print(LatexExpr(r"\frac{x^2 + 1}{x - 2}"))
        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\frac{x^2 + 1}{x - 2}</script></html>

    Iterators and generators are unwrapped::

        sage: iterator = iter(range(3));  iterator
        <listiterator object at 0x...>
        sage: pretty_print(iterator)
        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}0 1 2</script></html>

    TESTS::

        sage: plt = plot(sin)
        sage: pretty_print(plt)             # graphics output
        sage: pretty_print(ZZ, 123, plt)    # latex output
        <html><script type="math/tex">\newcommand{\Bold}[1]{\mathbf{#1}}\Bold{Z} 123 \verb|Graphics|\phantom{\verb!x!}\verb|object|\phantom{\verb!x!}\verb|consisting|\phantom{\verb!x!}\verb|of|\phantom{\verb!x!}\verb|1|\phantom{\verb!x!}\verb|graphics|\phantom{\verb!x!}\verb|primitive|</script></html>
        sage: pretty_print(plt, plt)        # graphics output
    """
    if len(args) == 1 and isinstance(args[0], (types.GeneratorType, collections.Iterator)):
        args = tuple(args[0])

    # Support deprecation trac #18292
    if len(args) == 1:
        import sage.misc.html
        if sage.misc.html.WarnIfNotPrinted.skip_pretty_print(args[0]):
            return

    dm = get_display_manager()
    old_preferences_text = dm.preferences.text
    try:
        if dm.preferences.text is None:
            dm.preferences.text = 'latex'
        if len(args) == 0:
            pass
        elif len(args) == 1:
            dm.display_immediately(*args, **kwds)
        else:
            SequencePrettyPrinter(*args, **kwds).pretty_print()
    finally:
        dm.preferences.text = old_preferences_text
예제 #22
0
    def display(self, args):
        r"""
        A magic command to switch between simple display and ASCII art display.

        - ``args`` -- string.  See
          :meth:`sage.misc.display_hook.DisplayHookBase.set_display`
          for allowed values. If the mode is ``ascii_art``, it can
          optionally be followed by a width.

        How to use: if you want activate the ASCII art mod::

            sage: from sage.repl.interpreter import get_test_shell
            sage: shell = get_test_shell()
            sage: shell.run_cell('%display ascii_art')

        That means you don't have to use :func:`ascii_art` to get an ASCII art
        output::

            sage: shell.run_cell("i = var('i')")
            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')
                 10       9       8       7       6       5       4      3      2
            100*x   + 81*x  + 64*x  + 49*x  + 36*x  + 25*x  + 16*x  + 9*x  + 4*x  + x

        Then when you want return in 'textual mode'::

            sage: shell.run_cell('%display text plain')
            sage: shell.run_cell('%display plain')        # shortcut for "text plain"
            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')
            100*x^10 + 81*x^9 + 64*x^8 + 49*x^7 + 36*x^6 + 25*x^5 + 16*x^4 + 9*x^3 + 4*x^2 + x

        Sometime you could have to use a special output width and you
        could specify it::

            sage: shell.run_cell('%display ascii_art')
            sage: shell.run_cell('StandardTableaux(4).list()')
            [
            [                                                                  1  4
            [                 1  3  4    1  2  4    1  2  3    1  3    1  2    2
            [   1  2  3  4,   2      ,   3      ,   4      ,   2  4,   3  4,   3   ,
            <BLANKLINE>
                               1 ]
               1  3    1  2    2 ]
               2       3       3 ]
               4   ,   4   ,   4 ]
            sage: shell.run_cell('%display ascii_art 50')
            sage: shell.run_cell('StandardTableaux(4).list()')
            [
            [
            [                 1  3  4    1  2  4    1  2  3
            [   1  2  3  4,   2      ,   3      ,   4      ,
            <BLANKLINE>
                                                      1 ]
                              1  4    1  3    1  2    2 ]
              1  3    1  2    2       2       3       3 ]
              2  4,   3  4,   3   ,   4   ,   4   ,   4 ]

        As yet another option, typeset mode. This is used in the emacs
        interface::

            sage: shell.run_cell('%display text latex')
            sage: shell.run_cell('1/2')
            \newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2}

        Switch back::

            sage: shell.run_cell('%display default')

        Switch graphics to default to vector or raster graphics file
        formats::

            sage: shell.run_cell('%display graphics vector')

        TESTS::

            sage: shell.run_cell('%display invalid_mode')
            value must be unset (None) or one of ('plain', 'ascii_art', 'unicode_art', 'latex'), got invalid_mode
            sage: shell.quit()
        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        args = args.strip().split()
        if not args:
            print(dm.preferences)
            return
        arg0 = args[0]
        # deprecated values
        if arg0 == 'simple':
            dm.preferences.text = 'plain'
        elif arg0 == 'typeset':
            dm.preferences.text = 'latex'
        elif arg0 in ['ascii_art', 'unicode_art'] and len(args) > 1:
            try:
                max_width = int(args[1])
            except ValueError:
                max_width = 0
            if max_width <= 0:
                raise ValueError(
                        "max width must be a positive integer")
            import sage.typeset.character_art as character_art
            character_art.MAX_WIDTH = max_width
            dm.preferences.text = arg0
        # Unset all
        elif arg0 in ['default', 'None']:  # un-stringify "%display None"
            for option in map(str, dm.preferences.available_options()):
                delattr(dm.preferences, option)
        # Normal argument handling
        elif arg0 in map(str, dm.preferences.available_options()) and len(args) <= 2:
            if len(args) == 1:
                # "%display text" => get current value
                print(getattr(dm.preferences, arg0))
            else:
                # "%display text latex" => set new value
                assert len(args) == 2
                if args[1] in ['default', 'None']:
                    delattr(dm.preferences, arg0)
                else:
                    try:
                        setattr(dm.preferences, arg0, args[1])
                    except ValueError as err:
                        print(err)  # do not show traceback
        # If all else fails: assume text
        else:
            try:
                dm.preferences.text = arg0
            except ValueError as err:
                print(err)  # do not show traceback
예제 #23
0
    def display(self, args):
        r"""
        A magic command to switch between simple display and ASCII art display.

        - ``args`` -- string.  See
          :meth:`sage.misc.display_hook.DisplayHookBase.set_display`
          for allowed values. If the mode is ``ascii_art``, it can
          optionally be followed by a width.

        How to use: if you want to activate the ASCII art mode::

            sage: from sage.repl.interpreter import get_test_shell
            sage: shell = get_test_shell()
            sage: shell.run_cell('%display ascii_art')

        That means you do not have to use :func:`ascii_art` to get an ASCII art
        output::

            sage: shell.run_cell("i = var('i')")
            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')
                 10       9       8       7       6       5       4      3      2
            100*x   + 81*x  + 64*x  + 49*x  + 36*x  + 25*x  + 16*x  + 9*x  + 4*x  + x

        Then when you want to return to 'textual mode'::

            sage: shell.run_cell('%display text plain')
            sage: shell.run_cell('%display plain')        # shortcut for "text plain"
            sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')
            100*x^10 + 81*x^9 + 64*x^8 + 49*x^7 + 36*x^6 + 25*x^5 + 16*x^4 + 9*x^3 + 4*x^2 + x

        Sometime you could have to use a special output width and you
        could specify it::

            sage: shell.run_cell('%display ascii_art')
            sage: shell.run_cell('StandardTableaux(4).list()')
            [
            [                                                                  1  4    1  3
            [                 1  3  4    1  2  4    1  2  3    1  3    1  2    2       2
            [   1  2  3  4,   2      ,   3      ,   4      ,   2  4,   3  4,   3   ,   4   ,
            <BLANKLINE>
                       1 ]
               1  2    2 ]
               3       3 ]
               4   ,   4 ]
            sage: shell.run_cell('%display ascii_art 50')
            sage: shell.run_cell('StandardTableaux(4).list()')
            [
            [
            [                 1  3  4    1  2  4    1  2  3
            [   1  2  3  4,   2      ,   3      ,   4      ,
            <BLANKLINE>
                                                      1 ]
                              1  4    1  3    1  2    2 ]
              1  3    1  2    2       2       3       3 ]
              2  4,   3  4,   3   ,   4   ,   4   ,   4 ]

        As yet another option, typeset mode. This is used in the emacs
        interface::

            sage: shell.run_cell('%display text latex')
            sage: shell.run_cell('1/2')
            \newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2}

        Switch back::

            sage: shell.run_cell('%display default')

        Switch graphics to default to vector or raster graphics file
        formats::

            sage: shell.run_cell('%display graphics vector')

        TESTS::

            sage: shell.run_cell('%display invalid_mode')
            value must be unset (None) or one of ('plain', 'ascii_art', 'unicode_art', 'latex'), got invalid_mode
            sage: shell.quit()
        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        args = args.strip().split()
        if not args:
            print(dm.preferences)
            return
        arg0 = args[0]
        # deprecated values
        if arg0 == 'simple':
            dm.preferences.text = 'plain'
        elif arg0 == 'typeset':
            dm.preferences.text = 'latex'
        elif arg0 in ['ascii_art', 'unicode_art'] and len(args) > 1:
            try:
                max_width = int(args[1])
            except ValueError:
                max_width = 0
            if max_width <= 0:
                raise ValueError(
                        "max width must be a positive integer")
            import sage.typeset.character_art as character_art
            character_art.MAX_WIDTH = max_width
            dm.preferences.text = arg0
        # Unset all
        elif arg0 in ['default', 'None']:  # un-stringify "%display None"
            for option in map(str, dm.preferences.available_options()):
                delattr(dm.preferences, option)
        # Normal argument handling
        elif arg0 in map(str, dm.preferences.available_options()) and len(args) <= 2:
            if len(args) == 1:
                # "%display text" => get current value
                print(getattr(dm.preferences, arg0))
            else:
                # "%display text latex" => set new value
                assert len(args) == 2
                if args[1] in ['default', 'None']:
                    delattr(dm.preferences, arg0)
                else:
                    try:
                        setattr(dm.preferences, arg0, args[1])
                    except ValueError as err:
                        print(err)  # do not show traceback
        # If all else fails: assume text
        else:
            try:
                dm.preferences.text = arg0
            except ValueError as err:
                print(err)  # do not show traceback
예제 #24
0
        return "Emacs babel"

    def displayhook(self, plain_text, rich_output):
        if isinstance(rich_output, OutputImagePng):
            msg = rich_output.png.filename(ext='png')
            babel_filename = self.state.filename
            if babel_filename is not None:
                rich_output.png.save_as(babel_filename)
                msg = babel_filename
            return ({u'text/plain': msg}, {})
        else:
            return super(BackendEmacsBabel,
                         self).displayhook(plain_text, rich_output)


gdm = get_display_manager()


def run_cell_babel_base(run_cell_func,
                        filename=None,
                        latex=None,
                        latex_formatter=None):
    last_state.filename = filename
    last_state.result = None
    last_state.latex = latex
    last_state.latex_formatter = latex_formatter

    backend_ob_sage = BackendEmacsBabel(last_state)
    with sagebackend(backend_ob_sage):
        res = run_cell_func()
        if res.success:
예제 #25
0
    def show(self, **kwds):
        r"""
        Show ``self`` immediately.

        This method attempts to display the graphics immediately,
        without waiting for the currently running code (if any) to
        return to the command line. Be careful, calling it from within
        a loop will potentially launch a large number of external
        viewer programs.

        OPTIONAL INPUT:

        - ``dpi`` -- dots per inch

        - ``figsize`` -- width or [width, height] of the figure, in inches; the
          default is 6.4 x 4.8 inches

        - ``axes`` -- boolean; if ``True``, all individual graphics are
          endowed with axes; if ``False``, all axes are removed (this overrides
          the ``axes`` option set in each graphics)

        - ``frame`` -- boolean; if ``True``, all individual graphics are
          drawn with a frame around them; if ``False``, all frames are removed
          (this overrides the ``frame`` option set in each graphics)

        - ``fontsize`` -- positive integer, the size of fonts for the axes
          labels (this overrides the ``fontsize`` option set in each graphics)

        OUTPUT:

        This method does not return anything. Use :meth:`save` if you
        want to save the figure as an image.

        EXAMPLES:

        This draws a graphics array with four trig plots and no axes in any of
        the plots and a figure width of 4 inches::

            sage: G = graphics_array([[plot(sin), plot(cos)],
            ....:                     [plot(tan), plot(sec)]])
            sage: G.show(axes=False, figsize=4)

        .. PLOT::

            G = graphics_array([[plot(sin), plot(cos)], \
                                [plot(tan), plot(sec)]])
            sphinx_plot(G, axes=False, figsize=4)

        Same thing with a frame around each individual graphics::

            sage: G.show(axes=False, frame=True, figsize=4)

        .. PLOT::

            G = graphics_array([[plot(sin), plot(cos)], \
                                [plot(tan), plot(sec)]])
            sphinx_plot(G, axes=False, frame=True, figsize=4)

        Actually, many options are possible; for instance, we may set
        ``fontsize`` and ``gridlines``::

            sage: G.show(axes=False, frame=True, figsize=4, fontsize=8,
            ....:        gridlines='major')

        .. PLOT::

            G = graphics_array([[plot(sin), plot(cos)], \
                                [plot(tan), plot(sec)]])
            sphinx_plot(G, axes=False, frame=True, figsize=4, fontsize=8, \
                        gridlines='major')

        """
        from sage.repl.rich_output import get_display_manager
        dm = get_display_manager()
        dm.display_immediately(self, **kwds)
예제 #26
0
    def _repr_(self):
        return "Emacs babel"

    def displayhook(self, plain_text, rich_output):
        if isinstance(rich_output, OutputImagePng):
            msg = rich_output.png.filename(ext='png')
            babel_filename = self.state.filename
            if babel_filename is not None:
                rich_output.png.save_as(babel_filename)
                msg = babel_filename
            return ({u'text/plain': msg}, {})
        else:
            return super(BackendEmacsBabel, self).displayhook(plain_text, rich_output)


gdm = get_display_manager()


def run_cell_babel_base(run_cell_func,
                        filename=None, latex=None, latex_formatter=None):
    last_state.filename = filename
    last_state.result = None
    last_state.latex = latex
    last_state.latex_formatter = latex_formatter

    backend_ob_sage = BackendEmacsBabel(last_state)
    with sagebackend(backend_ob_sage):
        res = run_cell_func()
        if res.success:
            last_state.result = res.result
            print(0)