Exemplo n.º 1
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if not HAVE_MATHTEX:
            return

        m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
                    self.dpi, rcParams['mathtext.default'], cache=True)
        b = MathtexBackendImage()
        m.render_to_backend(b)

        gc.draw_mathtext(x, y, angle, 255 - b.image.as_array())
Exemplo n.º 2
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if not HAVE_MATHTEX:
            return

        m = Mathtex(s, matplotlib.rcParams['mathtext.fontset'],
                    prop.get_size_in_points(), self.dpi, rcParams['mathtext.default'],
                    cache=True)
        b = MathtexBackendImage()
        m.render_to_backend(b)

        width, height = m.width, m.height + m.depth
        font_image = b.image

        if angle==90:
            width, height = height, width
            x -= width
        y -= height

        imw = font_image.get_width()
        imh = font_image.get_height()
        N = imw * imh

        # a numpixels by num fonts array
        Xall = npy.zeros((N,1), npy.uint8)

        image_str = font_image.as_str()
        Xall[:,0] = npy.fromstring(image_str, npy.uint8)

        # get the max alpha at each pixel
        Xs = npy.amax(Xall,axis=1)

        # convert it to it's proper shape
        Xs.shape = imh, imw

        pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=True,
                                bits_per_sample=8, width=imw, height=imh)

        array = pixbuf_get_pixels_array(pixbuf)

        rgb = gc.get_rgb()
        array[:,:,0]=int(rgb[0]*255)
        array[:,:,1]=int(rgb[1]*255)
        array[:,:,2]=int(rgb[2]*255)
        array[:,:,3]=Xs

        try: # new in 2.2
            # can use None instead of gc.gdkGC, if don't need clipping
            self.gdkDrawable.draw_pixbuf (gc.gdkGC, pixbuf, 0, 0,
                                          int(x), int(y), imw, imh,
                                          gdk.RGB_DITHER_NONE, 0, 0)
        except AttributeError:
            # deprecated in 2.2
            pixbuf.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0,
                                  int(x), int(y), imw, imh,
                                  gdk.RGB_DITHER_NONE, 0, 0)
Exemplo n.º 3
0
def latex2png(latex, filename, fontset='cm'):
    latex = "$%s$" % latex

    m = Mathtex(latex, 'bakoma')

    if not os.path.exists(filename):
        try:
            m.save(filename)
        except:
            warnings.warn("Could not render math expression %s" % latex,
                          Warning)
    sys.stdout.write("#")
    sys.stdout.flush()
    return m.depth
Exemplo n.º 4
0
    def draw_mathtext(self, gc, x, y, s, prop, angle):
        """
        Draw the math text using mathtex.mathtex_main
        """
        if __debug__: verbose.report('RendererAgg.draw_mathtext',
                                     'debug-annoying')
        if HAVE_MATHTEX:
            m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
                        self.dpi, rcParams['mathtext.default'], cache=True)
            b = MathtexBackendImage()

            m.render_to_backend(b)

            self._renderer.draw_text_image(b.image, int(x), int(y) + 1, angle, gc)
Exemplo n.º 5
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if not HAVE_MATHTEX:
            return

        m = Mathtex(s,
                    rcParams['mathtext.fontset'],
                    prop.get_size_in_points(),
                    self.dpi,
                    rcParams['mathtext.default'],
                    cache=True)
        b = MathtexBackendImage()
        m.render_to_backend(b)

        gc.draw_mathtext(x, y, angle, 255 - b.image.as_array())
Exemplo n.º 6
0
def latex2png(latex, filename, fontset='cm'):
    latex = "$%s$" % latex

    m = Mathtex(latex, 'bakoma')

    if not os.path.exists(filename):
        try:
	    m.save(filename)
        except:
            warnings.warn("Could not render math expression %s" % latex,
                          Warning)
    sys.stdout.write("#")
    sys.stdout.flush()
    return m.depth
