B
    &[_~H                 @   s  d dl mZ d dlmZ ddlmZ d dlmZ d dl	Z	ddl
mZmZmZ d dlZddlmZmZ d dlZyd dlZdZW n ek
r   d	ZY nX yd d
lmZ dZW n ek
r   d	ZY nX g ZdddZdddZdd Zdddi dddddddddddddddfddZdS )    N)ColorscaleValidator   )apply_default_cascade)BytesIO)rescale_intensity_integer_ranges_integer_types)Writer
from_arrayTF)Imagepil   pngc          	   C   s  |dk s|dkrt dd}| jdkr,d}nH| jdkrJ| jd dkrJd	}n*| jdkrl| jd d
krld}d}nt d|dkrtrdnd}|dkr|dkrt d|dkrD| j}| j}|dkr| |d |d |d  f} t|d |d |dk||d}t| |d}	d}
t ,}|||	j	 |
t
| d }W dQ R X nxtsRtdt| }|dksp|dkrzd}
d}nd}
d}t .}|j|||d |
t
| d }W dQ R X |S )a  Converts a numpy array of uint8 into a base64 png string.

    Parameters
    ----------
    img: ndarray of uint8
        array image
    backend: str
        'auto', 'pil' or 'pypng'. If 'auto', Pillow is used if installed,
        otherwise pypng.
    compression: int, between 0 and 9
        compression level to be passed to the backend
    ext: str, 'png' or 'jpg'
        compression format used to generate b64 string
    r   	   z*compression level must be between 0 and 9.F   L   ZRGBr   ZRGBATzInvalid image shapeautor   Zpypngr   z6jpg binary strings are only available with PIL backendr   )Z	greyscalealphacompression)modezdata:image/png;base64,zutf-8Nzapillow needs to be installed to use `backend='pil'. Pleaseinstall pillow or use `backend='pypng'.ZjpgZjpegzdata:image/jpeg;base64,)formatZcompress_level)
ValueErrorndimshapepil_importedZreshaper	   r
   r   writeZrowsbase64	b64encodegetvaluedecodeImportErrorr   Z	fromarraysave)imgbackendr   extr   r   r   shwZimg_pngprefixstreamZbase64_stringZpil_img r+   :/tmp/pip-install-l29rncou/plotly/plotly/express/_imshow.py_array_to_b64str   sP    

$
"r-   maxc             C   s   |dkrdnd}| d kr| S t | r6| gd |g S t| dkrTt| d |g S t| dkrnt| |g S t| dkr~| S tdt|  d S )Nr.      r   r   r   r   z\zmax can be a scalar, or an iterable of length 1, 3 or 4. A value of %s was passed for zmax.)npZisscalarlenlistr   str)zr   r   r+   r+   r,   _vectorize_zvalue\   s    
r5   c             C   sj   | j j}d}|tkr t| d S | t|   }|d| krBdS |d| krRdS |d| krbdS dS d S )Ng?r   r/   i  l        )dtypetyper   r   r0   isfiniter.   )r$   dtZrtolZim_maxr+   r+   r,   _infer_zmax_from_typeo   s    r:   r   c       &         s>  t  }t| | }tr&t tjr&|r6td jd  jd  }}x<||gD ]0}t	
 j| jt	jrV j| t j|< qVW |dkr j| }|dkr j| }|dkrd}|dddkr||d< |dddkr||d< |dddkr:tjj |d< |d d	d
