
    Ng                     B   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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j&        e'          Z(d Z)dZ*de*z  Z+dZ,de,z  Z-d Z.d Z/d Z0d Z1d Z2 G d de3          Z4 G d d          Z5 ej6        d          d             Z7 G d de          Z8 G d de          Z9eZ:ej;         G d d e                      Z< G d! d"          Z=dS )#    N)BytesIO)TemporaryDirectory)Image)_apicbookfont_manager)_BackendFigureCanvasBaseFigureManagerBaseRendererBase)MixedModeRenderer)_create_pdf_info_dict_datetime_to_pdf)Path)Figure)Gcfc            	         d                     ddt          j        d         ddgt          j        d         r&d t          g d	d
 dD                       D             ng dt          j                            dd                    S )z=Prepare a LaTeX preamble based on the rcParams configuration.
z\def\mathdefault#1{#1}z4\everymath=\expandafter{\the\everymath\displaystyle}zpgf.preamblez1\ifdefined\pdftexversion\else  % non-pdftex case.z  \usepackage{fontspec}zpgf.rcfontsc           	      d    g | ]-\  }}d |d|j         d|j                                        d.S )z  \{z}[Path=\detokenize{z/}])nameparentas_posix).0commandpaths      [/var/www/html/ai-engine/env/lib/python3.11/site-packages/matplotlib/backends/backend_pgf.py
<listcomp>z!_get_preamble.<locals>.<listcomp>/   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>4   sB     G G G bk&1122 G G Gr   )serifzsans\-serif	monospacez\fi
underscorestrings)option)joinmplrcParamszip
texmanager_usepackage_if_not_loadedr$   r   r   _get_preambler4   #   s    99 	"?^$<"$ \-(1 
 
 "%===G GEG G G" "
 
 
 
 /1%& 	'* 	00i0PP+   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_escaper9   F   s    
 <<(*;<<<r   c                 Z    |                      |           |                      d           d S )Nz%
)write)fhlines     r   _writelnr>   N   s&     HHTNNNHHUOOOOOr   c                    g }ddddd}|                                 d         |v r|                    |                    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   c              3   .   K   | ]}|j         k    V  d S N)r   )r   fontr(   s     r   	<genexpr>z*_escape_and_apply_props.<locals>.<genexpr>a   s*      DDTTY& DDDDDDr   z9\ifdefined\pdftexversion\else\setmainfont{%s}\rmfamily\fizIgnoring unknown font: %sz\fontsize{%f}{%f}g333333? 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%{\%}})
get_familyappendanyr&   fontManagerttflist_logwarningget_size_in_points	get_style
get_weightr.   r9   )spropcommandsfamiliessizestyles
boldstylesr(   s          @r   _escape_and_apply_propsra   U   s   
 H%|*G GH__q!F())))	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={rO   )
