a
    ëÝEb5¢  ã                   @   s0  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
Z
d dlZd dlZd dlmZ d dlZd dlmZ d dlZd dlmZmZmZ d dlmZmZmZmZmZmZ d dlm Z  d dl!m"Z"m#Z# d d	l$m%Z% d d
l&m'Z' d dl(m)Z) e *e+¡Z,dd„ Z-dd„ Z.dZ/de/ Z0dZ1de1 Z2dZ3e
 4e3d ¡Z5e 6e
 4e3d ¡j7d¡Z8e 6e
 4e3d ¡j7d¡Z9dd„ Z:dd„ Z;dd„ Z<dd „ Z=d!d"„ Z>G d#d$„ d$e?ƒZ@G d%d&„ d&ƒZAe Bd'¡d(d)„ ƒZCG d*d+„ d+eƒZDe Ed,¡G d-d.„ d.ƒƒZFG d/d0„ d0eƒZGeZHejIG d1d2„ d2eƒƒZJG d3d4„ d4ƒZKdS )5é    N)ÚBytesIO)ÚTemporaryDirectory)ÚImage)Ú_apiÚcbookÚfont_manager)Ú_BackendÚ_check_savefig_extra_argsÚFigureCanvasBaseÚFigureManagerBaseÚGraphicsContextBaseÚRendererBase)ÚMixedModeRenderer)Ú_create_pdf_info_dictÚ_datetime_to_pdf)ÚPath)ÚFigure)ÚGcfc                  C   s�   g } t jd }|dkr |  d¡ |dkr†t jd r†g d¢}g d¢}t||ƒD ]8\}}t t |¡¡}|  d||j|j	 
¡ d f ¡ qLd	 | ¡S )
z Build fontspec preamble from rc.úpgf.texsystemÚpdflatexz\usepackage{fontspec}zpgf.rcfonts)Úserifzsans\-serifÚ	monospace)ZsetmainfontZsetsansfontZsetmonofontz\%s{%s}[Path=\detokenize{%s}]ú/Ú
)ÚmplÚrcParamsÚappendÚzipÚpathlibr   ÚfmZfindfontÚnameÚparentÚas_posixÚjoin)Úlatex_fontspecÚ
texcommandÚfamiliesÚcommandsÚfamilyÚcommandÚpath© r+   ú_/home/ja/django-apps/lartica_env/lib/python3.9/site-packages/matplotlib/backends/backend_pgf.pyÚget_fontspec'   s    

ÿ
r-   c                   C   s
   t jd S )zGet LaTeX preamble from rc.zpgf.preamble©r   r   r+   r+   r+   r,   Úget_preamble<   s    r/   gRh�¸’VŒ?ç      ð?gÇqÇqŒ?z(?<!\\)(?:\\\\)*z\$z
(?=[_^$%])z\\z(\\mathdefault)Ú c                 C   s\   t | ƒ} |  dd¡} t | ¡}t|ƒD ]*\}}|d s@t|ƒ}nd| }|||< q&d |¡S )aX  
    Do some necessary and/or useful substitutions for texts to be included in
    LaTeX documents.

    This distinguishes text-mode and math-mode by replacing the math separator
    ``$`` with ``\(\displaystyle %s\)``. Escaped math separators (``\$``)
    are ignored.

    The following characters are escaped in text segments: ``_^$%``
    u   âˆ’z\ensuremath{-}é   z\(\displaystyle %s\)r1   )Ú_replace_mathdefaultÚreplaceÚ
re_mathsepÚsplitÚ	enumerateÚ_replace_escapetextr#   )ÚtextÚpartsÚiÚsr+   r+   r,   Úcommon_texificationZ   s    


r=   c                 C   s   |   |¡ |   d¡ d S )Nz%
)Úwrite)ÚfhÚliner+   r+   r,   Úwritelnv   s    
rA   c                    sô   g }dddddœ}|  ¡ d ‰ ˆ |v r6| |ˆ  ¡ nDt‡ fdd„tjjD ƒƒrntjd d	krn| d
ˆ  ¡ nt 	dˆ ¡ | 
¡ }| d||d f ¡ ddddœ}| || ¡  ¡ g d¢}| ¡ |v rÔ| d¡ | d¡ d |¡d t| ƒ S )zƒ
    Generate a TeX string that renders string *s* with font properties *prop*,
    also applying any required escapes to *s*.
    z	\rmfamilyz	\sffamilyz	\ttfamily)r   Úsansz
sans-serifr   r   c                 3   s   | ]}|j ˆ kV  qd S ©N)r    )Ú.0Úfont©r(   r+   r,   Ú	<genexpr>‰   ó    z*_escape_and_apply_props.<locals>.<genexpr>r   r   z\setmainfont{%s}\rmfamilyzIgnoring unknown font: %sz\fontsize{%f}{%f}g333333ó?r1   z\itshapez\slshape)ÚnormalÚitalicZoblique)ZsemiboldZdemiboldZdemiÚboldZheavyz
extra boldÚblackz	\bfseriesz\selectfontú )Z
get_familyr   Úanyr   ZfontManagerZttflistr   r   Ú_logÚwarningZget_size_in_pointsÚ	get_styleZ
get_weightr#   r=   )r<   Úpropr'   r&   ÚsizeÚstylesZ
boldstylesr+   rF   r,   Ú_escape_and_apply_props}   s*    ÿÿ

