B
    ]t\                 @   sz  d Z ddlZddlZddlZddlmZmZ ddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlmZ ddlZddlZddlmZmZmZmZ ddlmZ ddlmZmZmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$ dd	l%m&Z&m'Z'm(Z( dd
l)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddlm4Z4 ddl5m6Z6 ddl7m8Z8 e9e:Z;dZ<dZ=G dd de>Z?e? Z@dddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.ZAd/d0 ZBd1d2 ZCd3d4 ZDd5d6 ZEd7d8 ZFG d9d: d:eZGG d;d< d<eZHG d=d> d>eZId?d@ ZJdWdCdDZKdXdEdFZLdYdGdHZMeNdIdJdK ZOdZdLdMZPeZQdNdOdPdQdRdSdTgZRejSG dUdV dVeZTdS )[zG
A PostScript backend, which can produce both PostScript .ps and .eps.
    N)StringIOTextIOWrapper)TemporaryDirectory)cbook__version__rcParamscheckdep_ghostscript)AFM)_BackendFigureCanvasBaseFigureManagerBaseGraphicsContextBaseRendererBase)get_realpath_and_statis_writable_file_likemaxdictfile_requires_unicode)findfontis_opentype_cff_fontget_font)KERNING_DEFAULTLOAD_NO_HINTING)convert_ttf_to_ps)MathTextParser)	uni2type1)Path)_path)Affine2D)MixedModeRendererzLevel IIc               @   s8   e Zd Zdd Zedd Zedd Zedd Zd	S )
PsBackendHelperc             C   s
   i | _ d S )N)_cached)self r"   =lib/python3.7/site-packages/matplotlib/backends/backend_ps.py__init__/   s    zPsBackendHelper.__init__c             C   sL   y
| j d S  tk
r   Y nX t \}}|dkr6d}t|| j d< t|S )z1
        executable name of ghostscript.
        gs_exeNZgs)r    KeyErrorr   str)r!   r%   
gs_versionr"   r"   r#   r%   2   s    

zPsBackendHelper.gs_exec             C   s   y
| j d S  tk
r   Y nX tj| jdgtjd}| \}}|d}ytt	t
| d}W n tk
r   d}Y nX || j d< |S )z)
        version of ghostscript.
        r(   z	--version)stdoutascii.)r   r   )r    r&   
subprocessPopenr%   PIPEZcommunicatedecodetuplemapintstripsplit
ValueError)r!   spipestderrZverr(   r"   r"   r#   r(   C   s    



zPsBackendHelper.gs_versionc             C   s   | j d dkS )zM
        True if the installed ghostscript supports ps2write device.
        r   	   )r(   )r!   r"   r"   r#   supports_ps2writeY   s    z!PsBackendHelper.supports_ps2writeN)__name__
__module____qualname__r$   propertyr%   r(   r:   r"   r"   r"   r#   r   -   s   r   )g      !@   )g      !@   )r?      )gGz@@gHzgG@)gp=
c7@gGz@@)g
ףp=0@gp=
c7@)gzGa'@g
ףp=0@)g
ףp= @gzGa'@)gRQ@g
ףp= @)gQ@gRQ@)gHzG@gQ@)g(\ @gHzG@)gZd;O?gffffff @)gRQ?gZd;O?)gfffffFD@g)\L@)g)\<@gfffffFD@)gQE4@g)\<@)g)\,@gQE4@)gQ8$@g)\,@)gp=
ף@gQ8$@)g)\(@gp=
ף@)gp=
ף@g)\(@)gGz@gp=
ף@)g)\(?gGz@)g)\(?g)\(?)letterZlegalZledgera0Za1Za2Za3Za4Za5Za6Za7Za8Za9Za10Zb0Zb1Zb2Zb3Zb4Zb5Zb6Zb7Zb8Zb9Zb10c             C   sF   x@t t ddD ],\}\}}|dr*q| |k r||k r|S qW dS )NT)reverselrC   )sorted	papersizeitems
startswith)whkeyZpwZphr"   r"   r#   _get_papertype|   s    
rM   c             C   sF   t | tr| S t| }| |kr&t|S d|  }|d}|d}|S )Nz%1.3f0r+   )
isinstancer'   r2   rstrip)valZivalr6   r"   r"   r#   _num_to_str   s    
 

rR   c              G   s   d tt| S )N )joinr1   rR   )argsr"   r"   r#   _nums_to_str   s    rV   c             C   sX   |  dd} |  dd} |  dd} |  dd} |  d	d
} tddd | } | dS )zHQuote dangerous characters of S for use in a PostScript string constant.   \s   \\   (s   \(   )s   \)   's   \251   `s   \301s   [^ -~\n]c             S   s   dt |   S )Ns   \%03o)ordgroup)xr"   r"   r#   <lambda>   s    z!quote_ps_string.<locals>.<lambda>r*   )replaceresubr/   )r6   r"   r"   r#   quote_ps_string   s    rc   c          	   C   s\   t |rFt|rt| dddnt| d}| t|| W dQ R X ntj| |tjd dS )zMove the contents of file at *src* to path-or-filelike *dst*.

    If *dst* is a path, the metadata of *src* are *not* copied.
    rzlatin-1)encodingrbN)Zcopy_function)r   r   openshutilZcopyfileobjmoveZcopyfile)srcdstfhr"   r"   r#   _move_path_to_path_or_stream   s    
rm   c               @   sF  e Zd ZdZedZdNddZdd Zdd	 ZdOddZ	dPddZ
dQddZdRddZdSddZdTddZdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ ZdUd&d'Zd(d) Zd*d+ Zd,d- Zd.d/ ZdVd1d2ZdWd4d5Zd6d7 ZdXd8d9ZdYd:d;Zd<d= Z dZd?d@Z!d[dAdBZ"dCdD Z#dEdF Z$dGdH Z%dIdJ Z&d\dLdMZ'd0S )]
RendererPSz
    The renderer handles all the drawing primitives using a graphics
    context instance that controls the colors/styles.
    2   H   c             C   s   t |  || _|| _|| _td r0d| _g | _|| _d| _	d| _
