Пример #1
0
def test_fontconfig_preamble():
    """Test that the preamble is included in the source."""
    plt.rcParams['text.usetex'] = True

    src1 = TexManager()._get_tex_source("", fontsize=12)
    plt.rcParams['text.latex.preamble'] = '\\usepackage{txfonts}'
    src2 = TexManager()._get_tex_source("", fontsize=12)

    assert src1 != src2
Пример #2
0
def test_fontconfig_preamble():
    """Test that the preamble is included in _fontconfig."""
    plt.rcParams['text.usetex'] = True

    tm1 = TexManager()
    font_config1 = tm1.get_font_config()

    plt.rcParams['text.latex.preamble'] = '\\usepackage{txfonts}'
    tm2 = TexManager()
    font_config2 = tm2.get_font_config()

    assert font_config1 != font_config2
Пример #3
0
    def __init__(self, width, height, dpi):
        if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying')
        self.dpi = dpi
        self.width = width
        self.height = height
        self._renderer = _RendererAgg(int(width),
                                      int(height),
                                      dpi.get(),
                                      debug=False)
        self.draw_polygon = self._renderer.draw_polygon
        self.draw_rectangle = self._renderer.draw_rectangle
        self.draw_path = self._renderer.draw_path
        self.draw_lines = self._renderer.draw_lines
        self.draw_markers = self._renderer.draw_markers
        self.draw_image = self._renderer.draw_image
        self.draw_line_collection = self._renderer.draw_line_collection
        self.draw_quad_mesh = self._renderer.draw_quad_mesh
        self.draw_poly_collection = self._renderer.draw_poly_collection
        self.draw_regpoly_collection = self._renderer.draw_regpoly_collection

        self.copy_from_bbox = self._renderer.copy_from_bbox
        self.restore_region = self._renderer.restore_region

        self.texmanager = TexManager()

        self.bbox = lbwh_to_bbox(0, 0, self.width, self.height)
Пример #4
0
 def get_texmanager(self):
     """
     return the :class:`matplotlib.texmanager.TexManager` instance
     """
     if self._texmanager is None:
         from matplotlib.texmanager import TexManager
         self._texmanager = TexManager()
     return self._texmanager
Пример #5
0
    def get_glyphs_tex(self,
                       prop,
                       s,
                       glyph_map=None,
                       return_new_glyphs_only=False):
        """Convert the string *s* to vertices and codes using usetex mode."""
        # Mostly borrowed from pdf backend.

        dvifile = TexManager().make_dvi(s, self.FONT_SCALE)
        with dviread.Dvi(dvifile, self.DPI) as dvi:
            page, = dvi

        if glyph_map is None:
            glyph_map = OrderedDict()

        if return_new_glyphs_only:
            glyph_map_new = OrderedDict()
        else:
            glyph_map_new = glyph_map

        glyph_ids, xpositions, ypositions, sizes = [], [], [], []

        # Gather font information and do some setup for combining
        # characters into strings.
        for x1, y1, dvifont, glyph, width in page.text:
            font, enc = self._get_ps_font_and_encoding(dvifont.texname)
            char_id = self._get_char_id(font, glyph)

            if char_id not in glyph_map:
                font.clear()
                font.set_size(self.FONT_SCALE, self.DPI)
                # See comments in _get_ps_font_and_encoding.
                if enc is not None:
                    index = font.get_name_index(enc[glyph])
                    font.load_glyph(index, flags=LOAD_TARGET_LIGHT)
                else:
                    font.load_char(glyph, flags=LOAD_TARGET_LIGHT)
                glyph_map_new[char_id] = font.get_path()

            glyph_ids.append(char_id)
            xpositions.append(x1)
            ypositions.append(y1)
            sizes.append(dvifont.size / self.FONT_SCALE)

        myrects = []

        for ox, oy, h, w in page.boxes:
            vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h), (ox, oy + h),
                     (ox, oy), (0, 0)]
            code1 = [
                Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
                Path.LINETO, Path.CLOSEPOLY
            ]
            myrects.append((vert1, code1))

        return (list(zip(glyph_ids, xpositions, ypositions,
                         sizes)), glyph_map_new, myrects)
