B
    Mô`UB  ã               @   sZ  d Z ddlZddlZddlZddlmZ ddlZddlZddlZddl	Z	ddl
mZmZ ddlZddlmZ ddlZddlmZ ddlmZ dd	gZd
d„ Zdd„ Zd,dd„Ze d¡dd„ ƒZe d¡jZdd„ ZG dd„ de ƒZ!G dd„ dƒZ"G dd„ de"ƒZ#G dd„ de"ƒZ$dd „ Z%i Z&e%ƒ  d!d	„ Z'd"d#„ Z(d$d%„ Z)d&d'„ Z*d-d)d„Z+d*d+„ Z,dS ).z(
Utilities for comparing image results.
é    N)ÚPath)ÚTemporaryDirectoryÚTemporaryFile)ÚImage)Úcbook)ÚImageComparisonFailureÚcompare_imagesÚcomparable_formatsc             C   s   t j | ¡\}}d|||f S )zQ
    Make a new filename by inserting *purpose* before the file's extension.
    z%s-%s%s)ÚosÚpathÚsplitext)ÚfnameÚpurposeÚbaseÚext© r   ú>/tmp/pip-unpacked-wheel-0c1wfn4v/matplotlib/testing/compare.pyÚmake_test_filename   s    r   c              C   s$   t t ¡ dƒ} | jddd� t| ƒS )NZ
test_cacheT)ÚparentsÚexist_ok)r   ÚmplZget_cachedirÚmkdirÚstr)Ú	cache_dirr   r   r   Úget_cache_dir!   s    r   é   c          	   C   sœ   t  ¡ }t| dƒ�&}x| |¡}|s&P | |¡ qW W d Q R X t| ƒjdkrj| tt 	d¡j
ƒ d¡¡ n*t| ƒjdkr”| tt 	d¡j
ƒ d¡¡ | ¡ S )NÚrbz.pdfÚgszutf-8z.svgÚinkscape)ÚhashlibÚmd5ÚopenÚreadÚupdater   Úsuffixr   r   Ú_get_executable_infoÚversionÚencodeÚ	hexdigest)r   Ú
block_sizer    ÚfdÚdatar   r   r   Úget_file_hash'   s    

r,   z3.3c                s   ‡ fdd„}|S )Nc                s~   ˆ | |ƒ}t j|dt jt jd�}| ¡ \}}| ¡ }tj |¡rD|rzdd |¡ }|rb|d| 7 }|rr|d| 7 }t	|ƒ‚d S )NT)Úuniversal_newlinesÚstdoutÚstderrzConversion command failed:
%s
ú zStandard output:
%s
zStandard error:
%s
)
Ú
subprocessÚPopenÚPIPEÚcommunicateÚwaitr
   r   ÚexistsÚjoinÚIOError)ÚoldÚnewZcmdlineÚpiper.   r/   ÚerrcodeÚmsg)Úcmdr   r   Úconvert<   s    
z1make_external_conversion_command.<locals>.convertr   )r>   r?   r   )r>   r   Ú make_external_conversion_command:   s    r@   s   [^a-zA-Z0-9_@%+=:,./-]c             C   s$   t | ƒd kr| S d|  dd¡ d S )Nó   's   '"'"')Ú_find_unsafe_bytesÚreplace)Úbr   r   r   Ú_shlex_quote_bytesQ   s    rE   c               @   s   e Zd ZdS )Ú_ConverterErrorN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   rF   V   s   rF   c               @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )Ú
_Converterc             C   s   d | _ t | j¡ d S )N)Ú_procÚatexitÚregisterÚ__del__)Úselfr   r   r   Ú__init__[   s    z_Converter.__init__c             C   sR   | j rN| j  ¡  | j  ¡  x,td | j j| j j| j jgƒD ]}| ¡  q8W d | _ d S )N)rK   Úkillr5   ÚfilterÚstdinr.   r/   Úclose)rO   Ústreamr   r   r   rN   c   s    

z_Converter.__del__c             C   sP   t ƒ }xD| jj d¡}|st‚| |¡ | |¡rt|dt|ƒ … ƒS qW dS )z!Read until the prompt is reached.é   N)	Ú	bytearrayrK   r.   r"   rF   ÚextendÚendswithÚbytesÚlen)rO   Ú
terminatorÚbufÚcr   r   r   Ú_read_untilm   s    

z_Converter._read_untilN)rG   rH   rI   rP   rN   r_   r   r   r   r   rJ   Z   s   
rJ   c               @   s   e Zd Zdd„ ZdS )Ú_GSConverterc          
   C   s  | j shtjt d¡jdddgtjtjd�| _ y|  d¡ W n, tk
rf } zt	dƒ|‚W d d }~X Y nX dd	„ }| j j
 d
||ƒ d ||ƒ d ¡ | j j
 ¡  |  d¡}|  d¡}|sÈtj |¡�s|rÜt|dd … ƒnd}| j j
 d| ¡ t|d | d  t ¡ d¡ƒ‚d S )Nr   z	-dNOSAFERz	-dNOPAUSEz-sDEVICE=png16m)rS   r.   s   
GSzFailed to start Ghostscriptc             S   s"   t  | ¡ dd¡ dd¡ dd¡S )Nó   \s   \\ó   (s   \(ó   )s   \))r
   ÚfsencoderC   )Únamer   r   r   Úencode_and_escape†   s    
z0_GSConverter.__call__.<locals>.encode_and_escapes   << /OutputFile (s   ) >> setpagedevice (s   ) run flush
s   GSó   >rV   r   s   pop
rC   )rK   r1   r2   r   r%   Ú
executabler3   r_   rF   ÚOSErrorrS   ÚwriteÚflushr
   r   r6   Úintr   ÚdecodeÚsysÚgetfilesystemencoding)rO   ÚorigÚdestÚerrrf   ÚstackÚ
stack_sizer   r   r   Ú__call__z   s*    


z_GSConverter.__call__N)rG   rH   rI   ru   r   r   r   r   r`   y   s   r`   c                   s$   e Zd Zdd„ Z‡ fdd„Z‡  ZS )Ú_SVGConverterc       
   
   C   sÐ  t  d¡jdk }|rdnd}t| dƒs.tƒ | _| jrB| j ¡ d k	rÐtj	dtj
dœ–}tƒ }tj|rlddd	gndd	gtjtj||| jjd
�| _|| j_y|  |¡ W n, tk
rÎ } ztdƒ|‚W d d }~X Y nX t| jjt d¡ƒ}t| jjt d¡ƒ}	y| t|ƒ ¡ ¡ W n" tk
�r0   t ||¡ Y nX | jj |�rDdnd¡ | jj ¡  y|  |¡ W nP tk
�r´ } z0| jj d¡ t| jj ¡   t! "¡ d¡ƒ|‚W d d }~X Y nX t #|¡ t $|	|¡ d S )Nr   Ú1s   
>s   > Ú_tmpdirÚ )ZDISPLAYZINKSCAPE_PROFILE_DIRz--without-guiz--shell)rS   r.   r/   ÚenvÚcwdz,Failed to start Inkscape in interactive modes   f.svgs   f.pngs   f.svg --export-png=f.png
s;   file-open:f.svg;export-filename:f.png;export-do;file-close
r   rC   )%r   r%   r&   Úhasattrr   rx   rK   Úpollr
   ÚenvironÚdevnullr   r1   r2   r3   re   r/   r_   rF   ri   r   ÚfsdecodeÚ
symlink_toÚresolveÚshutilÚcopyfilerS   rj   rk   Úseekr   r"   rm   rn   ro   ÚremoveÚmove)
rO   rp   rq   Zold_inkscaper\   rz   r/   rr   Zinkscape_origZinkscape_destr   r   r   ru       sP    


"
z_SVGConverter.__call__c                s"   t ƒ  ¡  t| dƒr| j ¡  d S )Nrx   )ÚsuperrN   r|   rx   Úcleanup)rO   )Ú	__class__r   r   rN   Þ   s    

z_SVGConverter.__del__)rG   rH   rI   ru   rN   Ú__classcell__r   r   )rŠ   r   rv   Ÿ   s   >rv   c               C   sl   yt  d¡ W n t jk
r$   Y nX tƒ  td< td< yt  d¡ W n t jk
r\   Y nX tƒ td< d S )Nr   ÚpdfÚepsr   Úsvg)r   r%   ZExecutableNotFoundErrorr`   Ú	converterrv   r   r   r   r   Ú_update_converterä   s    r�   c               C   s   dt •S )z¹
    Return the list of file formats that `.compare_images` can compare
    on this system.

    Returns
    -------
    list of str
        E.g. ``['png', 'pdf', 'svg', 'eps']``.

    Úpng)r‘   )r�   r   r   r   r   r	   û   s    c             C   s  t | ƒ}| ¡ st|› d�ƒ‚|jdd… tkrLddl}| d|j› d�¡ |j|j› d|jdd… › d� }| ¡ rŒ| 	¡ j