rU   c                 C   sD   t |tjƒrt|ƒ}n| dkr,|j d¡}nt|ƒ}| › d|› d�S )z;Convert metadata key/value to a form that hyperref accepts.ZTrappedÚasciiz={Ú})Ú
isinstanceÚdatetimer   r    ÚdecodeÚstr)ÚkeyÚvaluer+   r+   r,   Ú_metadata_to_strž   s    
r^   c                     sV   t  d¡rdd„ } | S zt d¡‰ W n tjy8   Y n0 ‡ fdd„}|S tdƒ‚dS )	z9Return a function that converts a pdf file to a png file.Ú
pdftocairoc              	   S   s6   ddddd| | t j |¡d g}tj|tjd� d S )Nr_   z-singlefilez-pngz-rz%dr   ©Ústderr)Úosr*   ÚsplitextÚ
subprocessÚcheck_outputÚSTDOUT©ZpdffileZpngfileÚdpiÚcmdr+   r+   r,   Úcairo_convert¬   s    ÿz0make_pdf_to_png_converter.<locals>.cairo_convertÚgsc                    s>   ˆ j ddddddddd	d
d| d| | g}tj|tjd� d S )Nz-dQUIETz-dSAFERz-dBATCHz	-dNOPAUSEz
-dNOPROMPTz-dUseCIEColorz-dTextAlphaBits=4z-dGraphicsAlphaBits=4z-dDOINTERPOLATEz-sDEVICE=png16mz-sOutputFile=%sz-r%dr`   )Ú
executablerd   re   rf   rg   ©Zgs_infor+   r,   Ú
gs_convert¶   s    
ûz-make_pdf_to_png_converter.<locals>.gs_convertz&No suitable pdf to png renderer found.N)ÚshutilÚwhichr   Z_get_executable_infoZExecutableNotFoundErrorÚRuntimeError)rj   rn   r+   rm   r,   Úmake_pdf_to_png_converter©   s    
rr   c                       s&   e Zd Zd‡ fdd„	Zdd„ Z‡  ZS )Ú
LatexErrorr1   c                    s   t ƒ  |¡ || _d S rC   )ÚsuperÚ__init__Úlatex_output)ÚselfÚmessagerv   ©Ú	__class__r+   r,   ru   Ã   s    zLatexError.__init__c                 C   s    | j \}| jr|d| j 7 }|S ©Nr   )Úargsrv   ©rw   r<   r+   r+   r,   Ú__str__Ç   s    zLatexError.__str__)r1   )Ú__name__Ú
__module__Ú__qualname__ru   r~   Ú__classcell__r+   r+   ry   r,   rs   Â   s   rs   c                   @   sŒ   e Zd ZdZedd„ ƒZedd„ ƒZee 	d¡dd„ ƒƒZ
d	d
„ Zdd„ Zdd„ Zdd„ Ze d¡edd„ ƒƒZdd„ Zdd„ Zdd„ ZdS )ÚLatexManagerzÛ
    The LatexManager opens an instance of the LaTeX application for
    determining the metrics of text elements. The LaTeX environment can be
    modified by setting fonts and/or a custom preamble in `.rcParams`.
    c                  C   s6   t ƒ } tƒ }ddtjd › �d| |dddg}d |¡S )	Nz\documentclass{minimal}z% !TeX program = r   z\usepackage{graphicx}ú\begin{document}ztext $math \mu$z!\typeout{pgf_backend_query_start}r   )r/   r-   r   r   r#   )Zlatex_preambler$   Úlatex_headerr+   r+   r,   Ú_build_latex_headerÕ   s    õz LatexManager._build_latex_headerc                 C   s   |   |  ¡ ¡S )z„
        Return the previous LatexManager if the header and tex system did not
        change, or a new instance otherwise.
        )Ú_get_cached_or_new_implr†   ©Úclsr+   r+   r,   Ú_get_cached_or_newë   s    zLatexManager._get_cached_or_newé   c                 C   s   | ƒ S rC   r+   )r‰   Úheaderr+   r+   r,   r‡   ó   s    z$LatexManager._get_cached_or_new_implc                 C   s>   | j d u r|  ¡  | j j |¡ | j j d¡ | j j ¡  d S r{   )ÚlatexÚ_setup_latex_processÚstdinr>   Úflushr}   r+   r+   r,   Ú_stdin_writelnø   s
    
zLatexManager._stdin_writelnc                 C   sl   t |ƒ}g }| jj d¡}| |¡ |t|ƒ d … |kr<qb|s| j ¡  d | _tdd |¡ƒ‚qd |¡S )Nr‹   zLaTeX process haltedr1   )	Úlistr�   ÚstdoutÚreadr   ÚlenÚkillrs   r#   )rw   r<   ÚcharsÚcr+   r+   r,   Ú_expectÿ   s    

zLatexManager._expectc                 C   s
   |   d¡S )Nz
*)r™   ©rw   r+   r+   r,   Ú_expect_prompt  s    zLatexManager._expect_promptc              
   C   s  t ƒ | _| jj| _t | | jj¡| _tj	d | _
t ¡ | _d}z$tj| j
dgtjtjd| jd�}W nh ty˜ } zt| j
› d�ƒ|‚W Y d }~n<d }~0  tyÊ } ztd| j
 ƒ|‚W Y d }~n
d }~0 0 | j| }| |¡\}}|jdkrøtd	|ƒ‚d | _t ¡ | jƒ| _d S )
Nr   z
\makeatletter
\@@end
ú-halt-on-errorúutf-8©r�   r“   ÚencodingÚcwdz_ not found.  Install it or change rcParams['pgf.texsystem'] to an available TeX implementation.zError starting process %rr   zDLaTeX returned an error, probably missing font or error in preamble.)r   Z_tmpdirr    ÚtmpdirÚweakrefÚfinalizeÚcleanupZ_finalize_tmpdirr   r   r%   rƒ   r†   r…   rd   ÚPopenÚPIPEÚFileNotFoundErrorrq   ÚOSErrorÚcommunicateÚ
returncoders   r�   Ú	functoolsÚ	lru_cacheÚ_get_box_metrics)rw   Z	latex_endr�   ÚerrZ
test_inputr“   ra   r+   r+   r,   ru     s@    

ý

ÿýÿÿ

ÿzLatexManager.__init__z3.5c                 C   s   i S rC   r+   rš   r+   r+   r,   Ú<lambda>1  rH   zLatexManager.<lambda>c                 C   s`   t j| jdgt jt jd| jd�| _dd„ }t | || j¡| _|  	|  
¡ ¡ |  d¡ |  ¡  d S )Nrœ   r�   rž   c                 S   s   |   ¡  |  ¡  d S rC   )r–   r©   )r�   r+   r+   r,   Úfinalize_latex=  s    z9LatexManager._setup_latex_process.<locals>.finalize_latexz*pgf_backend_query_start)rd   r¥   r%   r¦   r¡   r�   r¢   r£   Z_finalize_latexr‘   r†   r™   r›   )rw   r°   r+   r+   r,   rŽ   3  s    ýÿ
z!LatexManager._setup_latex_processc                 C   s   |   t||ƒ¡S )z‡
        Get the width, total height, and descent (in TeX points) for a text
        typeset by the current LaTeX environment.
        )r­   rU   )rw   r9   rR   r+   r+   r,   Úget_width_height_descentI  s    z%LatexManager.get_width_height_descentc           
   
   C   sê   |   d| ¡ z|  ¡ }W n8 tyR } z td ||j¡ƒ|‚W Y d}~n