d| _d| _d| _d| _d| _i | _|d | _i | _d| _i | _td| _tjtd dd| _dS )	z
        Although postscript itself is dpi independent, we need to
        imform the image code about a requested dpi to generate high
        res images and them scale them before embeddin them
        ztext.usetexr   Ng      R@ZPSZdatapathZfontsafm)r   r$   widthheight	_pswriterr   textcntpsfragimagedpicolor	linewidthlinejoinlinecaplinedashfontnamefontsize_hatchesimage_magnification_clip_paths_path_collection_idused_charactersr   mathtext_parserospathrT   _afm_font_dir)r!   rr   rs   pswriterrw   r"   r"   r#   r$      s.    


zRendererPS.__init__c             C   s:   t |j\}}| j||t f}|d tt| dS )zDKeeps track of which characters are required from
        each font.   N)r   fnamer   
setdefaultsetupdater1   r\   )r!   fontr6   realpathstat_keyr   r"   r"   r#   track_characters   s    zRendererPS.track_charactersc             C   s@   x:|  D ].\}\}}| j||t f}|d | q
W d S )Nr   )rH   r   r   r   r   )r!   otherr   r   charsetr   r"   r"   r#   merge_used_characters   s    z RendererPS.merge_used_charactersr   c             C   s\   |||f| j krX||kr2||kr2| jd|  n| jd|||f  |rX|||f| _ d S )Nz%1.3f setgray
z%1.3f %1.3f %1.3f setrgbcolor
)rx   rt   write)r!   rd   gbstorer"   r"   r#   	set_color   s     zRendererPS.set_colorc             C   s0   t |}|| jkr,| jd|  |r,|| _d S )Nz%1.3f setlinewidth
)floatry   rt   r   )r!   ry   r   r"   r"   r#   set_linewidth   s
    
 zRendererPS.set_linewidthc             C   s(   || j kr$| jd|  |r$|| _ d S )Nz%d setlinejoin
)rz   rt   r   )r!   rz   r   r"   r"   r#   set_linejoin   s    
 zRendererPS.set_linejoinc             C   s(   || j kr$| jd|  |r$|| _ d S )Nz%d setlinecap
)r{   rt   r   )r!   r{   r   r"   r"   r#   set_linecap   s    
 zRendererPS.set_linecapc             C   sx   | j d k	r,| j \}}t||r,||kr,d S |d k	rZt|rZdt| |f }| j| n| jd |rt||f| _ d S )Nz[%s] %d setdash
z[] 0 setdash
)r|   npZarray_equallenrV   rt   r   )r!   offsetseqr   ZoldoZoldseqr6   r"   r"   r#   set_linedash   s    

zRendererPS.set_linedashc             C   sL   t d rd S ||f| j| jfkrHd||f }| j| |rH|| _|| _d S )Nz	ps.useafmz%/%s findfont
%1.3f scalefont
setfont
)r   r}   r~   rt   r   )r!   r}   r~   r   outr"   r"   r#   set_font  s    
zRendererPS.set_fontc             C   s   d}|| j kr| j | S dt| j  }td }| jd }| jdt   | j| jt	|t
 |dd | jdt   || j |< |S )Nrp   zH%dzhatch.linewidthz  << /PatternType 1
     /PaintType 2
     /TilingType 2
     /BBox[0 0 %(sidelen)d %(sidelen)d]
     /XStep %(sidelen)d
     /YStep %(sidelen)d

     /PaintProc {
        pop
        %(linewidth)f setlinewidth
F)simplifyz}        fill
        stroke
     } bind
   >>
   matrix
   0.0 %(pageheight)f translate
   makepattern
   /%(name)s exch def
)r   r   r   rs   rt   r   locals_convert_pathr   hatchr   scale)r!   r   Zsidelennamery   Z
pageheightr"   r"   r#   create_hatch  s    



	
zRendererPS.create_hatchc             C   s   | j d | jd fS )z4return the canvas width and height in display coordsg      R@)rr   rs   )r!   r"   r"   r#   get_canvas_width_height;  s    z"RendererPS.get_canvas_width_heightc             C   s  t d r8|  }| }|j||| d\}}}|||fS |r`| j|d|\}	}
}}}|	|
|fS t d r|rx|dd }| |}||\}}}}}| }d| }||9 }||9 }||9 }|||fS | |}|j	|dt
d	 | \}}|d
 }|d
 }| }|d
 }|||fS )zm
        get the width and height in display coords of the string s
        with FontPropertry prop

        ztext.usetex)rendererrp   z	ps.useafmr   gMbP?g        )flagsg      P@)r   get_texmanagerget_size_in_pointsget_text_width_height_descentr   parse_get_font_afmget_str_bbox_and_descent_get_font_ttfset_textr   Zget_width_heightZget_descent)r!   r6   propismath
texmanagerr~   rJ   rK   drr   rs   descentr   r   r   rE   r   r   r"   r"   r#   r   ?  s8    

 


z(RendererPS.get_text_width_height_descentc             C   s   dS )z3return true if small y numbers are top for rendererFr"   )r!   r"   r"   r#   flipyf  s    zRendererPS.flipyc          	   C   s   t |}| j|}|d krt|d| jd}|d krDtdd| jd}| j|}|d krt|d}t|}W d Q R X || j|< || j|< |S )Nrq   )ZfontextZ	directoryZ	Helveticarf   )hashafmfontdgetr   r   rg   r	   )r!   r   rL   r   r   rl   r"   r"   r#   r   j  s    