Exemplo n.º 7
0
 def get_text_width_height_descent(self, s, prop, ismath):
     if ismath == 'TeX':
         # todo: handle props
         texmanager = self.get_texmanager()
         fontsize = prop.get_size_in_points()
         w, h, d = texmanager.get_text_width_height_descent(s,
                                                            fontsize,
                                                            renderer=self)
         return w, h, d
     if ismath:
         if HAVE_MATHTEX:
             m = Mathtex(s,
                         rcParams['mathtext.fontset'],
                         prop.get_size_in_points(),
                         self.dpi,
                         rcParams['mathtext.default'],
                         cache=True)
             return m.width, m.height, m.depth
         else:
             warnings.warn(
                 'matplotlib was compiled without mathtex support. ' +
                 'Math will not be rendered.')
             return 0.0, 0.0, 0.0
     family = prop.get_family()
     weight = prop.get_weight()
     style = prop.get_style()
     points = prop.get_size_in_points()
     size = self.points_to_pixels(points)
     width, height, descent = self.gc.get_text_width_height_descent(
         unicode(s), family, size, weight, style)
     return width, height, 0.0 * descent
Exemplo n.º 8
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
        if not HAVE_MATHTEX: return

        ctx = gc.ctx

        m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
                    self.dpi, rcParams['mathtext.default'], cache=True)
        b = MathtexBackendCairo()
        m.render_to_backend(b)

        ctx.save()
        ctx.translate(x, y - m.height - m.depth)
        if angle:
           ctx.rotate (-angle * npy.pi / 180)

        b.render_to_context(ctx)

        ctx.restore()
Exemplo n.º 9
0
    def __init__(self, fig, labelstr, props=None, hoverprops=None, on_select=None):
        artist.Artist.__init__(self)

        self.set_figure(fig)
        self.labelstr = labelstr

        if props is None:
            props = ItemProperties()

        if hoverprops is None:
            hoverprops = ItemProperties()

        self.props = props
        self.hoverprops = hoverprops


        self.on_select = on_select

        m = Mathtex(labelstr, fontsize=props.fontsize, dpi=fig.dpi)
        x, self.depth = m.as_mask(), m.depth

        if props.fontsize!=hoverprops.fontsize:
            raise NotImplementedError('support for different font sizes not implemented')


        self.labelwidth = x.shape[1]
        self.labelheight = x.shape[0]

        self.labelArray = np.zeros((x.shape[0], x.shape[1], 4))
        self.labelArray[:,:,-1] = x/255.

        self.label = image.FigureImage(fig, origin='upper')
        self.label.set_array(self.labelArray)

        # we'll update these later
        self.rect = patches.Rectangle((0,0), 1,1)

        self.set_hover_props(False)

        fig.canvas.mpl_connect('button_release_event', self.check_select)
Exemplo n.º 10
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
        if not HAVE_MATHTEX: return

        ctx = gc.ctx

        m = Mathtex(s,
                    rcParams['mathtext.fontset'],
                    prop.get_size_in_points(),
                    self.dpi,
                    rcParams['mathtext.default'],
                    cache=True)
        b = MathtexBackendCairo()
        m.render_to_backend(b)

        ctx.save()
        ctx.translate(x, y - m.height - m.depth)
        if angle:
            ctx.rotate(-angle * npy.pi / 180)

        b.render_to_context(ctx)

        ctx.restore()
Exemplo n.º 11
0
    def get_text_width_height_descent(self, s, prop, ismath):
        if ismath:
            if not HAVE_MATHTEX:
                warnings.warn('matplotlib was compiled without mathtex support. ' +
                              'Math will not be rendered.')
                return 0.0, 0.0, 0.0
            else:
                m = Mathtex(s, matplotlib.rcParams['mathtext.fontset'],
                            prop.get_size_in_points(), self.dpi, rcParams['mathtext.default'],
                            cache=True)
                return m.width, m.height, m.depth

        layout, inkRect, logicalRect = self._get_pango_layout(s, prop)
        l, b, w, h = inkRect
        return w, h+1, h + 1