| 	¡ j
k �r|ršt tƒ ƒnd}|dk	rØt|ƒ}|||j  }| ¡ rØt ||¡ t|ƒS t|jdd…  ||ƒ |dk	�rt ||¡ t|ƒS )	at  
    Convert the named file to png; return the name of the created file.

    If *cache* is True, the result of the conversion is cached in
    `matplotlib.get_cachedir() + '/test_cache/'`.  The caching is based on a
    hash of the exact contents of the input file.  There is no limit on the
    size of the cache, so it may need to be manually cleared periodically.
    z does not existrV   Nr   zDon't know how to convert z files to pngÚ_z.png)r   r6   r8   r$   r�   ÚpytestÚskipÚparentÚstemÚstatÚst_mtimer   r,   rƒ   r„   r   )ÚfilenameÚcacher   r“   Únewpathr   Z
hash_valueZcached_pathr   r   r   r?   	  s&    	"
r?   c       
      C   s”   | dd… dkrŒ|dd… dkrŒ|j \}}}|j \}}}	|t|d |d  ƒt|d |d  ƒ…t|d |d  ƒt|d |d  ƒ…f }||fS )Niùÿÿÿéüÿÿÿr�   rŒ   é   )Úshaperl   )
Zactual_pathÚactual_imageZexpected_pathÚexpected_imageZawZahÚadÚewÚehZedr   r   r   Úcrop_to_same.  s     >r¤   c             C   s<   | j |j kr td | j |j ¡ƒ‚t | |  t¡d  ¡ ¡S )zR
    Calculate the per-pixel errors, then compute the root mean square error.
    z9Image sizes do not match expected size: {} actual size {}r�   )rž   r   ÚformatÚnpÚsqrtÚastypeÚfloatZmean)r    rŸ   r   r   r   Úcalculate_rms9  s
    rª   Fc       
         sz  t  |¡}t j |¡s"td| ƒ‚t  |¡jdkr>td| ƒ‚t  | ¡} t j | ¡s`td|  ƒ‚|  d¡d }|dkrŽt	|dd	�}t	| d