zRendererPS._get_font_afmc             C   s0   t |}t|}|  | }||d |S )Ng      R@)r   r   clearr   Zset_size)r!   r   r   r   sizer"   r"   r#   r   z  s    zRendererPS._get_font_ttfc             C   s<   |j d d \}}|d d dd d d df }||| fS )N   r      )shapetostring)r!   ZrgbarK   rJ   Zrgbr"   r"   r#   _rgb  s    zRendererPS._rgb   c             C   sP   t |}t|}g }x4td||D ]$}t|| |}||||  q$W |S )Nr   )binasciiZb2a_hexr   rangeminappend)r!   r6   Zchars_per_lineZnhexlinesilimitr"   r"   r#   
_hex_lines  s    
zRendererPS._hex_linesc             C   s   | j S )z
        Get the factor by which to magnify images passed to draw_image.
        Allows a backend to have images at a different resolution to other
        artists.
        )r   )r!   r"   r"   r#   get_image_magnification  s    z"RendererPS.get_image_magnificationc             C   s   dS )z@
        ps backend support arbitrary scaling of image.
        Tr"   )r!   r"   r"   r#   option_scale_image  s    zRendererPS.option_scale_imagec             C   s
   t d  S )zl
        return whether to generate a composite image from multiple images on
        a set of axes
        zimage.composite_image)r   )r!   r"   r"   r#   option_image_nocomposite  s    z#RendererPS.option_image_nocompositec             C   s    |  |\}}}d}||||fS )Nzfalse 3 colorimage)r   )r!   imrK   rJ   bitsimagecmdr"   r"   r#   _get_image_h_w_bits_command  s    z&RendererPS._get_image_h_w_bits_commandNc             C   s   |  |\}}}}	d| |d}
|dkrJd}|| j }|| j }n dtt|  }d}d}| j	d }|
 }| \}}g }|dk	r|j\}}}}|dt||||  |dk	r| ||}|d	|  d
|}dt  }| j| dS )z
        Draw the Image instance into the current axes; x is the
        distance in pixels from the left hand side of the canvas and y
        is the distance from bottom
           
r*   Nz1 0 0 1 0 0rS   g      ?rp   z
%s clipboxz%s
zgsave
%(clip)s
%(x)s %(y)s translate
[%(matrix)s] concat
%(xscale)s %(yscale)s scale
/DataString %(w)s string def
%(w)s %(h)s 8 [ %(w)s 0 0 -%(h)s 0 %(h)s ]
{
currentfile DataString readhexstring pop
} bind %(imagecmd)s
%(hexlines)s
grestore
)r   rT   r   r/   r   r1   r'   frozenZ	to_valuesrs   get_clip_rectangleget_clip_pathboundsr   rV   _get_clip_pathr   rt   r   )r!   gcr^   yr   	transformrK   rJ   r   r   ZhexlinesZmatrixZxscaleZyscaleZfighbboxclippathclippath_transclipZclipxZclipyZclipwZcliphidpsr"   r"   r#   
draw_image  s,    



zRendererPS.draw_imageFc             C   sJ   |rdd| j d | jd f}nd }t||||d ddddddgd	d
S )Ng        g      R@      m   l       cs   clTr*   )rr   rs   r   Zconvert_to_stringr/   )r!   r   r   r   r   r"   r"   r#   r     s    
zRendererPS._convert_pathc             C   s~   |t |f}| j|}|d krzdt| j }d| g}|| j||dd |dddg | jd	| || j|< |S )	Nzc%xz/%s {F)r   r   newpathz} bind def
r   )
r   r   r   r   r   r   extendrt   r   rT   )r!   r   Zclippath_transformrL   pidps_cmdr"   r"   r#   r     s    


zRendererPS._get_clip_pathc             C   sB   |dko|  dk}|jo|}| j||||d}| ||| dS )zI
        Draws a Path instance using the given affine transform.
        N)r   r   )Zget_hatch_pathZshould_simplifyr   _draw_ps)r!   r   r   r   rgbFacer   r   r   r"   r"   r#   	draw_path  s    
zRendererPS.draw_pathc             C   s  t r| jd |rtt|dkr2|d dkr2d}nB|d |d   krR|d krdn nd|d  }nd	|dd  }d
dddg}| }	| st| dkr| n
| d }
|	dko|
dk}|r|d|	  |	 }|d|  |
 }|d|  || j||dd |rT|r0|d |rD||dg |rT|d |rd|d |ddg x^|j|dd| jd | jd fddD ]6\}}t|r|dd \}}|d||f  qW d|}| j|||ddd dS )z
        Draw the markers defined by path at each of the positions in x
        and y.  path coordinates are points, x and y coords will be
        transformed by the transform
        z% draw_markers 
   r   r   Nr   r   z%1.3f setgrayz%1.3f %1.3f %1.3f setrgbcolorz/o {Zgsaver   	translatez%.1f setlinewidthz%d setlinejoinz%d setlinecapF)r   fillZgrestorestrokez
} bind defrp   )r   r   z%g %g or   )r   r   )debugPSrt   r   r   get_linewidthZget_forced_alphaget_rgbZ	get_alphar   get_joinstyleget_capstyler   r   Ziter_segmentsrr   rs   rT   r   )r!   r   Zmarker_pathZmarker_transr   transr   Zps_colorr   ZlwZalphar   jintcintverticescoder^   r   r   r"   r"   r#   draw_markers  sP     $ 





