
    P/Ph                     N   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mZ d dlZd dlmZ d dlZd dl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$ d dl%m&Z&  ej'        e(          Z)dZ*d Z+dZ,de,z  Z-dZ.de.z  Z/d Z0d Z1d Z2d Z3d Z4 G d de5          Z6 G d d          Z7 ej8        d          d             Z9 G d de          Z: G d d e          Z;eZ<ej=         G d! d"e                      Z> G d# d$          Z?dS )%    N)BytesIO)TemporaryDirectory)Image)cbookfont_manager)_BackendFigureCanvasBaseFigureManagerBaseRendererBase)MixedModeRenderer)_create_pdf_info_dict_datetime_to_pdf)Path)Figure)FontProperties)Gcfz\documentclass{article}c                     t          t          j        d                                                   } d                    dddd| z  dd	| d
| z  fz  ddt          j        d         g	t          j        d         r/ddgd t          g dd dD                       D             z   dgz   ng t          j                            dd                    S )z=Prepare a LaTeX preamble based on the rcParams configuration.z	font.size)size
z\def\mathdefault#1{#1}z4\everymath=\expandafter{\the\everymath\displaystyle}z\IfFileExists{scrextend.sty}{z'  \usepackage[fontsize=%fpt]{scrextend}z}{z:  \renewcommand{\normalsize}{\fontsize{%f}{%f}\selectfont}333333?z  \normalsize}zpgf.preamblepgf.rcfontsz1\ifdefined\pdftexversion\else  % non-pdftex case.z  \usepackage{fontspec}c           	      d    g | ]-\  }}d |d|j         d|j                                        d.S )z  \{z}[Path=\detokenize{z/}])nameparentas_posix).0commandpaths      _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/matplotlib/backends/backend_pgf.py
<listcomp>z!_get_preamble.<locals>.<listcomp>B   sW     
 
 
  ww			4;#7#7#9#9#9#9;
 
 
    )setmainfontsetsansfontsetmonofontc                 Z    g | ](}t          j        t          j        |                    )S  )pathlibr   fmfindfont)r   familys     r!   r"   z!_get_preamble.<locals>.<listcomp>G   sB     G G G bk&1122 G G Gr#   )serifzsans\-serif	monospacez\fi
underscorestrings)option)r   mplrcParamsget_size_in_pointsjoinzip
texmanager_usepackage_if_not_loaded)font_size_pts    r!   _get_preambler:   '   s8   !\+&    99 	"?
 	)2\AE|+