Пример #6
0
def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble,
                    paper_width, paper_height, orientation):
    """
    When we want to use the LaTeX backend with postscript, we write PSFrag tags
    to a temporary postscript file, each one marking a position for LaTeX to
    render some text. convert_psfrags generates a LaTeX document containing the
    commands to convert those tags to text. LaTeX/dvips produces the postscript
    file that includes the actual text.
    """
    with mpl.rc_context({
            "text.latex.preamble": mpl.rcParams["text.latex.preamble"] +
            # Only load these packages if they have not already been loaded, in
            # order not to clash with custom packages.
            r"\makeatletter"
            r"\@ifpackageloaded{color}{}{\usepackage{color}}"
            r"\@ifpackageloaded{graphicx}{}{\usepackage{graphicx}}"
            r"\@ifpackageloaded{psfrag}{}{\usepackage{psfrag}}"
            r"\makeatother"
            r"\geometry{papersize={%(width)sin,%(height)sin},margin=0in}" % {
                "width": paper_width,
                "height": paper_height
            }
    }):
        dvifile = TexManager().make_dvi(
            "\n"
            r"\begin{figure}"
            "\n"
            r"  \centering\leavevmode"
            "\n"
            r"  %(psfrags)s"
            "\n"
            r"  \includegraphics*[angle=%(angle)s]{%(epsfile)s}"
            "\n"
            r"\end{figure}" % {
                "psfrags": "\n".join(psfrags),
                "angle": 90 if orientation == 'landscape' else 0,
                "epsfile": pathlib.Path(tmpfile).resolve().as_posix(),
            },
            fontsize=10)  # tex's default fontsize.

    with TemporaryDirectory() as tmpdir:
        psfile = os.path.join(tmpdir, "tmp.ps")
        cbook._check_and_log_subprocess(
            ['dvips', '-q', '-R0', '-o', psfile, dvifile], _log)
        shutil.move(psfile, tmpfile)

    # check if the dvips created a ps in landscape paper.  Somehow,
    # above latex+dvips results in a ps file in a landscape mode for a
    # certain figure sizes (e.g., 8.3in, 5.8in which is a5). And the
    # bounding box of the final output got messed up. We check see if
    # the generated ps file is in landscape and return this
    # information. The return value is used in pstoeps step to recover
    # the correct bounding box. 2010-06-05 JJL
    with open(tmpfile) as fh:
        psfrag_rotated = "Landscape" in fh.read(1000)
    return psfrag_rotated
Пример #7
0
 def __init__(self, dpi, width, height):
     self.dpi = dpi
     if __version__[0] >= '2':
         self.nominal_fontsize = 0.001625
         default_dpi = 100
     else:
         self.nominal_fontsize = 0.0013
         default_dpi = 80
     self.width = float(width) * dpi / default_dpi
     self.height = float(height) * dpi / default_dpi
     self.mathtext_parser = MathTextParser('agg')
     self.texmanager = TexManager()
Пример #8
0
 def __init__(self, dpi):
     self.dpi = dpi
     self.width = 640.0 * dpi / 80
     self.height = 480.0 * dpi / 80
     mwidth, mheight, width, height = gr.inqdspsize()
     if (width / (mwidth / 0.0256) < 200):
         mwidth *= self.width / width
         gr.setwsviewport(0, mwidth, 0, mwidth * 0.75)
     else:
         gr.setwsviewport(0, 0.192, 0, 0.144)
     gr.setwswindow(0, 1, 0, 0.75)
     gr.setviewport(0, 1, 0, 0.75)
     gr.setwindow(0, self.width, 0, self.height)
     self.mathtext_parser = MathTextParser('agg')
     self.texmanager = TexManager()