zRendererPS.draw_markersc             C   s`  t |dkrt |d jnd}| |||||}|d|  d |d | k }|stt| |||||||||	|
|||S | jj}g }xxt| |||D ]b\}\}}d| j	|f }d| ddg}|
| j||dd	 |d
g |d| |
| qW xR| |||||||||	|
|||D ],\}}}}}d|||f }| ||| qW |  j	d7  _	d S )Nr   r   r   zp%x_%xz/%s {r   r   F)r   z} bind def
r   z%g %g %sr   )r   r  Z_iter_collection_uses_per_pathr   draw_path_collectionrt   r   	enumerateZ_iter_collection_raw_pathsr   r   r   r   rT   Z_iter_collectionr   )r!   r   Zmaster_transformpathsZall_transformsZoffsetsZoffsetTransZ
facecolorsZ
edgecolorsZ
linewidthsZ
linestylesZantialiasedsZurlsZoffset_positionZlen_pathZuses_per_pathZshould_do_optimizationr   Z
path_codesr   r   r   r   r   xoyoZpath_idZgc0r   r   r"   r"   r#   r  6  s8    	


zRendererPS.draw_path_collectionTeX!c	             C   s   |  |||\}	}
}| }d| j }d| dd  }dddtd d	 d
}|| }d||f }d	}td rt|| |}| jd||||d |f  n0t|| || }| jd||||d |f  dt	  }| j
| |  jd7  _dS )z&
        draw a Text instance
        z
psmarker%dz%1.3f,%1.3f,%1.3fNr   z{\sffamily %s}z{\ttfamily %s})z
sans-serifZ	monospacezfont.familyr   z{\rmfamily %s}z\color[rgb]{%s} %sztext.latex.previewz/\psfrag{%s}[Bl][Bl][1][%f]{\fontsize{%f}{%f}%s}g      ?z/\psfrag{%s}[bl][bl][1][%f]{\fontsize{%f}{%f}%s}z5gsave
%(pos)s moveto
(%(thetext)s)
show
grestore
    r   )r   r   ru   r   r   r   rV   rv   r   r   rt   r   )r!   r   r^   r   r6   r   angler   mtextrJ   rK   Zblr~   thetextrx   ZfontcmdZtexZcorrposr   r"   r"   r#   draw_texa  s$    
 
zRendererPS.draw_texc	          	   C   s  | j j}	tr|	d t| dkr8| d dkr8dS |dkrT| ||||||S |rl| ||||||S td r| j|   | 	|}
|

 }| }d| }d}|
|d | }d}g }x|D ]}tt|d	}y|
|}W n$ tk
r   d	}|
d
}Y nX |dk	r*|
||}nd}|}||| 7 }|d|||f  ||| 7 }qW d|}dt  }| j | n.| |}
|
j|dtd | |
| | j|   |
jddd}| ||  d}g }d}d}x|D ]}t|}|
|}|dkr&td
}d}d}n
|
 |}|
j!|td}|dk	rX|
"||t#}nd}|}||d 7 }|d|||f  ||j$d 7 }qW d|}dt  }| j | dS )z'
        Draw a Text instance.
        z% text
r   r   r   NZTeXz	ps.useafmgMbP?Zquestion?z%f %f m /%s glyphshowr   z|gsave
/%(fontname)s findfont
%(fontsize)s scalefont
setfont
%(x)f %(y)f translate
%(angle)f rotate
%(thetext)s
grestore
    )r   r*   r`   z.notdefg      P@g      @zBgsave
%(x)f %(y)f translate
%(angle)f rotate
%(thetext)s
grestore
)%rt   r   r   r   r   r  draw_mathtextr   r   r   Zget_fontnamer   r   r   r   r\   Zget_width_from_char_namer&   Zget_width_charZget_kern_dist_from_namer   rT   r   r   r   r   r   Zpostscript_nameencoder/   r   get_char_indexZget_glyph_nameZ	load_charZget_kerningr   ZlinearHoriAdvance)r!   r   r^   r   r6   r   r  r   r  r   r   r}   r~   r   ZthisxZthisy	last_namer   cr   rr   Zkernr  r   Zps_nameZlastgindZccodegindZglyphr"   r"   r#   	draw_text  s     














zRendererPS.draw_textc             C   s   t  S )N)GraphicsContextPS)r!   r"   r"   r#   new_gc  s    zRendererPS.new_gcc             C   sd   t r| jd | j|d|\}}}	}
}| | | j|   |
 }dt	  }| j| dS )z>
        Draw the math text using matplotlib.mathtext
        z% mathtext
rp   zBgsave
%(x)f %(y)f translate
%(angle)f rotate
%(thetext)s
grestore
N)
r   rt   r   r   r   r   r   r   getvaluer   )r!   r   r^   r   r6   r   r  rr   rs   r   r   r   r  r   r"   r"   r#   r    s    

zRendererPS.draw_mathtextc             C   s    |  ||d|d| d S )N)r   r   r   )r   r   r   )draw_gouraud_trianglesreshape)r!   r   pointscolorsr   r"   r"   r#   draw_gouraud_triangle  s    z RendererPS.draw_gouraud_trianglec             C   sz  t |t |kst|jdks"t|jd dks4t|jd dksFt|jdksTt|jd dksft|jd dksxt|j}||d |d  df}||}||d |d  df}tj|ddd }tj|ddd }	t	d|	|  }
|\}}|	\}}tj
|d |d  fd	d
dgd}d|d< || |
 |d< |d d d df d |d< t| }| jdt   d S )Nr   r   r   r   r   )Zaxisi   l    )r   u1)r  z>u4)r   )r  r   )r   )Zdtyper   r  g     o@r  z
gsave
<< /ShadingType 4
   /ColorSpace [/DeviceRGB]
   /BitsPerCoordinate 32
   /BitsPerComponent 8
   /BitsPerFlag 8
   /AntiAlias true
   /Decode [ %(xmin)f %(xmax)f %(ymin)f %(ymax)f 0 1 0 1 0 1 ]
   /DataSource (%(stream)s)