d}~0 0 z| ¡ d  d¡\}}}W n6 ty¦ } ztd ||¡ƒ|‚W Y d}~n
d}~0 0 t	|dd… ƒt	|dd… ƒt	|dd… ƒ  }}}	|||	 |	fS )zŽ
        Get the width, total height and descent (in TeX points) for a TeX
        command's output in the current LaTeX environment.
        z.\sbox0{%s}\typeout{\the\wd0,\the\ht0,\the\dp0}z%Error measuring {!r}
LaTeX Output:
{}Néýÿÿÿú,éþÿÿÿ)
r‘   r›   rs   Ú
ValueErrorÚformatrv   Ú
splitlinesr6   Ú	ExceptionÚfloat)
rw   ÚtexZanswerr®   ÚwidthÚheightÚoffsetÚwÚhÚor+   r+   r,   r­   P  s*    ÿÿÿÿÿ4zLatexManager._get_box_metricsN)r   r€   r�   Ú__doc__Ústaticmethodr†   ÚclassmethodrŠ   r«   r¬   r‡   r‘   r™   r›   ru   r   Ú
deprecatedÚpropertyZ	str_cacherŽ   r±   r­   r+   r+   r+   r,   rƒ   Î   s    

!rƒ   r‹   c                  C   sR   t  ¡ } |  dt d¡ ¡  ¡ z|  ¡  W dS  tyL   t j 	¡  Y dS 0 d S )Nz&\includegraphics[interpolate=true]{%s}zimages/matplotlib.pngz\includegraphicsz	\pgfimage)
rƒ   rŠ   r‘   r   Z_get_data_pathr"   r›   rs   r‡   Úcache_clear)Úmanr+   r+   r,   Ú_get_image_inclusion_commandj  s    þÿ
rÈ   c                       s¢   e Zd Z‡ fdd„Zd%dd„Zd&dd„Zdd	„ Zd
d„ Zd'dd„Zd(dd„Z	dd„ Z
dd„ Zd)dd„Zd*dd„Zd+dd„Zdd„ Zdd „ Zd!d"„ Zd#d$„ Z‡  ZS ),ÚRendererPgfc                    s(   t ƒ  ¡  |j| _|| _|| _d| _dS )a•  
        Create a new PGF renderer that translates any drawing instruction
        into text commands to be interpreted in a latex pgfpicture environment.

        Attributes
        ----------
        figure : `matplotlib.figure.Figure`
            Matplotlib figure to initialize height, width and dpi from.
        fh : file-like
            File handle for the output of the drawing commands.
        r   N)rt   ru   rh   r?   ÚfigureÚimage_counter)rw   rÊ   r?   ry   r+   r,   ru   |  s
    
zRendererPgf.__init__Nc                 C   sD  t | jdƒ d| j }|  |¡ |  ||¡ | |¡ ¡ \}}	|d | |d | |	d | |	d | f}
t | jd|
 ƒ |  d ||¡ | j| 	¡ dk|d ud� t | jdƒ d	| j }| | ||f}|j
