3
ƽh=                 @   s   d Z ddlZddlZddlZddlZddlZddlmZ ddlZddl	Z	ddl
ZddlZddlmZmZmZ ejeZG dd dZdS )a  
Support for embedded TeX expressions in Matplotlib via dvipng and dvips for the
raster and PostScript backends.  The tex and dvipng/dvips information is cached
in ~/.matplotlib/tex.cache for reuse between sessions.

Requirements:

* latex
* \*Agg backends: dvipng>=1.6
* PS backend: psfrag, dvips, and Ghostscript>=8.60

Backends:

* \*Agg
* PS
* PDF

For raster output, you can get RGBA numpy arrays from TeX expressions
as follows::

  texmanager = TexManager()
  s = ('\TeX\ is Number '
       '$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!')
  Z = texmanager.get_rgba(s, fontsize=12, dpi=80, rgb=(1, 0, 0))

To enable tex rendering of all text in your matplotlib figure, set
:rc:`text.usetex` to True.
    N)Path)cbookdvireadrcParamsc               @   s  e Zd ZdZejjej dZ	i Z
dZdOZdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_dZejdd d!ed"d# Zejded$d% Zej d&d' Zi Zejded(d) Zejded*d+ Zejded,d- Zejded.d/ Zd0d1 Zd`d3d4Zd5d6 Zd7d8 Zd9d: Zd;d< Z e!j"d=Z#ejdd>d? Z$d@dA Z%dBdC Z&ejddDdE Z'dFdG Z(dadHdIZ)dcdKdLZ*dddMdNZ+d2S )e
TexManagerz
    Convert strings to dvi files using TeX, caching the results to a directory.

    Repeated calls to this constructor always return the same instance.
    z	tex.cacheserif
sans-serifcursive	monospacepnc\renewcommand{\rmdefault}{pnc}pbk\renewcommand{\rmdefault}{pbk}ptm\usepackage{mathptmx}ppl\usepackage{mathpazo}pzc\usepackage{chancery}pch\usepackage{charter}cmr cmssphv\usepackage{helvet}pag\usepackage{avant}pcr\usepackage{courier}cmtt\usepackage{type1ec})znew century schoolbookZbookmantimesZpalatinozzapf chanceryr	   Zcharterr   z
sans-serifZ	helveticazavant gardeZcourierr
   zcomputer modern romanzcomputer modern sans serifzcomputer modern typewriterz3.3zmatplotlib.get_cachedir())alternativec             C   s   t j S )N)mplget_cachedir)self r'   ;/tmp/pip-build-7iwl8md4/matplotlib/matplotlib/texmanager.pycachedirR   s    zTexManager.cachedirc             C   s   i S )Nr'   )r&   r'   r'   r(   rgba_arraydW   s    zTexManager.rgba_arraydc             C   s   t | jjddd tj| S )NT)parentsexist_ok)r   texcachemkdirobject__new__)clsr'   r'   r(   r0   \   s    zTexManager.__new__c             C   s   | j jddS )Nr   r   r   )r   r   )_fontsget)r&   r'   r'   r(   r   c   s    zTexManager.serifc             C   s   | j jddS )Nz
sans-serifr   r   )r   r   )r2   r3   )r&   r'   r'   r(   
sans_serifh   s    zTexManager.sans_serifc             C   s   | j jddS )Nr	   r   \usepackage{chancery})r   r5   )r2   r3   )r&   r'   r'   r(   r	   m   s    zTexManager.cursivec             C   s   | j jddS )Nr
   r    r   )r    r   )r2   r3   )r&   r'   r'   r(   r
   r   s    zTexManager.monospacec             C   s~  t d }t|dkr6|d j | jkr6|d j | _ntjddj| j d| _| jg}x| jD ]}x|t d|  D ]P}|j | jkr| j|j  | j	|< tj