>>
shfill
grestore
)r   AssertionErrorndimr   r  r   r   r   maxceilemptyrc   r   rt   r   r   )r!   r   r  r  r   r   Zflat_pointsZflat_colorsZ
points_minZ
points_maxZfactorZxminZyminZxmaxZymaxZ	streamarrstreamr"   r"   r#   r  
  s6    

z!RendererPS.draw_gouraud_trianglesTc             C   s  | j j}tr |r |d| d  | }|o.|}|oR|dk	oRt|dkpR|d dk}| }	|r| |  | }
| 	|
 |
 }| | | j|   | j| dd   |d | }|r|j\}}}}|d||||f  | \}}|r| ||}|d|  ||  |d |rx|s<|	rD|d | j|dd d	d
i |d |sp|	rx|d |	r| |	}|d |d| dd   |d|  |r|d |d dS )av  
        Emit the PostScript sniplet 'ps' with all the attributes from 'gc'
        applied.  'ps' must consist of PostScript commands to construct a path.

        The fill and/or stroke kwargs can be set to False if the
        'ps' string already includes filling and/or stroking, in
        which case _draw_ps is just supplying properties and
        clipping.
        z% r   Nr   g        zgsave
z %1.4g %1.4g %1.4g %1.4g clipbox
z%s
r   r   zfill
z	grestore
z	%f %f %f z%s setpattern fill grestore
zstroke
)rt   r   r   shouldstroker   Z	get_hatchr   r   r   r   r   r   r   Z
get_dashesr   r   r   r   r   r   r3   r   Zget_hatch_color)r!   r   r   r   r   r   commandr   Zmightstroker   r   r  Zcliprectr^   r   rJ   rK   r   r   r   Z
hatch_namer"   r"   r#   r   8  sT    


zRendererPS._draw_ps)rp   )r   )r   )r   )r   )r   )r   )r   )N)FN)N)N)r
  N)FN)TTN)(r;   r<   r=   __doc__r   r   r$   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r   r"   r"   r"   r#   rn      sH   
"





#'
	
0




:+
#
j.rn   c               @   s$   e Zd Zdd Zdd Zdd ZdS )r  c             C   s   ddddt |  S )Nr   r   r   )ZbuttroundZ
projecting)r   r   )r!   r"   r"   r#   r   x  s    zGraphicsContextPS.get_capstylec             C   s   ddddt |  S )Nr   r   r   )Zmiterr*  Zbevel)r   r   )r!   r"   r"   r#   r   }  s    zGraphicsContextPS.get_joinstylec             C   s,   |   dko*t|  dkp*|  d dkS )Ng        r   )r   r   r   )r!   r"   r"   r#   r'    s    zGraphicsContextPS.shouldstrokeN)r;   r<   r=   r   r   r'  r"   r"   r"   r#   r  w  s   r  c               @   sx   e Zd ZeZdZdd ZdddZdd Zd	d
 Z	dd Z
ddddddddZddddddZddddddZdS )FigureCanvasPSrp   c             C   s   d S )Nr"   )r!   r"   r"   r#   draw  s    zFigureCanvasPS.drawZ
PostscriptzEncapsulated Postscript)r   epsc             C   s   dS )Nr   r"   )r!   r"   r"   r#   get_default_filetype  s    z#FigureCanvasPS.get_default_filetypec             O   s   | j |df||S )Nr   )	_print_ps)r!   outfilerU   kwargsr"   r"   r#   print_ps  s    zFigureCanvasPS.print_psc             O   s   | j |df||S )Nr-  )r/  )r!   r0  rU   r1  r"   r"   r#   	print_eps  s    zFigureCanvasPS.print_epsNrJ   portrait)	papertypedpi	facecolor	edgecolororientationc         	   O   s   |d krt d }| }|dkr"n|tkr@td|dtf | }|dkrVd}
n|dkrdd}
ntd	| jd
 t d r| j|||||||
|f|	 n| j|||||||
|f|	 d S )Nzps.papersizeautoz*%s is not a valid papertype. Use one of %sz, 	landscapeTr4  Fz-Orientation must be "portrait" or "landscape"rp   ztext.usetex)	r   lowerrG   RuntimeErrorrT   figureZset_dpi_print_figure_tex_print_figure)r!   r0  formatr5  r6  r7  r8  r9  rU   r1  isLandscaper"   r"   r#   r/    s,      zFigureCanvasPS._print_psF)dryrunbbox_inches_restorec
      "         s  |dkt |tttddfrNttddd | }		ddd	d	}nt|r`d
	d}ntdj	 \
dkr|rt

n
t

|rt \}}nt \}}td rdks
|ks܈|kr|rt

t \}}nt

t \}}d|
  d|  jjj\}}}}}}|| }|| }d|r||||f\}}}}d|   d||||f j }j }j| j| |
rG dd dt}| _nt _j
j|dtj
||d}j| |
r$d
S j| j| |	d
k	rZd|	krZ|	d ndt d  	
fdd}td r t ~}tj|d}t|ddd}|| W d
Q R X td d krt| d! ntd d"kr
t| d! t || W d
Q R X n`|r^t!|} | sPt"|dd}d#d$ }!|!|_#n|}|| n"t|ddd}|| W d
Q R X d
S )%a  
        Render the figure to hardcopy.  Set the figure patch face and
        edge colors.  This is useful because some of the GUIs have a
        gray figure face color background and you'll probably want to
        override this on hardcopy

        If outfile is a string, it is interpreted as a file name.
        If the extension matches .ep* write encapsulated postscript,
        otherwise write a stand-alone PostScript file.

        If outfile is a file object, a stand-alone PostScript file is
        written into this file object.

        metadata must be a dictionary. Currently, only the value for
        the key 'Creator' is used.
        r-  PathLiker"   fspathc             S   s   | S )Nr"   )objr"   r"   r#   r_     s    z.FigureCanvasPS._print_figure.<locals>.<lambda>r*   r`   FNTz,outfile must be a path or a file-like objectr:  zps.usedistillerg      B@r   rp   Z   c               @   s   e Zd Zdd ZdS )z0FigureCanvasPS._print_figure.<locals>.NullWriterc             _   s   d S )Nr"   )r!   klr1  r"   r"   r#   r     s    z6FigureCanvasPS._print_figure.<locals>.NullWriter.writeN)r;   r<   r=   r   r"   r"   r"   r#   