isinstancedatetimer   r   decodestr)keyvalues     r   _metadata_to_strrk      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 )	Nrm   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%dro   )rq   rr   
executableru   )rv   rw   rx   gs_infos      r   ry   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.)r/   _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 )
LatexErrorrE   c                 X    t                                          |           || _        d S rB   )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   rZ   s     r   __str__zLatexError.__str__   s-    Y 	*)))Ar   )rE   )__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                  z    ddt           j        d          dt                      ddg} d                    |           S )Nz\documentclass{article}z% !TeX program = pgf.texsystemz\usepackage{graphicx}\begin{document}z!\typeout{pgf_backend_query_start}r   )r/   r0   r4   r.   )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 rB   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stdinr;   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 haltedrE   )	listr   stdoutreadrQ   lenkillr   r.   )r   rZ   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   rp   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rB   )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)rq   Popenr/   r0   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   ra   )r   r8   r[   s      r   get_width_height_descentz%LatexManager.get_width_height_descent#  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   J  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   rx   r<   figureimage_counter)r   r   r<   r   s      r   r   zRendererPgf.__init__\  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}r5   r   r   zQ\pgfsys@defobject{currentmarker}{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}{        strokefillrO   B^!Vl@F)simplifyclip"\pgfsys@transformshift{%fin}{%fin}z"\pgfsys@useobject{currentmarker}{}\end{pgfscope})r>   r<   rx   _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_markerso  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   rO   r5   r   z#\pgfsys@useobject{currentpattern}{}z \pgfsys@transformshift{1in}{0in}z"\pgfsys@transformshift{-%din}{0in}z \pgfsys@transformshift{0in}{1in})r>   r<   r   r   r  r  r  	get_hatchr/   
transformsAffine2Dscalerx   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 )Nr5   r   r   zA\pgfpathrectangle{\pgfqpoint{%fin}{%fin}}{\pgfqpoint{%fin}{%fin}}r  )rx   get_clip_rectangler   r>   r<   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)miterr2  bevel   r5   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}rE   c              3       K   | ]	}d |z  V  
dS )z{%fpt}Nr$   )r   dashs     r   rD   z5RendererPgf._print_pgf_path_styles.<locals>.<genexpr>  s'      GGT	D 0GGGGGGr   )r>   r<   get_capstyleget_joinstyleget_forced_alpha	get_alphaget_rgbr   tupler  mpl_pt_to_inlatex_in_to_pt
get_dashesr.   )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 )Nr5   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{rO   z%\pgfdecoratecurrentpath{random steps})rx   r)  r   maxminr  r   MOVETOr@  r>   r<   	CLOSEPOLYLINETOCURVE3CURVE4get_sketch_paramsint)r   r  r   r  r	  r
  r+  r  r,  r-  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   )rQ   r>   r<   r.   )r   r   r   actionss       r   r  zRendererPgf._pgf_path_drawS  se     	%NN8$$$ 	#NN6""",sxx/@/@@AAAAAr   c                     dS )NTr$   r   s    r   option_scale_imagezRendererPgf.option_scale_image[  s    tr   c                 (    t           j        d          S )Nzimage.composite_image)r/   r0   r   s    r   option_image_nocompositez$RendererPgf.option_image_nocomposite_  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 )NrN  r   r   rE   zXstreamed pgf-code does not support raster graphics, consider using the pgf-to-pdf optionz%s-img%d.pngr   r   r5   r   z/\pgfsys@transformcm{%f}{%f}{%f}{%f}{%fin}{%fin}zD\pgftext[left,bottom]{%s[interpolate=%s,width=%fin,height=%fin]{%s}}r   )shapers   r   existsgetattrr<   r   r%   r   r   stemr   r   	fromarraysaver   r>   r   rx   frozen	to_valuesrh   lowerr   )r   r  r  r  imr  r   r   r   	fname_imgr
  tr1tr2tr3tr4tr5tr6interps                     r   
draw_imagezRendererPgf.draw_imagec  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  rZ   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   r5   r7  r8  r6  z&\definecolor{textcolor}{rgb}{%f,%f,%f}z\pgfsetstrokecolor{textcolor}z\pgfsetfillcolor{textcolor}z\color{textcolor}r   anchorcenter_baselineleftrightrE   )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]{rO   r   )ra   r>   r<   r   r>  r@  r?  r   rx   get_rotation_modeget_verticalalignmentget_unitless_positionget_transformr  extendget_horizontalalignmentrQ   r.   )r   r  r  r  rZ   r[   r  r  r  alphargbrx   	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 rB   )r   r   r   rA  rx   )r   rZ   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 rB   )r   get_figwidthrx   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 rB   )rA  rx   )r   rX  s     r   points_to_pixelszRendererPgf.points_to_pixels  s    $tx//r   rB   )TF)FN)r   r   r   r   r  r'  r   r   r  r  rg  ri  r~  r  r  r  r  r  r  r   r   s   @r   r   r   Z  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)r4   r   rQ   r.   r   r  r  rx   r;   r>   r   r   draw)
r   r<   r  header_textheader_info_preambler=   r   r   rx   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                8   | j                                         \  }}t          d|pi           }d                    d |                                D                       }t                      5 }t          j        |          }	 | j        |	dz  fi | |	dz  	                    d                    d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 rB   rk   r   kvs      r   rD   z,FigureCanvasPgf.print_pdf.<locals>.<genexpr>(  sJ       B B'+q!Q""B B B B B Br   z
figure.pgfz
figure.texr   \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   r  r   -interaction=nonstopmoder   r   
figure.pdfrbwbN)r   get_size_inchesr   r.   itemsr   r%   r   r  
write_textr4   r/   r0   r   _check_and_log_subprocessrU   openr  shutilcopyfileobj)r   r  r  r  r   r   	info_dictpdfinfor   tmppath
texcommandorigdests                r   	print_pdfzFigureCanvasPgf.print_pdf#  s   {**,,1)%R@@	(( B B/8/@/@B B B B B  !! 	/Vl6**GDN7\1<<V<<<|#//		4:WDO!f'!OO'!)%   % 0 & & & o6J+79I $&2 2 2 2 L(..t44 /#K66/:>"4.../ / / / / / / / / / / / / / / / / / / / / / / / / / / / / /)	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/s[   .B:F(E7>E E7 E$$E7'E$(E7+F7E;	;F>E;	?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)rx   r  r  N)r   r   r%   r   r  r   rx   r  r   r  r  r  )
r   r  r  	converterr   r  pdf_pathpng_pathr  r  s
             r   	print_pngzFigureCanvasPgf.print_pngD  s   -//	!! 	/Vl6**G-H-HDN8..v...Ihdko>>>>t$$ /#K66/:>"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 rB   )r   r   r   s    r   get_rendererzFigureCanvasPgf.get_rendererQ  s    4;---r   c                 v    | j                                          t                                                      S rB   )r   draw_without_renderingr   r  )r   r   s    r   r  zFigureCanvasPgf.drawT  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  \  s        "LLLr   r  c                       e Zd ZdZ e            ZedddZ ej        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()
    N)