d||| j|j   P qrtj
d	| qrW tjd
| | j| | j	|< |j| j	| d  q`W | j jd}|jtj|j  | j	d d | j	d d | j	d d g}| jdkrd|j| j	d d  djd|| _dj|S )Nzfont.family   r   zXfont.family must be one of (%s) when text.usetex is True. serif will be used by default.z, r   zfont.zfamily: %s, font: %s, info: %sz&%s font is not compatible with usetex.zQNo LaTeX-compatible font found for the %s font family in rcParams. Using default.zutf-8z
sans-serifr
   r	   
\usepackage{type1cm}r   )r8   )r   lenlowerfont_familiesfont_family_loginfojoin	font_infor2   debugappendget_custom_preambleencodehashlibmd5	hexdigest_font_preamble)r&   ffZ
fontconfigr<   fontZpreamble_bytescmdr'   r'   r(   get_font_configw   s8    zTexManager.get_font_configNc             C   sH   dj || j d| | j t|p dg}tjj | jtj|j	dj
 S )zU
        Return a filename based on a hash of the string, fontsize, and dpi.
        r   z%fzutf-8)r?   rL   rC   strospathr-   rE   rF   rD   rG   )r&   texfontsizedpisr'   r'   r(   get_basefile   s    zTexManager.get_basefilec             C   s   | j S )zU
        Return a string containing font configuration for the tex preamble.
        )rH   )r&   r'   r'   r(   get_font_preamble   s    zTexManager.get_font_preamblec             C   s   t d S )z>Return a string containing user additions to the tex preamble.ztext.latex.preamble)r   )r&   r'   r'   r(   rC      s    zTexManager.get_custom_preamblec          	   C   s    dj dd| jddd| j dgS )Nr7   z\documentclass{article}z \newcommand{\mathdefault}[1]{#1}z\usepackage[utf8]{inputenc}z.\DeclareUnicodeCharacter{2212}{\ensuremath{-}}z:\usepackage[papersize=72in,body=70in,margin=1in]{geometry}zM\makeatletter\@ifpackageloaded{textcomp}{}{\usepackage{textcomp}}\makeatother)r?   rH   rC   )r&   r'   r'   r(   _get_preamble   s    zTexManager._get_preamblec             C   sV   | j ||}d| }dddj| jd}t|jd| j ||d || f dd	 |S )
zv
        Generate a tex file to render the tex string at a specific font size.

        Return the file name.
        z%s.texz{\sffamily %s}z{\ttfamily %s})z
sans-serifr
   z{\rmfamily %s}z
%s
\pagestyle{empty}
\begin{document}
%% The empty hbox ensures that a page is printed even for empty inputs, except
%% when using psfrag which gets confused by it.
\fontsize{%f}{%f}%%
\ifdefined\psfrag\else\hbox{}\fi%%
%s
\end{document}
g      ?zutf-8)encoding)rT   r3   r<   r   
write_textrV   )r&   rP   rQ   basefiletexfilefontcmdr'   r'   r(   make_tex   s    zTexManager.make_texz3MatplotlibBox:\(([\d.]+)pt\+([\d.]+)pt\)x([\d.]+)ptc             C   sV   | j ||}d| }dddj| jd}t|jd| j ||d || f dd	 |S )
z
        Generate a tex file to render the tex string at a specific font size.

        It uses the preview.sty to determine the dimension (width, height,
        descent) of the output.

        Return the file name.
        z%s.texz{\sffamily %s}z{\ttfamily %s})z
sans-serifr
   z{\rmfamily %s}aD  
%s
\usepackage[active,showbox,tightpage]{preview}

%% we override the default showbox as it is treated as an error and makes
%% the exit status not zero
\def\showbox#1%%
{\immediate\write16{MatplotlibBox:(\the\ht#1+\the\dp#1)x\the\wd#1}}

\begin{document}
\begin{preview}
{\fontsize{%f}{%f}%s}
\end{preview}
\end{document}
g      ?zutf-8)rW   )rT   r3   r<   r   rX   rV   )r&   rP   rQ   rY   rZ   r[   r'   r'   r(   make_tex_preview   s    
zTexManager.make_tex_previewc             C   s   t jtj| ytj|| jtjd}W n tk
r^ } zt	dj
|d |W Y d d }~X nL tjk
r } z.t	dj
|d |jd|jjdd|W Y d d }~X nX t j| |S )N)cwdstderrz?Failed to process string with tex because {} could not be foundr   zr{prog} was not able to process the following string:
{tex!r}

Here is the full report generated by {prog}:
{exc}

Zunicode_escapezutf-8)progrP   exc)r=   rA   r   Z_pformat_subprocess
subprocesscheck_outputr-   STDOUTFileNotFoundErrorRuntimeErrorformatCalledProcessErrorrD   outputdecode)r&   commandrP   reportra   r'   r'   r(   _run_checked_subprocess  s"    &
z"TexManager._run_checked_subprocessc             C   s   t jtdr| j||S | j||}d| }tjj|s| j||}t	j
| | jddd|g| W dQ R X xDtj|d D ]2}|jd
s~ytj| W q~ tk
r   Y q~X q~W |S )zm
        Generate a dvi file containing latex's layout of tex string.

        Return the file name.
        ztext.latex.previewz%s.dvilatexz-interaction=nonstopmodez--halt-on-errorN*dvirP   )rp   rP   )dict__getitem__r   make_dvi_previewrT   rN   rO   existsr\   r   Z
_lock_pathrm   globendswithremoveOSError)r&   rP   rQ   rY   dvifilerZ   fnamer'   r'   r(   make_dvi&  s"    

zTexManager.make_dvic             C   s   | j ||}d| }d| }tjj| s8tjj| r| j||}| jddd|g|}tjj|j	d}t
|d d}	|	jd	j|j  W d
Q R X xDtj|d D ]2}
|
jdsytj|
 W q tk
r   Y qX qW |S )z
        Generate a dvi file containing latex's layout of tex string.

        It calls make_tex_preview() method and store the size information
        (width, height, descent) in a separate file.

        Return the file name.
        z%s.dviz%s.baselinern   z-interaction=nonstopmodez--halt-on-errorzutf-8z	.baselinew Nro   rp   rP   baseline)rp   rP   r~   )rT   rN   rO   rt   r]   rm   r   _re_vboxsearchrj   openwriter?   groupsru   rv   rw   rx   )r&   rP   rQ   rY   ry   baselinefilerZ   rl   mfhrz   r'   r'   r(   rs   A  s$    



zTexManager.make_dvi_previewc          
   C   s   | j |||}d| }tjj|s~| j||}ddddt|ddd||g
}ttd	d
rrtjdj	dkrr|j
dd | j|| |S )zp
        Generate a png file containing latex's rendering of tex string.

        Return the file name.
        z%s.pngZdvipngz-bgZTransparentz-Dz-TZtightz-oZ_called_from_pytestFz1.16r6   z--freetype0)rT   rN   rO   rt   r{   rM   getattrr$   Z_get_executable_infoversioninsertrm   )r&   rP   rQ   rR   rY   pngfilery   rK   r'   r'   r(   make_pngd  s    zTexManager.make_pngc             C   s   |st d }|st d }|| j ||f}| jj|}|dkr| j|||}tjjtj	j
| j|}|dddddf  | j|< }|S )zReturn the alpha channel.z	font.sizezsavefig.dpiNr6   )r   rL   grey_arraydr3   r   r$   imageZimreadrN   rO   r?   r-   )r&   rP   rQ   rR   keyalphar   rgbar'   r'   r(   get_grey{  s     zTexManager.get_greyr   c             C   sB   | j |||}tj|jd}tjj||dddf< ||d< |S )	z<Return latex's rendering of the tex string as an rgba array.   .N   r6   )r   r   ).r   )r   npemptyshaper$   colorsZto_rgb)r&   rP   rQ   rR   Zrgbr   r   r'   r'   r(   get_rgba  s
    zTexManager.get_rgbac          
      s   |j  dkrdS |r|jdnd tjtdr| j||}d| }tjj|sZ| j	||}t
|}|j j }W dQ R X  fdd	|D \}	}
}||	|
 |
fS | j||}tj|d
  }|\}W dQ R X |j|j|j |jfS dS )z-Return width, height and descent of the text.r   r   g      ?r6   ztext.latex.previewz%s.baselineNc                s   g | ]}t |  qS r'   )float).0l1)dpi_fractionr'   r(   
<listcomp>  s    z<TexManager.get_text_width_height_descent.<locals>.<listcomp>H   )r   r   r   )stripZpoints_to_pixelsrq   rr   r   rT   rN   rO   rt   rs   r   readsplitr{   r   ZDviwidthheightZdescent)r&   rP   rQ   ZrendererrY   r   ry   r   lr   depthr   rp   pager'   )r   r(   get_text_width_height_descent  s     
z(TexManager.get_text_width_height_descent)r   r   r	   r
   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r   r   )r    r!   )r   r!   )r   r!   )r    r!   )N)NNr   r   r   )NNr   )N),__name__
__module____qualname____doc__rN   rO   r?   r$   r%   r-   r   r<   r;   r@   r   Z
deprecatedpropertyr)   r*   	functools	lru_cacher0   r2   r   r4   r	   r
   rL   rT   rU   rC   rV   r\   recompiler   r]   rm   r{   rs   r   r   r   r   r'   r'   r'   r(   r   /   sf   *
	'#

r   )r   r   ru   rE   loggingrN   Zpathlibr   r   rb   numpyr   Z
matplotlibr$   r   r   r   	getLoggerr   r=   r   r'   r'   r'   r(   <module>   s   