,	-^$%!< ]3<@&

 
 "%===G GEG G G" "
 
 

 H  :<=!@ 	00i0PPA! ! ! !r#   gRhV?      ?gqq?c                 .    |                      dd          S )zh
    Do some necessary and/or useful substitutions for texts to be included in
    LaTeX documents.
    u   −z\ensuremath{-})replace)texts    r!   _tex_escaper?   X   s    
 <<(*;<<<r#   c                 Z    |                      |           |                      d           d S )Nz%
)write)fhlines     r!   _writelnrD   `   s&     HHTNNNHHUOOOOOr#   c                 H   g }ddddd}|                                 d         |v r|                    |                    nt          j        d         s|                    d           n^t	          fdt
          j        j        D                       r|                    d	z             nt          	                    d
           |
                                }|                    d||dz  fz             dddd}|                    ||                                                    g d}|                                |v r|                    d           |                    d           dd                    |          z   dz   dz   t          |           z   dz   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   r   z\fontfamily{\familydefault}c              3   .   K   | ]}|j         k    V  d S N)r   )r   fontr,   s     r!   	<genexpr>z*_escape_and_apply_props.<locals>.<genexpr>u   s*      DDTTY& DDDDDDr#   z9\ifdefined\pdftexversion\else\setmainfont{%s}\rmfamily\fizIgnoring unknown font: %sz\fontsize{%f}{%f}r    z\itshapez\slshape)normalitalicoblique)semibolddemibolddemiboldheavyz
extra boldblackz	\bfseriesz\selectfontr   z1\catcode`\^=\active\def^{\ifmmode\sp\else\^{}\fi}z\catcode`\%=\active\def%{\%}r   )
get_familyappendr2   r3   anyr*   fontManagerttflist_logwarningr4   	get_style
get_weightr5   r?   )spropcommandsfamiliesr   styles
boldstylesr,   s          @r!   _escape_and_apply_propsrd   g   s   
 H%|*G GH__q!F())))\-( :67777	DDDDR^-CDDD	D	D :H6Q	S 	S 	S 	S 	0&999""$$DOO(D$*+==>>>{{KKFOOF4>>++,---) ) )JJ&&%%%OON###
''(

	
>	? *	* a..	 	
r#   c                     t          |t          j                  rt          |          }n0| dk    r|j                            d          }nt          |          }|  d| dS )z;Convert metadata key/value to a form that hyperref accepts.Trappedasciiz={r   )
isinstancedatetimer   r   decodestr)keyvalues     r!   _metadata_to_strrn      sj    %*++  ''				
!!'**E

er#   c                       	 t          j        d           d S # t           j        $ r Y nw xY w	 t          j        d            fdS # t           j        $ r Y nw xY wt          d          )z9Return a function that converts a pdf file to a png file.
pdftocairoc                     t          j        dddddd|z  | t          j                            |          d         gt           j                  S )	Nrp   z-singlefilez-transpz-pngz-rz%dr   stderr)
subprocesscheck_outputosr    splitextSTDOUT)pdffilepngfiledpis      r!   <lambda>z+make_pdf_to_png_converter.<locals>.<lambda>   sN    Z-D=)VT4#:bg&&w//24$.& .& .& r#   gsc                 v    t          j        j        ddddddddd	d
d|z  d|z  | gt           j                  S )Nz-dQUIETz-dSAFERz-dBATCHz	-dNOPAUSEz
-dNOPROMPTz-dUseCIEColorz-dTextAlphaBits=4z-dGraphicsAlphaBits=4z-dDOINTERPOLATEz-sDEVICE=pngalphaz-sOutputFile=%sz-r%drr   )rt   ru   
executablerx   )ry   rz   r{   gs_infos      r!   r|   z+make_pdf_to_png_converter.<locals>.<lambda>   sW    Z-D	9k<1$&7 "3g"=c\7$ $.& .& .& r#   z&No suitable pdf to png renderer found.)r2   _get_executable_infoExecutableNotFoundErrorRuntimeError)r   s   @r!   make_pdf_to_png_converterr      s    & ...& & 	& &   &*400& & & & 	& &    ?
@
@@s    ,,A	 	AAc                   &     e Zd Zd fd	Zd Z xZS )
LatexErrorrK   c                 X    t                                          |           || _        d S rH   )super__init__latex_output)selfmessager   	__class__s      r!   r   zLatexError.__init__   s)    !!!(r#   c                 @    | j         \  }| j        r|d| j        z   z  }|S Nr   )argsr   r   r^   s     r!   __str__zLatexError.__str__   s-    Y 	*)))Ar#   )rK   )__name__
__module____qualname__r   r   __classcell__r   s   @r!   r   r      sL        ) ) ) ) ) )      r#   r   c                       e Zd ZdZed             Zed             Ze ej	        d          d                         Z
d Zd Zd Zd	 Zd
ddZd Z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                      t           dt          j        d          dt                      ddg} d                    |           S )Nz% !TeX program = pgf.texsystemz\usepackage{graphicx}\begin{document}z!\typeout{pgf_backend_query_start}r   )_DOCUMENTCLASSr2   r3   r:   r5   )latex_headers    r!   _build_latex_headerz LatexManager._build_latex_header   sG      Ao!>@@$OO0

 yy&&&r#   c                 P    |                      |                                           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   )clss    r!   _get_cached_or_newzLatexManager._get_cached_or_new   s$     **3+B+B+D+DEEEr#      c                      |             S rH   r(   )r   headers     r!   r   z$LatexManager._get_cached_or_new_impl   s     suur#   c                     | j         |                                  | j         j                            |           | j         j                            d           | j         j                                         d S r   )latex_setup_latex_processstdinrA   flushr   s     r!   _stdin_writelnzLatexManager._stdin_writeln   sk    :%%'''
q!!!
t$$$
     r#   c                 ~   t          |          }g }	 | j        j                            d          }|                    |           |t          |           d          |k    rnF|sC| j                                         d | _        t          dd                    |                    d                    |          S )NTr   zLaTeX process haltedrK   )	listr   stdoutreadrV   lenkillr   r5   )r   r^   charscs       r!   _expectzLatexManager._expect   s    GG	I
!&&q))ALLOOOc!ffWXX!## I
!!!!
 !7HHH	I wwu~~r#   c                 ,    |                      d          S )Nz
*)r   r   s    r!   _expect_promptzLatexManager._expect_prompt   s    ||E"""r#   c                    t                      | _        | j        j        | _        t	          j        | | j        j                  | _        |                     d           | j	        
                    d          \  }}| j	        j        dk    r%t          d|                                  |          d | _	        t          j        | j                  | _        d S )NFexpect_replyz
\makeatletter\@@end
r   zaLaTeX errored (probably missing font or error in preamble) while processing the following input:
)r   _tmpdirr   tmpdirweakreffinalizecleanup_finalize_tmpdirr   r   communicate
returncoder   r   	functools	lru_cache_get_box_metrics)r   r   rs   s      r!   r   zLatexManager.__init__  s    )++l' ' 0t|7K L L 	!!u!555//0KLL: A%%0++--0 0 	  
 
 ) 3D4I J Jr#   Tr   c                T   	 t          j        t          j        d         dgt           j        t           j        d| j                  | _        ne# t          $ r(}t          t          j        d         d          |d }~wt          $ r(}t          dt          j        d                   |d }~ww xY wd }t          j        | || j                  | _        |                     |                                            |r+|                     d           |                                  d S d S )	Nr   -halt-on-errorutf-8)r   r   encodingcwdz] not found; install it or change rcParams['pgf.texsystem'] to an available TeX implementationzError starting c                     |                                   	 |                                  d S # t          $ r |                                  Y d S w xY wrH   )r   r   r   wait)r   s    r!   finalize_latexz9LatexManager._setup_latex_process.<locals>.finalize_latex(  sZ    JJLLL!!#####   

s   , AAz*pgf_backend_query_start)rt   Popenr2   r3   PIPEr   r   FileNotFoundErrorr   OSErrorr   r   _finalize_latexr   r   r   r   )r   r   errr   s       r!   r   z!LatexManager._setup_latex_process  sk   	N#)o.0@A ojo dk3 3 3DJJ ! 	 	 	<0 P P P    	N 	N 	NC#,"?CCE EJMN	N	 	 	  '/.$* .  . 	D4466777 	"LL3444!!!!!	" 	"s$   A	A 
B.#A99B.#B))B.c                 H    |                      t          ||                    S )z
        Get the width, total height, and descent (in TeX points) for a text
        typeset by the current LaTeX environment.
        )r   rd   )r   r>   r_   s      r!   get_width_height_descentz%LatexManager.get_width_height_descent7  s#    
 $$%<T4%H%HIIIr#   c                 @   |                      d|z             	 |                                 }n;# t          $ r.}t          d                    ||j                            |d}~ww xY w	 |                                d                             d          \  }}}n6# t          $ r)}t          d                    ||                    |d}~ww xY wt          |dd                   t          |dd                   t          |dd                   }	}}|||	z   |	fS )z
        Get the width, total height and descent (in TeX points) for a TeX
        command's output in the current LaTeX environment.
        zW{\catcode`\^=\active\catcode`\%%=\active\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os
             r!   r   zLatexManager._get_box_metrics>  s]    	5	 	 		F((**FF 	F 	F 	F D$fS#*:;;= =BEF	F
	< %+$5$5$7$7$;$A$A#$F$F!E666 	< 	< 	<D$fS&113 38;<	< crc
##U6#2#;%7%7vcrc{9K9Ka1 !a%{s,   / 
A')A""A'+1B 
C'$CCN)r   r   r   __doc__staticmethodr   classmethodr   r   r   r   r   r   r   r   r   r   r   r(   r#   r!   r   r      s	         ' ' \' F F [F Y   [! ! !  # # #K K K& 48 !" !" !" !" !"FJ J J    r#   r   r   c                  8   t                                           } |                     dt          j        d                                          z             	 |                                  dS # t          $ r" t           j        	                                 Y dS w xY w)Nz&\includegraphics[interpolate=true]{%s}zimages/matplotlib.pngz\includegraphicsz	\pgfimage)
r   r   r   r   _get_data_pathr   r   r   r   cache_clear)mans    r!   _get_image_inclusion_commandr   ^  s    

)
)
+
+C1

6
7
7
@
@
B
B	CD D D""   ,88:::||s   A- -(BBc                        e Zd Z fdZ	 ddZddZd Zd ZddZdd
Z	d Z
d ZddZdddZddZd Zd Zd Zd Z xZS )RendererPgfc                     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   r{   rB   figureimage_counter)r   r   rB   r   s      r!   r   zRendererPgf.__init__p  s@     	:r#   Nc                    t          | j        d           d| j        z  }|                     |           |                     ||           |                    |                                          \  }}	|d         |z  |d         |z  |	d         |z  |	d         |z  f}
t          | j        d|
z             |                     d ||           |                     |	                                dk    |d u           t          | j        d           d	| j        z  }| | ||f}|
                    |d
|          D ]t\  }}|d         |z  |d         |z  }}t          | j        d           t          | j        d||fz             t          | j        d           t          | j        d           ut          | j        d           d S )N\begin{pgfscope}r;   r   r   zQ\pgfsys@defobject{currentmarker}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{        strokefillr   B^!Vl@F)simplifyclip"\pgfsys@transformshift{%fin}{%fin}z"\pgfsys@useobject{currentmarker}{}\end{pgfscope})rD   rB   r{   _print_pgf_clip_print_pgf_path_stylesget_extents
get_points_print_pgf_path_pgf_path_drawget_linewidthiter_segments)r   gcmarker_pathmarker_transr    transrgbFacefbltrcoordsmaxcoordr   pointcodexys                    r!   draw_markerszRendererPgf.draw_markers  s    	-... M 	R   ##B000 ((66AACCBABqEAIr!uqy"Q%!);FHNO	P 	P 	P 	T;===2#3#3#5#5#<!(!4 	 	6 	6 	6$ 48+	H9h9  --ee37 . 9 9 	1 	1KE48a<qAqATW1222TWCq!fLMMMTWCDDDTW/0000+,,,,,r#   c                 x   t          | j        d           |                     |           |                     ||           |                     ||||           |                     |                                dk    |d u           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 |                                |           |                     d	           t          | j        d           t          | j        d
           d| j        z  }|                    |                                          \  \  }}\  }	}
||z  ||	z  }	}||z  ||
z  }
}t!          j        |	|z
            t!          j        |
|z
            }}t          | j        d||fz             t%          |          D ]k}t%          |          D ],}t          | j        d           t          | j        d           -t          | j        d|z             t          | j        d           lt          | j        d           d S 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   r   r;   r   z#\pgfsys@useobject{currentpattern}{}z \pgfsys@transformshift{1in}{0in}z"\pgfsys@transformshift{-%din}{0in}z \pgfsys@transformshift{0in}{1in})rD   rB   r  r  r  r  r  	get_hatchr2   
transformsAffine2Dscaler{   get_hatch_pathr  r  mathceilrange)r   r	  r    	transformr  r  r  xminyminxmaxymaxrepxrepyiyixs                  r!   	draw_pathzRendererPgf.draw_path  s]   -...R   ##B000Ry':::2#3#3#5#5#<!(!4 	 	6 	6 	6+,,, <<>> '	1TW1222''G444   $$$  T9g>>>TW2333 TWFG G G TW1222TWEF F F TW2333N++--33DH==E  r'8'8':':EBBBt,,,TW/000TWd###TXA  ++6688 'LT4,4T1t8$DT1t8$D4$;//4$;1G1G$DTW:dD\IK K KDkk G G++ K KBTW&LMMMTW&IJJJJ"G$"NOOO"EFFFFTW/00000O'	1 '	1r#   c                    d| j         z  }|                                }|rj|                                \  }}||z
  \  }}|d         |z  |d         |z  ||z  ||z  f}t          | j        d|z             t          | j        d           |                                \  }	}
|	.|                     ||	|
           t          | j        d           d S d S )Nr;   r   r   zA\pgfpathrectangle{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}r  )r{   get_clip_rectangler  rD   rB   get_clip_pathr  )r   r	  r  bboxp1p2r   r   r  clippathclippath_transs              r!   r  zRendererPgf._print_pgf_clip  s    M$$&& 	4__&&FB7DAqUQY1	1q5!a%7FTWI   TW2333 $&#3#3#5#5 .  X~>>>TW233333  r#   c           	      ~   dddd}t          | j        ||                                                    dddd}t          | j        ||                                                    |d u}|                                r|                                x}}n9|                                d	         }|rt          |          d	k    r|d	         nd
}|rBt          | j        dt          |d d	                   z             t          | j        d           |r|d
k    rt          | j        d|z             |	                                t          z  t          z  }|                                }	t          | j        d|z             t          | j        d|	d d	         z             t          | j        d           |d
k    rt          | j        d|z             |                                \  }
}|t          | j        d           d S t          | j        dd                    d |D                       |
fz             d S )Nz\pgfsetbuttcapz\pgfsetroundcapz\pgfsetrectcap)buttround
projectingz\pgfsetmiterjoinz\pgfsetroundjoinz\pgfsetbeveljoin)miterr6  bevel   r;   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}rK   c              3       K   | ]	}d |z  V  
dS )z{%fpt}Nr(   )r   dashs     r!   rJ   z5RendererPgf._print_pgf_path_styles.<locals>.<genexpr>"  s'      GGT	D 0GGGGGGr#   )rD   rB   get_capstyleget_joinstyleget_forced_alpha	get_alphaget_rgbr   tupler  mpl_pt_to_inlatex_in_to_pt
get_dashesr5   )r   r	  r  	capstyles
joinstyleshas_fillfillopacitystrokeopacitylwstroke_rgbadash_offset	dash_lists               r!   r  z"RendererPgf._print_pgf_path_styles  s|   .0#46 6	 	)BOO$5$56777  3224 4
 	*R%5%5%7%78999 $&   	O*,,,..8K--JJLLOM(0NS\\A5E5E'!**3K 	@TW@WRaR[))*+ + + TW>??? 	Gs**TW7+EFFF ,.?jjll3b8999>rr?#	$ 	$ 	$ 	>???CTW9MIJJJ "$YTW344444TW-GGYGGGGG#%%& & & & &r#   c                    d| j         z  }|r|                                nd }d| j         z  }|rr|p|                                \  }}	t          |d         |           t          |d         |           t	          |	d         |          t	          |	d         |          f}
n| | ||f}
|                    ||
          D ]Z\  }}|t          j        k    r3t          |          \  }}t          | j
        d||z  ||z  fz             I|t          j        k    rt          | j
        d           o|t          j        k    r3t          |          \  }}t          | j
        d||z  ||z  fz             |t          j        k    r@t          |          \  }}}}||z  ||z  ||z  ||z  f}t          | j
        d	|z             |t          j        k    rHt          |          \  }}}}}}||z  ||z  ||z  ||z  ||z  ||z  f}t          | j
        d
|z             \|r|                                nd }||\  }}}||dz  }|dz  }t          | j
        d           t          | j
        d           t          | j
        d||z  dd||z  dd           t          | j
        dt!          |           d           t          | j
        d           d S d S d S )Nr;   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      ?   z\usepgfmodule{decorations}z(\usepgflibrary{decorations.pathmorphing}z/\pgfkeys{/pgf/decoration/.cd, segment length = r  zin, amplitude = zin}z\pgfmathsetseed{r   z%\pgfdecoratecurrentpath{random steps})r{   r-  r  maxminr  r   MOVETOrD  rD   rB   	CLOSEPOLYLINETOCURVE3CURVE4get_sketch_paramsint)r   r	  r    r"  r  r  r/  r  r0  r1  r   pointsr  r  r  cxcypxpyr  c1xc1yc2xc2ysketch_paramsr  length
randomnesss                               r!   r  zRendererPgf._print_pgf_path%  s   M*,6r$$&&&$ 48+ 	>W___&&FB1y))3r!uxi+@+@1x((#beX*>*>@DD Iy(H=D ..yt.DD 	# 	#LFDt{""V}}1Ba%Q() ) ) ) ''"23333$$V}}1Ba%Q() ) ) ) $$!&vBBaaaa7M!"# # # # $$-26]]*S#sBq#'37C!GR!VR!VK5 "	"# # # 35>,,...$$ )6%E6: #
"?@@@"MNNN #<.4qjA#< #<).;#< #< #< = = = "Js:"J"J"JKKK"JKKKKK) %$ ! r#   TFc                     g }|r|                     d           |r|                     d           t          | j        dd                    |          z             d S )Nr   r   z\pgfusepath{%s}r   )rV   rD   rB   r5   )r   r   r   actionss       r!   r  zRendererPgf._pgf_path_drawg  se     	%NN8$$$ 	#NN6""",sxx/@/@@AAAAAr#   c                     dS )NTr(   r   s    r!   option_scale_imagezRendererPgf.option_scale_imageo  s    tr#   c                 (    t           j        d          S )Nzimage.composite_image)r2   r3   r   s    r!   option_image_nocompositez$RendererPgf.option_image_nocomposites  s    < 7888r#   c                 
   |j         d d         \  }}|dk    s|dk    rd S t          j                            t	          | j        dd                    st          d          t          j        | j        j	                  }d|j
        | j        fz  }	t          j        |d d d                                       |j        |	z             | xj        dz  c_        t!          | j        d	           |                     |           d
| j        z  }
|+t!          | j        d||
z  ||
z  fz             ||
z  ||
z  }}ng|                                                                \  }}}}}}t!          | j        d||
z  ||
z  ||
z  ||
z  ||z   |
z  ||z   |
z  fz             dx}}t+          |d u                                           }t!          | j        dt/                      ||||	fz             t!          | j        d           d S )NrR  r   r   rK   zXstreamed pgf-code does not support raster graphics, consider using the pgf-to-pdf optionz%s-img%d.pngr   r   r;   r   z/\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}zD\pgftext[left,bottom]{%s[interpolate=%s,width=%fin,height=%fin]{%s}}r   )shaperv   r    existsgetattrrB   r   r)   r   r   stemr   r   	fromarraysaver   rD   r  r{   frozen	to_valuesrk   lowerr   )r   r	  r  r  imr"  r   r   r    	fname_imgr  tr1tr2tr3tr4tr5tr6interps                     r!   
draw_imagezRendererPgf.draw_imagew  sE    x|166Q!VVFw~~gdgvr::;; 	/./ / /
 |DGL))"di1C%DD	44R4!!&&t{Y'>???a 	-...R   MTW:a!eQU^KM M Mq5!a%qAA+4+;+;+=+=+G+G+I+I(Cc3STWGAgsQwaqQw!mcAg]445 5 5 IAY$&''--//D.00!Q	++	, 	, 	,
 	+,,,,,r#   )mtextc          
      @    |                      ||||||d|           d S )NTeX)ismathr  )	draw_text)r   r	  r  r  r^   r_   angler  s           r!   draw_texzRendererPgf.draw_tex  s*    r1aD%UKKKKKr#   c	                    t          ||          }t          | j        d           |                     |           |                                }	|	dk    r0t          | j        d|	z             t          | j        d|	z             t          |                                          d d         }
t          | j        d|
z             t          | j        d           t          | j        d           d	|z   }| j        j        }g }|r|d
k    s|	                                dk    r|
                                dk    r|                                }|                                                    |          \  }}dddd}ddddd}|                    d||z  ddd||z  dd||                                         ||
                                         g           n$|                    d||z  dd||z  dd           |d
k    r|                    d|z             t          | j        dd                    |          d|d           t          | j        d            d S )!Nr   r;   r;  r<  r:  z&\definecolor{textcolor}{rgb}{%f,%f,%f}z\pgfsetstrokecolor{textcolor}z\pgfsetfillcolor{textcolor}z\color{textcolor}r   anchorcenter_baselineleftrightrK   )r  r  centertopbottombase)r  r  baseliner  zx=r  inzy=zin, y=zin, left, basez	rotate=%fz	\pgftext[r   z]{r   r   )rd   rD   rB   r  rB  rD  rC  r   r{   get_rotation_modeget_verticalalignmentget_unitless_positionget_transformr"  extendget_horizontalalignmentrV   r5   )r   r	  r  r  r^   r_   r  r  r  alphargbr{   	text_argsposhalignvaligns                   r!   r  zRendererPgf.draw_text  s    $At,,-...R   C<<TW7%?@@@TW9EABBBBJJLL!!"1"%CcIJJJ:;;;8999 1$ko	 	J!((**h66++--1BBB --//C&&((22377DAq$w"EEF"h"(B8 8F QsU     QsU    u44667u22445	     H!C%HHH3HHHHIIIA::[50111)1D1D1D1DaaaHIII+,,,,,r#   c                     t                                                               ||          \  }}}t          | j        z  }||z  ||z  ||z  fS rH   )r   r   r   rE  r{   )r   r^   r_   r  r   r   dr  s           r!   get_text_width_height_descentz)RendererPgf.get_text_width_height_descent  sU      2244,,Q55 	1a
 48#1ua!eQU""r#   c                     dS )NFr(   r   s    r!   flipyzRendererPgf.flipy  s    ur#   c                     | j                                         | j        z  | j                                         | j        z  fS rH   )r   get_figwidthr{   get_figheightr   s    r!   get_canvas_width_heightz#RendererPgf.get_canvas_width_height  s<    ((**TX5))++dh68 	8r#   c                 &    |t           z  | j        z  S rH   )rE  r{   )r   r\  s     r!   points_to_pixelszRendererPgf.points_to_pixels  s    $tx//r#   rH   )TF)FN)r   r   r   r   r  r+  r  r  r  r  rk  rm  r  r  r  r  r  r  r  r   r   s   @r!   r   r   n  sb           ( "$- $- $- $-L31 31 31 31j4 4 4(1& 1& 1&f@L @L @L @LDB B B B  9 9 9'- '- '- '-R ;? L L L L L.- .- .- .-`	# 	# 	#  8 8 8
