3
$ßL]TH  ã               @   sX  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 ddlZddlZddlmZ ddlmZ ddd	gZd
d„ Zejdƒd.dd„ƒZdd„ Zd0dd„Zdd„ ZejdƒjZdd„ ZG dd„ deƒZG dd„ de ƒ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)d1d+d„Z*d,d-„ Z+dS )2zD
Provides a collection of utilities for comparing (image) results.

é    N)ÚPath)ÚTemporaryFile)ÚImageComparisonFailure)ÚcbookÚcompare_floatÚcompare_imagesÚcomparable_formatsc             C   s   t jj| ƒ\}}d|||f S )zU
    Make a new filename by inserting `purpose` before the file's
    extension.
    z%s-%s%s)ÚosÚpathÚsplitext)ÚfnameÚpurposeÚbaseÚext© r   úB/tmp/pip-install-edjban26/matplotlib/matplotlib/testing/compare.pyÚmake_test_filename   s    r   z3.0c             C   s¸   |dkr|dkrt dƒ‚d}|dk	r^t| | ƒ}||k r^dddddg}|djd	d
„ |D ƒƒ7 }|dk	r°t| | ƒ}| r‚|t| ƒ }||k r°dddddg}|djdd
„ |D ƒƒ7 }|p¶dS )z¦
    Fail if the floating point values are not close enough, with
    the given message.

    You can specify a relative tolerance, absolute tolerance, or both.

    Nz}You haven't specified a 'relTol' relative tolerance or a 'absTol' absolute tolerance function argument. You must specify one.Ú zExpected: {expected}zActual:   {actual}zAbs diff: {absDiff}zAbs tol:  {absTol}z
  c             S   s   g | ]}|j f tƒ Ž‘qS r   )ÚformatÚlocals)Ú.0Úliner   r   r   ú
<listcomp>9   s    z!compare_float.<locals>.<listcomp>zRel diff: {relDiff}zRel tol:  {relTol}c             S   s   g | ]}|j f tƒ Ž‘qS r   )r   r   )r   r   r   r   r   r   I   s    )Ú
ValueErrorÚabsÚjoin)ÚexpectedÚactualZrelTolZabsTolÚmsgZabsDiffÚtemplateZrelDiffr   r   r   r   "   s0    	c              C   sh   t jƒ } | d krtdƒ‚tjj| dƒ}yt|ƒjddd� W n tk
rP   d S X tj	|tj
ƒsdd S |S )Nz1Could not find a suitable configuration directoryZ
test_cacheT)ÚparentsÚexist_ok)ÚmplZget_cachedirÚRuntimeErrorr	   r
   r   r   ÚmkdirÚIOErrorÚaccessÚW_OK)ZcachedirÚ	cache_dirr   r   r   Úget_cache_dirN   s    r)   é   é   c             C   s”   t jƒ }t| dƒ�&}x|j|ƒ}|s&P |j|ƒ qW W d Q R X | jdƒrf|jttjdƒj	ƒj
dƒƒ n&| jdƒrŒ|jttjdƒj	ƒj
dƒƒ |jƒ S )NÚrbz.pdfÚgszutf-8z.svgÚinkscape)ÚhashlibÚmd5ÚopenÚreadÚupdateÚendswithÚstrr"   Ú_get_executable_infoÚversionÚencodeÚ	hexdigest)r
   Ú
block_sizer0   ÚfdÚdatar   r   r   Úget_file_hash\   s    



r=   c                s   ‡ fdd„}|S )Nc                s€   ˆ | |ƒ}t j|dt jt jd�}|jƒ \}}|jƒ }tjj|ƒ sF|r|ddj|ƒ }|rd|d| 7 }|rt|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
   Úexistsr   r%   )ÚoldÚnewZcmdlineÚpiper?   r@   Úerrcoder   )Úcmdr   r   Úconvertp   s    
z1make_external_conversion_command.<locals>.convertr   )rL   rM   r   )rL   r   Ú make_external_conversion_commando   s    rN   s   [^a-zA-Z0-9_@%+=:,./-]c             C   s$   t | ƒd kr| S d| jddƒ d S )Nó   's   '"'"')Ú_find_unsafe_bytesÚreplace)Úbr   r   r   Ú_shlex_quote_bytes…   s    rS   c               @   s   e Zd ZdS )Ú_ConverterErrorN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   rT   Š   s   rT   c               @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )Ú
_Converterc             C   s   d | _ tj| jƒ d S )N)Ú_procÚatexitÚregisterÚ__del__)Úselfr   r   r   Ú__init__�   s    z_Converter.__init__c             C   sR   | j rN| j jƒ  | j jƒ  x,td | j j| j j| j jgƒD ]}|jƒ  q8W d | _ d S )N)rY   ÚkillrF   ÚfilterÚstdinr?   r@   Úclose)r]   Ústreamr   r   r   r\   —   s    