|d
|d�D ]Z\}}|d | |d |  }}t | jdƒ t | jd||f ƒ t | jdƒ t | jdƒ qØt | jdƒ d S )Nú\begin{pgfscope}r0   r   r‹   zQ\pgfsys@defobject{currentmarker}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{ç        ©ÚstrokeÚfillrW   ç†B^!Vl@F)ÚsimplifyÚclipú"\pgfsys@transformshift{%fin}{%fin}z"\pgfsys@useobject{currentmarker}{}ú\end{pgfscope})rA   r?   rh   Ú_print_pgf_clipÚ_print_pgf_path_stylesÚget_extentsÚ
get_pointsÚ_print_pgf_pathÚ_pgf_path_drawÚget_linewidthÚiter_segments)rw   ÚgcZmarker_pathZmarker_transr*   ZtransÚrgbFaceÚfÚblÚtrÚcoordsÚmaxcoordrÓ   ÚpointÚcodeÚxÚyr+   r+   r,   Údraw_markers�  s6    

,ÿÿÿ
ÿzRendererPgf.draw_markersc                 C   sö  t | jdƒ |  |¡ |  ||¡ |  ||||¡ | j| ¡ dk|d ud� t | jdƒ | ¡ �ròt | jdƒ |  ||¡ |  |¡ |  ||||¡ t | jdƒ t | jdƒ t | jdƒ t | jdƒ t | jdƒ tj	 
¡  | j¡}|  d | ¡ |¡ | jdd	� t | jdƒ t | jd
ƒ d| j }| |¡ ¡ \\}}\}	}
|| ||	  }}	|| ||
  }}
t |	| ¡t |
| ¡ }}t | jd||f ƒ t|ƒD ]J}t|ƒD ]}t | jdƒ t | jdƒ �q¦t | jd| ƒ t | jdƒ �qšt | jdƒ d S )NrÌ   rÍ   rÎ   rÕ   ú\pgfusepath{clip}zN\pgfsys@defobject{currentpattern}{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}{z=\pgfpathrectangle{\pgfqpoint{0in}{0in}}{\pgfqpoint{1in}{1in}}T)rÏ   rW   r0   rÔ   z#\pgfsys@useobject{currentpattern}{}z \pgfsys@transformshift{1in}{0in}z"\pgfsys@transformshift{-%din}{0in}z \pgfsys@transformshift{0in}{1in})rA   r?   rÖ   r×   rÚ   rÛ   rÜ   Z	get_hatchr   Z
transformsZAffine2DÚscalerh   Zget_hatch_pathrØ   rÙ   ÚmathÚceilÚrange)rw   rÞ   r*   Ú	transformrß   rë   rà   ZxminZyminZxmaxZymaxZrepxZrepyZiyÚixr+   r+   r,   Ú	draw_pathµ  sV    
ÿ

ÿÿ
ÿ
ÿzRendererPgf.draw_pathc                 C   s    d| j  }| ¡ }|rn| ¡ \}}|| \}}|d | |d | || || f}t| jd| ƒ t| jdƒ | ¡ \}	}
|	d urœ|  ||	|
¡ t| jdƒ d S )Nr0   r   r‹   zA\pgfpathrectangle{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}rê   )rh   Úget_clip_rectanglerÙ   rA   r?   Zget_clip_pathrÚ   )rw   rÞ   rà   ÚbboxÚp1Úp2r¾   r¿   rã   ÚclippathZclippath_transr+   r+   r,   rÖ   ê  s     
$þÿzRendererPgf._print_pgf_clipc                 C   s€  ddddœ}t | j|| ¡  ƒ ddddœ}t | j|| ¡  ƒ |d u}| ¡ r^| ¡  }}n(| ¡ d	 }|r‚t|ƒd	kr‚|d	 nd
}|r²t | jdt|d d	… ƒ ƒ t | jdƒ |rÎ|d
krÎt | jd| ƒ | 	¡ t
 t }| ¡ }	t | jd| ƒ t | jd|	d d	…  ƒ t | jdƒ |d
k�r4t | jd| ƒ | ¡ \}
}|d u �rXt | jdƒ n$t | jdd dd„ |D ƒ¡|
f ƒ d S )Nz\pgfsetbuttcapz\pgfsetroundcapz\pgfsetrectcap)ZbuttÚroundZ
projectingz\pgfsetmiterjoinz\pgfsetroundjoinz\pgfsetbeveljoin)Zmiterr÷   Zbevelé   r0   z(\definecolor{currentfill}{rgb}{%f,%f,%f}z\pgfsetfillcolor{currentfill}ú\pgfsetfillopacity{%f}z\pgfsetlinewidth{%fpt}z*\definecolor{currentstroke}{rgb}{%f,%f,%f}z!\pgfsetstrokecolor{currentstroke}ú\pgfsetstrokeopacity{%f}z\pgfsetdash{}{0pt}z\pgfsetdash{%s}{%fpt}r1   c                 s   s   | ]}d | V  qdS )z{%fpt}Nr+   )rD   Údashr+   r+   r,   rG   .  rH   z5RendererPgf._print_pgf_path_styles.<locals>.<genexpr>)rA   r?   Zget_capstyleZget_joinstyleZget_forced_alphaÚ	get_alphaÚget_rgbr•   ÚtuplerÜ   Úmpl_pt_to_inÚlatex_in_to_ptZ
get_dashesr#   )rw   rÞ   rß   Z	capstylesZ
joinstylesZhas_fillZfillopacityZstrokeopacityZlwZstroke_rgbaZdash_offsetZ	dash_listr+   r+   r,   r×   þ  sZ    þþÿÿ
ÿÿ