0 0 0 0 0 0 0r#   r   c                   Z     e Zd ZddddZd ZdddZd	 Zdd
dZd Zd Z	 fdZ
 xZS )FigureCanvasPgfzLaTeX PGF picturezLaTeX compiled PGF picturezPortable Network Graphics)pgfpdfpngc                     dS )Nr  r(   r   s    r!   get_default_filetypez$FigureCanvasPgf.get_default_filetype  s    ur#   Nbbox_inches_restorec          
      l   d}dg}t                                                      D ]}|                    d|z              |                    d           d                    |          }| j                                        | j                                        }}| j        j        }|                    |           |                    |           |                    d           t          |d           t          |d           t          |d           t          |d	||fz             t          |d
           t          | j        |||t          | j        |          |          }	| 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   rV   r5   r   r  r  r{   rA   rD   r   r   draw)
r   rB   r  header_textheader_info_preamblerC   r   r   r{   renderers
             r!   _print_pgf_to_fhz FigureCanvasPgf._print_pgf_to_fh  s   . !LL!OO..00 	8 	8D ''$7777##D)))#yy)=>> {''))4;+D+D+F+F1ko 	
%&&&
^$$$%&&&*+++Nq6	 	 	 	>???$T[!Q%0b%A%A9LN N N 	""" 	()))_%%%\"""""r#   c                     t          j        |dd          5 }t          j        |          s t          j        d          |          } | j        |fi | ddd           dS # 1 swxY w 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_cmfile_requires_unicodecodecs	getwriterr  )r   fname_or_fhkwargsfiles       r!   	print_pgfzFigureCanvasPgf.print_pgf-  s    
 S7CCC 	2t.t44 70v'0066!D!$11&111	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2s   A A%%A),A)metadatac                B   | j                                         \  }}t          d|pi           }d                    d |                                D                       }t                      5 }t          j        |          }	 | j        |	dz  fi | |	dz  	                    d                    t          d|z  d||fz  d	t                      d
dddg	          d           t          j        d         }
t          j        |
dddgt           |           |	dz                      d          5 }t          j        |d          5 }t'          j        ||           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )z3Use LaTeX to compile a pgf generated figure to pdf.r  r   c              3   <   K   | ]\  }}t          ||          V  d S rH   rn   r   kvs      r!   rJ   z,FigureCanvasPgf.print_pdf.<locals>.<genexpr><  sJ       B B'+q!Q""B B B B B Br#   z
figure.pgfz
figure.texr   #\usepackage[pdfinfo={%s}]{hyperref}8\usepackage[papersize={%fin,%fin}, margin=0in]{geometry}\usepackage{pgf}r   z
\centeringz\input{figure.pgf}z\end{document}r   r  r   -interaction=nonstopmoder   r   
figure.pdfrbwbN)r   get_size_inchesr   r5   itemsr   r)   r   r  
write_textr   r:   r2   r3   r   _check_and_log_subprocessrZ   openr  shutilcopyfileobj)r   r  r  r  r   r   	info_dictpdfinfor   tmppath
texcommandorigdests                r!   	print_pdfzFigureCanvasPgf.print_pdf7  s   {**,,1)%R@@	(( B B/8/@/@B B B B B  !! 	/Vl6**GDN7\1<<V<<<|#//		":WDO!f'!OO'!)%   % 0 & & & o6J+79I $&2 2 2 2 \)//55 /$[$77/;?"4.../ / / / / / / / / / / / / / / / / / / / / / / / / / / / / /)	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/s[   .B?F-E<E%E<%E))E<,E)-E<0F<F 	 FF 	FFFc                    t                      }t                      5 }t          j        |          }|dz  }|dz  } | j        |fi |  |||| j        j                   |                    d          5 }t          j	        |d          5 }	t          j        ||	           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )z?Use LaTeX to compile a pgf figure to pdf and convert it to png.r  z
figure.png)r{   r  r  N)r   r   r)   r   r  r   r{   r  r   r  r  r  )
r   r  r  	converterr   r  pdf_pathpng_pathr  r  s
             r!   	print_pngzFigureCanvasPgf.print_pngX  s   -//	!! 	/Vl6**G-H-HDN8..v...Ihdko>>>>--%% /$[$77/;?"4.../ / / / / / / / / / / / / / / / / / / / / / / / / / / / / /	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/sZ   AC7CB/#C/B33C6B37C:CC
	
