Exemple #1
0
def test_latex_to_png_color():
    """
    Test color settings for latex_to_png.
    """
    latex_string = "$x^2$"
    default_value = latextools.latex_to_png(latex_string, wrap=False)
    default_hexblack = latextools.latex_to_png(latex_string,
                                               wrap=False,
                                               color="#000000")
    dvipng_default = latextools.latex_to_png_dvipng(latex_string, False)
    dvipng_black = latextools.latex_to_png_dvipng(latex_string, False, "Black")
    nt.assert_equal(dvipng_default, dvipng_black)
    mpl_default = latextools.latex_to_png_mpl(latex_string, False)
    mpl_black = latextools.latex_to_png_mpl(latex_string, False, "Black")
    nt.assert_equal(mpl_default, mpl_black)
    nt.assert_in(default_value, [dvipng_black, mpl_black])
    nt.assert_in(default_hexblack, [dvipng_black, mpl_black])

    # Test that dvips name colors can be used without error
    dvipng_maroon = latextools.latex_to_png_dvipng(latex_string, False,
                                                   "Maroon")
    # And that it doesn't return the black one
    nt.assert_not_equal(dvipng_black, dvipng_maroon)

    mpl_maroon = latextools.latex_to_png_mpl(latex_string, False, "Maroon")
    nt.assert_not_equal(mpl_black, mpl_maroon)
    mpl_white = latextools.latex_to_png_mpl(latex_string, False, "White")
    mpl_hexwhite = latextools.latex_to_png_mpl(latex_string, False, "#FFFFFF")
    nt.assert_equal(mpl_white, mpl_hexwhite)

    mpl_white_scale = latextools.latex_to_png_mpl(latex_string, False, "White",
                                                  1.2)
    nt.assert_not_equal(mpl_white, mpl_white_scale)
    def _append_latex(self, latex, before_prompt=False, metadata=None):
        """ Append latex data to the widget."""
        png = None

        if self._is_latex_math(latex):
            png = latex_to_png(latex,
                               wrap=False,
                               backend='dvipng',
                               color=self._get_color('fgcolor'))

        # Matplotlib only supports strings enclosed in dollar signs
        if png is None and latex.startswith('$') and latex.endswith('$'):
            # To avoid long and ugly errors, like the one reported in
            # spyder-ide/spyder#7619
            try:
                png = latex_to_png(latex,
                                   wrap=False,
                                   backend='matplotlib',
                                   color=self._get_color('fgcolor'))
            except Exception:
                pass

        if png:
            self._append_png(png, before_prompt, metadata)
        else:
            raise LatexError
Exemple #3
0
def test_latex_to_png_color():
    """
    Test color settings for latex_to_png.
    """
    latex_string = "$x^2$"
    default_value = latextools.latex_to_png(latex_string, wrap=False)
    default_hexblack = latextools.latex_to_png(latex_string, wrap=False,
                                               color='#000000')
    dvipng_default = latextools.latex_to_png_dvipng(latex_string, False)
    dvipng_black = latextools.latex_to_png_dvipng(latex_string, False, 'Black')
    assert dvipng_default == dvipng_black
    mpl_default = latextools.latex_to_png_mpl(latex_string, False)
    mpl_black = latextools.latex_to_png_mpl(latex_string, False, 'Black')
    assert mpl_default == mpl_black
    assert default_value in [dvipng_black, mpl_black]
    assert default_hexblack in [dvipng_black, mpl_black]

    # Test that dvips name colors can be used without error
    dvipng_maroon = latextools.latex_to_png_dvipng(latex_string, False,
                                                   'Maroon')
    # And that it doesn't return the black one
    assert dvipng_black != dvipng_maroon

    mpl_maroon = latextools.latex_to_png_mpl(latex_string, False, 'Maroon')
    assert mpl_black != mpl_maroon
    mpl_white = latextools.latex_to_png_mpl(latex_string, False, 'White')
    mpl_hexwhite = latextools.latex_to_png_mpl(latex_string, False, '#FFFFFF')
    assert mpl_white == mpl_hexwhite

    mpl_white_scale = latextools.latex_to_png_mpl(latex_string, False,
                                                  'White', 1.2)
    assert mpl_white != mpl_white_scale