NullWriter  s   rJ  )rw   )rD  Creatorzmatplotlib version z, http://matplotlib.org/c                s  rt d| d nt d| d 	r2t d	 | d t d | d td}|rhtjt|d}nt }t d| | d t d	 | d st d
 | d t d  | d st d| d t d| d t	t
}t d| d td s|t	j7 }t d| | d t d| d x<t
D ]4}| }x$|dD ]}t | | d q4W qW td sxj D ]\}}t	|rjt|}g }	x"|D ]}
||
}|	| qW td }t	|	dkrd}t|rtdn|   tt|| ||	 qjW t d| d t d| d s&t d| d t d| d t dt | d r^t d | d t dt
d d dd | d j }t|ts|d}t || d t d| d t d | d st d!| d |   d S )"Nz%!PS-Adobe-3.0 EPSF-3.0)filez%!PS-Adobe-3.0z	%%Title: z%%Creator: SOURCE_DATE_EPOCHz%a %b %d %H:%M:%S %Yz%%CreationDate: z%%Orientation: z%%DocumentPaperSizes: z%%%%BoundingBox: %d %d %d %dz
%%Pages: 1z%%EndCommentsz%%BeginPrologz	ps.useafmz/mpldict %d dict defzmpldict beginr   zps.fonttype   *   zxOpenType CFF fonts can not be saved using the internal Postscript backend at this time; consider using the Cairo backendendz%%EndPrologz%%Page: 1 1z%s translatez	%d rotatez
%s clipboxrp   r   r*   showpagez%%EOF)printr   getenvdatetimeutcfromtimestampr2   strftimetimectimer   psDefsr   r   r3   r4   valuesr   r  r   r   r=  flushr   fsencoderV   rt   r  rO   r'   r/   )rl   source_date_epochsource_dateNdictr   rE   Zfont_filenamecharsr   Z	glyph_idsr  r  ZfonttypeZcontent)r   creator_strrs   isEPSFr9  r5  ps_rendererrotationr!   titlerr   r  r	  r"   r#   print_figure_impl!  s    









z7FigureCanvasPS._print_figure.<locals>.print_figure_implztmp.psrJ   zlatin-1)re   ghostscript)ptyper   xpdfc               S   s   d S )Nr"   r"   r"   r"   r#   
do_nothing  s    z0FigureCanvasPS._print_figure.<locals>.do_nothing)$rO   r'   getattrr   r  r/   r   r5   r>  get_size_inchesrM   rG   r   r   r   get_facecolorget_edgecolorset_facecolorset_edgecolorobjectrt   r   _renderer_classr   r,  r   r   r   rT   rg   
gs_distillxpdf_distillrm   r   r   close)"r!   r0  rA  r6  r7  r8  r9  rB  r5  metadatarC  rD  r1  Zpassed_in_file_objectpaperHeight
paperWidthrE   r   rJ   rK   llxllyurxuryorigfacecolororigedgecolorrJ  r   rf  tmpdirtmpfilerl   Zrequires_unicoderj  r"   )r   ra  rs   rb  r9  r5  rc  rd  r!   re  rr   r  r	  r#   r@    s     
 





$\

zFigureCanvasPS._print_figurec
      0   
   K   sR  |dk}t |tr|}nt|r&d}ntdd| j_| j \}}d}d}| jjj\}}}}|}|}|| }|| }||||f}| j	 }| j
 }| j| | j| |
rG dd dt}| | _nt | _| j||| j|d}t| j|||||d	} | j|  |
rdS | j| | j| |	dk	rJd
|	krJ|	d
 }!ndt d }!t }"tj|"d}#t|#ddd}$td|$d |rtd| |$d td|! |$d td}%|%rtjt|%d}&nt  }&td|& |$d td| |$d td|$d t!t"}'td|$d td|' |$d td|$d x<t"D ]4}(|(# }(x$|($dD ]}t|# |$d q\W qDW td|$d td|$d td|$d td t%|| |$d td!t%|d |d dd |$d t| j& |$d td|$d td"|$d |$'  W dQ R X |r4d#}|| }}||||f}|rZ| j \})}*|r|*|) })}*nft(||}+|d$kr|+}t)|+ \})}*n@t)| \})}*||)ks||*kr|rt)|+ \})}*t*+d%||+ |, },|,- }-|,. }.t/|#|j0|-|.|)|*|}/t1d& d'kst1d( rt2|#||||/d) n t1d& d*kr:t3|#||||/d) t4|#| W dQ R X dS )+aS  
        If text.usetex is True in rc, a temporary pair of tex/eps files
        are created to allow tex to manage the text layout via the PSFrags
        package. These files are processed to yield the final ps or eps file.

        metadata must be a dictionary. Currently, only the value for
        the key 'Creator' is used.
        r-  Nz,outfile must be a path or a file-like objectrp   r   c               @   s   e Zd Zdd ZdS )z4FigureCanvasPS._print_figure_tex.<locals>.NullWriterc             _   s   d S )Nr"   )r!   rI  r1  r"   r"   r#   r     s    z:FigureCanvasPS._print_figure_tex.<locals>.NullWriter.writeN)r;   r<   r=   r   r"   r"   r"   r#   rJ    s   rJ  )rw   )rD  rK  zmatplotlib version z, http://matplotlib.org/ztmp.psrJ   zlatin-1)re   z%!PS-Adobe-3.0 EPSF-3.0)rL  z	%%Title: z%%Creator: rM  z%a %b %d %H:%M:%S %Yz%%CreationDate: z%%%%BoundingBox: %d %d %d %dz%%EndCommentsz%%BeginPrologz/mpldict %d dict defzmpldict beginr   rP  z%%EndPrologz%s translatez
