a
    s=icX                     @   s^  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 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)ej*G dd dZ+e,ddd Z-e,ddd Z.dd Z/dZ0de0 Z1dZ2de2 Z3dZ4e	5e4d j6Z7e8e	5e4d j9dZ:e8e	5e4d j9dZ;e,ddd Z<d d! Z=e,dd"d# Z>d$d% Z?d&d' Z@d(d) ZAd*d+ ZBG d,d- d-eCZDG d.d/ d/ZEeFd0d1d2 ZGG d3d4 d4eZHG d5d6 d6eZIeZJejKG d7d8 d8eZLG d9d: d:ZMdS );    N)BytesIO)TemporaryDirectory)Image)_apicbookfont_manager)_BackendFigureCanvasBaseFigureManagerBaseRendererBase)MixedModeRenderer)_create_pdf_info_dict_datetime_to_pdf)Path)Figure)Gcfc                   @   s@   e Zd Zejdddedd Zejdddedd ZdS )__getattr__3.6 )obj_typec                 C   s   t S N)
_NO_ESCAPEself r   p/home/droni/.local/share/virtualenvs/DPS-5Je3_V2c/lib/python3.9/site-packages/matplotlib/backends/backend_pgf.py<lambda>(       z__getattr__.<lambda>c                 C   s   t jS r   )_split_math__self__r   r   r   r   r   *   r   N)__name__
__module____qualname__r   
deprecatedpropertyZ	NO_ESCAPEZ
re_mathsepr   r   r   r   r   %   s   

r   r   c                   C   s8   t ddi t W  d   S 1 s*0    Y  dS )z Build fontspec preamble from rc.pgf.preambler   N)mplZ
rc_context_get_preambler   r   r   r   get_fontspec-   s    r(   c                   C   s
   t jd S )zGet LaTeX preamble from rc.r%   r&   rcParamsr   r   r   r   get_preamble4   s    r+   c                  C   s   t jd g} t jd dkr~| d t jd r~g d}g d}t||D ]4\}}tt|}| d||j|j	
 f  qH| t jjd	d
d d| S )z=Prepare a LaTeX preamble based on the rcParams configuration.r%   pgf.texsystempdflatexz\usepackage{fontspec}zpgf.rcfonts)serifzsans\-serif	monospace)ZsetmainfontZsetsansfontZsetmonofontz\%s{%s}[Path=\detokenize{%s/}]Z
underscorestrings)option
)r&   r*   appendzippathlibr   fmZfindfontnameparentas_posixZ
texmanagerZ_usepackage_if_not_loadedjoin)preamblefamiliescommandsfamilycommandpathr   r   r   r'   :   s    



r'   gRhV?      ?gqq?z(?<!\\)(?:\\\\)*z\$z(?=[%^])z\\z(\\mathdefault)r   c                 C   s   t | S r   )_tex_escape)textr   r   r   common_texification_   s    rD   c                 C   sZ   t | } | dd} t| }t|D ]*\}}|d s>t|}nd| }|||< q$d|S )aV  
    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\)r   )_replace_mathdefaultreplacer   	enumerate_replace_escapetextr:   )rC   partsisr   r   r   rB   d   s    

rB   c                 C   s
   t | |S r   )_writelnfhliner   r   r   writeln   s    rQ   c                 C   s   |  | |  d d S )Nz%
)writerN   r   r   r   rM      s    
rM   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 r   )r7   ).0Zfontr>   r   r   	<genexpr>   r   z*_escape_and_apply_props.<locals>.<genexpr>r,   r-   z\setmainfont{%s}\rmfamilyzIgnoring unknown font: %sz\fontsize{%f}{%f}g333333?r   z\itshapez\slshape)normalitalicZoblique)ZsemiboldZdemiboldZdemiboldZheavyz
extra boldblackz	\bfseriesz\selectfont )Z
get_familyr3   anyr6   ZfontManagerZttflistr&   r*   _logwarningZget_size_in_points	get_styleZ
get_weightr:   rB   )rL   propr=   r<   sizestylesZ
boldstylesr   rU   r   _escape_and_apply_props   s*    

rc   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   r7   decodestr)keyvaluer   r   r   _metadata_to_str   s    
rl   c                      sh   zt d W n t jy"   Y n
0 dd S zt d W n t jyN   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   s0   t jdddddd| | tj|d gt jdS )	Nrm   z-singlefilez-transpz-pngz-rz%dr   stderr)
subprocesscheck_outputosr@   splitextSTDOUTZpdffileZpngfiledpir   r   r   r      s
   z+make_pdf_to_png_converter.<locals>.<lambda>gsc                    s6   t j jddddddddd	d