d	�} t
 t | ¡ 	d¡¡}t
 t |¡ 	d¡¡}t||| |ƒ\}}t|dƒ}|dkrît
 ||¡rîdS | t
j¡}| t
j¡}t||ƒ}||k�rdS t| ||ƒ t|t| ƒt|ƒt|ƒ|d�‰ |�svddddddg}	d ‡ fdd„|	D ƒ¡‰ ˆ S )a+  
    Compare two "image" files checking differences within a tolerance.

    The two given filenames may point to files which are convertible to
    PNG via the `.converter` dictionary. The underlying RMS is calculated
    with the `.calculate_rms` function.

    Parameters
    ----------
    expected : str
        The filename of the expected image.
    actual : str
        The filename of the actual image.
    tol : float
        The tolerance (a color value difference, where 255 is the
        maximal difference).  The test fails if the average pixel
        difference is greater than this value.
    in_decorator : bool
        Determines the output format. If called from image_comparison
        decorator, this should be True. (default=False)

    Returns
    -------
    None or dict or str
        Return *None* if the images are equal within the given tolerance.

        If the images differ, the return value depends on  *in_decorator*.
        If *in_decorator* is true, a dict with the following entries is
        returned:

        - *rms*: The RMS of the image difference.
        - *expected*: The filename of the expected image.
        - *actual*: The filename of the actual image.
        - *diff_image*: The filename of the difference image.
        - *tol*: The comparison tolerance.

        Otherwise, a human-readable multi-line string representation of this
        information is returned.

    Examples
    --------
    ::

        img1 = "./baseline/plot.png"
        img2 = "./output/plot.png"
        compare_images(img1, img2, 0.001)

    zOutput image %s does not exist.r   zOutput image file %s is empty.z!Baseline image %r does not exist.Ú.éÿÿÿÿr‘   F)rš   TÚRGBzfailed-diffN)ÚrmsÚexpectedÚactualZdiffÚtolz!Error: Image files did not match.zRMS Value: {rms}zExpected:  
    {expected}zActual:    
    {actual}zDifference:
    {diff}zTolerance: 
    {tol}z
  c                s   g | ]}|j f ˆ Ž‘qS r   )r¥   )Ú.0Úline)Úresultsr   r   ú
