U
    \	a>                     @   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
mZ ddlZddlZddlmZmZmZmZ e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>=9.0

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)TemporaryDirectory)_apicbookdvireadrcParamsc                   @   s  e Zd ZdZeje dZ	i Z
dZdZddddd	d	d
ddddddddddZejdddedd Zededd Zi Zededd Zededd Zededd Zededd Ze dd Zd d! Zd@d#d$Zd%d& Zd'd( Zd)d* Zd+d, Z e!"d-Z#edd.d/ Z$d"d0d1d2Z%d3d4 Z&edd5d6 Z'd7d8 Z(dAd9d:Z)dBd<d=Z*dCd>d?Z+d"S )D
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)r	   
sans-serifcursive	monospace)Zpncz\renewcommand{\rmdefault}{pnc})Zpbkz\renewcommand{\rmdefault}{pbk})Zptmz\usepackage{mathptmx})Zpplz\usepackage{mathpazo}Zpzcz\usepackage{chancery})Zpchz\usepackage{charter}cmr cmssr   )Zphvz\usepackage{helvet})Zpagz\usepackage{avant})Zpcrz\usepackage{courier})cmtt\usepackage{type1ec})r   r   )r   r   )znew century schoolbookZbookmantimesZpalatinozzapf chanceryr   Zcharterr	   r
   Z	helveticazavant gardeZcourierr   zcomputer modern romanzcomputer modern sans serifzcomputer modern typewriterz3.3zmatplotlib.get_cachedir())alternativec                 C   s   t  S N)mplget_cachedirself r   9/tmp/pip-unpacked-wheel-wjyw_3jo/matplotlib/texmanager.py<lambda>N       zTexManager.<lambda>c                 C   s   i S r   r   r   r   r   r   r   O   r   c                 C   s   | j ddS )Nr	   r   _fontsgetr   r   r   r   r   R   r   c                 C   s   | j ddS )Nr
   r   r    r   r   r   r   r   T   r   c                 C   s   | j ddS )Nr   r   r    r   r   r   r   r   V   s    c                 C   s   | j ddS )Nr   )r   r   r    r   r   r   r   r   Y   r   c                 C   s   t | jjddd t| S )NT)parentsexist_ok)r   texcachemkdirobject__new__)clsr   r   r   r(   [   s    zTexManager.__new__c              
   C   sx  t d }t|dkr6|d  | jkr6|d  | _ntdd| j d| _| jg}| jD ]}t d|  D ]R}| | jkr| j|  | j	|< t
d||| j|    qqnt
d	| qntd
| | j| | j	|< || j	| d  q^|  d}|t|  | j	d d | j	d d | j	d d g}| jdkr^|| j	d d  dd|| _d|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.utf-8r
   r   r   