ÿÿÿz"RendererPgf._print_pgf_path_stylesc                 C   sh  d| j  }|r| ¡ nd }d| j  }|rv|d u rv| ¡ \}}	t|d | ƒt|d | ƒt|	d |ƒt|	d |ƒf}
n| | ||f}
|j||
d�D �]*\}}|tjkrÒt|ƒ\}}t	| j
d|| || f ƒ q”|tjkrêt	| j
dƒ q”|tjk�r t|ƒ\}}t	| j
d|| || f ƒ q”|tjk�rjt|ƒ\}}}}|| || || || f}t	| j
d	| ƒ q”|tjkr”t|ƒ\}}}}}}|| || || || || || f}t	| j
d
| ƒ q”|�rÐ| ¡ nd }|d u�rd|\}}}|d u�rd|d9 }|d9 }t	| j
dƒ t	| j
dƒ t	| j
d|| d›d|| d›d�ƒ t	| j
dt|ƒ› d�ƒ t	| j
dƒ d S )Nr0   rÑ   r   r‹   )rÓ   z&\pgfpathmoveto{\pgfqpoint{%fin}{%fin}}z\pgfpathclosez&\pgfpathlineto{\pgfqpoint{%fin}{%fin}}zH\pgfpathquadraticcurveto{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}zW\pgfpathcurveto{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}g      à?r2   z\usepgfmodule{decorations}z(\usepgflibrary{decorations.pathmorphing}z/\pgfkeys{/pgf/decoration/.cd, segment length = rà   zin, amplitude = zin}z\pgfmathsetseed{rW   z%\pgfdecoratecurrentpath{random steps})rh   rò   rÙ   ÚmaxÚminrÝ   r   ZMOVETOrþ   rA   r?   Z	CLOSEPOLYZLINETOZCURVE3ZCURVE4Zget_sketch_paramsÚint)rw   rÞ   r*   rï   rß   rà   ró   rä   rô   rõ   rÓ   Úpointsræ   rç   rè   ZcxÚcyZpxÚpyrã   Zc1xZc1yZc2xZc2yZsketch_paramsrë   ÚlengthZ
randomnessr+   r+   r,   rÚ   1  sr    

ÿ
ÿÿ
ÿÿþÿ
(üÿ


ÿþ
zRendererPgf._print_pgf_pathTFc                 C   s:   g }|r|  d¡ |r |  d¡ t| jdd |¡ ƒ d S )NrÏ   rÐ   z\pgfusepath{%s}r³   )r   rA   r?   r#   )rw   rÏ   rÐ   Úactionsr+   r+   r,   rÛ   s  s    

zRendererPgf._pgf_path_drawc                 C   s   dS )NTr+   rš   r+   r+   r,   Úoption_scale_image{  s    zRendererPgf.option_scale_imagec                 C   s   t jd  S )Nzimage.composite_imager.   rš   r+   r+   r,   Úoption_image_nocomposite  s    z$RendererPgf.option_image_nocompositec              
   C   s€  |j d d… \}}|dks"|dkr&d S tj t| jddƒ¡sDtdƒ‚t | jj	¡}d|j
| jf }	t |d d d… ¡ |j|	 ¡ |  jd7  _t| jd	ƒ |  |¡ d
| j }
|d u rèt| jd||
 ||
 f ƒ ||
 ||
  }}n\| ¡  ¡ \}}}}}}t| jd||
 ||
 ||
 ||
 || |
 || |
 f ƒ d }}t|d u ƒ ¡ }t| jdtƒ ||||	f ƒ t| jdƒ d S )Nr2   r   r    r1   zXstreamed pgf-code does not support raster graphics, consider using the pgf-to-pdf optionz%s-img%d.pngéÿÿÿÿr‹   rÌ   r0   rÔ   z/\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}zD\pgftext[left,bottom]{%s[interpolate=%s,width=%fin,height=%fin]{%s}}rÕ   )Úshaperb   r*   ÚexistsÚgetattrr?   rµ   r   r   r    ÚstemrË   r   Z	fromarrayÚsaver!   rA   rÖ   rh   ÚfrozenZ	to_valuesr[   ÚlowerrÈ   )rw   rÞ   rç   rè   Zimrï   r¿   r¾   r*   Z	fname_imgrà   Ztr1Ztr2Ztr3Ztr4Ztr5Ztr6Zinterpr+   r+   r,   Ú
draw_imageƒ  sJ    ÿ 

ÿÿÿÿÿþÿzRendererPgf.draw_imageÚTeXc	           	   
   C   s   |   ||||||||¡ d S rC   )Ú	draw_text)	rw   rÞ   rç   rè   r<   rR   ÚangleÚismathÚmtextr+   r+   r,   Údraw_tex¬  s    zRendererPgf.draw_texc	                 C   sš  t ||ƒ}t| jdƒ | ¡ }	|	dkrFt| jd|	 ƒ t| jd|	 ƒ t| ¡ ƒd d… }
t| jd|
 ƒ t| jdƒ t| jdƒ d	| }| jj}g }|�r4|d