Exemplo n.º 12
0
 def get_text_width_height_descent(self, s, prop, ismath):
     if ismath:
         if HAVE_MATHTEX:
             m = Mathtex(s, rcParams['mathtext.fontset'],
                         prop.get_size_in_points(), 72.0,
                         rcParams['mathtext.default'])
             return m.width, m.height, m.depth
         else:
             warnings.warn(
                 'matplotlib was compiled without mathtex support. ' +
                 'Math will not be rendered.')
             return 0.0, 0.0, 0.0
     font = self._get_font(prop)
     font.set_text(s, 0.0, flags=LOAD_NO_HINTING)
     w, h = font.get_width_height()
     w /= 64.0  # convert from subpixels
     h /= 64.0
     d = font.get_descent()
     d /= 64.0
     return w, h, d
Exemplo n.º 13
0
    def get_text_width_height_descent(self, s, prop, ismath):
        """
        get the width and height in display coords of the string s
        with FontPropertry prop

        # passing rgb is a little hack to make cacheing in the
        # texmanager more efficient.  It is not meant to be used
        # outside the backend
        """
        if ismath=='TeX':
            # todo: handle props
            size = prop.get_size_in_points()
            texmanager = self.get_texmanager()
            fontsize = prop.get_size_in_points()
            w, h, d = texmanager.get_text_width_height_descent(s, fontsize,
                                                               renderer=self)
            return w, h, d

        if ismath:
            if not HAVE_MATHTEX:
                warnings.warn('matplotlib was compiled without mathtex support. ' +
                              'Math will not be rendered.')
                return 0.0, 0.0, 0.0
            else:
                m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
                            self.dpi, rcParams['mathtext.default'], cache=True)
                return m.width, m.height, m.depth

        flags = self._get_hinting_flag()
        font = self._get_agg_font(prop)
        font.set_text(s, 0.0, flags=flags)  # the width and height of unrotated string
        w, h = font.get_width_height()
        d = font.get_descent()
        w /= 64.0  # convert from subpixels
        h /= 64.0
        d /= 64.0
        return w, h, d
Exemplo n.º 14
0
    def get_text_width_height_descent(self, s, prop, ismath):
        if _debug: print '%s.%s()' % (self.__class__.__name__, _fn_name())
        if ismath:
            if HAVE_MATHTEX:
                m = Mathtex(s,
                            rcParams['mathtext.fontset'],
                            prop.get_size_in_points(),
                            self.dpi,
                            rcParams['mathtext.default'],
                            cache=True)
                return m.width, m.height, m.depth
            else:
                warnings.warn(
                    'matplotlib was compiled without mathtex support. ' +
                    'Math will not be rendered.')
                return 0.0, 0.0, 0.0

        ctx = self.text_ctx
        ctx.save()
        ctx.select_font_face(prop.get_name(),
                             self.fontangles[prop.get_style()],
                             self.fontweights[prop.get_weight()])

        # Cairo (says it) uses 1/96 inch user space units, ref: cairo_gstate.c
        # but if /96.0 is used the font is too small

        size = prop.get_size_in_points() * self.dpi / 72.0

        # problem - scale remembers last setting and font can become
        # enormous causing program to crash
        # save/restore prevents the problem
        ctx.set_font_size(size)

        y_bearing, w, h = ctx.text_extents(s)[1:4]
        ctx.restore()

        return w, h, h + y_bearing
Exemplo n.º 15
0
    if name.isdigit():
        name = tests.keys()[name]
    actual_tests[name] = tests[name]

actual_presets = [presets[int(i)] for i in options.presets.split(",")]

# For progress reports
total = len(actual_tests) * len(actual_presets)
count = 0

for (name, tex) in actual_tests.iteritems():
    for fontsize, dpi, font in actual_presets:
        count += 1
        print "Test %d of %d ['%s' at (%.1f, %d, %s)]" % (count, total, name, fontsize, dpi, font)

        m = Mathtex(tex, fontset=font, fontsize=fontsize, dpi=dpi)

        if options.gen_output:
            m.save(os.path.join(os.path.dirname(__file__), "%s.%s.%dpt.%ddpi.png" % (name, font, fontsize, dpi)))

        key = (name, fontsize, dpi, font)

        glyphs[key] = extract_glyphs(m.glyphs)
        rects[key] = m.rects
        bitmap[key] = md5(m.as_rgba_bitmap()).hexdigest()