z_Converter.__del__c             C   sP   t ƒ }xD| jjjdƒ}|st‚|j|ƒ |j|ƒrt|dt|ƒ … ƒS qW dS )z!Read until the prompt is reached.é   N)	Ú	bytearrayrY   r?   r2   rT   Úextendr4   ÚbytesÚlen)r]   Ú
terminatorÚbufÚcr   r   r   Ú_read_until¡   s    

z_Converter._read_untilN)rU   rV   rW   r^   r\   rl   r   r   r   r   rX   Ž   s   
rX   c               @   s   e Zd Zdd„ ZdS )Ú_GSConverterc             C   s  | j sVtjtjdƒjddgtjtjd�| _ y| jdƒ W n tk
rT   t	dƒ‚Y nX dd„ }| j j
jd	||ƒ d
 ||ƒ d ƒ | j j
jƒ  | jdƒ}| jdƒ}|s¸tjj|ƒ �r|rÌt|dd … ƒnd}| j j
jd| ƒ t|d | d jtjƒ dƒƒ‚d S )Nr-   z	-dNOPAUSEz-sDEVICE=png16m)ra   r?   s   
GSzFailed to start Ghostscriptc             S   s"   t j| ƒjddƒjddƒjddƒS )Nó   \s   \\ó   (s   \(ó   )s   \))r	   ÚfsencoderQ   )Únamer   r   r   Úencode_and_escapeº   s    
z0_GSConverter.__call__.<locals>.encode_and_escapes   << /OutputFile (s   ) >> setpagedevice (s   ) run flush
s   GSó   >rd   r   s   pop
rQ   )rY   rB   rC   r"   r6   Ú
executablerD   rl   rT   ÚOSErrorra   ÚwriteÚflushr	   r
   rG   Úintr   ÚdecodeÚsysÚgetfilesystemencoding)r]   ÚorigÚdestrs   ÚerrÚstackÚ
stack_sizer   r   r   Ú__call__®   s*    


z_GSConverter.__call__N)rU   rV   rW   r‚   r   r   r   r   rm   ­   s   rm   c               @   s   e Zd Zdd„ ZdS )Ú_SVGConverterc             C   sB  | j  s| j jƒ d k	r�tjjƒ }|jdd ƒ tj|d< tƒ }tj	dddgtj
tj
||d�| _ || j _y| jdƒ W n tk
rŽ   tdƒ‚Y nX ttttj||gƒƒ\}}d	|ksºd	|krÌtd
d„ ƒ||ƒS | j jj|d | d	 ƒ | j jjƒ  y| jdƒ W n< tk
�r<   | jjdƒ t| jjƒ jtjƒ dƒƒ‚Y nX d S )NZDISPLAYZINKSCAPE_PROFILE_DIRr.   z--without-guiz--shell)ra   r?   r@   Úenvs   
>z,Failed to start Inkscape in interactive modeó   
c             S   s   dd| d|gS )Nr.   z-zz--export-pngr   )rH   rI   r   r   r   Ú<lambda>ù   s    z(_SVGConverter.__call__.<locals>.<lambda>s    --export-png=r   rQ   )rY   Úpollr	   ÚenvironÚcopyÚpopÚdevnullr   rB   rC   rD   r@   rl   rT   rv   ÚmaprS   rq   rN   ra   rw   rx   Ú_stderrÚseekr   r2   rz   r{   r|   )r]   r}   r~   r„   r@   Zorig_bZdest_br   r   r   r‚   Ô   s:    



z_SVGConverter.__call__N)rU   rV   rW   r‚   r   r   r   r   rƒ   Ó   s   rƒ   c               C   sh   yt jdƒ W n tk
r"   Y nX tƒ  td< td< yt jdƒ W n tk
rX   Y nX tƒ td< d S )Nr-   ÚpdfÚepsr.   Úsvg)r"   r6   ÚFileNotFoundErrorrm   Ú	converterrƒ   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
    -------
    supported_formats : list of str
        E.g. ``['png', 'pdf', 'svg', 'eps']``.

    Úpng)r•   )r“   r   r   r   r   r      s    c             C   s4  | j ddƒ\}}|tkrZd| }ddlm} |ƒ rFddl}|j|ƒ nddlm} ||ƒ‚|d | d	 }tj	j