CC
	CC"%C"c                 ,    t          | j        d           S rH   )r   r   r   s    r!   get_rendererzFigureCanvasPgf.get_renderere  s    4;---r#   c                 v    | j                                          t                                                      S rH   )r   draw_without_renderingr   r  )r   r   s    r!   r  zFigureCanvasPgf.drawh  s)    **,,,ww||~~r#   )r   r   r   	filetypesr  r  r  r  r  r  r  r   r   s   @r!   r  r    s        +437 7I   ;? 6# 6# 6# 6# 6#p2 2 2 26 / / / / /B/ / /. . .        r#   r  c                       e Zd ZeZdS )_BackendPgfN)r   r   r   r  FigureCanvasr(   r#   r!   r  r  p  s        "LLLr#   r  c                   J    e Zd ZdZdddZd Zd Zd Zd Zd	 Z	dd
Z
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()
    Nr  c                    || _         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.

        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)_output_name
_n_figurescopy	_metadatar   
_info_dictr   _file)r   filenamer  s      r!   r   zPdfPages.__init__  sL    . %".b..00/t~FFYY


r#   c           	      6   d                     d | j                                        D                       }d                     t          d|z  d||fz  dt	                      ddg          }| j                            |                    d	                     d S )
Nr   c              3   <   K   | ]\  }}t          ||          V  d S rH   r  r  s      r!   rJ   z)PdfPages._write_header.<locals>.<genexpr>  sJ       H H'+q!Q""H H H H H Hr#   r   r  r  r  z\setlength{\parindent}{0pt}z\begin{document}%r   )r5   r  r  r   r:   r  rA   encode)r   width_inchesheight_inchesr  r   s        r!   _write_headerzPdfPages._write_header  s    (( H H/3/D/D/F/FH H H H Hyy2W<G]+,OO* 	"
 	 	 	
