Example #1
0
def cplot_in_terminal(expr, *args, prec=None, logname=None, color=lambda i:
    -mpmath.floor(mpmath.log(abs(i), 10))/(30 -
        mpmath.floor(mpmath.log(abs(i), 10))), points=1000000, **kwargs):
    """
    Run mpmath.cplot() but show in terminal if possible
    """
    kwargs['color'] = color
    kwargs['points'] = points
    from mpmath import cplot
    if prec:
        mpmath.mp.dps = prec
    f = lambdify(t, expr, mpmath)
    try:
        from iterm2_tools.images import display_image_bytes
    except ImportError:
        if logname:
            os.makedirs('plots', exist_ok=True)
            file = 'plots/%s.png' % logname
        else:
            file = None
        cplot(f, *args, file=file, **kwargs)
    else:
        from io import BytesIO
        b = BytesIO()
        cplot(f, *args, **kwargs, file=b)
        if logname:
            os.makedirs('plots', exist_ok=True)
            with open('plots/%s.png' % logname, 'wb') as f:
                f.write(b.getvalue())
        print(display_image_bytes(b.getvalue()))
Example #2
0
def _pil_to_image(pil):
    from io import BytesIO
    from iterm2_tools.images import display_image_bytes

    b = BytesIO()
    pil.save(b, format='png')
    return display_image_bytes(b.getbuffer())
Example #3
0
def display_figure_with_iterm2(fig):
    """Displays a matplotlib figure using iterm2 inline-image escape sequence.

    Parameters
    ----------
    fig : matplotlib.figure.Figure
        the figure to be plotted
    """
    print(display_image_bytes(_get_buffer(fig, format='png', dpi=fig.dpi).read()))
Example #4
0
    def _mol_repr_pretty_(self, p, cycle):
        p.color_results = False
        drawer = rdMolDraw2D.MolDraw2DCairo(300, 300)
        if self.GetNumConformers() == 0:
            Compute2DCoords(self)

        drawer.DrawMolecule(self, highlightAtoms=getattr(self, "__sssAtoms", None))
        drawer.FinishDrawing()
        p.text(display_image_bytes(drawer.GetDrawingText()))
def imshow(image, colormap=False, video=False):
    import imageio
    import iterm2_tools
    from matplotlib import cm
    from scipy.misc import bytescale
    from PIL import Image
    from iterm2_tools.images import display_image_bytes

    if type(image).__name__ == 'Variable':
        image = image.data
    if 'torch.cuda' in type(image).__module__:
        image = image.cpu()
    if 'Tensor' in type(image).__name__:
        image = image.numpy()

    if colormap:
        image = (cm.Blues(image) * 255).astype(np.uint8)
    else:
        image = bytescale(image)

    if image.ndim == 4:
        video = True
    if image.ndim==3 and (image.shape[0] not in [1,3] and image.shape[-1] not in [1,3]):
        video = True

    if video:
        if image.shape[1] == 3:
            image = image.transpose([2,3,1]).astype(np.uint8)
        image = image.squeeze()
        if image.ndim == 2:
            image = image[None]
        images = [im for im in image]
        s = imageio.mimsave(imageio.RETURN_BYTES, images, format='gif', duration=0.3)
        print(display_image_bytes(s))
    else:
        if image.shape[0] == 3:
            image = image.transpose([1,2,0]).astype(np.uint8)
        image = image.squeeze()
        s = imageio.imsave(imageio.RETURN_BYTES, image, format='png')
        s = display_image_bytes(s)
        # Depending on the version of iterm2_tools, display_image_bytes can
        # either print directly to stdout or return the string to print.
        if s is not None:
            print(s)
Example #6
0
def plt_show_in_terminal(logname=None, show_without_iterm2=False):
    import matplotlib.pyplot as plt
    try:
        from iterm2_tools.images import display_image_bytes
    except ImportError:
        if show_without_iterm2:
            plt.show()
    else:
        b = io.BytesIO()
        plt.savefig(b, format='png')
        print(display_image_bytes(b.getvalue()))
    if logname:
        os.makedirs('plots', exist_ok=True)
        plt.savefig('plots/%s.png' % logname, format='png')
def output_plot(use_iterm2=True, format='png'):
    import matplotlib.pyplot as plt

    output = BytesIO()
    plt.savefig(output, format=format, dpi=None, bbox_inches='tight' )
    if use_iterm2:
        from iterm2_tools.images import display_image_bytes
        s = display_image_bytes(output.getvalue(), filename="plot.{}".format(format))
        # Depending on the version of iterm2_tools, display_image_bytes can
        # either print directly to stdout or return the string to print.
        if s is not None:
            print(s)
    else:
        sys.stdout.write(output.getvalue())
Example #8
0
def plot_in_terminal(expr, *args, prec=None, logname=None, file=None, **kwargs):
    """
    Run mpmath.plot() but show in terminal if possible
    """
    from mpmath import plot

    if logname:
        os.makedirs('plots', exist_ok=True)
        file = 'plots/%s.png' % logname

    if prec:
        mpmath.mp.dps = prec
    if isinstance(expr, (list, tuple)):
        f = [lambdify(t, i, 'mpmath') for i in expr]
    else:
        f = lambdify(t, expr, 'mpmath')

    try:
        if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
            from iterm2_tools.images import display_image_bytes
        else:
            raise ImportError
    except ImportError:
        plot(f, *args, file=file, **kwargs)
    else:
        # mpmath.plot ignores the axes argument if file is given, so let
        # file=False, disable this.
        if 'axes' in kwargs:
            file=False
        if file is not False:
            from io import BytesIO
            b = BytesIO()
        else:
            b = None
        plot(f, *args, **kwargs, file=b)
        if file:
            with open(file, 'wb') as f:
                f.write(b.getvalue())
        if b:
            print(display_image_bytes(b.getvalue()))