# Compare hashes against a previous run
if os.path.isfile(options.hashfile) and not options.update:
    # Load the reference results set
    fh = open(options.hashfile, "rb")
    ref_glyphs = pickle.load(fh)
Exemplo n.º 16
0
total = len(actual_tests) * len(actual_presets)
count = 0

# Warn if pdiff is not available
if not use_pdiff:
    print "WARNING: Perceptual diff was not found, bitmap comparisons will not be performed!"

for (name, tex) in actual_tests.iteritems():
    for fontsize, dpi, font in actual_presets:
        count += 1
        print "Test %d of %d ['%s' at (%.1f, %d, %s)]" % (count, total, name,
                                                          fontsize, dpi, font)

        key = (name, fontsize, dpi, font)

        m = Mathtex(tex, fontset=font, fontsize=fontsize, dpi=dpi)

        if options.gen_output:
            # Generate the base file name
            fn = os.path.join(os.path.dirname(__file__),
                              "%s.%s.%dpt.%ddpi" % (name, font, fontsize, dpi))
            # Produce the normal and reference file names
            filenames[key] = (fn + '.png', fn + '-ref.png')

            if options.update:
                m.save(filenames[key][1])
            else:
                m.save(filenames[key][0])

        glyphs[key] = extract_glyphs(m.glyphs)
        rects[key] = m.rects
Exemplo n.º 17
0
from mathtex.fonts import StixFonts
from mathtex.backends.backend_cairo import MathtexBackendCairo
from mathtex.backends.backend_image import MathtexBackendImage

parser = MathtexParser()
bakoma = BakomaFonts()
stix = StixFonts()

box =  parser.parse(r"$x_{1,2}=\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$", stix, 18, 99.0)

#print box

rects, glyphs, bbox =  ship(0, 0, box)

width = bbox[2] - bbox[0]
height = box.height
depth = box.depth