,,W5566666r#   c                     | S rH   r(   r   s    r!   	__enter__zPdfPages.__enter__  s    r#   c                 .    |                                   d S rH   )close)r   exc_typeexc_valexc_tbs       r!   __exit__zPdfPages.__exit__  s    

r#   c                     | j                             d           | j        dk    r|                                  | 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   N)r  rA   r  
_run_latexr  r   s    r!   r  zPdfPages.close  sR    
 	
-...?QOO
r#   c                    t           j        d         }t                      5 }t          j        |d          }|                    | j                                                   t          j	        |dd|gt          |           t          j        |                    d          | j                   d d d            d S # 1 swxY w Y   d S )Nr   zpdf_pages.texr  r   r  z.pdf)r2   r3   r   r)   r   write_bytesr  getvaluer   r  rZ   r  movewith_suffixr  )r   r  r   
tex_sources       r!   r	  zPdfPages._run_latex  s   \/2
!! 	KV fo>>J""4:#6#6#8#8999+79I&" " " " K
..v668IJJJ	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	K 	Ks   BB==CCc                    t          |t                    sJ|t          j                    }nt          j        |          }|t          d|           |j        j        }|                                \  }}| j	        dk    r| 
                    ||           n| j                            d||fz              |j        | j        fddd| | xj	        dz  c_	        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=%fin\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=%fin%%