d| d| | gt jdS )Nz-dQUIETz-dSAFERz-dBATCHz	-dNOPAUSEz
-dNOPROMPTz-dUseCIEColorz-dTextAlphaBits=4z-dGraphicsAlphaBits=4z-dDOINTERPOLATEz-sDEVICE=pngalphaz-sOutputFile=%sz-r%drn   )rp   rq   
executablert   ru   Zgs_infor   r   r      s   
z&No suitable pdf to png renderer found.N)r&   Z_get_executable_infoZExecutableNotFoundErrorRuntimeErrorr   r   ry   r   make_pdf_to_png_converter   s    r{   c                       s&   e Zd Zd fdd	Zdd Z  ZS )
LatexErrorr   c                    s   t  | || _d S r   )super__init__latex_output)r   messager   	__class__r   r   r~      s    zLatexError.__init__c                 C   s    | j \}| jr|d| j 7 }|S Nr2   )argsr   r   rL   r   r   r   __str__   s    zLatexError.__str__)r   )r    r!   r"   r~   r   __classcell__r   r   r   r   r|      s   r|   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ededd Zededd Zdd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   s(   ddt jd  dt ddg} d| S )Nz\documentclass{article}z% !TeX program = r,   z\usepackage{graphicx}\begin{document}z!\typeout{pgf_backend_query_start}r2   )r&   r*   r'   r:   )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 r   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stdinrR   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 haltedr   )	listr   stdoutreadr3   lenkillr|   r:   )r   rL   charscr   r   r   _expect	  s    

zLatexManager._expectc                 C   s
   |  dS )Nz
*)r   r   r   r   r   _expect_prompt  s    zLatexManager._expect_promptc              
   C   s   t  | _| jj| _t| | jj| _z| jdd W nv t	yp } z$t
| jjd d|W Y d }~nDd }~0  ty } z$t
d| jjd |W Y d }~n
d }~0 0 | jd\}}| jjdkrtd|   |d | _t | j| _d S )NFexpect_replyr   z_ not found.  Install it or change rcParams['pgf.texsystem'] to an available TeX implementation.zError starting process z
\makeatletter\@@end
zaLaTeX errored (probably missing font or error in preamble) while processing the following input:
)r   Z_tmpdirr7   tmpdirweakreffinalizecleanupZ_finalize_tmpdirr   FileNotFoundErrorrz   r   r   OSErrorcommunicate
returncoder|   r   	functools	lru_cache_get_box_metrics)r   errr   ro   r   r   r   r~     s6    
zLatexManager.__init__z3.5c                 C   s   i S r   r   r   r   r   r   r   7  r   zLatexManager.<lambda>r   c                 C   s
   t jd S )Nr,   r)   r   r   r   r   r   9  r   c                 C   s   |   S r   )r   r   r   r   r   r   ;  r   Tr   c                C   sh   t jtjd dgt jt jd| jd| _dd }t| || j| _	| 
