B
    ò¶I`ü=  ã               @   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 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 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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d%d&„ ZdDd(d)„Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Z e! "d2¡Z#e d¡d3d4„ ƒZ$d5d6„ Z%d7d8„ Z&e d¡d9d:„ ƒZ'd;d<„ Z(dEd=d>„Z)dFd@dA„Z*dGdBdC„Z+d'S )HÚ
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   z
sans-serifÚcursiveÚ	monospace)Zpncz\renewcommand{\rmdefault}{pnc})Zpbkz\renewcommand{\rmdefault}{pbk})Zptmz\usepackage{mathptmx})Zpplz\usepackage{mathpazo})Úpzcz\usepackage{chancery})Zpchz\usepackage{charter})ÚcmrÚ )Úcmssr   )Zphvz\usepackage{helvet})Zpagz\usepackage{avant})Zpcrz\usepackage{courier})Úcmttz\usepackage{type1ec})r   z\usepackage{type1ec})r   z\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  ¡ S )N)ÚmplÚget_cachedir)Úself© r   ú9/tmp/pip-unpacked-wheel-tvo012g9/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 | ¡S )NT)ÚparentsÚexist_ok)r   ÚtexcacheÚmkdirÚobjectÚ__new__)Úclsr   r   r   r   \   s    zTexManager.__new__c             C   s   | j  dd¡S )Nr   )r   r   )Ú_fontsÚget)r   r   r   r   r   c   s    zTexManager.serifc             C   s   | j  dd¡S )Nz
sans-serif)r   r   )r   r    )r   r   r   r   Ú
sans_serifh   s    zTexManager.sans_serifc             C   s   | j  dd¡S )Nr   )r
   z\usepackage{chancery})r   r    )r   r   r   r   r   m   s    zTexManager.cursivec             C   s   | j  dd¡S )Nr	   )r   r   )r   r    )r   r   r   r   r	   r   s    zTexManager.monospacec          
   C   s~  t d }t|ƒdkr6|d  ¡ | jkr6|d  ¡ | _nt dd | j¡¡ d| _| jg}x | jD ]–}x|t d|  D ]P}| ¡ | jkr¶| j| ¡  | j	|< t 
d||| j| ¡  ¡ P qrt 
d	|¡ qrW t d
|¡ | j| | j	|< | | j	| d ¡ q`W |  ¡  d¡}| t |¡ ¡ ¡ | j	d d | j	d d | j	d d g}| jdk�rd| | 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.zutf-8z
sans-serifr	   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
fontconfigr(   ÚfontZpreamble_bytesÚcmdr   r   r   Úget_font_configw   s8    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%fzutf-8)r+   r8   r/   ÚstrÚosÚpathr   r1   r2   r0   r3   )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.
        )r4   )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   r/   °   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{-}}z:\usepackage[papersize=72in,body=70in,margin=1in]{geometry}zM\makeatletter\@ifpackageloaded{textcomp}{}{\usepackage{textcomp}}\makeatother)r+   r4   r/   )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.
        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)r@   r    r(   r   Ú
write_textrB   )r   r<   r=   ÚbasefileÚtexfileÚ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.
        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)rC   )r@   r    r(   r   rD   rB   )r   r<   r=   rE   rF   rG   r   r   r   Úmake_tex_previewé   s    
zTexManager.make_tex_previewc          
   C   s¸   t  t |¡¡ ytj|| jtjd�}W n€ tk
r^ } zt	d 
|d ¡ƒ|‚W d d }~X Y nL tjk
r¨ } z,t	dj
|d | d¡|j d¡d�ƒ|‚W d d }~X Y nX t  |¡ |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)Úprogr<   Úexc)r)   r-   r   Z_pformat_subprocessÚ
subprocessÚcheck_outputr   ÚSTDOUTÚFileNotFoundErrorÚRuntimeErrorÚformatÚCalledProcessErrorr0   ÚoutputÚdecode)r   Úcommandr<   ÚreportrM   r   r   r   Ú_run_checked_subprocess  s"    &
z"TexManager._run_checked_subprocessc          	   C   s¸   t  td¡r|  ||¡S |  ||¡}d| }tj |¡s´|  ||¡}t	 
|¡� |  ddd|g|¡ W dQ R X xDt |d ¡D ]2}| d¡s~yt |¡ 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Ú*)Údvir<   )ÚdictÚ__getitem__r   Úmake_dvi_previewr@   r:   r;   ÚexistsrH   r   Z
_lock_pathrY   ÚglobÚendswithÚremoveÚOSError)r   r<   r=   rE   ÚdvifilerF   Úfnamer   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 d
Q R X xDt |d ¡D ]2}
|
 d¡s¤yt |
¡ W q¤ tk
rÔ   Y q¤X q¤W |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.baselinerZ   z-interaction=nonstopmodez--halt-on-errorzutf-8z	.baselineÚwú Nr[   )r\   r<   Zbaseline)r@   r:   r;   r`   rI   rY   r   Ú_re_vboxÚsearchrV   ÚopenÚwriter+   Úgroupsra   rb   rc   rd   )r   r<   r=   rE   re   ÚbaselinefilerF   rX   ÚmÚfhrf   r   r   r   r_   A  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)r@   r:   r;   r`   rg   r9   Úgetattrr   Z_get_executable_infoÚversionÚinsertrY   )r   r<   r=   r>   rE   Úpngfilere   r7   r   r   r   Úmake_pngd  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   r8   Úgrey_arraydr    rv   r   ÚimageZimreadr:   r;   r+   r   )r   r<   r=   r>   ÚkeyÚalpharu   Úrgbar   r   r   Úget_grey{  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é   ).rw   )r   )r}   ÚnpÚemptyÚshaper   ÚcolorsZto_rgb)r   r<   r=   r>   Zrgbr{   r|   r   r   r   Úget_rgba‰  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 dQ R X ‡ fdd	„|D ƒ\}	}
}||	|
 |
fS |  ||¡}t |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   r   r   g      ð?r"   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   )ÚstripZpoints_to_pixelsr]   r^   r   r@   r:   r;   r`   r_   rl   ÚreadÚsplitrg   r   ZDviÚwidthÚheightZdescent)r   r<   r=   ZrendererrE   ro   re   rq   Úlr�   Údepthr�   r\   Úpager   )r‰   r   Úget_text_width_height_descent‘  s     
z(TexManager.get_text_width_height_descent)N)NN)NNr~   )N),Ú__name__Ú
__module__Ú__qualname__Ú__doc__r:   r;   r+   r   r   r   rx   r(   r'   r,   r   Ú
deprecatedÚpropertyr   r   Ú	functoolsÚ	lru_cacher   r   r   r!   r   r	   r8   r@   rA   r/   rB   rH   ÚreÚcompilerj   rI   rY   rg   r_   rv   r}   r…   r”   r   r   r   r   r   /   sf   *
	'#

r   )r˜   r›   ra   r1   Úloggingr:   Úpathlibr   r�   rN   Znumpyr�   Z
matplotlibr   r   r   r   Ú	getLoggerr•   r)   r   r   r   r   r   Ú<module>   s   