Exemple #4
0
def test_latex_to_png_invalid_hex_colors():
    """
    Test that invalid hex colors provided to dvipng gives an exception.
    """
    latex_string = "$x^2$"
    nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
                                        backend='dvipng', color="#f00bar"))
    nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
                                        backend='dvipng', color="#f00"))
Exemple #5
0
 def _matplotlib_wrapper(o):
     # mathtext can't render some LaTeX commands. For example, it can't
     # render any LaTeX environments such as array or matrix. So here we
     # ensure that if mathtext fails to render, we return None.
     try:
         try:
             return latex_to_png(o, color=forecolor, scale=scale)
         except TypeError:  #  Old IPython version without color and scale
             return latex_to_png(o)
     except ValueError as e:
         debug('matplotlib exception caught:', repr(e))
         return None
    def _append_latex(self, latex, before_prompt=False, metadata=None):
        """ Append latex data to the widget."""
        png = None
        if self._is_latex_math(latex):
            png = latex_to_png(latex, wrap=False, backend='dvipng')
        if png is None and latex.startswith('$') and latex.endswith('$'):
            # matplotlib only supports strings enclosed in dollar signs
            png = latex_to_png(latex, wrap=False, backend='matplotlib')

        if png:
            self._append_png(png, before_prompt, metadata)
        else:
            raise LatexError
Exemple #7
0
 def _matplotlib_wrapper(o):
     # mathtext does not understand certain latex flags, so we try to
     # replace them with suitable subs
     o = o.replace(r'\operatorname', '')
     o = o.replace(r'\overline', r'\bar')
     # mathtext can't render some LaTeX commands. For example, it can't
     # render any LaTeX environments such as array or matrix. So here we
     # ensure that if mathtext fails to render, we return None.
     try:
         try:
             return latex_to_png(o, color=forecolor, scale=scale)
         except TypeError:  #  Old IPython version without color and scale
             return latex_to_png(o)
     except ValueError as e:
         debug('matplotlib exception caught:', repr(e))
         return None
 def _append_latex(self, latex, before_prompt=False, metadata=None):
     """ Append latex data to the widget."""
     try:
         png = latex_to_png(latex, wrap=False)
     except Exception as e:
         self.log.error("Failed to render latex: '%s'", latex, exc_info=True)
         self._append_plain_text("Failed to render latex: %s" % e, before_prompt)
     else:
         self._append_png(png, before_prompt, metadata)
Exemple #9
0
def print_png(o):
    """A function to display sympy expression using LaTex -> PNG."""
    s = latex(o, mode='inline')
    # mathtext does not understand certain latex flags, so we try to replace
    # them with suitable subs.
    s = s.replace('\\operatorname','')
    s = s.replace('\\overline', '\\bar')
    png = latex_to_png(s)
    return png
Exemple #10
0
def print_png(o):
    """A funciton to display sympy expression using LaTex -> PNG."""
    s = latex(o, mode='inline')
    # mathtext does not understand certain latex flags, so we try to replace
    # them with suitable subs.
    s = s.replace('\\operatorname', '')
    s = s.replace('\\overline', '\\bar')
    png = latex_to_png(s, encode=True)
    return png
Exemple #11
0
 def _print_display_png(o):
     """
     A function to display sympy expression using display style LaTeX in PNG.
     """
     s = latex(o, mode='plain')
     s = s.strip('$')
     # As matplotlib does not support display style, dvipng backend is used
     # here
     png = latex_to_png(s, backend='dvipng', wrap=True)
     return png
def print_display_png(o):
    """
    A function to display sympy expression using display style LaTeX in PNG.
    """
    s = latex(o, mode='plain')
    s = s.strip('$')
    # As matplotlib does not support display style, dvipng backend is
    # used here.
    png = latex_to_png('$$%s$$' % s, backend='dvipng')
    return png
Exemple #13
0
 def _print_display_png(o):
     """
     A function to display sympy expression using display style LaTeX in PNG.
     """
     s = latex(o, mode='plain')
     s = s.strip('$')
     # As matplotlib does not support display style, dvipng backend is used
     # here
     png = latex_to_png(s, backend='dvipng', wrap=True)
     return png