ks²| ¡ dk�r4| 	¡ dk�r4| 
¡ }| ¡  |¡\}}ddddœ}dddddœ}| d|| d›d�d|| d›d�|| ¡  || 	¡  g¡ n$| d|| d›d|| d›d�¡ |d
k�rp| d| ¡ t| jdd |¡|f ƒ t| jdƒ d S )NrÌ   r0   rù   rú   rø   z&\definecolor{textcolor}{rgb}{%f,%f,%f}z\pgfsetstrokecolor{textcolor}z\pgfsetfillcolor{textcolor}z\color{textcolor}r   ÚanchorZcenter_baselineÚleftÚrightr1   )r  r  ÚcenterÚtopÚbottomÚbase)r  r  Zbaseliner  zx=rà   Úinzy=zin, y=zin, left, basez	rotate=%fz\pgftext[%s]{%s}r³   rÕ   )rU   rA   r?   rü   rþ   rý   rÊ   rh   Zget_rotation_modeZget_verticalalignmentZget_unitless_positionZget_transformrï   ÚextendZget_horizontalalignmentr   r#   )rw   rÞ   rç   rè   r<   rR   r  r  r  ÚalphaÚrgbrh   Z	text_argsÚposZhalignZvalignr+   r+   r,   r  °  sJ    
ÿ
þ
ýÿ

ü$
zRendererPgf.draw_textc                 C   s6   t  ¡  ||¡\}}}t| j }|| || || fS rC   )rƒ   rŠ   r±   rÿ   rh   )rw   r<   rR   r  r¾   r¿   Údrà   r+   r+   r,   Úget_text_width_height_descentß  s
    ÿ

z)RendererPgf.get_text_width_height_descentc                 C   s   dS )NFr+   rš   r+   r+   r,   Úflipyê  s    zRendererPgf.flipyc                 C   s    | j  ¡ | j | j  ¡ | j fS rC   )rÊ   Úget_figwidthrh   Úget_figheightrš   r+   r+   r,   Úget_canvas_width_heightî  s    ÿz#RendererPgf.get_canvas_width_heightc                 C   s   |t  | j S rC   )rÿ   rh   )rw   r  r+   r+   r,   Úpoints_to_pixelsó  s    zRendererPgf.points_to_pixels)N)N)N)TF)N)r  N)FN)r   r€   r�   ru   ré   rñ   rÖ   r×   rÚ   rÛ   r	  r
  r  r  r  r'  r(  r+  r,  r‚   r+   r+   ry   r,   rÉ   z  s"    ÿ
&
53
B

)

/rÉ   ú3.4c                   @   s\   e Zd Zeƒ Zeje d¡dd„ ƒƒZe	e d¡dd„ ƒƒZ
e	e d¡ejdd„ ƒƒƒZdS )	ÚTmpDirCleanerr-  c                 C   s   | j S rC   )Ú_remaining_tmpdirsrˆ   r+   r+   r,   Úremaining_tmpdirsü  s    zTmpDirCleaner.remaining_tmpdirsc                 C   s   t j | ¡ d S rC   )r.  r/  Úadd©r¡   r+   r+   r,   r1    s    zTmpDirCleaner.addc                     s0   t jD ]$} d | ¡‰ tj| ‡ fdd„d� qd S )Nzerror deleting tmp directory {}c                     s
   t  ˆ ¡S rC   )rO   Úerror)r|   ©Úerror_messager+   r,   r¯     rH   z9TmpDirCleaner.cleanup_remaining_tmpdirs.<locals>.<lambda>)Úonerror)r.  r/  r¶   ro   Úrmtreer2  r+   r4  r,   Úcleanup_remaining_tmpdirs  s    


þz'TmpDirCleaner.cleanup_remaining_tmpdirsN)r   r€   r�   Úsetr/  r   ZclasspropertyrÄ   r0  rÂ   r1  ÚatexitÚregisterr8  r+   r+   r+   r,   r.  ø  s   r.  c                       sh   e Zd ZddddœZdd„ Zeddœd	d
„ƒZdd„ Zddœdd„Zdd„ Z	dd„ Z
‡ fdd„Z‡  ZS )ÚFigureCanvasPgfzLaTeX PGF picturezLaTeX compiled PGF picturezPortable Network Graphics)ÚpgfÚpdfZpngc                 C   s   dS )Nr>  r+   rš   r+   r+   r,   Úget_default_filetype  s    z$FigureCanvasPgf.get_default_filetypeN©Úbbox_inches_restorec          
      C   s  d}dg}t ƒ  ¡ D ]}| d| ¡ qtƒ  ¡ D ]}| d| ¡ q2| d¡ d |¡}| j ¡ | j ¡  }}| j ¡ }| 	|¡ | 	|¡ | 	d¡ t
|dƒ t
|dƒ t
|dƒ t
|d	||f ƒ t
|d
ƒ t| j|||t| j|ƒ|d�}	| j |	¡ t
|dƒ t
|dƒ t
|dƒ d S )NaÉ  %% Creator: Matplotlib, PGF backend
%%
%% To include the figure in your LaTeX document, write
%%   \input{<filename>.pgf}
%%
%% Make sure the required packages are loaded in your preamble
%%   \usepackage{pgf}
%%
%% Also ensure that all the required font packages are loaded; for instance,
%% the lmodern package is sometimes necessary when using math font.
%%   \usepackage{lmodern}
%%
%% Figures using additional raster images can only be included by \input if
%% they are in the same directory as the main LaTeX file. For loading figures
%% from other directories you can use the `import` package
%%   \usepackage{import}
%%
%% and then include the figures with
%%   \import{<path to file>}{<filename>.pgf}
%%
z)%% Matplotlib used the following preamblez%%   z%%r   z\begingroupz\makeatletterz\begin{pgfpicture}z:\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}z&\pgfusepath{use as bounding box, clip}r@  z\end{pgfpicture}z\makeatotherz	\endgroup)r/   r·   r   r-   r#   rÊ   r)  r*  Zget_dpir>   rA   r   rÉ   Údraw)
rw   r?   rA  Zheader_textZheader_info_preambler@   r¾   r¿   rh   Úrendererr+   r+   r,   Ú_print_pgf_to_fh  s<    