\usepackage{type1cm}r   )r-   )r   lenlowerfont_familiesfont_family_loginfojoin	font_infor!   debugappendget_custom_preambleencodehashlibmd5	hexdigest_font_preamble)r   ffZ
fontconfigr1   fontZpreamble_bytescmdr   r   r   get_font_config`   sD    

  zTexManager.get_font_configNc                 C   sH   d ||  d| |  t|p dg}tj | jt|	d
 S )zU
        Return a filename based on a hash of the string, fontsize, and dpi.
        r   z%fr+   )r4   rA   r8   strospathr%   r:   r;   r9   r<   )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.
        )r=   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   r8      s    zTexManager.get_custom_preamblec              
   C   s    d dd| jddd|  dgS )Nr,   z\documentclass{article}z \newcommand{\mathdefault}[1]{#1}z\usepackage[utf8]{inputenc}z.\DeclareUnicodeCharacter{2212}{\ensuremath{-}}z1\usepackage[papersize=72in, margin=1in]{geometry}zM\makeatletter\@ifpackageloaded{textcomp}{}{\usepackage{textcomp}}\makeatother)r4   r=   r8   r   r   r   r   _get_preamble   s    zTexManager._get_preamblec                 C   sV   |  ||}d| }ddd| jd}t|jd|  ||d || f dd	 |S )
zv
        Generate a tex file to render the tex string at a specific font size.

        Return the file name.
        %s.tex{\sffamily %s}{\ttfamily %s}r
   r   {\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}
      ?r+   encodingrI   r"   r1   r   
write_textrK   r   rE   rF   basefiletexfileZfontcmdr   r   r   make_tex   s    
zTexManager.make_texz3MatplotlibBox:\(([\d.]+)pt\+([\d.]+)pt\)x([\d.]+)ptc                 C   sV   |  ||}d| }ddd| jd}t|jd|  ||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.
        rL   rM   rN   rO   rP   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}
rQ   r+   rR   rT   rV   r   r   r   make_tex_preview   s    
zTexManager.make_tex_previewcwdc             
   C   s   t t| z$tj||d k	r$|n| jtjd}W n tk
rj } zt	d
|d |W 5 d }~X Y nL tjk
r } z,t	dj
|d |d|jdd|W 5 d }~X Y nX t | |S )N)r\   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_escaper+   )progrE   exc)r2   r6   r   Z_pformat_subprocess
subprocesscheck_outputr%   STDOUTFileNotFoundErrorRuntimeErrorformatCalledProcessErrorr9   outputdecode)r   commandrE   r\   reportr_   r   r   r   _run_checked_subprocess   s6     


z"TexManager._run_checked_subprocessc              	   C   s   t tdr| ||S | ||}d| }tj|s| ||}t	t
|jd6}| jddd|g||d t
|t
|j | W 5 Q R X |S )zm
        Generate a dvi file containing latex's layout of tex string.

        Return the file name.
        text.latex.preview%s.dvi)dirlatex-interaction=nonstopmode--halt-on-errorr[   )dict__getitem__r   make_dvi_previewrI   rC   rD   existsrY   r   r   parentrk   namereplace)r   rE   rF   rW   dvifilerX   Ztmpdirr   r   r   make_dvi  s      "zTexManager.make_dvic              	   C   s   |  ||}d| }d| }tj|r4tj|s| ||}| ddd|g|}tj|	d}t
|d d}	|	d	|  W 5 Q R X t|d
 D ]2}
|
dszt|
 W q tk
r   Y qX q|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.
        rm   %s.baselinero   rp   rq   r+   z	.baselinew *)dvirE   Zbaseline)rI   rC   rD   ru   rZ   rk   r   _re_vboxsearchrh   openwriter4   groupsglobendswithremoveOSError)r   rE   rF   rW   ry   baselinefilerX   rj   mfhfnamer   r   r   rt   )  s*    

zTexManager.make_dvi_previewc              
   C   s   |  |||}d| }tj|s~| ||}ddddt|ddd||g
}ttd	d
rrtdj	dkrr|
dd | || |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.16r*   z--freetype0)rI   rC   rD   ru   rz   rB   getattrr   Z_get_executable_infoversioninsertrk   )r   rE   rF   rG   rW   pngfilery   r@   r   r   r   make_pngL  s"        zTexManager.make_pngc                 C   s   |st d }|st d }||  ||f}| j|}|dkr| |||}tjtj	
| j|}|dddddf  | j|< }|S )zReturn the alpha channel.z	font.sizezsavefig.dpiN)r   rA   grey_arraydr"   r   r   imageZimreadrC   rD   r4   r%   )r   rE   rF   rG   keyalphar   rgbar   r   r   get_greyc  s     zTexManager.get_greyr   r   r   c                 C   sB   |  |||}t|jd}tj||dddf< ||d< |S )z<Return latex's rendering of the tex string as an rgba array.   .N   ).r   )r   )r   npemptyshaper   colorsZto_rgb)r   rE   rF   rG   Zrgbr   r   r   r   r   get_rgbaq  s
    zTexManager.get_rgbac              	      s   |  dkrdS |r|dnd ttdr| ||}d| }tj|sZ| 	||}t
|}|  }W 5 Q R X  fdd|D \}	}
}||	|
 |
fS | ||}t|d	  }|\}W 5 Q R X |j|j|j |jfS d
S )z-Return width, height and descent of the text.r   r   g      ?r*   rl   r{   c                    s   g | ]}t |  qS r   )float).0l1Zdpi_fractionr   r   
<listcomp>  s     z<TexManager.get_text_width_height_descent.<locals>.<listcomp>H   N)stripZpoints_to_pixelsrr   rs   r   rI   rC   rD   ru   rt   r   readsplitrz   r   ZDviwidthheightZdescent)r   rE   rF   ZrendererrW   r   ry   r   lr   depthr   r   pager   r   r   get_text_width_height_descenty  s     
z(TexManager.get_text_width_height_descent)N)NN)NNr   )N),__name__
__module____qualname____doc__rC   rD   r4   r   r   r%   r   r1   r0   r5   r   
deprecatedpropertyZcachedirZrgba_arraydr!   r	   Z
sans_serifr   r   	functools	lru_cacher(   rA   rI   rJ   r8   rK   rY   recompiler   rZ   rk   rz   rt   r   r   r   r   r   r   r   r   r   )   s~    





*
	
&
"

r   )r   r   r   r:   loggingrC   pathlibr   r   r`   tempfiler   Znumpyr   Z
matplotlibr   r   r   r   r   	getLoggerr   r2   r   r   r   r   r   <module>   s   