r  )r   backendr   )rh   r   r   
get_activeget_fig_managerr   canvasr   r  r  r  r  rA   savefig)r   r   r  managerr   r   s         r!   r  zPdfPages.savefig  s    &&)) 	+~.**-f55 !6f!6!6777^*F..00v?auf----
 J !&/*   	tzI%II&III1r#   c                     | j         S )z=Return the current number of pages in the multipage pdf file.)r  r   s    r!   get_pagecountzPdfPages.get_pagecount  s
    r#   rH   )r   r   r   r   r   r  r  r  r  r	  r  r  r(   r#   r!   r  r  u  s          .2     :7 7 7      	K 	K 	K" " " "H    r#   r  )@r  ri   r   ior   loggingr  rv   r)   r  rt   tempfiler   r   PILr   
matplotlibr2   r   r   r*   matplotlib.backend_basesr   r	   r
   r   !matplotlib.backends.backend_mixedr   matplotlib.backends.backend_pdfr   r   matplotlib.pathr   matplotlib.figurer   matplotlib.font_managerr   matplotlib._pylab_helpersr   	getLoggerr   rZ   r   r:   latex_pt_to_inrF  rE  mpl_in_to_ptr?   rD   rd   rn   r   r   r   r   r   r   r   r  FigureManagerPgfexportr  r  r(   r#   r!   <module>r*     s                 				       ' ' ' ' ' '            0 0 0 0 0 0 0 0            @ ? ? ? ? ?- - - - - - - -             $ $ $ $ $ $ 2 2 2 2 2 2 ) ) ) ) ) )w"" ,& & &V n$L = = =  * * *Z     A A A6	 	 	 	 	 	 	 	U U U U U U U Up Q  |0 |0 |0 |0 |0, |0 |0 |0~} } } } }& } } }@ %  
# # # # #( # # #} } } } } } } } } }r#   