ÿÿ

þ

z FigureCanvasPgf._print_pgf_to_fhc                 K   s^   t j|ddd��:}t  |¡s*t d¡|ƒ}| j|fi |¤Ž W d  ƒ n1 sP0    Y  dS )zy
        Output pgf macros for drawing the figure so it can be included and
        rendered in latex documents.
        r¾   r�   ©rŸ   N)r   Úopen_file_cmZfile_requires_unicodeÚcodecsÚ	getwriterrD  )rw   Úfname_or_fhÚkwargsÚfiler+   r+   r,   Ú	print_pgfT  s    
zFigureCanvasPgf.print_pgf)Úmetadatac                K   sH  | j  ¡ \}}td|pi ƒ}d dd„ | ¡ D ƒ¡}tƒ �ø}t |¡}	| j|	d fi |¤Ž |	d j	d d| d	d
d||f t
ƒ tƒ dddddg¡dd� tjd }
tj|
dddgt|d� |	d  d¡�H}t |d¡�}t ||¡ W d  ƒ n1 sú0    Y  W d  ƒ n1 �s0    Y  W d  ƒ n1 �s:0    Y  dS )z3Use LaTeX to compile a pgf generated figure to pdf.r=  r³   c                 s   s   | ]\}}t ||ƒV  qd S rC   ©r^   ©rD   ÚkÚvr+   r+   r,   rG   c  s   z,FigureCanvasPgf.print_pdf.<locals>.<genexpr>z
figure.pgfz
figure.texr   ú-\PassOptionsToPackage{pdfinfo={%s}}{hyperref}ú\RequirePackage{hyperref}ú\documentclass[12pt]{minimal}ú8\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}ú\usepackage{pgf}r„   z
\centeringz\input{figure.pgf}z\end{document}r�   rE  r   ú-interaction=nonstopmoderœ   ©r    ú
figure.pdfÚrbÚwbN)rÊ   Úget_size_inchesr   r#   Úitemsr   r   r   rL  Ú
write_textr/   r-   r   r   r   Ú_check_and_log_subprocessrO   ÚopenrF  ro   Úcopyfileobj)rw   rI  rM  rJ  r¾   r¿   Z	info_dictÚpdfinfor¡   Útmppathr%   ÚorigÚdestr+   r+   r,   Ú	print_pdf^  sL    
ÿ
ÿôò
ÿþ
ÿzFigureCanvasPgf.print_pdfc           
   
   K   sÐ   t ƒ }tƒ �°}t |¡}|d }|d }| j|fi |¤Ž |||| jjd� | d¡�H}t 	|d¡�}	t
 ||	¡ W d  ƒ n1 s†0    Y  W d  ƒ n1 s¤0    Y  W d  ƒ n1 sÂ0    Y  dS )z?Use LaTeX to compile a pgf figure to pdf and convert it to png.rY  z