Exemple #14
0
def print_display_png(o):
    """
    A function to display sympy expression using display style LaTeX in PNG.
    """
    s = latex(o, mode='plain')
    s = s.strip('$')
    # As matplotlib does not support display style, dvipng backend is
    # used here.
    png = latex_to_png('$$%s$$' % s, backend='dvipng')
    return png
Exemple #15
0
 def _print_latex_matplotlib(o):
     """
     A function that returns a png rendered by mathtext
     """
     if _can_print_latex(o):
         s = latex(o, mode='inline')
         # mathtext does not understand centain latex flags, so we try to
         # replace them with suitable subs
         s = s.replace(r'\operatorname', '')
         s = s.replace(r'\overline', r'\bar')
         return latex_to_png(s)
Exemple #16
0
 def _print_png(o):
     """
     A function to display sympy expressions using inline style LaTeX in PNG.
     """
     s = latex(o, mode='inline')
     # mathtext does not understand centain latex flags, so we try to
     # replace them with suitable subs
     s = s.replace(r'\operatorname', '')
     s = s.replace(r'\overline', r'\bar')
     png = latex_to_png(s)
     return png
Exemple #17
0
 def _print_latex_matplotlib(o):
     """
     A function that returns a png rendered by mathtext
     """
     if _can_print_latex(o):
         s = latex(o, mode='inline')
         # mathtext does not understand centain latex flags, so we try to
         # replace them with suitable subs
         s = s.replace(r'\operatorname', '')
         s = s.replace(r'\overline', r'\bar')
         return latex_to_png(s)
Exemple #18
0
 def _print_png(o):
     """
     A function to display sympy expressions using inline style LaTeX in PNG.
     """
     s = latex(o, mode='inline')
     # mathtext does not understand centain latex flags, so we try to
     # replace them with suitable subs
     s = s.replace(r'\operatorname', '')
     s = s.replace(r'\overline', r'\bar')
     png = latex_to_png(s)
     return png
    def _append_latex(self, latex, before_prompt=False, metadata=None):
        """ Append latex data to the widget."""
        png = None

        if self._is_latex_math(latex):
            png = latex_to_png(latex, wrap=False, backend='dvipng')

        # Matplotlib only supports strings enclosed in dollar signs
        if png is None and latex.startswith('$') and latex.endswith('$'):
            # To avoid long and ugly errors, like the one reported in
            # spyder-ide/spyder#7619
            try:
                png = latex_to_png(latex, wrap=False, backend='matplotlib')
            except Exception:
                pass

        if png:
            self._append_png(png, before_prompt, metadata)
        else:
            raise LatexError
Exemple #20
0
 def _matplotlib_wrapper(o):
     debug("_matplotlib_wrapper:", "called with %s" % o)
     # mathtext does not understand certain latex flags, so we try to
     # replace them with suitable subs
     o = o.replace(r'\operatorname', '')
     o = o.replace(r'\overline', r'\bar')
     try:
         return latex_to_png(o)
     except Exception:
         debug("_matplotlib_wrapper:", "exeption raised")
         # Matplotlib.mathtext cannot render some things (like
         # matrices)
         return None
 def _matplotlib_wrapper(o):
     # mathtext does not understand certain latex flags, so we try to
     # replace them with suitable subs
     o = o.replace(r"\operatorname", "")
     o = o.replace(r"\overline", r"\bar")
     # mathtext can't render some LaTeX commands. For example, it can't
     # render any LaTeX environments such as array or matrix. So here we
     # ensure that if mathtext fails to render, we return None.
     try:
         return latex_to_png(o)
     except ValueError as e:
         debug("matplotlib exception caught:", repr(e))
         return None
Exemple #22
0
 def _matplotlib_wrapper(o):
     # mathtext does not understand certain latex flags, so we try to
     # replace them with suitable subs
     o = o.replace(r'\operatorname', '')
     o = o.replace(r'\overline', r'\bar')
     # mathtext can't render some LaTeX commands. For example, it can't
     # render any LaTeX environments such as array or matrix. So here we
     # ensure that if mathtext fails to render, we return None.
     try:
         return latex_to_png(o)
     except ValueError as e:
         debug('matplotlib exception caught:', repr(e))
         return None