<listcomp>­  s    z"compare_images.<locals>.<listcomp>)r
   Úfspathr   r6   Ú	Exceptionr—   Úst_sizer8   Úsplitr?   r¦   Úasarrayr   r!   r¤   r   Zarray_equalr¨   Zint16rª   Úsave_diff_imageÚdictr   r7   )
r¯   r°   r±   Zin_decoratorÚ	extensionr    rŸ   Z
diff_imager®   Útemplater   )r´   r   r   I  sJ    1





c             C   s   t  t | ¡ d¡¡}t  t |¡ d¡¡}t||| |ƒ\}}t  |¡ t¡}t  |¡ t¡}|j	|j	kr~t
d |j	|j	¡ƒ‚t  || ¡}|d9 }t  |dd¡ t j¡}|j	\}}}	|	dkròt j||dft jd�}
||
d	d	…d	d	…dd…f< |
}d|d	d	…d	d	…df< t |¡j|d
d� d	S )zÏ
    Parameters
    ----------
    expected : str
        File path of expected image.
    actual : str
        File path of actual image.
    output : str
        File path to save difference image to.
    r­   z9Image sizes do not match expected size: {} actual size {}iö	  r   éÿ   é   é   )ZdtypeNr‘   )r¥   )r¦   rº   r   r!   r?   r¤   Úarrayr¨   r©   rž   r   r¥   ÚabsZclipZuint8ÚemptyZ	fromarrayÚsave)r¯   r°   Úoutputr    rŸ   Zabs_diff_imageZsave_image_npÚheightÚwidthÚdepthZ
with_alphar   r   r   r»   ±  s(    r»   )r   )F)-Ú__doc__rL   r   r
   Úpathlibr   Úrerƒ   r1   rn   Útempfiler   r   Znumpyr¦   ZPILr   Z
matplotlibr   r   Zmatplotlib.testing.exceptionsr   Ú__all__r   r   r,   Ú
deprecatedr@   ÚcompileÚsearchrB   rE   r·   rF   rJ   r`   rv   r�   r�   r	   r?   r¤   rª   r   r»   r   r   r   r   Ú<module>   sD   
&E%
h