|d< nt drt jdr|dkrP j}|dddkrt jdr jjp|d|d< t drt jdr|dkr j}|dddkrt jdrވ jjpd|d< |dddkrd|d< |dddkrd|d< |dddkr,d|d< |dkr:d}t tjr\|rVtdd}nd}t	  |dkr jdko| } jt	jkrd t	j  |	dk	r|	d |	d |dkr܈ jdkrdnd}|dkr,dk	s|rdkr  dk	s|rddkrd   n8dkrL jt	jkrLt! dkrddk	rdd jdkrh|sh|dk	r j"d t#|krtd|dk	r j"d t#|krtdt$j%|| dd}|dkrdnd}t&t&|dd }|dkrt&dd!d"|d#< d!|d$ d%< t'd&d'}t&|(|d( |d)|d< |d rt&|d d*|d d+< nL jdkr j"d, d-ks jdkr|rd}dk	rȈdk	rt)d.d/t)d0d/ |rZdkrdkr }d}nP jdkrt* d d ft	jd1}n&t	+ fd2d3t, j"d, D }t-||||d4}t$j.|d5}n* j"d, dkrnd6nd7} t$j. | d8}i }|dkrt&dd|d$< ntd9t j" t& }!x$d:D ]}"||" r||" |!|"< qW |d; r|d; |!d<< n |d= j/j0j1dkrd>d?i|!d@< t$j2||dA}#|#3|! |rn|rnt	4 |ksndB|d pZd|d pfdf }$nz|dC dDkrdE}%n8 jdkrdF}%n& jdkr j"d, dkrdG}%ndE}%dH|d pd|d pd|d pd|%f }$|#j5|$dI |d r|#j6|d d* |d r(|#j7|d d* |#j3|d= ddJ |#S )Ka  
    Display an image, i.e. data on a 2D regular raster.

    Parameters
    ----------

    img: array-like image, or xarray
        The image data. Supported array shapes are

        - (M, N): an image with scalar data. The data is visualized
          using a colormap.
        - (M, N, 3): an image with RGB values.
        - (M, N, 4): an image with RGBA values, i.e. including transparency.

    zmin, zmax : scalar or iterable, optional
        zmin and zmax define the scalar range that the colormap covers. By default,
        zmin and zmax correspond to the min and max values of the datatype for integer
        datatypes (ie [0-255] for uint8 images, [0, 65535] for uint16 images, etc.). For
        a multichannel image of floats, the max of the image is computed and zmax is the
        smallest power of 256 (1, 255, 65535) greater than this max value,
        with a 5% tolerance. For a single-channel image, the max of the image is used.
        Overridden by range_color.

    origin : str, 'upper' or 'lower' (default 'upper')
        position of the [0, 0] pixel of the image array, in the upper left or lower left
        corner. The convention 'upper' is typically used for matrices and images.

    labels : dict with str keys and str values (default `{}`)
        Sets names used in the figure for axis titles (keys ``x`` and ``y``),
        colorbar title and hoverlabel (key ``color``). The values should correspond
        to the desired label to be displayed. If ``img`` is an xarray, dimension
        names are used for axis titles, and long name for the colorbar title
        (unless overridden in ``labels``). Possible keys are: x, y, and color.

    x, y: list-like, optional
        x and y are used to label the axes of single-channel heatmap visualizations and
        their lengths must match the lengths of the second and first dimensions of the
        img argument. They are auto-populated if the input is an xarray.

    color_continuous_scale : str or list of str
        colormap used to map scalar data to colors (for a 2D image). This parameter is
        not used for RGB or RGBA images. If a string is provided, it should be the name
        of a known color scale, and if a list is provided, it should be a list of CSS-
        compatible colors.

    color_continuous_midpoint : number
        If set, computes the bounds of the continuous color scale to have the desired
        midpoint. Overridden by range_color or zmin and zmax.

    range_color : list of two numbers
        If provided, overrides auto-scaling on the continuous color scale, including
        overriding `color_continuous_midpoint`. Also overrides zmin and zmax. Used only
        for single-channel images.

    title : str
        The figure title.

    template : str or dict or plotly.graph_objects.layout.Template instance
        The figure template name or definition.

    width : number
        The figure width in pixels.

    height: number
        The figure height in pixels.

    aspect: 'equal', 'auto', or None
      - 'equal': Ensures an aspect ratio of 1 or pixels (square pixels)
      - 'auto': The axes is kept fixed and the aspect ratio of pixels is
        adjusted so that the data fit in the axes. In general, this will
        result in non-square pixels.
      - if None, 'equal' is used for numpy arrays and 'auto' for xarrays
        (which have typically heterogeneous coordinates)

    contrast_rescaling: 'minmax', 'infer', or None
        how to determine data values corresponding to the bounds of the color
        range, when zmin or zmax are not passed. If `minmax`, the min and max
        values of the image are used. If `infer`, a heuristic based on the image
        data type is used.

    binary_string: bool, default None
        if True, the image data are first rescaled and encoded as uint8 and
        then passed to plotly.js as a b64 PNG string. If False, data are passed
        unchanged as a numerical array. Setting to True may lead to performance
        gains, at the cost of a loss of precision depending on the original data
        type. If None, use_binary_string is set to True for multichannel (eg) RGB
        arrays, and to False for single-channel (2D) arrays. 2D arrays are
        represented as grayscale and with no colorbar if use_binary_string is
        True.

    binary_backend: str, 'auto' (default), 'pil' or 'pypng'
        Third-party package for the transformation of numpy arrays to
        png b64 strings. If 'auto', Pillow is used if installed,  otherwise
        pypng.

    binary_compression_level: int, between 0 and 9 (default 4)
        png compression level to be passed to the backend when transforming an
        array to a png b64 string. Increasing `binary_compression` decreases the
        size of the png string, but the compression step takes more time. For most
        images it is not worth using levels greater than 5, but it's possible to
        test `len(fig.data[0].source)` and to time the execution of `imshow` to
        tune the level of compression. 0 means no compression (not recommended).

    binary_format: str, 'png' (default) or 'jpg'
        compression format used to generate b64 string. 'png' is recommended
        since it uses lossless compression, but 'jpg' (lossy) compression can
        result if smaller binary strings for natural images.

    Returns
    -------
    fig : graph_objects.Figure containing the displayed image

    See also
    --------

    plotly.graph_objects.Image : image trace
    plotly.graph_objects.Heatmap : heatmap trace

    Notes
    -----

    In order to update and customize the returned figure, use
    `go.Figure.update_traces` or `go.Figure.update_layout`.

    If an xarray is passed, dimensions names and coordinates are used for
    axes labels and ticks.
    z{It is not possible to use binary image strings for xarrays.Please pass your data as a numpy array instead using`img.values`r   r   Nr   xycolor
z<br>columns__len__name indexequalz0Binary strings cannot be used with pandas arraysTFr   r/   r   ZminmaxZinferzZThe length of the y vector must match the length of the first dimension of the img matrix.z[The length of the x vector must match the length of the second dimension of the img matrix.Z
coloraxis1)r;   r<   r4   Z	coloraxislowerreversed)	autorange)yaxisdomain)Zscaleanchor	constrainZxaxisrH   rJ   
colorscaleimshowcolor_continuous_scale)rK   ZcmidZcminZcmax)
title_textZcolorbarr   )r   r   min)r   r.   )in_range	out_rangec                s0   g | ](}t  d |f | | ftjdqS ).)rP   rQ   )r   r0   uint8).0ch)r$   zmaxzminr+   r,   
<listcomp>  s   zimshow.<locals>.<listcomp>)r%   r   r&   )sourceZrgbZrgba256)r4   rV   rU   
colormodelz_px.imshow only accepts 2D single-channel, RGB or RGBA images. An image of shape %s was provided)heightwidthtitlerN   templatet<   margin)datalayoutz%%s: %%{x}<br>%s: %%{y}<extra></extra>r7   Zheatmapz%{z}z%{z[0]}z[%{z[0]}, %{z[1]}, %{z[2]}]z/%s: %%{x}<br>%s: %%{y}<br>%s: %s<extra></extra>)hovertemplate)r]   	overwrite)8localsr   copyxarray_imported
isinstancexarrayZ	DataArrayr   Zdimsr0   Z
issubdtypeZcoordsr6   Z
datetime64Zastyper3   getZplotutilsZlabel_from_attrsreplacehasattrr?   rA   rC   pdZ	DataFrameZ
asanyarrayr   boolrR   r.   rO   r:   r   r1   goZHeatmapdictr   Zvalidate_coercer5   r   Zdstackranger-   r   rb   r`   r^   ZFigureZupdate_layoutallZupdate_tracesZupdate_xaxesZupdate_yaxes)&r$   rV   rU   originlabelsr;   r<   rM   Zcolor_continuous_midpointZrange_colorr\   r]   r[   rZ   ZaspectZcontrast_rescalingZbinary_stringZbinary_backendZbinary_compression_levelZbinary_formatargsZy_labelZx_labelZaxZis_dataframetracerG   rb   Zcolorscale_validatorZrescale_imageZimg_rescaledZimg_strrY   Zlayout_patch	attr_nameZfigrc   Z
hover_namer+   )r$   rU   rV   r,   rL      s.    


 
 









.







rL   )r   r   r   )r.   ) Zplotly.graph_objsZ
graph_objsrp   Z_plotly_utils.basevalidatorsr   Z_corer   ior   r   Zimshow_utilsr   r   r   Zpandasrn   r   r	   r
   Znumpyr0   ri   rg   r"   ZPILr   r   Z_float_typesr-   r5   r:   rL   r+   r+   r+   r,   <module>   sR   


A