|   |rd| d |   d S )Nr,   -halt-on-errorutf-8)r   r   encodingcwdc                 S   s   |    |   d S r   )r   r   )r   r   r   r   finalize_latexG  s    z9LatexManager._setup_latex_process.<locals>.finalize_latexz*pgf_backend_query_start)rp   Popenr&   r*   PIPEr   r   r   r   Z_finalize_latexr   r   r   r   )r   r   r   r   r   r   r   =  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   rc   )r   rC   r`   r   r   r   get_width_height_descentS  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 {}
LaTeX Output:
{}N,)
r   r   r|   
ValueErrorformatr   
splitlinessplit	Exceptionfloat)
r   texanswerr   widthheightoffsetwhor   r   r   r   Z  s*    4zLatexManager._get_box_metricsN)r    r!   r"   __doc__staticmethodr   classmethodr   r   r   r   r   r   r   r~   r   r#   r$   Z	str_cache
texcommandr   r   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_pathr9   r   r|   r   cache_clear)manr   r   r   _get_image_inclusion_commandv  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)r}   r~   rv   rO   figureimage_counter)r   r   rO   r   r   r   r~     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 qt | jd d S )N\begin{pgfscope}rA   r   r   zQ\pgfsys@defobject{currentmarker}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{        strokefillre   B^!Vl@F)simplifyclip"\pgfsys@transformshift{%fin}{%fin}z"\pgfsys@useobject{currentmarker}{}\end{pgfscope})rM   rO   rv   _print_pgf_clip_print_pgf_path_stylesget_extents
get_points_print_pgf_path_pgf_path_drawget_linewidthiter_segments)r   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 | rt | 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 qt | jd|  t | jd qt | 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   re   rA   r   z#\pgfsys@useobject{currentpattern}{}z \pgfsys@transformshift{1in}{0in}z"\pgfsys@transformshift{-%din}{0in}z \pgfsys@transformshift{0in}{1in})rM   rO   r   r   r   r   r   Z	get_hatchr&   Z
transformsZAffine2Dscalerv   Zget_hatch_pathr   r   mathceilrange)r   r   r@   	transformr   r   r   ZxminZyminZxmaxZymaxZrepxZrepyZiyZ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 )NrA   r   r   zA\pgfpathrectangle{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}r   )rv   get_clip_rectangler   rM   rO   Zget_clip_pathr   )r   r   r   bboxp1p2r   r   r   Z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	 }|rt|d	kr|d	 nd
}|rt | jdt|d d	   t | jd |r|d
krt | 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   rA   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}r   c                 s   s   | ]}d | V  qdS )z{%fpt}Nr   )rT   dashr   r   r   rV   :  r   z5RendererPgf._print_pgf_path_styles.<locals>.<genexpr>)rM   rO   Zget_capstyleZget_joinstyleZget_forced_alpha	get_alphaget_rgbr   tupler   mpl_pt_to_inlatex_in_to_ptZ
get_dashesr:   )r   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rt|\}}t	| j
d|| || f  q|tjkrt	| 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rt|\}}}}}}|| || || || || || 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 )NrA   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      ?rE   z\usepgfmodule{decorations}z(\usepgflibrary{decorations.pathmorphing}z/\pgfkeys{/pgf/decoration/.cd, segment length = r   zin, amplitude = zin}z\pgfmathsetseed{re   z%\pgfdecoratecurrentpath{random steps})rv   r   r   maxminr   r   ZMOVETOr   rM   rO   Z	CLOSEPOLYZLINETOZCURVE3ZCURVE4Zget_sketch_paramsint)r   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   =  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   )r3   rM   rO   r:   )r   r   r   actionsr   r   r   r     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 rt| jd||
 ||
 f  ||
 ||
  }}n\|  \}}}}}}t| jd||
 ||
 ||
 ||
 || |
 || |
 f  d }}t|d u  }t| jdt ||||	f  t| jd d S )NrE   r   r7   r   zXstreamed pgf-code does not support raster graphics, consider using the pgf-to-pdf optionz%s-img%d.pngr   r   rA   r   z/\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}zD\pgftext[left,bottom]{%s[interpolate=%s,width=%fin,height=%fin]{%s}}r   )shaperr   r@   existsgetattrrO   r   r5   r   r7   stemr   r   Z	fromarraysaver8   rM   r   rv   frozenZ	to_valuesri   lowerr   )r   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 r   )	draw_text)	r   r   r   r   rL   r`   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   rA   r   r   r   z&\definecolor{textcolor}{rgb}{%f,%f,%f}z\pgfsetstrokecolor{textcolor}z\pgfsetfillcolor{textcolor}z\color{textcolor}r   anchorZcenter_baselineleftrightr   )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   )rc   rM   rO   r   r   r   r   rv   Zget_rotation_modeZget_verticalalignmentZget_unitless_positionZget_transformr   extendZget_horizontalalignmentr3   r:   )r   r   r   r   rL   r`   r  r  r  alphargbrv   Z	text_argsposZhalignZvalignr   r   r   r    sJ    




$
zRendererPgf.draw_textc                 C   s6   t  ||\}}}t| j }|| || || fS r   )r   r   r   r  rv   )r   rL   r`   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 r   )r   get_figwidthrv   get_figheightr   r   r   r   get_canvas_width_height  s    z#RendererPgf.get_canvas_width_heightc                 C   s   |t  | j S r   )r  rv   )r   r  r   r   r   points_to_pixels  s    zRendererPgf.points_to_pixels)N)N)N)TF)N)r  N)FN)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     s"    
&
53
B

)

/r   c                       sd   e Zd ZddddZdd Z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 )Nr1  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|d d|}| j | 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%%r2   z\begingroupz\makeatletterz\begin{pgfpicture}z:\pgfpathrectangle{\pgfpointorigin}{\pgfqpoint{%fin}{%fin}}z&\pgfusepath{use as bounding box, clip}r3  z\end{pgfpicture}z\makeatotherz	\endgroup)r'   r   r3   r:   r   r+  r,  rv   rR   rM   r   r   draw)
r   rO   r4  Zheader_textZheader_info_preamblerP   r   r   rv   rendererr   r   r   _print_pgf_to_fh  s8    











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	getwriterr7  )r   fname_or_fhkwargsfiler   r   r   	print_pgfD  s    
zFigureCanvasPgf.print_pgf)metadatac                K   sB  | j  \}}td|pi }ddd | D }t }t|}	| j|	d fi | |	d j	ddd	| d
||f dt
 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 s0    Y  W d   n1 s0    Y  W d   n1 s40    Y  dS )z3Use LaTeX to compile a pgf generated figure to pdf.r0  r   c                 s   s   | ]\}}t ||V  qd S r   rl   rT   kvr   r   r   rV   S  s   z,FigureCanvasPgf.print_pdf.<locals>.<genexpr>z