%s clipboxrQ  Tr:  zUYour figure is too big to fit on %s paper. %s paper will be used to prevent clipping.zps.usedistillerrg  ztext.usetex)rh  r   rotatedri  )5rO   r'   r   r5   r>  r6  rl  r   r   rm  rn  ro  rp  rq  rt   r   rr  r   r,  r   r   r   r   rT   rg   rR  rS  rT  rU  r2   rV  rW  rX  r   rY  r3   r4   rV   r  r[  rM   rG   _loginfor   Zget_font_preambleZget_custom_preambleconvert_psfragsrv   r   rs  rt  rm   )0r!   r0  rA  r6  r7  r8  r9  rB  r5  rv  rC  rD  r1  rb  re  rr   rs   r  r	  rE   r   rJ   rK   ry  rz  r{  r|  r   r}  r~  rJ  rc  r   ra  r  r  rl   r]  r^  r_  r   rx  rw  Ztemp_papertyper   font_preamblecustom_preamblepsfrag_rotatedr"   r"   r#   r?    s    















z FigureCanvasPS._print_figure_tex)rp   rJ   rJ   r4  FNN)N)r;   r<   r=   rn   rr  Z	fixed_dpir,  Z	filetypesr.  r2  r3  r/  r@  r?  r"   r"   r"   r#   r+    s"      er+  c             C   sb  t j| d }| d }t| | | d }	| d }
| d }|dkrJd}nd}td r\d	}nd
}d|||||||d||t j|d f
 }y$t|	j	|td rdndd W n  t
k
r   td  Y nX |	dd}	|	dd}	ddd|	 g}td| ytj||tjd}W n> tjk
rZ } ztd|	|jdf W dd}~X Y nX t| dddd t j|t j|
g}t| ytj||tjd}W n> tjk
r } ztd!|
|jdf W dd}~X Y nX t| t | t||  t|  }d"|d#kr&d$}nd%}W dQ R X ts^x"t| d& D ]}t | qJW |S )'aj  
    When we want to use the LaTeX backend with postscript, we write PSFrag tags
    to a temporary postscript file, each one marking a position for LaTeX to
    render some text. convert_psfrags generates a LaTeX document containing the
    commands to convert those tags to text. LaTeX/dvips produces the postscript
    file that includes the actual text.
    r   z.epsz.texz.dviz.psr;  rH  ztext.latex.unicodez-\usepackage{ucs}
\usepackage[utf8x]{inputenc} aE  \documentclass{article}
%s
%s
%s
\usepackage[dvips, papersize={%sin,%sin}, body={%sin,%sin}, margin={0in,0in}]{geometry}
\usepackage{psfrag}
\usepackage[dvips]{graphicx}
\usepackage{color}
\pagestyle{empty}
\begin{document}
\begin{figure}
\centering
\leavevmode
%s
\includegraphics*[angle=%s]{%s}
\end{figure}
\end{document}
r   r   zutf-8r*   )re   zbYou are using unicode and latex, but have not enabled the Matplotlib 'text.latex.unicode' rcParam.\/~z\string~Zlatexz-interaction=nonstopmodez"%s"z%s)cwdr8   zgLaTeX was not able to process the following file:
%s

Here is the full report generated by LaTeX:
%s 

NZdvipsz-qz-R0z-ozgdvips was not able to process the following file:
%s

Here is the full report generated by dvips:
%s 