Пример #9
0
    def __init__(self, width, height, pswriter):
        self.width = width
        self.height = height
        self._pswriter = pswriter
        if rcParams['text.usetex']:
            self.textcnt = 0
            self.psfrag = []
            self.texmanager = TexManager()

        # current renderer state (None=uninitialised)
        self.color = None
        self.linewidth = None
        self.linejoin = None
        self.linecap = None
        self.linedash = None
        self.fontname = None
        self.fontsize = None
Пример #10
0
    def get_text_width_height_descent(self, s, prop, ismath):
        fontsize = prop.get_size_in_points()

        if ismath == "TeX":
            return TexManager().get_text_width_height_descent(s, fontsize)

        scale = fontsize / self.FONT_SCALE

        if ismath:
            prop = prop.copy()
            prop.set_size(self.FONT_SCALE)
            width, height, descent, *_ = \
                self.mathtext_parser.parse(s, 72, prop)
            return width * scale, height * scale, descent * scale

        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 * scale, h * scale, d * scale
Пример #11
0
 def get_texmanager(self):
     """Return the cached `~.texmanager.TexManager` instance."""
     if self._texmanager is None:
         from matplotlib.texmanager import TexManager
         self._texmanager = TexManager()
     return self._texmanager
Пример #12
0
def test_font_selection(rc, preamble, family):
    plt.rcParams.update(rc)
    tm = TexManager()
    src = Path(tm.make_tex("hello, world", fontsize=12)).read_text()
    assert preamble in src
    assert [*re.findall(r"\\\w+family", src)] == [family]
Пример #13
0
 def get_texmanager(self):
     """Return the cached `~.texmanager.TexManager` instance."""
     if self._texmanager is None:
         self._texmanager = TexManager()
     return self._texmanager
Пример #14
0
    def get_glyphs_tex(self,
                       prop,
                       s,
                       glyph_map=None,
                       return_new_glyphs_only=False):
        """Convert the string *s* to vertices and codes using usetex mode."""
        # Mostly borrowed from pdf backend.

        dvifile = TexManager().make_dvi(s, self.FONT_SCALE)
        with dviread.Dvi(dvifile, self.DPI) as dvi:
            page, = dvi

        if glyph_map is None:
            glyph_map = OrderedDict()

        if return_new_glyphs_only:
            glyph_map_new = OrderedDict()
        else:
            glyph_map_new = glyph_map

        glyph_ids, xpositions, ypositions, sizes = [], [], [], []

        # Gather font information and do some setup for combining
        # characters into strings.
        for text in page.text:
            font = get_font(text.font_path)
            char_id = self._get_char_id(font, text.glyph)
            if char_id not in glyph_map:
                font.clear()
                font.set_size(self.FONT_SCALE, self.DPI)
                glyph_name_or_index = text.glyph_name_or_index
                if isinstance(glyph_name_or_index, str):
                    index = font.get_name_index(glyph_name_or_index)
                    font.load_glyph(index, flags=LOAD_TARGET_LIGHT)
                elif isinstance(glyph_name_or_index, int):
                    self._select_native_charmap(font)
                    font.load_char(glyph_name_or_index,
                                   flags=LOAD_TARGET_LIGHT)
                else:  # Should not occur.
                    raise TypeError(f"Glyph spec of unexpected type: "
                                    f"{glyph_name_or_index!r}")
                glyph_map_new[char_id] = font.get_path()

            glyph_ids.append(char_id)
            xpositions.append(text.x)
            ypositions.append(text.y)
            sizes.append(text.font_size / self.FONT_SCALE)

        myrects = []

        for ox, oy, h, w in page.boxes:
            vert1 = [(ox, oy), (ox + w, oy), (ox + w, oy + h), (ox, oy + h),
                     (ox, oy), (0, 0)]
            code1 = [
                Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
                Path.LINETO, Path.CLOSEPOLY
            ]
            myrects.append((vert1, code1))

        return (list(zip(glyph_ids, xpositions, ypositions,
                         sizes)), glyph_map_new, myrects)