keep_emptyr  c                   || _         d| _        |r|| j        urt          j        d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   3.8^Keeping empty pdf files is deprecated since %(since)s and support will be removed %(removal)s.r   r  N)_output_name
_n_figures_UNSETr   warn_deprecated_keep_emptycopy	_metadatar   
_info_dictr   _file)r   filenamer  r  s       r   r   zPdfPages.__init__s  s    6 % 	1*DK77 /1 1 1 1 &".b..00/t~FFYY


r   r  c           	      ,   d                     d | j                                        D                       }d                     dd|z  d||fz  dt                      dd	g          }| j                            |                    d
                     d S )Nr   c              3   <   K   | ]\  }}t          ||          V  d S rB   r  r  s      r   rD   z)PdfPages._write_header.<locals>.<genexpr>  sJ       H H'+q!Q""H H H H H Hr   r   r  r  r  r  z\setlength{\parindent}{0pt}z\begin{document}%r   )r.   r  r  r4   r  r;   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 rB   r$   r   s    r   	__enter__zPdfPages.__enter__  s    r   c                 .    |                                   d S rB   )close)r   exc_typeexc_valexc_tbs       r   __exit__zPdfPages.__exit__  s    

r   c                 4   | j                             d           | j        dk    r|                                  nD| j        r=t          j        dd           t          | 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  r  r  r  N)
r  r;   r  
_run_latexr  r   r  r  r  r  r   s    r   r  zPdfPages.close  s    
 	
-...?QOO 	2 /1 1 1 1 "D))//111
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)r/   r0   r   r%   r   write_bytesr  getvaluer   r  rU   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| 
                    ||           n4| j                            d| d| d                    d                      |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   z?\newpage\ifdefined\pdfpagewidth\pdfpagewidth\else\pagewidth\fi=z<in\ifdefined\pdfpageheight\pdfpageheight\else\pageheight\fi=zin%%
rd   r  )r   backendr   )re   r   r   
get_activeget_fig_managerr   canvasr   r  r  r  r  r;   r  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+0  -3	   &//	 	 	 	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   rB   )r   r   r   r   objectr  r   r   deprecate_privatize_attributer  r  r  r
  r  r  r  r  r$   r   r   r  r  a  s          VXXF/5 $ $ $ $ $L 43E::J7 7 7      	K 	K 	K& & & &P    r   r  )>r  rf   r   ior   loggingr  rs   r%   r  rq   tempfiler   r   PILr   
matplotlibr/   r   r   r   r&   matplotlib.backend_basesr	   r
   r   r   !matplotlib.backends.backend_mixedr   matplotlib.backends.backend_pdfr   r   matplotlib.pathr   matplotlib.figurer   matplotlib._pylab_helpersr   	getLoggerr   rU   r4   latex_pt_to_inrB  rA  mpl_in_to_ptr9   r>   ra   rk   r   r   r   r   r   r   r   r  FigureManagerPgfexportr  r  r$   r   r   <module>r.     sk                 				       ' ' ' ' ' '            6 6 6 6 6 6 6 6 6 6            @ ? ? ? ? ?- - - - - - - -             $ $ $ $ $ $ ) ) ) ) ) )w""  : n$L = = =  ( ( (V     A A A6	 	 	 	 	 	 	 	U U U U U U U Up Q  |0 |0 |0 |0 |0, |0 |0 |0~} } } } }& } } }@ %  
# # # # #( # # #S S S S S S S S S Sr   