figure.pgfz
figure.texr2   \documentclass[12pt]{article}#\usepackage[pdfinfo={%s}]{hyperref}8\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}\usepackage{pgf}r   z
\centeringz\input{figure.pgf}z\end{document}r   r8  r,   -interaction=nonstopmoder   r   
figure.pdfrbwbN)r   get_size_inchesr   r:   itemsr   r5   r   r?  
write_textr'   r&   r*   r   _check_and_log_subprocessr]   openr9  shutilcopyfileobj)r   r<  r@  r=  r   r   	info_dictpdfinfor   tmppathr   origdestr   r   r   	print_pdfN  sH    



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 s0    Y  W d   n1 s0    Y  W d   n1 s0    Y  dS )z?Use LaTeX to compile a pgf figure to pdf and convert it to png.rK  z
figure.png)rv   rL  rM  N)r{   r   r5   r   rZ  r   rv   rR  r   r9  rS  rT  )
r   r<  r=  	converterr   rW  Zpdf_pathZpng_pathrX  rY  r   r   r   	print_pngo  s    

zFigureCanvasPgf.print_pngc                 C   s   t | jd S r   )r   r   r   r   r   r   get_renderer|  s    zFigureCanvasPgf.get_rendererc                    s   | j   t  S r   )r   Zdraw_without_renderingr}   r5  r   r   r   r   r5    s    
zFigureCanvasPgf.draw)r    r!   r"   	filetypesr2  r7  r?  rZ  r\  r]  r5  r   r   r   r   r   r/    s   8
!r/  c                   @   s   e Zd ZeZdS )_BackendPgfN)r    r!   r"   r/  ZFigureCanvasr   r   r   r   r_    s   r_  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)rb  r@  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   r0  N)	ra  rc  rb  copyrf  r   re  r   rd  )r   filenamerb  r@  r   r   r   r~     s    zPdfPages.__init__c              	   C   sV   d dd | j D }d dd| d||f dt d	d
g}| j|d d S )Nr   c                 s   s   | ]\}}t ||V  qd S r   rA  rB  r   r   r   rV     s   z)PdfPages._write_header.<locals>.<genexpr>r2   rE  rF  rG  rH  z\setlength{\parindent}{0pt}z\begin{document}%r   )r:   re  rO  r'   rd  rR   encode)r   Zwidth_inchesZheight_inchesrV  r   r   r   r   _write_header  s    

zPdfPages._write_headerc                 C   s   | S r   r   r   r   r   r   	__enter__  s    zPdfPages.__enter__c                 C   s   |    d S r   )close)r   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   rM  N)rd  rR   rc  
_run_latexrb  rR  ra  rl  r   r   r   r   rl    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.texrI  r   rJ  z.pdf)r&   r*   r   r5   r   write_bytesrd  getvaluer   rQ  r]   rS  movewith_suffixra  )r   r   r   Z
tex_sourcer   r   r   rq    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   r0  r   )rf   r   r   Z
get_activeZget_fig_managerr   r   Zcanvasr   r/  rN  rc  rj  rd  rR   savefig)r   r   r=  managerZorig_canvasr   r   r   r   r   rv    s*    




	zPdfPages.savefigc                 C   s   | j S )z=Return the current number of pages in the multipage pdf file.)rc  r   r   r   r   get_pagecount  s    zPdfPages.get_pagecount)N)r    r!   r"   r   	__slots__r~   rj  rk  rp  rl  rq  rv  rx  r   r   r   r   r`    s   	"
-r`  )Nr:  rg   r   ior   loggingr   rr   r5   rerS  rp   tempfiler   r   ZPILr   Z
matplotlibr&   r   r   r   r6   Zmatplotlib.backend_basesr   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    r]   Zcaching_module_getattrr   r#   r(   r+   r'   Zlatex_pt_to_inr  r  Zmpl_in_to_ptr   compiler   r   partialsubrI   rF   rD   rB   rQ   rM   rc   rl   r{   r   r|   r   r   r   r   r/  ZFigureManagerPgfexportr_  r`  r   r   r   r   <module>   s   




! 
    