| ƒs‚td
|  ƒ‚tj	j
|ƒ sªtj|ƒjtj| ƒjk �r0|r¶tƒ }	nd}	|	dk	�rt| ƒ}
tj	j|ƒd }tj	j|	|
| ƒ}tj	j
|ƒ�rtj||ƒ |S t| | |ƒ |	dk	�r0tj||ƒ |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.
    Ú.rd   z)Don't know how to convert %s files to png)Úis_called_from_pytestr   N)ÚSkipTestÚ_z.pngz'%s' does not exist)Úrsplitr“   r   r—   ÚpytestÚskipZnoser˜   r	   r
   rG   r%   ÚstatÚst_mtimer)   r=   r   r   ÚshutilÚcopyfile)ÚfilenameÚcacher   Ú	extensionÚreasonr—   r›   r˜   Znewnamer(   Z
hash_valueZnew_extZcached_filer   r   r   rM   .  s8    	

rM   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 )
Né   é   r�   r�   r*   iùÿÿÿéüÿÿÿiùÿÿÿr§   )Úshapery   )
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 |j ƒƒ‚tj| | jtƒd jƒ ƒS )zHCalculate the per-pixel errors, then compute the root mean square error.z9Image sizes do not match expected size: {} actual size {}r*   )r¨   r   r   ÚnpÚsqrtÚastypeÚfloatZmean)rª   r©   r   r   r   Úcalculate_rmsi  s
    r³   Fc                sŽ  ddl m} tjj|ƒs$td| ƒ‚tj|ƒjdkr@td| ƒ‚| jdƒd }tjj| ƒsft	d|  ƒ‚|dkr‚t
|d	ƒ}t
| d
ƒ} |j| ƒ}|j|ƒ}|dd…dd…dd…f }|dd…dd…dd…f }t||| |ƒ\}}t|dƒ}|dk�rtj||ƒ�rdS |jtjƒ}|jtjƒ}t||ƒ}	|	|k�r2dS t| ||ƒ t|	t| ƒt|ƒt|ƒ|d�‰ |�sŠddddddg}
dj‡ 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
    -------
    comparison_result : 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)

    r   )Ú_pngzOutput image %s does not exist.zOutput image file %s is empty.r–   rd   z!Baseline image %r does not exist.r•   FTNé   zfailed-diff)Úrmsr   r   Z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   )r   r   )Úresultsr   r   r   Ü  s    z"compare_images.<locals>.<listcomp>éÿÿÿÿ)Ú
matplotlibr´   r	   r
   rG   Ú	Exceptionr�   Úst_sizeÚsplitr%   rM   Zread_png_intr®   r   r¯   Zarray_equalr±   Zint16r³   Úsave_diff_imageÚdictr5   r   )r   r   r·   Zin_decoratorr´   r£   rª   r©   Z
diff_imager¶   r   r   )r¸   r   r   s  sL    1








c             C   s&  ddl m} |j| ƒddd…f }|j|ƒddd…f }t||| |ƒ\}}tj|ƒjtƒ}tj|ƒjtƒ}|j|jkrŠt	dj
|j|jƒƒ‚tj|| ƒ}|d9 }tj|ddƒj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< |j||ƒ 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   )r´   .Nrµ   z9Image sizes do not match expected size: {} actual size {}éÿ   é
   r¦   )Zdtypeiö	  )rº   r´   Zread_pngr®   r¯   Úarrayr±   r²   r¨   r   r   r   ZclipZuint8ÚemptyZ	write_png)r   r   Úoutputr´   rª   r©   Zabs_diff_imageZsave_image_npÚheightÚwidthÚdepthZ
with_alphar   r   r   r¾   à  s*    
r¾   )NNé   )rÈ   )F),Ú__doc__rZ   r/   r	   Zpathlibr   ÚrerŸ   rB   r{   Útempfiler   Znumpyr¯   rº   r"   Zmatplotlib.testing.exceptionsr   r   Ú__all__r   Ú
deprecatedr   r)   r=   rN   ÚcompileÚsearchrP   rS   r»   rT   ÚobjectrX   rm   rƒ   r”   r“   r   rM   r®   r³   r   r¾   r   r   r   r   Ú<module>   sF   
	+
&60

m