Z	Landscapei  TFz.*)r   r   r4   rh   ri   r   rT   pathlibr   Z
write_textUnicodeEncodeErrorr  r  r`   debugr,   check_outputSTDOUTCalledProcessErrorr=  outputr/   basenameremoverg   readr   glob)r  Zpsfragsr  r  rx  rw  r9  r  epsfileZ	latexfileZdvifilepsfiler  Zunicode_preambler6   r(  reportexcrl   r  r   r"   r"   r#   r  @  sp    	

$

$

	
r  FrB   c          
   C   s   |r
d}nd| }| d }t d }tj}tjr4d}	nd}	t|ddd	| d
|	 |d| | g}
t|
 ytj|
tj	d}W n8 tj
k
r } ztd|jd W dd}~X Y nX t| t|  t||  |rtjrt| ||d nt|  dS )z
    Use ghostscript's pswrite or epswrite device to distill a file.
    This yields smaller files without illegal encapsulated postscript
    operators. The output is low-level, converting text to outlines.
    z	-dEPSCropz-sPAPERSIZE=%sz.pszps.distiller.resZps2writeZpswritez-dBATCHz	-dNOPAUSEz-r%dz-sDEVICE=%sz-sOutputFile=%s)r8   zgghostscript was not able to process your image.
Here is the full report generated by ghostscript:
%s 

zutf-8N)r  )r   ps_backend_helperr%   r:   r'   r  r  r,   r  r  r  r=  r  r/   r   r  rh   ri   pstoeps)r  r-  rh  r   r  Zpaper_optionr  r6  r%   Zdevice_namer(  r  r  r"   r"   r#   rs    s4    
"

rs  c          
   C   sR  | d }| d }dddddd|r$d	nd
| | |g	}t | ytj|tjd}W n8 tjk
r }	 ztd|	jd W dd}	~	X Y nX t | dddd||g}t | ytj|tjd}W n8 tjk
r }	 ztd|	jd W dd}	~	X Y nX t | t	
|  t||  |r*t|  x"t| d D ]}
t	
|
 q:W dS )a
  
    Use ghostscript's ps2pdf and xpdf's/poppler's pdftops to distill a file.
    This yields smaller files without illegal encapsulated postscript
    operators. This distiller is preferred, generating high-level postscript
    output that treats text as text.
    z.pdfz.psZps2pdfz-dAutoFilterColorImages#falsez-dAutoFilterGrayImages#falsez-dAutoRotatePages#falsez-sGrayImageFilter#FlateEncodez-sColorImageFilter#FlateEncodez	-dEPSCropz-sPAPERSIZE#%s)r8   z]ps2pdf was not able to process your image.
Here is the full report generated by ps2pdf:
%s 

zutf-8NZpdftopsz-papermatchz-level2z_pdftops was not able to process your image.
Here is the full report generated by pdftops:
%s 

z.*)r  r  r,   r  r  r  r=  r  r/   r   r  rh   ri   r  r  )r  r-  rh  r   r  Zpdffiler  r(  r  r  r   r"   r"   r#   rt    sB    
"

"

rt  c       	      C   sd   | \}}}}|r"d|| df }nd}d||t |t |f }d||||f }d||g|fS )zw
    return a postscript header stringfor the given bbox lbrt=(l, b, r, t).
    Optionally, return rotate command.
    z%.2f %.2f translate
90 rotater   r  z%%%%BoundingBox: %d %d %d %dz)%%%%HiResBoundingBox: %.6f %.6f %.6f %.6fr   )r   r$  rT   )	Zlbrtr  rE   r   rd   trotate	bbox_infohires_bbox_infor"   r"   r#   get_bbox_header  s    r  z3.0c             C   s~  t j}|dddd|  g}t| tj|tjtjtjdd}|j|j }}t|	  |	 }t
| td|}|r| }ntd| d	d
 | dd D \}	}
}}|dkr|	d |
d |d |d f\}	}
}}nd|	| d }|
| d }|d |d  d }|d |d  d }|| || || || f\}	}
}}d|	|
t|t|f }d|	|
||f }d||gS )z
    Use ghostscript's bbox device to find the center of the bounding box.
    Return an appropriately sized bbox centered around that point. A bit of a
    hack.
    z-dBATCHz	-dNOPAUSEz-sDEVICE=bboxz%sT)stdinr)   r8   Z	close_fdsz%%HiResBoundingBox: .*zVGhostscript was not able to extract a bounding box.Here is the Ghostscript output:

%sc             S   s   g | ]}t |qS r"   )r   ).0r   r"   r"   r#   
<listcomp>A  s    zget_bbox.<locals>.<listcomp>Nr   r   r   r   z%%%%BoundingBox: %d %d %d %dz)%%%%HiResBoundingBox: %.6f %.6f %.6f %.6fr   )r  r%   r  r  r,   r-   r.   r)   r8   r  r  ra   searchr]   r=  r4   r   r$  rT   )r  r   r%   r(  pr)   r8   r  Z
bbox_foundrE   r   rd   r  r^   r   ZdxZdyr  r"   r"   r#   get_bbox)  s4    




"&$r  c       
   
   C   s,  |rt ||d\}}nd\}}| d }t|d}t| d}|j}x|D ]z}	|	drx|d |r||dd	  qJ|	d
r||	 |d |r||dd	  P qJ|r|	drqJ||	 qJW x4|D ],}	|	dr|d q|	drq||	 qW W dQ R X W dQ R X t|  t||  dS )z
    Convert the postscript to encapsulated postscript.  The bbox of
    the eps file will be replaced with the given *bbox* argument. If
    None, original bbox will be used.
    )r  )NNz.epswbrf   s   %!PSs   %!PS-Adobe-3.0 EPSF-3.0
r*   r   s   %%EndCommentssp   %%BeginProlog
save
countdictstack
mark
newpath
/showpage {} def
/setpagedevice {pop} def
%%EndProlog
%%Page 1 1
)s   %%Bounds   %%HiResBounds   %%DocumentMedias   %%Pagess   %%EOFsJ   cleartomark
countdictstack
exch sub { end } repeat
restore
showpage
%%EOF
s   %%PageBoundingBoxN)	r  rg   r   rI   r  r   r  rh   ri   )
r  r   r  r  r  r  ZepshZtmphr   liner"   r"   r#   r  V  s8    


	



 
r  z/m { moveto } bind defz/l { lineto } bind defz/r { rlineto } bind defz/c { curveto } bind defz/cl { closepath } bind defzU/box {
      m
      1 index 0 r
      0 exch r
      neg 0 r
      cl
    } bind defz</clipbox {
      box
      clip
      newpath
    } bind defc               @   s   e Zd ZeZdS )
_BackendPSN)r;   r<   r=   r+  ZFigureCanvasr"   r"   r"   r#   r    s   r  )FrB   NF)FrB   NF)F)NF)Ur)  r   rT  r  ior   r   Zloggingr   r  ra   rh   r,   sysZtempfiler   rW  Znumpyr   Z
matplotlibr   r   r   r   Zmatplotlib.afmr	   Zmatplotlib.backend_basesr
   r   r   r   r   Zmatplotlib.cbookr   r   r   r   Zmatplotlib.font_managerr   r   r   Zmatplotlib.ft2fontr   r   Zmatplotlib.ttconvr   Zmatplotlib.mathtextr   Zmatplotlib._mathtext_datar   Zmatplotlib.pathr   r   Zmatplotlib.transformsr   Z!matplotlib.backends.backend_mixedr   Z	getLoggerr;   r  Zbackend_versionr   rq  r   r  rG   rM   rR   rV   rc   rm   rn   r  r+  r  rs  rt  r  Z
deprecatedr  r  ZFigureManagerPSrY  Zexportr  r"   r"   r"   r#   <module>   s   
3     N   <o
4
3
-
=