backend = MathtexBackendImage(99.0)
backend.set_canvas_size(box.width, box.height, box.depth)
backend.render(glyphs, rects)
backend.save('test.png', 'png')
"""
from mathtex.mathtex_main import Mathtex
from mathtex.fonts import UnicodeFonts

u = UnicodeFonts(rm="times new roman",it='times new roman:italic',bf='times new roman:bold')

m = Mathtex(r"$\sqrt{x^2} \times \frac{2}{3}$", u)
m.save('testnew.png', 'png')
Exemplo n.º 18
0
# Import Mathtex and the appropriate font set
from mathtex.mathtex_main import Mathtex
from mathtex.fonts import UnicodeFonts

# Create the font set instance; if \bf and \it are not provided
# they will be the bold and italic versions of \rm
u = UnicodeFonts(rm='Times New Roman', sf='Arial')

# Create the expression object and save it as a PNG
m = Mathtex(r"${\it x} = {\rm x} = {\sf x} = {\bf x}$", u, 20)
m.save('unicode.png')

# Attempt to also save it as a PDF -- requires PyCairo
try:
    m.save('unicode.pdf')
except:
    print 'PDF output requires PyCairo.'
Exemplo n.º 19
0
# For progress reports
total = len(actual_tests) * len(actual_presets)
count = 0

# Warn if pdiff is not available
if not use_pdiff:
    print "WARNING: Perceptual diff was not found, bitmap comparisons will not be performed!"

for (name, tex) in actual_tests.iteritems():
    for fontsize, dpi, font in actual_presets:
        count += 1
        print "Test %d of %d ['%s' at (%.1f, %d, %s)]" % (count, total, name, fontsize, dpi, font)

        key = (name, fontsize, dpi, font)

        m = Mathtex(tex, fontset=font, fontsize=fontsize, dpi=dpi)

        if options.gen_output:
            # Generate the base file name
            fn = os.path.join(os.path.dirname(__file__), "%s.%s.%dpt.%ddpi" % (name, font, fontsize, dpi))
            # Produce the normal and reference file names
            filenames[key] = (fn + ".png", fn + "-ref.png")

            if options.update:
                m.save(filenames[key][1])
            else:
                m.save(filenames[key][0])

        glyphs[key] = extract_glyphs(m.glyphs)
        rects[key] = m.rects
        bitmap[key] = md5(m.as_rgba_bitmap()).hexdigest()
Exemplo n.º 20
0
 def onResult(self):
     m = Mathtex (self.result_tex, self.mathfont, 26)
     m.save('result.png', 'png')
     img = wx.Image('result.png', wx.BITMAP_TYPE_ANY)
     self.img_result.SetBitmap(wx.BitmapFromImage(img))
     self.panel.Refresh()
Exemplo n.º 21
0
    def _draw_mathtext(self, gc, x, y, s, prop, angle):
        """
        Draw math text using mathtex
        """
        if not HAVE_MATHTEX:
            return

        m = Mathtex(s, rcParams['mathtext.fontset'], prop.get_size_in_points(),
                    72.0, rcParams['mathtext.default'])

        # Extract the glyphs and rects to render
        svg_glyphs = [(info.font, info.fontsize, unichr(info.num), ox,
                       m.height - oy + info.offset, info.metrics)
                      for ox, oy, info in m.glyphs]
        svg_rects = [(x1, m.height - y1 + 1, x2 - x1, y2 - y1)
                     for x1, y1, x2, y2 in m.rects]

        color = rgb2hex(gc.get_rgb()[:3])
        write = self._svgwriter.write

        style = "fill: %s" % color

        if rcParams['svg.embed_char_paths']:
            new_chars = []
            for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:
                path = self._add_char_def(font, thetext)
                if path is not None:
                    new_chars.append(path)
            if len(new_chars):
                write('<defs>\n')
                for path in new_chars:
                    write(path)
                write('</defs>\n')

            svg = ['<g style="%s" transform="' % style]
            if angle != 0:
                svg.append('translate(%f,%f)rotate(%1.1f)' % (x, y, -angle))
            else:
                svg.append('translate(%f,%f)' % (x, y))
            svg.append('">\n')

            for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:
                charid = self._get_char_def_id(font, thetext)

                svg.append(
                    '<use xlink:href="#%s" transform="translate(%f,%f)scale(%f)"/>\n'
                    % (charid, new_x, -new_y_mtc, fontsize / self.FONT_SCALE))
            svg.append('</g>\n')
        else:  # not rcParams['svg.embed_char_paths']
            svg = ['<text style="%s" x="%f" y="%f"' % (style, x, y)]

            if angle != 0:
                svg.append(
                    ' transform="translate(%f,%f) rotate(%1.1f) translate(%f,%f)"'
                    % (x, y, -angle, -x,
                       -y))  # Inkscape doesn't support rotate(angle x y)
            svg.append('>\n')

            curr_x, curr_y = 0.0, 0.0

            for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:
                new_y = -new_y_mtc
                style = "font-size: %f; font-family: %s" % (fontsize,
                                                            font.family_name)

                svg.append('<tspan style="%s"' % style)
                xadvance = metrics.advance
                svg.append(' textLength="%f"' % xadvance)

                dx = new_x - curr_x
                if dx != 0.0:
                    svg.append(' dx="%f"' % dx)

                dy = new_y - curr_y
                if dy != 0.0:
                    svg.append(' dy="%f"' % dy)

                thetext = escape_xml_text(thetext)

                svg.append('>%s</tspan>\n' % thetext)

                curr_x = new_x + xadvance
                curr_y = new_y

            svg.append('</text>\n')

        if len(svg_rects):
            style = "fill: %s; stroke: none" % color
            svg.append('<g style="%s" transform="' % style)
            if angle != 0:
                svg.append('translate(%f,%f) rotate(%1.1f)' % (x, y, -angle))
            else:
                svg.append('translate(%f,%f)' % (x, y))
            svg.append('">\n')

            for x, y, width, height in svg_rects:
                svg.append(
                    '<rect x="%f" y="%f" width="%f" height="%f" fill="black" stroke="none" />'
                    % (x, -y + height, width, height))
            svg.append("</g>")

        self.open_group("mathtext")
        write(''.join(svg))
        self.close_group("mathtext")