figure.png)rh   rZ  r[  N)rr   r   r   r   rf  rÊ   rh   r`  r   rF  ro   ra  )
rw   rI  rJ  Ú	converterr¡   rc  Zpdf_pathZpng_pathrd  re  r+   r+   r,   Ú	print_png�  s    

ÿzFigureCanvasPgf.print_pngc                 C   s   t | jd ƒS rC   )rÉ   rÊ   rš   r+   r+   r,   Úget_rendererŽ  s    zFigureCanvasPgf.get_rendererc                    s   | j  ¡  tƒ  ¡ S rC   )rÊ   Zdraw_without_renderingrt   rB  rš   ry   r+   r,   rB  ‘  s    
zFigureCanvasPgf.draw)r   r€   r�   Ú	filetypesr?  r	   rD  rL  rf  rh  ri  rB  r‚   r+   r+   ry   r,   r<    s   þ:
#r<  c                   @   s   e Zd ZeZdS )Ú_BackendPgfN)r   r€   r�   r<  ZFigureCanvasr+   r+   r+   r,   rk  ™  s   rk  c                   @   s^   e Zd ZdZdZdddœdd„Zdd	„ Zd
d„ Zdd„ Zdd„ Z	dd„ Z
ddd„Zdd„ ZdS )ÚPdfPagesa�  
    A multi-page PDF file using the pgf backend

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> # Initialize:
    >>> with PdfPages('foo.pdf') as pdf:
    ...     # As many times as you like, create a figure fig and save it:
    ...     fig = plt.figure()
    ...     pdf.savefig(fig)
    ...     # When no figure is specified the current figure is saved
    ...     pdf.savefig()
    )Ú_output_nameÚ
keep_emptyÚ
_n_figuresÚ_fileÚ
_info_dictÚ	_metadataTN)rn  rM  c                C   s:   || _ d| _|| _|pi  ¡ | _td| jƒ| _tƒ | _dS )a<  
        Create a new PdfPages object.

        Parameters
        ----------
        filename : str or path-like
            Plots using `PdfPages.savefig` will be written to a file at this
            location. Any older file with the same name is overwritten.

        keep_empty : bool, default: True
            If set to False, then empty pdf files will be deleted automatically
            when closed.

        metadata : dict, optional
            Information dictionary object (see PDF reference section 10.2.1
            'Document Information Dictionary'), e.g.:
            ``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.

            The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
            'Creator', 'Producer', 'CreationDate', 'ModDate', and
            'Trapped'. Values have been predefined for 'Creator', 'Producer'
            and 'CreationDate'. They can be removed by setting them to `None`.

            Note that some versions of LaTeX engines may ignore the 'Producer'
            key and set it to themselves.
        r   r=  N)	rm  ro  rn  Úcopyrr  r   rq  r   rp  )rw   Úfilenamern  rM  r+   r+   r,   ru   ¶  s    zPdfPages.__init__c                 C   s\   d  dd„ | j ¡ D ƒ¡}d  d| ddd||f tƒ tƒ d	d
dg	¡}| j | d¡¡ d S )Nr³   c                 s   s   | ]\}}t ||ƒV  qd S rC   rN  rO  r+   r+   r,   rG   Ù  s   z)PdfPages._write_header.<locals>.<genexpr>r   rR  rS  rT  rU  rV  z\setlength{\parindent}{0pt}z\begin{document}%r�   )r#   rq  r]  r/   r-   rp  r>   Úencode)rw   Zwidth_inchesZheight_inchesrb  r…   r+   r+   r,   Ú_write_headerØ  s"    
ÿÿözPdfPages._write_headerc                 C   s   | S rC   r+   rš   r+   r+   r,   Ú	__enter__é  s    zPdfPages.__enter__c                 C   s   |   ¡  d S rC   )Úclose)rw   Úexc_typeÚexc_valÚexc_tbr+   r+   r,   Ú__exit__ì  s    zPdfPages.__exit__c                 C   sD   | j  d¡ | jdkr |  ¡  n| jr6t| jdƒ ¡  | j  ¡  dS )zƒ
        Finalize this object, running LaTeX in a temporary directory
        and moving the final pdf file to *filename*.
        s   \end{document}\nr   r[  N)rp  r>   ro  Ú
_run_latexrn  r`  rm  rx  rš   r+   r+   r,   rx  ï  s    

zPdfPages.closec                 C   s|   t jd }tƒ �X}t |d¡}| | j ¡ ¡ tj	|dd|gt
|d� t | d¡| j¡ W d   ƒ n1 sn0    Y  d S )Nr   zpdf_pages.texrW  rœ   rX  z.pdf)r   r   r   r   r   Úwrite_bytesrp  Úgetvaluer   r_  rO   ro   ÚmoveÚwith_suffixrm  )rw   r%   r¡   Z
tex_sourcer+   r+   r,   r}  û  s    
ÿýzPdfPages._run_latexc                 K   sÊ   t |tƒsD|du rt ¡ }n
t |¡}|du r<td |¡ƒ‚|jj}zx|j}t	|ƒ|_| 
¡ \}}| jdkrz|  ||¡ n| j d||f ¡ |j| jfddi|¤Ž |  jd7  _W ||_n||_0 dS )a5  
        Save a `.Figure` to this file as a new page.

        Any other keyword arguments are passed to `~.Figure.savefig`.

        Parameters
        ----------
        figure : `.Figure` or int, default: the active figure
            The figure, or index of the figure, that is saved to the file.
        NzNo figure {}r   s„   \newpage\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=%ain\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%ain%%
r¶   r=  r‹   )rX   r   r   Z
get_activeZget_fig_managerrµ   r¶   ZcanvasrÊ   r<  r\  ro  rv  rp  r>   Úsavefig)rw   rÊ   rJ  ÚmanagerZorig_canvasr»   r¼   r+   r+   r,   r‚    s*    




ûÿ	zPdfPages.savefigc                 C   s   | j S )z=Return the current number of pages in the multipage pdf file.)ro  rš   r+   r+   r,   Úget_pagecount3  s    zPdfPages.get_pagecount)N)r   r€   r�   rÁ   Ú	__slots__ru   rv  rw  r|  rx  r}  r‚  r„  r+   r+   r+   r,   rl  ž  s   	"
-rl  )Lr:  rG  rY   r«   Úior   Úloggingrì   rb   r   Úrero   rd   Útempfiler   r¢   ZPILr   Z
matplotlibr   r   r   r   r   Zmatplotlib.backend_basesr   r	   r
   r   r   r   Z!matplotlib.backends.backend_mixedr   Zmatplotlib.backends.backend_pdfr   r   Zmatplotlib.pathr   Zmatplotlib.figurer   Zmatplotlib._pylab_helpersr   Ú	getLoggerr   rO   r-   r/   Zlatex_pt_to_inr   rÿ   Zmpl_in_to_ptZ	NO_ESCAPEÚcompiler5   ÚpartialÚsubr8   r3   r=   rA   rU   r^   rr   r¸   rs   rƒ   r¬   rÈ   rÉ   rÄ   r.  r<  ZFigureManagerPgfZexportrk  rl  r+   r+   r+   r,   Ú<module>   sv    
	ýþ! 
    