Exemple #23
0
 def _handle_execute_result(self, msg):
     """ Overridden to handle rich data types, like SVG.
     """
     if self.include_output(msg):
         self.flush_clearoutput()
         content = msg['content']
         prompt_number = content.get('execution_count', 0)
         data = content['data']
         metadata = msg['content']['metadata']
         if 'image/svg+xml' in data:
             self._pre_image_append(msg, prompt_number)
             self._append_svg(data['image/svg+xml'], True)
             self._append_html(self.output_sep2, True)
         elif 'image/png' in data:
             self._pre_image_append(msg, prompt_number)
             png = decodestring(data['image/png'].encode('ascii'))
             self._append_png(png,
                              True,
                              metadata=metadata.get('image/png', None))
             self._append_html(self.output_sep2, True)
         elif 'image/jpeg' in data and self._jpg_supported:
             self._pre_image_append(msg, prompt_number)
             jpg = decodestring(data['image/jpeg'].encode('ascii'))
             self._append_jpg(jpg,
                              True,
                              metadata=metadata.get('image/jpeg', None))
             self._append_html(self.output_sep2, True)
         elif 'text/latex' in data:
             self._pre_image_append(msg, prompt_number)
             latex = data['text/latex'].encode('ascii')
             # latex_to_png takes care of handling $
             latex = latex.strip('$')
             png = latex_to_png(latex, wrap=True)
             if png is not None:
                 self._append_png(png, True)
                 self._append_html(self.output_sep2, True)
             else:
                 # Print plain text if png can't be generated
                 return super(RichIPythonWidget,
                              self)._handle_execute_result(msg)
         else:
             # Default back to the plain text representation.
             return super(RichIPythonWidget,
                          self)._handle_execute_result(msg)
 def _handle_execute_result(self, msg):
     """ Overridden to handle rich data types, like SVG.
     """
     if self.include_output(msg):
         self.flush_clearoutput()
         content = msg['content']
         prompt_number = content.get('execution_count', 0)
         data = content['data']
         metadata = msg['content']['metadata']
         if 'image/svg+xml' in data:
             self._pre_image_append(msg, prompt_number)
             self._append_svg(data['image/svg+xml'], True)
             self._append_html(self.output_sep2, True)
         elif 'image/png' in data:
             self._pre_image_append(msg, prompt_number)
             png = decodestring(data['image/png'].encode('ascii'))
             self._append_png(
                 png, True, metadata=metadata.get('image/png', None))
             self._append_html(self.output_sep2, True)
         elif 'image/jpeg' in data and self._jpg_supported:
             self._pre_image_append(msg, prompt_number)
             jpg = decodestring(data['image/jpeg'].encode('ascii'))
             self._append_jpg(
                 jpg, True, metadata=metadata.get('image/jpeg', None))
             self._append_html(self.output_sep2, True)
         elif 'text/latex' in data:
             self._pre_image_append(msg, prompt_number)
             latex = data['text/latex'].encode('ascii')
             # latex_to_png takes care of handling $
             latex = latex.strip('$')
             png = latex_to_png(latex, wrap=True)
             if png is not None:
                 self._append_png(png, True)
                 self._append_html(self.output_sep2, True)
             else:
                 # Print plain text if png can't be generated
                 return super(RichIPythonWidget, self)._handle_execute_result(msg)
         else:
             # Default back to the plain text representation.
             return super(RichIPythonWidget, self)._handle_execute_result(msg)
Exemple #25
0
 def x_repr_png_(self):  # TODO: This works, but enable when form latex rendering is fixed
     from IPython.lib.latextools import latex_to_png
     return latex_to_png(self._repr_latex_())
Exemple #26
0
 def _matplotlib_wrapper(o):
     # mathtext does not understand centain latex flags, so we try to
     # replace them with suitable subs
     o = o.replace(r'\operatorname', '')
     o = o.replace(r'\overline', r'\bar')
     return latex_to_png(o)
Exemple #27
0
 def __init__(self, s, encode = False):
   self.png = latex_to_png(s, encode)
"""

import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from IPython.display import Image, display
from IPython.lib.latextools import latex_to_png

""" Displaying the equations used for optimization """

parameter_optimization = r'\theta^{+} = \theta^{-} - \frac{\alpha}{m} (h(x_{i}) - y_{i} )\bar{x}'
cost_function = r'J(x, \theta, y) = \frac{1}{2m}\sum_{i=1}^{m}(h(x_i) - y_i)^2'
estimated_point = r'h(x_i) = \theta^T \bar{x}'
print('In linear regression, I derived the equation to update the linear model parameters as:')
display(Image(data=latex_to_png(parameter_optimization, wrap=True)))
print('This minimizes the following cost function:')
display(Image(data=latex_to_png(cost_function, wrap=True)))
print('where')
display(Image(data=latex_to_png(estimated_point, wrap=True)))


""" Generate Random Data for testing the program """

slope_true = 12.963
intercept_true = 4.525
input_variable = np.arange(0.0,200.0)
output_variable = slope_true * input_variable + intercept_true + 500 * np.random.rand(len(input_variable)) - 250


""" Using Matplotlib to plot and visualize the data """
Exemple #29
0
 def _repr_png_(self):
     return latex_to_png("$\circle$")
Exemple #30
0
 def _matplotlib_wrapper(o):
     # mathtext does not understand centain latex flags, so we try to
     # replace them with suitable subs
     o = o.replace(r"\operatorname", "")
     o = o.replace(r"\overline", r"\bar")
     return latex_to_png(o)
Exemple #31
0
 def _repr_png_(self):
     from IPython.lib.latextools import latex_to_png
     return latex_to_png(self._repr_latex_())
Exemple #32
0
 def _repr_png_(self):
     return latex_to_png('$\\circle$')
Exemple #33
0
def latex_to_qimage(text):
    png = latex_to_png(text)
    return jpg_png_to_qimage(png, "png")
Exemple #34
0
 def x_repr_png_(
     self
 ):  # TODO: This works, but enable when form latex rendering is fixed
     from IPython.lib.latextools import latex_to_png
     return latex_to_png(self._repr_latex_())
def equToPNG(equ, show=False):
    lt = latex(equ)
    data = latex_to_png(lt, wrap=True, color='white')
    if show:
        display(Image(data=data))
Exemple #36
0
 def _matplotlib_wrapper(o):
     # mathtext does not understand certain latex flags, so we try to
     # replace them with suitable subs
     o = o.replace(r'\operatorname', '')
     o = o.replace(r'\overline', r'\bar')
     return latex_to_png(o)
 def _append_latex(self, latex, before_prompt=False, metadata=None):
     """ Append latex data to the widget."""
     self._append_png(latex_to_png(latex, wrap=False), before_prompt, metadata)
"""Calculate the Shape function"""
ShapeMatrix=zeros(NbDOF,1)

ShapeList=[]
for i in range(0,NbDOF):
    ShapeList.insert(i,(CoefMatrix.inv())[:,i].transpose()*Matrix(PBL))
"""Problem of Latex reading the array, have to read just one element"""
x = np.arange(-0.5, 0.5, 0.01)  
s = ShapeList[1]
              
from IPython.display import Image, display
from IPython.lib.latextools import latex_to_png


eq = r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'
data = latex_to_png(latex(ShapeList[1]), wrap=True)
display(Image(data=data))
with open('picture_out.png', 'wb') as f:
    f.write(data)

from sympy import symbols
from sympy.plotting import plot

x = symbols('x')
p = plot(x)

plot(x, x**2, x, (x, -1, 1),hold='true')

x = N . arange ( -1 , 1 , 0.01)
s=(x,ShapeList[0][0])
values=s[0]
Exemple #39
0
 def _repr_png_(self):
     from IPython.lib.latextools import latex_to_png
     return latex_to_png(self._repr_latex_())
Exemple #40
0
 def __init__(self, s, encode = False):
   self.png = latex_to_png(s, encode)
Exemple #41
0
 def _repr_png_(self):
     return latextools.latex_to_png(self.lat)
def latexToPNG(latex, show=False):
    data = latex_to_png(latex, wrap=True, color='white')
    if show:
        display(Image(data=data))