B
    Jd^                @   s  d 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
mZ ddlZddlmZ ddlmZ ddl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 G d
d deZi Ze e e dd e! D  e e e e e dd e! D  e e eeZdZ"dd Z#dd Z$dd Z%dd Z&dd Z'dd Z(d\ddZ)d]ddZ*d^d d!Z+d"d# Z,d_d%d&Z-eZ.e/d'Z0e-Z1e,Z2G d(d) d)Z3e3 Z4d`d+d,Z5d-d. Z6G d/d0 d0Z7G d1d2 d2e7Z8G d3d4 d4e7Z9G d5d6 d6Z:G d7d8 d8e:Z;G d9d: d:e:Z<dadd;d<d=Z=e=ej>dbd>d?d;G d@dA dAe:Z?e=ej@ejAdBdCG dDdE dEe:ZBe=ejCdcdFdGdHd?d;G dIdJ dJe:ZDG dKdL dLe:ZEG dMdN dNe:ZFG dOdP dPe:ZGdQdR ZHdSdT ZIdUdV ZJG dWdX dXZKdddZd[ZLdS )ea3  
A module for converting numbers or color arguments to *RGB* or *RGBA*.

*RGB* and *RGBA* are sequences of, respectively, 3 or 4 floats in the
range 0-1.

This module includes functions and classes for color specification conversions,
and for mapping numbers to colors in a 1-D array of colors called a colormap.

Mapping data onto colors using a colormap typically involves two steps: a data
array is first mapped onto the range 0-1 using a subclass of `Normalize`,
then this number is mapped to a color using a subclass of `Colormap`.  Two
subclasses of `Colormap` provided here:  `LinearSegmentedColormap`, which uses
piecewise-linear interpolation to define colormaps, and `ListedColormap`, which
makes a colormap from a list of colors.

.. seealso::

  :doc:`/tutorials/colors/colormap-manipulation` for examples of how to
  make colormaps and

  :doc:`/tutorials/colors/colormaps` for a list of built-in colormaps.

  :doc:`/tutorials/colors/colormapnorms` for more details about data
  normalization

  More colormaps are available at palettable_.

The module also provides functions for checking whether an object can be
interpreted as a color (`is_color_like`), for converting such an object
to an RGBA tuple (`to_rgba`) or to an HTML-like hex string in the
"#rrggbb" format (`to_hex`), and a sequence of colors to an (n, 4)
RGBA array (`to_rgba_array`).  Caching is used for efficiency.

Colors that Matplotlib recognizes are listed at
:doc:`/tutorials/colors/colors`.

.. _palettable: https://jiffyclub.github.io/palettable/
.. _xkcd color survey: https://xkcd.com/color/rgb/
    N)SizedSequence)Number)Image)PngInfo)_apicbookscale   )BASE_COLORSTABLEAU_COLORSCSS4_COLORSXKCD_COLORSc                   s4   e Zd Z fddZ fddZ fddZ  ZS )_ColorMappingc                s   t  | i | _d S )N)super__init__cache)selfmapping)	__class__ C/var/www/html/venv/lib/python3.7/site-packages/matplotlib/colors.pyr   =   s    z_ColorMapping.__init__c                s   t  || | j  d S )N)r   __setitem__r   clear)r   keyvalue)r   r   r   r   A   s    z_ColorMapping.__setitem__c                s   t  | | j  d S )N)r   __delitem__r   r   )r   r   )r   r   r   r   E   s    z_ColorMapping.__delitem__)__name__
__module____qualname__r   r   r   __classcell__r   r   )r   r   r   <   s   r   c             C   s&   i | ]\}}d |kr|| d dqS )greygray)replace).0kvr   r   r   
<dictcomp>M   s   r'   c             C   s&   i | ]\}}d |kr|| d dqS )r"   r!   )r#   )r$   r%   r&   r   r   r   r'   R   s   )i   @   c               C   s   t S )z3Return the global mapping of names to named colors.)_colors_full_mapr   r   r   r   get_named_colors_mapping[   s    r*   c             C   s:   | d kr| S y|   }W n tk
r4   t| }Y nX |S )N)itemAttributeErrorfloat)exretr   r   r   _sanitize_extrema`   s    r0   c             C   s   t | totd| S )zDReturn whether *c* can be interpreted as an item in the color cycle.z\AC[0-9]+\Z)
isinstancestrrematch)cr   r   r   _is_nth_colorj   s    r6   c             C   s6   t | rdS yt|  W n tk
r,   dS X dS dS )z9Return whether *c* can be interpreted as an RGB(A) color.TFN)r6   to_rgba
ValueError)r5   r   r   r   is_color_likeo   s    r9   c              K   s4   x.|   D ]"\}}t|s
t|d| q
W dS )zS
    For each *key, value* pair in *kwargs*, check that *value* is color-like.
    z is not a valid value for N)itemsr9   r8   )kwargsr%   r&   r   r   r   _check_color_like|   s    r<   c             C   sX   t | } t |}t| jd d}t|jd d}||kr@td| j|jkoV| |k S )z
    Return whether the colors *c1* and *c2* are the same.

    *c1*, *c2* can be single colors or lists/arrays of colors.
    r   r
   z$Different number of elements passed.)to_rgba_arraymaxshaper8   all)c1c2Zn1Zn2r   r   r   
same_color   s    rC   c          	   C   s   t | rJddlm} |d }| ddg}|t| dd t|  } ytj| |f }W n t	t
fk
rx   d}Y nX |dkrt| |}y|tj| |f< W n t
k
r   Y nX |S )a  
    Convert *c* to an RGBA color.

    Parameters
    ----------
    c : Matplotlib color or ``np.ma.masked``

    alpha : float, optional
        If *alpha* is given, force the alpha value of the returned RGBA tuple
        to *alpha*.

        If None, the alpha value from *c* is used. If *c* does not have an
        alpha channel, then alpha defaults to 1.

        *alpha* is ignored for the color value ``"none"`` (case-insensitive),
        which always maps to ``(0, 0, 0, 0)``.

    Returns
    -------
    tuple
        Tuple of floats ``(r, g, b, a)``, where each channel (red, green, blue,
        alpha) can assume values between 0 and 1.
    r   )rcParamszaxes.prop_cyclecolorr%   r
   N)r6   
matplotlibrD   by_keygetintlenr)   r   KeyError	TypeError_to_rgba_no_colorcycle)r5   alpharD   Zprop_cyclercolorsrgbar   r   r   r7      s     

r7   c             C   s\  | }| t jjkrdS t| tr|  dkr.dS yt|  } W nF tk
r   t|dkr|yt|   } W n tk
rz   Y nX Y nX t| trpt	
d| }|rtdd | dd | dd | dd	 gD |d
k	r|ndf S t	
d| }|r6tdd | d d | d d | d d gD |d
k	r.|ndf S t	
d| }|rdd | dd | dd | dd	 | d	d gD }|d
k	r||d< t|S t	
d| }|rdd | d d | d d | d d | d d gD }|d
k	r||d< t|S yt| } W n tk
r   Y nFX d|   kr6dksHn td|d| | | |d
k	r\|ndfS td|t| t jr| jdkr| jd dkr| d} t | std|t| dkrtdtdd | D std|ttt| } t| dkr |d
kr d}|d
k	r<| d
d |f } tdd | D rXtd| S ) a  
    Convert *c* to an RGBA color, with no support for color-cycle syntax.

    If *alpha* is given, force the alpha value of the returned RGBA tuple
    to *alpha*. Otherwise, the alpha value from *c* is used, if it has alpha
    information, or defaults to 1.

    *alpha* is ignored for the color value ``"none"`` (case-insensitive),
    which always maps to ``(0, 0, 0, 0)``.
    )g        g        g        g        noner
   z\A#[a-fA-F0-9]{6}\Zc             s   s   | ]}t |d d V  qdS )      N)rI   )r$   nr   r   r   	<genexpr>   s   z)_to_rgba_no_colorcycle.<locals>.<genexpr>         Ng      ?z\A#[a-fA-F0-9]{3}\Zc             s   s   | ]}t |d d V  qdS )rR   rS   N)rI   )r$   rT   r   r   r   rU      s      z\A#[a-fA-F0-9]{8}\Zc             S   s   g | ]}t |d d qS )rR   rS   )rI   )r$   rT   r   r   r   
<listcomp>   s   z*_to_rgba_no_colorcycle.<locals>.<listcomp>	   z\A#[a-fA-F0-9]{4}\Zc             S   s   g | ]}t |d d qS )rR   rS   )rI   )r$   rT   r   r   r   rZ      s      r   zInvalid string grayscale value z . Value must be within 0-1 rangezInvalid RGBA argument: )rV   r]   z'RGBA sequence should have length 3 or 4c             s   s   | ]}t |tV  qd S )N)r1   r   )r$   xr   r   r   rU     s    c             s   s   | ]}|d k p|dkV  qdS )r   r
   Nr   )r$   elemr   r   r   rU     s    z&RGBA values should be within 0-1 range)npmaZmaskedr1   r2   lowerr)   rK   rJ   r3   r4   tupler-   r8   ndarrayndimr?   reshapeiterabler@   mapany)r5   rN   Zorig_cr4   rE   r   r   r   rM      s    
&&0
0


rM   c          	      s  t |rt | }t t jr jjdkr jdkr j	d dkrt j
 rj jjddnd}t j
  t |rԈ j	d dkr|j	d dkrt  |j	d df n j	d |j	d krtd j	d d	krt  t t g}|dk	r
|nd
|dddf< n2 j	d dkrN  }|dk	rN||dddf< |dk	r`d||< t |dk |dkB rtd|S t drt dtS y>t |rt  fdd|D tS t t |gtS W n ttfk
r   Y nX t trtdt dkr&t dtS t trdd  D }|d	hkrft  t t g}n,|dhkr~t  }nt dd  D }nt dd  D }|dk	r||ddd	f< |S )a  
    Convert *c* to a (n, 4) array of RGBA colors.

    Parameters
    ----------
    c : Matplotlib color or array of colors
        If *c* is a masked array, an ndarray is returned with a (0, 0, 0, 0)
        row for each masked value or row in *c*.

    alpha : float or sequence of floats, optional
        If *alpha* is given, force the alpha value of the returned RGBA tuple
        to *alpha*.

        If None, the alpha value from *c* is used. If *c* does not have an
        alpha channel, then alpha defaults to 1.

        *alpha* is ignored for the color value ``"none"`` (case-insensitive),
        which always maps to ``(0, 0, 0, 0)``.

        If *alpha* is a sequence and *c* is a single color, *c* will be
        repeated to match the length of *alpha*.

    Returns
    -------
    array
        (n, 4) array of RGBA colors,  where each channel (red, green, blue,
        alpha) can assume values between 0 and 1.
    ifrY   r
   )rV   r]   )axisNr   z^The number of colors must match the number of alpha values if there are more than one of each.rV   g      ?r\   r]   z&RGBA values should be within 0-1 rangerQ   )r   r]   c                s   g | ]}t  |qS r   )r7   )r$   a)r5   r   r   rZ   `  s    z!to_rgba_array.<locals>.<listcomp>zUsing a string of single character colors as a color sequence is not supported. The colors can be passed as an explicit list instead.c             S   s&   h | ]}t |ttfrt|nd qS )r\   )r1   listrc   rJ   )r$   ccr   r   r   	<setcomp>q  s    z to_rgba_array.<locals>.<setcomp>c             S   s   g | ]}t |qS r   )r7   )r$   rn   r   r   r   rZ   w  s    c             S   s   g | ]}t |qS r   )r7   )r$   rn   r   r   r   rZ   y  s    )r`   rg   asarrayZravelr1   rd   dtypekindre   r?   ra   	is_maskedmaskri   Zgetdatatiler8   column_stackzerosrJ   copyr   Z_str_lower_equalr-   arrayr7   rL   r2   r   ones)r5   rN   rt   resultZlensrP   r   )r5   r   r=     s\     

 


r=   c             C   s   t | dd S )zAConvert *c* to an RGB color, silently dropping the alpha channel.NrV   )r7   )r5   r   r   r   to_rgb  s    r|   Fc             C   s0   t | } |s| dd } dddd | D  S )aM  
    Convert *c* to a hex color.

    Parameters
    ----------
    c : :doc:`color </tutorials/colors/colors>` or `numpy.ma.masked`

    keep_alpha: bool, default: False
      If False, use the ``#rrggbb`` format, otherwise use ``#rrggbbaa``.

    Returns
    -------
    str
      ``#rrggbb`` or ``#rrggbbaa`` hex color string
    NrV   # c             s   s$   | ]}t tt|d  dV  qdS )rS   02xN)formatrI   round)r$   valr   r   r   rU     s    zto_hex.<locals>.<genexpr>)r7   join)r5   
keep_alphar   r   r   to_hex  s    r   z\A#[a-fA-F0-9]{6}\Zc               @   s2   e Zd ZdZeZejZeeZee	Z	ee
Z
dS )ColorConverterz
    A class only kept for backwards compatibility.

    Its functionality is entirely provided by module-level functions.
    N)r   r   r   __doc__r)   rO   r   staticmethodr|   r7   r=   r   r   r   r   r     s   r         ?c          
   C   s  t |r:tdd| | }ttj||tddd}|S yt|}W n, tk
rt } ztd|W dd}~X Y nX |j}t	|dks|d dkrt
d|dddf }|dddf }	|dddf }
|d d	ks|d
 dkrt
dt|dk  rt
d| dkr"t|	d
 }n|| d  }| d tdd| |  }t||dd
 }|dd
 ||d   || ||d    }t|
d g||	| |
|d    |
|d   |	d
 gg}t|d	dS )af  
    Create an *N* -element 1D lookup table.

    This assumes a mapping :math:`f : [0, 1] \rightarrow [0, 1]`. The returned
    data is an array of N values :math:`y = f(x)` where x is sampled from
    [0, 1].

    By default (*gamma* = 1) x is equidistantly sampled from [0, 1]. The
    *gamma* correction factor :math:`\gamma` distorts this equidistant
    sampling by :math:`x \rightarrow x^\gamma`.

    Parameters
    ----------
    N : int
        The number of elements of the created lookup table; at least 1.

    data : (M, 3) array-like or callable
        Defines the mapping :math:`f`.

        If a (M, 3) array-like, the rows define values (x, y0, y1).  The x
        values must start with x=0, end with x=1, and all x values be in
        increasing order.

        A value between :math:`x_i` and :math:`x_{i+1}` is mapped to the range
        :math:`y^1_{i-1} \ldots y^0_i` by linear interpolation.

        For the simple case of a y-continuous mapping, y0 and y1 are identical.

        The two values of y are to allow for discontinuous mapping functions.
        E.g. a sawtooth with a period of 0.2 and an amplitude of 1 would be::

            [(0, 1, 0), (0.2, 1, 0), (0.4, 1, 0), ..., [(1, 1, 0)]

        In the special case of ``N == 1``, by convention the returned value
        is y0 for x == 1.

        If *data* is a callable, it must accept and return numpy arrays::

           data(x : ndarray) -> ndarray

        and map values between 0 - 1 to 0 - 1.

    gamma : float
        Gamma correction factor for input distribution x of the mapping.

        See also https://en.wikipedia.org/wiki/Gamma_correction.

    Returns
    -------
    array
        The lookup table where ``lut[x * (N-1)]`` gives the closest value
        for values of x between 0 and 1.

    Notes
    -----
    This function is internally used for `.LinearSegmentedColormap`.
    r   r
   )rq   z$data must be convertible to an arrayNrY   rV   zdata must be nx3 formatg        r\   g      ?z8data mapping points must start with x=0 and end with x=1z3data mapping points must have x in increasing order)callabler`   linspaceclipry   r-   	ExceptionrL   r?   rJ   r8   diffri   ZsearchsortedZconcatenate)NdatagammaZxindlutZadataerrr?   r^   y0y1indZdistancer   r   r   _create_lookup_table  s<    ;
,"r   c             C   s*   t | ddr&tjddd| j dd d S )N_globalFz3.3z3.6a  You are modifying the state of a globally registered colormap. This has been deprecated since %(since)s and %(removal)s, you will not be able to modify a registered colormap in-place. To remove this warning, you can make a copy of the colormap first. cmap = mpl.cm.get_cmap("z	").copy())Zremovalmessage)getattrr   Zwarn_deprecatedname)cmapr   r   r   _warn_if_global_cmap_modified  s
    r   c               @   s   e Zd ZdZd/ddZd0ddZd	d
 Zdd Zdd Zd1ddZ	dd Z
d2ddZdd Zd3ddZddddddZddddddZdd  Zd!d" Zd#d$ Zd%d& Zd4d'd(Zd)d* Zd+d, Zd-d. ZdS )5Colormapa  
    Baseclass for all scalar to RGBA mappings.

    Typically, Colormap instances are used to convert data values (floats)
    from the interval ``[0, 1]`` to the RGBA color that the respective
    Colormap represents. For scaling of data into the ``[0, 1]`` interval see
    `matplotlib.colors.Normalize`. Subclasses of `matplotlib.cm.ScalarMappable`
    make heavy use of this ``data -> normalize -> map-to-color`` processing
    chain.
       c             C   sR   || _ t|| _d| _d| _d| _| j| _| jd | _| jd | _d| _	d| _
dS )z
        Parameters
        ----------
        name : str
            The name of the colormap.
        N : int
            The number of rgb quantization levels.
        )g        g        g        g        Nr
   rY   F)r   rI   r   	_rgba_bad_rgba_under
_rgba_over_i_under_i_over_i_bad_isinitcolorbar_extend)r   r   r   r   r   r   r   5  s    	
zColormap.__init__NFc          	   C   s  | j s|   tj|r |jnt|}tj|dd}|jj	sL|
  }|jjdkrtjddN || j9 }d||dk < | jd ||| jk< tj|d| j|d	 |t}W d
Q R X | j||| jd k< | j||dk < | j||< |r| jd tj}n
| j }tj|jd |jd}|j|dd|d |d
k	rt|rpt|}|j|jkrptd|j|jf t|dd}|r|d tj}||d< |d dk rt|rt|r|j|jkrd||< nd|dd
d
f< t|st |}|S )a  
        Parameters
        ----------
        X : float or int, ndarray or scalar
            The data value(s) to convert to RGBA.
            For floats, X should be in the interval ``[0.0, 1.0]`` to
            return the RGBA values ``X*100`` percent along the Colormap line.
            For integers, X should be in the interval ``[0, Colormap.N)`` to
            return RGBA values *indexed* from the Colormap with index ``X``.
        alpha : float or array-like or None
            Alpha must be a scalar between 0 and 1, a sequence of such
            floats with shape matching X, or None.
        bytes : bool
            If False (default), the returned RGBA values will be floats in the
            interval ``[0, 1]`` otherwise they will be uint8s in the interval
            ``[0, 255]``.

        Returns
        -------
        Tuple of RGBA values if X is scalar, otherwise an array of
        RGBA values with a shape of ``X.shape + (4, )``.
        T)rx   fignore)invalidr\   r   r
   )outNrS   )r]   )r?   rq   r   )rk   moder   z?alpha is array-like but its shape %s doesn't match that of X %s).r\   )r   r   r   r   .)!r   _initr`   ra   rs   rt   isnanry   rq   ZisnativebyteswapZnewbyteorderrr   Zerrstater   r   astyperI   r   r   r   _lutZuint8rx   emptyr?   Ztakerg   rp   r8   r@   ri   rc   )r   XrN   bytesZmask_badZxar   rP   r   r   r   __call__M  sL    





zColormap.__call__c             C   s<   | j }||}|j| j | jr2t| j|_d|_|S )NF)	r   __new____dict__updater   r`   rx   r   r   )r   clsZ
cmapobjectr   r   r   __copy__  s    
zColormap.__copy__c             C   sR   t |tr"| j|jks"| j|jkr&dS | js4|   |jsB|  t| j|jS )NF)	r1   r   r   r   r   r   r`   Zarray_equalr   )r   otherr   r   r   __eq__  s    zColormap.__eq__c             C   s    | j s|   t| j| j S )z Get the color for masked values.)r   r   r`   ry   r   r   )r   r   r   r   get_bad  s    zColormap.get_badr%   c             C   s&   t |  t||| _| jr"|   dS )z Set the color for masked values.N)r   r7   r   r   _set_extremes)r   rE   rN   r   r   r   set_bad  s    zColormap.set_badc             C   s    | j s|   t| j| j S )z*Get the color for low out-of-range values.)r   r   r`   ry   r   r   )r   r   r   r   	get_under  s    zColormap.get_underc             C   s&   t |  t||| _| jr"|   dS )z*Set the color for low out-of-range values.N)r   r7   r   r   r   )r   rE   rN   r   r   r   	set_under  s    zColormap.set_underc             C   s    | j s|   t| j| j S )z+Get the color for high out-of-range values.)r   r   r`   ry   r   r   )r   r   r   r   get_over  s    zColormap.get_overc             C   s&   t |  t||| _| jr"|   dS )z+Set the color for high out-of-range values.N)r   r7   r   r   r   )r   rE   rN   r   r   r   set_over  s    zColormap.set_over)badunderoverc            C   s:   |dk	r|  | |dk	r$| | |dk	r6| | dS )z
        Set the colors for masked (*bad*) values and, when ``norm.clip =
        False``, low (*under*) and high (*over*) out-of-range values.
        N)r   r   r   )r   r   r   r   r   r   r   set_extremes  s    

zColormap.set_extremesc            C   s   t  | }|j|||d |S )z
        Return a copy of the colormap, for which the colors for masked (*bad*)
        values and, when ``norm.clip = False``, low (*under*) and high (*over*)
        out-of-range values, have been set accordingly.
        )r   r   r   )rx   r   )r   r   r   r   Znew_cmr   r   r   with_extremes  s    
zColormap.with_extremesc             C   sh   | j r| j | j| j< n| jd | j| j< | jr>| j| j| j< n| j| jd  | j| j< | j| j| j< d S )Nr   r
   )r   r   r   r   r   r   r   r   )r   r   r   r   r     s    zColormap._set_extremesc             C   s   t ddS )z)Generate the lookup table, ``self._lut``.zAbstract class onlyN)NotImplementedError)r   r   r   r   r     s    zColormap._initc             C   sb   | j s|   t| jdddf | jdddf ko`t| jdddf | jdddf kS )z)Return whether the colormap is grayscale.Nr   r
   rY   )r   r   r`   r@   r   )r   r   r   r   is_gray  s    *zColormap.is_grayc             C   s
   t  dS )z-Return a new colormap with *lutsize* entries.N)r   )r   lutsizer   r   r   	_resample  s    zColormap._resamplec             C   s
   t  dS )a  
        Return a reversed instance of the Colormap.

        .. note:: This function is not implemented for base class.

        Parameters
        ----------
        name : str, optional
            The name for the reversed colormap. If it's None the
            name will be the name of the parent colormap + "_r".

        See Also
        --------
        LinearSegmentedColormap.reversed
        ListedColormap.reversed
        N)r   )r   r   r   r   r   reversed  s    zColormap.reversedc             C   s   t t ddtd td df}| |dd}t }| jd }dtj d}t	 }|
d| |
d	| |
d
| |
d| t|j|d|d | S )z.Generate a PNG representation of the Colormap.r   r
   T)r   z	 colormapzMatplotlib vz, https://matplotlib.orgZTitleDescriptionAuthorZSoftwareZpng)r   pnginfo)r`   ru   r   _REPR_PNG_SIZEioBytesIOr   mpl__version__r   add_textr   Z	fromarraysavegetvalue)r   r   Zpixels	png_bytestitleauthorr   r   r   r   
_repr_png_  s    
zColormap._repr_png_c             C   s|   |   }t|d}dd }d| j d| j d| j d| dtd	 d
  d||   d||   d||   dS )z0Generate an HTML representation of the Colormap.asciic             S   s   t | dd}d| d| dS )NT)r   z<div title="z" style="display: inline-block; width: 1em; height: 1em; margin: 0; vertical-align: middle; border: 1px solid #555; background-color: z	;"></div>)r   )rE   	hex_colorr   r   r   color_block-  s    z)Colormap._repr_html_.<locals>.color_blockz-<div style="vertical-align: middle;"><strong>z,</strong> </div><div class="cmap"><img alt="z colormap" title="z=" style="border: 1px solid #555;" src="data:image/png;base64,z7"></div><div style="vertical-align: middle; max-width: r   rY   zNpx; display: flex; justify-content: space-between;"><div style="float: left;">zD under</div><div style="margin: 0 auto; display: inline-block;">bad z&</div><div style="float: right;">over z</div>)	r   base64	b64encodedecoder   r   r   r   r   )r   r   Z
png_base64r   r   r   r   _repr_html_)  s    
zColormap._repr_html_c             C   s   |   S )zReturn a copy of the colormap.)r   )r   r   r   r   rx   L  s    zColormap.copy)r   )NF)r%   N)r%   N)r%   N)N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rx   r   r   r   r   r   )  s*   


N	




#r   c                   s^   e Zd ZdZd fdd	Zdd Zdd	 Zedd
dZdd Z	edd Z
dddZ  ZS )LinearSegmentedColormapz
    Colormap objects based on lookup tables using linear segments.

    The lookup table is generated using linear interpolation for each
    primary color, with the 0-1 domain divided into any number of
    segments.
    r         ?c                s$   d| _ t || || _|| _dS )a  
        Create colormap from linear mapping segments

        segmentdata argument is a dictionary with a red, green and blue
        entries. Each entry should be a list of *x*, *y0*, *y1* tuples,
        forming rows in a table. Entries for alpha are optional.

        Example: suppose you want red to increase from 0 to 1 over
        the bottom half, green to do the same over the middle half,
        and blue over the top half.  Then you would use::

            cdict = {'red':   [(0.0,  0.0, 0.0),
                               (0.5,  1.0, 1.0),
                               (1.0,  1.0, 1.0)],

                     'green': [(0.0,  0.0, 0.0),
                               (0.25, 0.0, 0.0),
                               (0.75, 1.0, 1.0),
                               (1.0,  1.0, 1.0)],

                     'blue':  [(0.0,  0.0, 0.0),
                               (0.5,  0.0, 0.0),
                               (1.0,  1.0, 1.0)]}

        Each row in the table for a given color is a sequence of
        *x*, *y0*, *y1* tuples.  In each sequence, *x* must increase
        monotonically from 0 to 1.  For any input value *z* falling
        between *x[i]* and *x[i+1]*, the output value of a given color
        will be linearly interpolated between *y1[i]* and *y0[i+1]*::

            row i:   x  y0  y1
                           /
                          /
            row i+1: x  y0  y1

        Hence y0 in the first row and y1 in the last row are never used.

        See Also
        --------
        LinearSegmentedColormap.from_list
            Static method; factory function for generating a smoothly-varying
            LinearSegmentedColormap.
        FN)
monochromer   r   _segmentdata_gamma)r   r   Zsegmentdatar   r   )r   r   r   r   Z  s    -z LinearSegmentedColormap.__init__c             C   s   t | jd dft| _t| j| jd | j| jd ddf< t| j| jd | j| jd ddf< t| j| jd | j| jd dd	f< d
| jkrt| j| jd
 d| jd ddf< d| _| 	  d S )NrV   r]   redr   greenr
   bluerY   rN   T)
r`   rz   r   r-   r   r   r   r   r   r   )r   r   r   r   r     s    """
 zLinearSegmentedColormap._initc             C   s   || _ |   dS )z.Set a new gamma value and regenerate colormap.N)r   r   )r   r   r   r   r   	set_gamma  s    z!LinearSegmentedColormap.set_gammac       
      C   s   t |stdt|d trLt|d dkrLt|d tsLt| \}}nt ddt|}t	|j
\}}}}t |||gt |||gt |||gt |||gd}	t| |	||S )a  
        Create a `LinearSegmentedColormap` from a list of colors.

        Parameters
        ----------
        name : str
            The name of the colormap.
        colors : array-like of colors or array-like of (value, color)
            If only colors are given, they are equidistantly mapped from the
            range :math:`[0, 1]`; i.e. 0 maps to ``colors[0]`` and 1 maps to
            ``colors[-1]``.
            If (value, color) pairs are given, the mapping is from *value*
            to *color*. This can be used to divide the range unevenly.
        N : int
            The number of rgb quantization levels.
        gamma : float
        zcolors must be iterabler   rY   r
   )r   r   r   rN   )r`   rg   r8   r1   r   rJ   r2   zipr   r=   Trv   r   )
r   rO   r   r   valsrgbrl   Zcdictr   r   r   	from_list  s    
z!LinearSegmentedColormap.from_listc             C   s,   t | j| j|}| j|_| j|_| j|_|S )z-Return a new colormap with *lutsize* entries.)r   r   r   r   r   r   )r   r   new_cmapr   r   r   r     s    
z!LinearSegmentedColormap._resamplec             C   s   | d| S )Nr
   r   )funcr^   r   r   r   	_reverser  s    z!LinearSegmentedColormap._reverserNc                sX   |dkr j d } fdd j D }t|| j j} j|_ j|_ j|_|S )ag  
        Return a reversed instance of the Colormap.

        Parameters
        ----------
        name : str, optional
            The name for the reversed colormap. If it's None the
            name will be the name of the parent colormap + "_r".

        Returns
        -------
        LinearSegmentedColormap
            The reversed colormap.
        N_rc                s:   i | ]2\}}t |r"t j|nd d t|D |qS )c             S   s    g | ]\}}}d | ||fqS )g      ?r   )r$   r^   r   r   r   r   r   rZ     s    z?LinearSegmentedColormap.reversed.<locals>.<dictcomp>.<listcomp>)r   	functoolspartialr   r   )r$   r   r   )r   r   r   r'     s   z4LinearSegmentedColormap.reversed.<locals>.<dictcomp>)	r   r   r:   r   r   r   r   r   r   )r   r   Zdata_rr   r   )r   r   r     s    

z LinearSegmentedColormap.reversed)r   r   )r   r   )N)r   r   r   r   r   r   r   r   r   r   r   r   r    r   r   )r   r   r   Q  s   2&
r   c                   s<   e Zd ZdZd fdd	Zdd Zdd	 Zdd
dZ  ZS )ListedColormapa*  
    Colormap object generated from a list of colors.

    This may be most useful when indexing directly into a colormap,
    but it can also be used to generate special colormaps for ordinary
    mapping.

    Parameters
    ----------
    colors : list, array
        List of Matplotlib color specifications, or an equivalent Nx3 or Nx4
        floating point array (*N* rgb or rgba values).
    name : str, optional
        String to identify the colormap.
    N : int, optional
        Number of entries in the map. The default is *None*, in which case
        there is one colormap entry for each element in the list of colors.
        If ::

            N < len(colors)

        the list will be truncated at *N*. If ::

            N > len(colors)

        the list will be extended by repetition.
    r   Nc                s   d| _ |d kr|| _t|}nt|tr<|g| | _d| _ njt|rrt|dkrXd| _ tt	t
||| _n4yt|}W n tk
r   Y nX |g| | _d| _ t || d S )NFTr
   )r   rO   rJ   r1   r2   r`   rg   rm   	itertoolsislicecycler-   rL   r   r   )r   rO   r   r   r"   )r   r   r   r     s&    


zListedColormap.__init__c             C   s>   t | jd dft| _t| j| jd d< d| _|   d S )NrV   r]   r   T)	r`   rw   r   r-   r   r=   rO   r   r   )r   r   r   r   r   (  s    zListedColormap._initc             C   s<   | t dd|}t|| jd}| j|_| j|_| j|_|S )z-Return a new colormap with *lutsize* entries.r   r
   )r   )r`   r   r   r   r   r   r   )r   r   rO   r   r   r   r   r   .  s    zListedColormap._resamplec             C   sL   |dkr| j d }tt| j}t||| jd}| j|_| j|_| j|_|S )al  
        Return a reversed instance of the Colormap.

        Parameters
        ----------
        name : str, optional
            The name for the reversed colormap. If it's None the
            name will be the name of the parent colormap + "_r".

        Returns
        -------
        ListedColormap
            A reversed instance of the colormap.
        Nr   )r   r   )	r   rm   r   rO   r   r   r   r   r   )r   r   Zcolors_rr   r   r   r   r   8  s    
zListedColormap.reversed)r   N)N)	r   r   r   r   r   r   r   r   r    r   r   )r   r   r     s
   
r   c               @   s   e Zd ZdZdddZedd Zejdd Zed	d
 Zejdd
 Zedd Z	e	jdd Z	dd Z
edd ZdddZdd Zdd Zdd Zdd ZdS )	Normalizezd
    A class which, when called, linearly normalizes data into the
    ``[0.0, 1.0]`` interval.
    NFc             C   s.   t || _t || _|| _d| _t | _dS )aM  
        Parameters
        ----------
        vmin, vmax : float or None
            If *vmin* and/or *vmax* is not given, they are initialized from the
            minimum and maximum value, respectively, of the first input
            processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.

        clip : bool, default: False
            If ``True`` values falling outside the range ``[vmin, vmax]``,
            are mapped to 0 or 1, whichever is closer, and masked values are
            set to 1.  If ``False`` masked values remain masked.

            Clipping silently defeats the purpose of setting the over, under,
            and masked colors in a colormap, so it is likely to lead to
            surprises; therefore the default is ``clip=False``.

        Notes
        -----
        Returns 0 if ``vmin == vmax``.
        N)r0   _vmin_vmax_clip_scaler   ZCallbackRegistry	callbacks)r   vminvmaxr   r   r   r   r   Y  s
    

zNormalize.__init__c             C   s   | j S )N)r   )r   r   r   r   r  u  s    zNormalize.vminc             C   s$   t |}|| jkr || _|   d S )N)r0   r   _changed)r   r   r   r   r   r  y  s    
c             C   s   | j S )N)r  )r   r   r   r   r    s    zNormalize.vmaxc             C   s$   t |}|| jkr || _|   d S )N)r0   r  r  )r   r   r   r   r   r    s    
c             C   s   | j S )N)r  )r   r   r   r   r     s    zNormalize.clipc             C   s   || j kr|| _ |   d S )N)r  r  )r   r   r   r   r   r     s    
c             C   s   | j d dS )z~
        Call this whenever the norm is changed to notify all the
        callback listeners to the 'changed' signal.
        changedN)r  process)r   r   r   r   r    s    zNormalize._changedc             C   sz   t |  }|r| g} t | }t |t js:|jt jkrHt |t j}t j	
| }t | }t j	j|||dd}||fS )ar  
        Homogenize the input *value* for easy and efficient normalization.

        *value* can be a scalar or sequence.

        Returns
        -------
        result : masked array
            Masked array with the same shape as *value*.
        is_scalar : bool
            Whether *value* is a scalar.

        Notes
        -----
        Float dtypes are preserved; integer types with two bytes or smaller are
        converted to np.float32, and larger types are converted to np.float64.
        Preserving float32 when possible, and using in-place operations,
        greatly improves speed for large arrays.
        T)rt   rq   rx   )r`   rg   Zmin_scalar_typeZ
issubdtypeintegertypeZbool_promote_typesfloat32ra   getmaskrp   ry   )r   	is_scalarrq   rt   r   r{   r   r   r   process_value  s    

zNormalize.process_valuec       
      C   s   |dkr| j }| |\}}| | | | j\\}}| | j\\}}||kr^|d np||krptdn^|rtj	|}tjj
t |||||d}|j}	|	|8 }	|	||  }	tjj
|	|jdd}|r|d }|S )a  
        Normalize *value* data in the ``[vmin, vmax]`` interval into the
        ``[0.0, 1.0]`` interval and return it.

        Parameters
        ----------
        value
            Data to normalize.
        clip : bool
            If ``None``, defaults to ``self.clip`` (which defaults to
            ``False``).

        Notes
        -----
        If not already initialized, ``self.vmin`` and ``self.vmax`` are
        initialized using ``self.autoscale_None(value)``.
        Nr   z/minvalue must be less than or equal to maxvalue)rt   F)rt   rx   )r   r  autoscale_Noner  r  fillr8   r`   ra   r  ry   filledr   rt   )
r   r   r   r{   r  r  _r  rt   resdatr   r   r   r     s*    

zNormalize.__call__c             C   sn   |   std| | j\\}}| | j\\}}t|rZtj|}||||   S ||||   S d S )Nz/Not invertible until both vmin and vmax are set)	scaledr8   r  r  r  r`   rg   ra   rp   )r   r   r  r  r  r   r   r   r   inverse  s    
zNormalize.inversec             C   s"   t |}| | _| | _dS )z&Set *vmin*, *vmax* to min, max of *A*.N)r`   
asanyarrayminr  r>   r  )r   Ar   r   r   	autoscale  s    

zNormalize.autoscalec             C   sB   t |}| jdkr$|jr$| | _| jdkr>|jr>| | _dS )z@If vmin or vmax are not set, use the min/max of *A* to set them.N)r`   r  r  sizer  r  r>   )r   r  r   r   r   r    s
    

zNormalize.autoscale_Nonec             C   s   | j dk	o| jdk	S )z%Return whether vmin and vmax are set.N)r  r  )r   r   r   r   r    s    zNormalize.scaled)NNF)N)r   r   r   r   r   propertyr  setterr  r   r  r   r  r   r  r  r  r  r   r   r   r   r   S  s   
#
-r   c                   sV   e Zd Zd fdd	Zedd Zejdd Z fddZdd	d
Zdd Z	  Z
S )TwoSlopeNormNc                sZ   t  j||d || _|dk	r6|dk	r6||kr6td|dk	rV|dk	rV||krVtddS )a  
        Normalize data with a set center.

        Useful when mapping data with an unequal rates of change around a
        conceptual center, e.g., data that range from -2 to 4, with 0 as
        the midpoint.

        Parameters
        ----------
        vcenter : float
            The data value that defines ``0.5`` in the normalization.
        vmin : float, optional
            The data value that defines ``0.0`` in the normalization.
            Defaults to the min value of the dataset.
        vmax : float, optional
            The data value that defines ``1.0`` in the normalization.
            Defaults to the max value of the dataset.

        Examples
        --------
        This maps data value -4000 to 0., 0 to 0.5, and +10000 to 1.0; data
        between is linearly interpolated::

            >>> import matplotlib.colors as mcolors
            >>> offset = mcolors.TwoSlopeNorm(vmin=-4000.,
                                              vcenter=0., vmax=10000)
            >>> data = [-4000., -2000., 0., 2500., 5000., 7500., 10000.]
            >>> offset(data)
            array([0., 0.25, 0.5, 0.625, 0.75, 0.875, 1.0])
        )r  r  Nz2vmin, vcenter, and vmax must be in ascending order)r   r   _vcenterr8   )r   vcenterr  r  )r   r   r   r     s     zTwoSlopeNorm.__init__c             C   s   | j S )N)r   )r   r   r   r   r!  5  s    zTwoSlopeNorm.vcenterc             C   s   || j kr|| _ |   d S )N)r   r  )r   r   r   r   r   r!  9  s    
c                s8   t  | | j| jkr | j| _| j| jk r4| j| _dS )z=
        Get vmin and vmax, and then clip at vcenter
        N)r   r  r  r!  r  )r   r  )r   r   r   r  ?  s
    zTwoSlopeNorm.autoscale_Nonec             C   s   |  |\}}| | | j| j  kr2| jks<n tdtjjtj	|| j| j| jgdddgtj
 tj
dtj|d}|rt|d }|S )zP
        Map value to the interval [0, 1]. The clip argument is unused.
        z/vmin, vcenter, vmax must increase monotonicallyr   g      ?r
   )leftright)rt   )r  r  r  r!  r  r8   r`   ra   Zmasked_arrayinterpinfr  
atleast_1d)r   r   r   r{   r  r   r   r   r   I  s    
zTwoSlopeNorm.__call__c             C   sp   |   std| | j\\}}| | j\\}}| | j\\}}tj|dddg|||gtj tjd}|S )Nz/Not invertible until both vmin and vmax are setr   g      ?r
   )r"  r#  )	r  r8   r  r  r  r!  r`   r$  r%  )r   r   r  r  r  r!  r{   r   r   r   r  [  s    zTwoSlopeNorm.inverse)NN)N)r   r   r   r   r  r!  r  r  r   r  r    r   r   )r   r   r    s   )

r  c                   sx   e Zd Zd fdd	Zdd Zdd	 Zd
d Zedd Zej	dd Zedd Z
e
j	dd Z
d fdd	Z  ZS )CenteredNormr   NFc                s"   t  jdd|d || _|| _dS )a  
        Normalize symmetrical data around a center (0 by default).

        Unlike `TwoSlopeNorm`, `CenteredNorm` applies an equal rate of change
        around the center.

        Useful when mapping symmetrical data around a conceptual center
        e.g., data that range from -2 to 4, with 0 as the midpoint, and
        with equal rates of change around that midpoint.

        Parameters
        ----------
        vcenter : float, default: 0
            The data value that defines ``0.5`` in the normalization.
        halfrange : float, optional
            The range of data values that defines a range of ``0.5`` in the
            normalization, so that *vcenter* - *halfrange* is ``0.0`` and
            *vcenter* + *halfrange* is ``1.0`` in the normalization.
            Defaults to the largest absolute difference to *vcenter* for
            the values in the dataset.

        Examples
        --------
        This maps data values -2 to 0.25, 0 to 0.5, and 4 to 1.0
        (assuming equal rates of change above and below 0.0):

            >>> import matplotlib.colors as mcolors
            >>> norm = mcolors.CenteredNorm(halfrange=4.0)
            >>> data = [-2., 0., 4.]
            >>> norm(data)
            array([0.25, 0.5 , 1.  ])
        N)r  r  r   )r   r   r   	halfrange)r   r!  r(  r   )r   r   r   r   g  s    !zCenteredNorm.__init__c             C   s    | j | j | _| j | j | _dS )zK
        Set *vmin* and *vmax* based on *vcenter* and *halfrange*.
        N)r   
_halfranger  r  )r   r   r   r   _set_vmin_vmax  s    zCenteredNorm._set_vmin_vmaxc             C   s6   t |}t| j|  | | j | _|   dS )zY
        Set *halfrange* to ``max(abs(A-vcenter))``, then set *vmin* and *vmax*.
        N)r`   r  r>   r   r  r)  r*  )r   r  r   r   r   r    s    
zCenteredNorm.autoscalec             C   s(   t |}| jdkr$|jr$| | dS )zSet *vmin* and *vmax*.N)r`   r  r)  r  r  )r   r  r   r   r   r    s    
zCenteredNorm.autoscale_Nonec             C   s   | j S )N)r   )r   r   r   r   r!    s    zCenteredNorm.vcenterc             C   sJ   || j kr|| _ |   | jd k	rFt| j | j | j| j  | _|   d S )N)r   r  r  r>   r  r)  r*  )r   r!  r   r   r   r!    s    

c             C   s   | j S )N)r)  )r   r   r   r   r(    s    zCenteredNorm.halfrangec             C   s*   |d krd | _ d | _d | _n
t|| _ d S )N)r)  r  r  abs)r   r(  r   r   r   r(    s
    c                s"   | j d k	r|   t j||dS )N)r   )r)  r*  r   r   )r   r   r   )r   r   r   r     s    
zCenteredNorm.__call__)r   NF)N)r   r   r   r   r*  r  r  r  r!  r  r(  r   r    r   r   )r   r   r'  f  s   &		r'  )initc               s   |dkrt jt|dS |dkr*d
dd}t| G  fddd|}|tkr^j dn|j|_|j|_|j|_|j	|_	 j
tdtjjf j d	|j_|S )a/  
    Decorator for building a `.Normalize` subclass from a `~.scale.ScaleBase`
    subclass.

    After ::

        @make_norm_from_scale(scale_cls)
        class norm_cls(Normalize):
            ...

    *norm_cls* is filled with methods so that normalization computations are
    forwarded to *scale_cls* (i.e., *scale_cls* is the scale that would be used
    for the colorbar of a mappable normalized with *norm_cls*).

    If *init* is not passed, then the constructor signature of *norm_cls*
    will be ``norm_cls(vmin=None, vmax=None, clip=False)``; these three
    parameters will be forwarded to the base class (``Normalize.__init__``),
    and a *scale_cls* object will be initialized with no arguments (other than
    a dummy axis).

    If the *scale_cls* constructor takes additional parameters, then *init*
    should be passed to `make_norm_from_scale`.  It is a callable which is
    *only* used for its signature.  First, this signature will become the
    signature of *norm_cls*.  Second, the *norm_cls* constructor will bind the
    parameters passed to it using this signature, extract the bound *vmin*,
    *vmax*, and *clip* values, pass those to ``Normalize.__init__``, and
    forward the remaining bound values (including any defaults defined by the
    signature) to the *scale_cls* constructor.
    N)r,  Fc             S   s   d S )Nr   )r  r  r   r   r   r   r,        z"make_norm_from_scale.<locals>.initc                   s2   e Zd Z fddZdddZdd Z  ZS )	z"make_norm_from_scale.<locals>.Normc                sV   j ||    t jf  fdddD  f dd i j| _| j | _d S )Nc                s   i | ]} j ||qS r   )	argumentspop)r$   r%   )bar   r   r'     s    z?make_norm_from_scale.<locals>.Norm.__init__.<locals>.<dictcomp>)r  r  r   rk   )bindapply_defaultsr   r   r.  r  Zget_transform_trf)r   argsr;   )r   bound_init_signature	scale_cls)r0  r   r     s    z+make_norm_from_scale.<locals>.Norm.__init__Nc             S   s   |  |\}}| | | j| jkr,td| j| jkrDt|dS |d krR| j}|rht|| j| j}| j	|
t|}| j	| j| jg\}}t||g std||8 }|||  }tjj|dd}|r|d S |S )Nz"vmin must be less or equal to vmaxr   zInvalid vmin or vmaxF)rx   )r  r  r  r  r8   r`   Z	full_liker   r3  	transformrf   r?   isfiniter@   ra   Zmasked_invalid)r   r   r   r  Zt_valuet_vmint_vmaxr   r   r   r     s$    
z+make_norm_from_scale.<locals>.Norm.__call__c             S   s   |   std| j| jkr$td| j| j| jg\}}t||g sVtd| 	|\}}|||  }||7 }| j
 |t|}|r|d S |S )NzNot invertible until scaledz"vmin must be less or equal to vmaxzInvalid vmin or vmaxr   )r  r8   r  r  r3  r7  r`   r8  r@   r  invertedrf   r?   )r   r   r9  r:  r  Zrescaledr   r   r   r    s    
z*make_norm_from_scale.<locals>.Norm.inverse)N)r   r   r   r   r   r  r    r   )r5  r6  )r   r   Norm  s   
r<  r   )
parameters)NNF)r   r   make_norm_from_scaleinspect	signaturer   r   r   r   r   r#   	ParameterPOSITIONAL_OR_KEYWORDr=  valuesr   __signature__)r6  Zbase_norm_clsr,  r<  r   )r5  r6  r   r>    s    

/r>  c             C   s   d S )Nr   )Z	functionsr  r  r   r   r   r   <lambda>)  r-  rE  c               @   s   e Zd ZdZdS )FuncNorma,  
    Arbitrary normalization using functions for the forward and inverse.

    Parameters
    ----------
    functions : (callable, callable)
        two-tuple of the forward and inverse functions for the normalization.
        The forward function must be monotonic.

        Both functions must have the signature ::

           def forward(values: array-like) -> array-like

    vmin, vmax : float or None
        If *vmin* and/or *vmax* is not given, they are initialized from the
        minimum and maximum value, respectively, of the first input
        processed; i.e., ``__call__(A)`` calls ``autoscale_None(A)``.

    clip : bool, default: False
        If ``True`` values falling outside the range ``[vmin, vmax]``,
        are mapped to 0 or 1, whichever is closer, and masked values are
        set to 1.  If ``False`` masked values remain masked.

        Clipping silently defeats the purpose of setting the over, under,
        and masked colors in a colormap, so it is likely to lead to
        surprises; therefore the default is ``clip=False``.
    N)r   r   r   r   r   r   r   r   rF  '  s   rF  rt   )nonpositivec                   s,   e Zd ZdZ fddZ fddZ  ZS )LogNormz8Normalize a given value to the 0-1 range on a log scale.c                s    t  tjj||dkd d S )Nr   )rt   )r   r  r`   ra   ry   )r   r  )r   r   r   r  L  s    zLogNorm.autoscalec                s    t  tjj||dkd d S )Nr   )rt   )r   r  r`   ra   ry   )r   r  )r   r   r   r  P  s    zLogNorm.autoscale_None)r   r   r   r   r  r  r    r   r   )r   r   rH  H  s   rH  
   )basec            C   s   d S )Nr   )	linthreshZlinscaler  r  r   rJ  r   r   r   rE  W  s    c               @   s*   e Zd ZdZedd Zejdd ZdS )
SymLogNorma  
    The symmetrical logarithmic scale is logarithmic in both the
    positive and negative directions from the origin.

    Since the values close to zero tend toward infinity, there is a
    need to have a range around zero that is linear.  The parameter
    *linthresh* allows the user to specify the size of this range
    (-*linthresh*, *linthresh*).

    Parameters
    ----------
    linthresh : float
        The range within which the plot is linear (to avoid having the plot
        go to infinity around zero).
    linscale : float, default: 1
        This allows the linear range (-*linthresh* to *linthresh*) to be
        stretched relative to the logarithmic range. Its value is the
        number of decades to use for each half of the linear range. For
        example, when *linscale* == 1.0 (the default), the space used for
        the positive and negative halves of the linear range will be equal
        to one decade in the logarithmic range.
    base : float, default: 10
    c             C   s   | j jS )N)r  rK  )r   r   r   r   rK  r  s    zSymLogNorm.linthreshc             C   s   || j _d S )N)r  rK  )r   r   r   r   r   rK  v  s    N)r   r   r   r   r  rK  r  r   r   r   r   rL  U  s   rL  c                   s4   e Zd ZdZd
 fdd	ZdddZdd	 Z  ZS )	PowerNormzs
    Linearly map a given value to the 0-1 range and then apply
    a power-law normalization over that range.
    NFc                s   t  ||| || _d S )N)r   r   r   )r   r   r  r  r   )r   r   r   r     s    zPowerNorm.__init__c       
      C   s   |d kr| j }| |\}}| | | j}| j| j }}||krLtdn||kr`|d n||rtj	
|}tj	jt |||||d}|j}	|	|8 }	d|	|	dk < t|	||	 |	|| |  }	tj	j|	|jdd}|r|d }|S )Nz/minvalue must be less than or equal to maxvaluer   )rt   F)rt   rx   )r   r  r  r   r  r  r8   r  r`   ra   r  ry   r  r   powerrt   )
r   r   r   r{   r  r   r  r  rt   r  r   r   r   r     s.    

zPowerNorm.__call__c             C   sv   |   std| j}| j| j }}t|rXtj|}tj	|d| ||  | S t
|d| ||  | S d S )NzNot invertible until scaledg      ?)r  r8   r   r  r  r`   rg   ra   rp   rN  pow)r   r   r   r  r  r   r   r   r   r    s    
zPowerNorm.inverse)NNF)N)r   r   r   r   r   r   r  r    r   r   )r   r   rM  {  s   
rM  c                   s:   e Zd ZdZddd fddZddd	Zd
d Z  ZS )BoundaryNorma  
    Generate a colormap index based on discrete intervals.

    Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
    instead of to the interval 0-1.

    Mapping to the 0-1 interval could have been done via piece-wise linear
    interpolation, but using integers seems simpler, and reduces the number of
    conversions back and forth between integer and floating point.
    Fneither)extendc               s   |r|dkrt dt j|d |d |d t|| _t| j| _| jdk r^t d||| _|| _	d| _
| jd	 | _d| _|d
kr|  jd	7  _d	| _|dkr|  jd	7  _| j| jkrt d| j d| ddS )a  
        Parameters
        ----------
        boundaries : array-like
            Monotonically increasing sequence of at least 2 boundaries.
        ncolors : int
            Number of colors in the colormap to be used.
        clip : bool, optional
            If clip is ``True``, out of range values are mapped to 0 if they
            are below ``boundaries[0]`` or mapped to ``ncolors - 1`` if they
            are above ``boundaries[-1]``.

            If clip is ``False``, out of range values are mapped to -1 if
            they are below ``boundaries[0]`` or mapped to *ncolors* if they are
            above ``boundaries[-1]``. These are then converted to valid indices
            by `Colormap.__call__`.
        extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
            Extend the number of bins to include one or both of the
            regions beyond the boundaries.  For example, if ``extend``
            is 'min', then the color to which the region between the first
            pair of boundaries is mapped will be distinct from the first
            color in the colormap, and by default a
            `~matplotlib.colorbar.Colorbar` will be drawn with
            the triangle extension on the left or lower end.

        Returns
        -------
        int16 scalar or array

        Notes
        -----
        *boundaries* defines the edges of bins, and data falling within a bin
        is mapped to the color with the same index.

        If the number of bins, including any extensions, is less than
        *ncolors*, the color index is chosen by linear interpolation, mapping
        the ``[0, nbins - 1]`` range onto the ``[0, ncolors - 1]`` range.
        rQ  z+'clip=True' is not compatible with 'extend'r   r\   )r  r  r   rY   zDYou must provide at least 2 boundaries (1 region) but you passed in Nr
   )r  both)r>   rS  z
There are z0 color bins including extensions, but ncolors = z1; ncolors must equal or exceed the number of bins)r8   r   r   r`   rp   
boundariesrJ   r   NcmaprR  r  
_n_regions_offset)r   rT  ncolorsr   rR  )r   r   r   r     s&    '
zBoundaryNorm.__init__Nc       	      C   s  |d kr| j }| |\}}tj|}t|| jd }|rdtj || j| j|d | j	d }n| j	}t
|| jd | j }| j	| jkr| jdkr| j	d d ||dk< n| j	d | jd  | }|tj}d||| jk < |||| jk< tjj||d}|rt|d }|S )Nr
   )r   rY   r   r\   )rt   )r   r  r`   ra   Zgetmaskarrayr&  r  r  r  rU  ZdigitizerT  rW  rV  r   Zint16ry   rI   )	r   r   r   Zxxr  rt   Zmax_colZiretr/   r   r   r   r     s*    
zBoundaryNorm.__call__c             C   s   t ddS )z
        Raises
        ------
        ValueError
            BoundaryNorm is not invertible, so calling this method will always
            raise an error
        zBoundaryNorm is not invertibleN)r8   )r   r   r   r   r   r     s    zBoundaryNorm.inverse)F)N)r   r   r   r   r   r   r  r    r   r   )r   r   rP    s   
A
&rP  c               @   s"   e Zd ZdZdddZdd ZdS )NoNormz
    Dummy replacement for `Normalize`, for the case where we want to use
    indices directly in a `~matplotlib.cm.ScalarMappable`.
    Nc             C   s   |S )Nr   )r   r   r   r   r   r   r   0  s    zNoNorm.__call__c             C   s   |S )Nr   )r   r   r   r   r   r  3  s    zNoNorm.inverse)N)r   r   r   r   r   r  r   r   r   r   rY  +  s   
rY  c             C   sv  t | } | jd dkr(td| j| j}t j| dt | jt jdd} t 	| }| 
d}|dk}| d}t 	|}|| ||  ||< |dk}| d |k|@ }| |d	f | |df  ||  ||df< | d
 |k|@ }d| |df | |df  ||   ||df< | d |k|@ }d| |df | |d	f  ||   ||df< |d d d |d< ||d
< ||d< ||S )a,  
    Convert float rgb values (in the range [0, 1]), in a numpy array to hsv
    values.

    Parameters
    ----------
    arr : (..., 3) array-like
       All values must be in the range [0, 1]

    Returns
    -------
    (..., 3) ndarray
       Colors converted to hsv values in range [0, 1]
    r\   rV   z<Last dimension of input array must be 3; shape {} was found.FrY   )rx   rq   ndminr   ).r   r
   ).r
   g       @).rY   g      @g      @g      ?)r`   rp   r?   r8   r   ry   r  rq   r  Z
zeros_liker>   Zptprf   )arrin_shaper   Zarr_maxZiposdeltasidxr   r   r   
rgb_to_hsv7  s4    





(,,r`  c             C   s$  t | } | jd dkr*tdj| jd| j}t j| dt | jt jdd} | d }| d	 }| d
 }t 	|}t 	|}t 	|}|d 
t}|d | }	|d|  }
|d||	   }|d|d|	    }|d dk}|| ||< || ||< |
| ||< |dk}|| ||< || ||< |
| ||< |dk}|
| ||< || ||< || ||< |dk}|
| ||< || ||< || ||< |dk}|| ||< |
| ||< || ||< |dk}|| ||< |
| ||< || ||< |dk}|| ||< || ||< || ||< t j|||gdd}||S )z
    Convert hsv values to rgb.

    Parameters
    ----------
    hsv : (..., 3) array-like
       All values assumed to be in range [0, 1]

    Returns
    -------
    (..., 3) ndarray
       Colors converted to RGB values in range [0, 1]
    r\   rV   z?Last dimension of input array must be 3; shape {shp} was found.)ZshpFrY   )rx   rq   rZ  ).r   ).r
   ).rY   g      @g      ?   r   r
   r]   rW   )rk   )r`   rp   r?   r8   r   ry   r  rq   r  Z
empty_liker   rI   stackrf   )hsvr\  hr^  r&   r   r   r   ir   pqtr_  rgbr   r   r   
hsv_to_rgbk  sd    



rj  c             C   s>   d}x.t | jd D ]}|| d|tjf d 7 }qW t|S )Nr   r\   .rY   )ranger?   r`   newaxissqrt)r[  Zsum_sqre  r   r   r   _vector_magnitude  s    rn  c               @   sh   e Zd ZdZdddZedd	 ZdddZdddZdddZ	d ddZ
d!ddZdd Zdd ZdS )"LightSourcea  
    Create a light source coming from the specified azimuth and elevation.
    Angles are in degrees, with the azimuth measured
    clockwise from north and elevation up from the zero plane of the surface.

    `shade` is used to produce "shaded" rgb values for a data array.
    `shade_rgb` can be used to combine an rgb image with an elevation map.
    `hillshade` produces an illumination map of a surface.
    ;  -   r   r
   c             C   s(   || _ || _|| _|| _|| _|| _dS )a{  
        Specify the azimuth (measured clockwise from south) and altitude
        (measured up from the plane of the surface) of the light source
        in degrees.

        Parameters
        ----------
        azdeg : float, default: 315 degrees (from the northwest)
            The azimuth (0-360, degrees clockwise from North) of the light
            source.
        altdeg : float, default: 45 degrees
            The altitude (0-90, degrees up from horizontal) of the light
            source.

        Notes
        -----
        For backwards compatibility, the parameters *hsv_min_val*,
        *hsv_max_val*, *hsv_min_sat*, and *hsv_max_sat* may be supplied at
        initialization as well.  However, these parameters will only be used if
        "blend_mode='hsv'" is passed into `shade` or `shade_rgb`.
        See the documentation for `blend_hsv` for more details.
        N)azdegaltdeghsv_min_valhsv_max_valhsv_min_sathsv_max_sat)r   rr  rs  rt  ru  rv  rw  r   r   r   r     s    zLightSource.__init__c             C   sR   t d| j }t | j}t t |t | t |t | t |gS )z3The unit vector direction towards the light source.Z   )r`   radiansrr  rs  ry   cossin)r   azZaltr   r   r   	direction  s    zLightSource.direction      ?c       	      C   sj   | }t || ||\}}t |jd t|}| |d< | |d< d|d< |t| }| ||S )a
  
        Calculate the illumination intensity for a surface using the defined
        azimuth and elevation for the light source.

        This computes the normal vectors for the surface, and then passes them
        on to `shade_normals`

        Parameters
        ----------
        elevation : 2D array-like
            The height values used to generate an illumination map
        vert_exag : number, optional
            The amount to exaggerate the elevation values by when calculating
            illumination. This can be used either to correct for differences in
            units between the x-y coordinate system and the elevation
            coordinate system (e.g. decimal degrees vs. meters) or to
            exaggerate or de-emphasize topographic effects.
        dx : number, optional
            The x-spacing (columns) of the input *elevation* grid.
        dy : number, optional
            The y-spacing (rows) of the input *elevation* grid.
        fraction : number, optional
            Increases or decreases the contrast of the hillshade.  Values
            greater than one will cause intermediate values to move closer to
            full illumination or shadow (and clipping any values that move
            beyond 0 or 1). Note that this is not visually or mathematically
            the same as vertical exaggeration.

        Returns
        -------
        ndarray
            A 2D array of illumination values between 0-1, where 0 is
            completely in shadow and 1 is completely illuminated.
        )rV   ).r   ).r
   r
   ).rY   )r`   Zgradientr   r?   viewr  rn  shade_normals)	r   	elevation	vert_exagdxdyfractionZe_dyZe_dxnormalr   r   r   	hillshade  s    '

zLightSource.hillshadec             C   sX   | | j}| |  }}||9 }|| dkrF||8 }|||  }t|dd}|S )a	  
        Calculate the illumination intensity for the normal vectors of a
        surface using the defined azimuth and elevation for the light source.

        Imagine an artificial sun placed at infinity in some azimuth and
        elevation position illuminating our surface. The parts of the surface
        that slope toward the sun should brighten while those sides facing away
        should become darker.

        Parameters
        ----------
        fraction : number, optional
            Increases or decreases the contrast of the hillshade.  Values
            greater than one will cause intermediate values to move closer to
            full illumination or shadow (and clipping any values that move
            beyond 0 or 1). Note that this is not visually or mathematically
            the same as vertical exaggeration.

        Returns
        -------
        ndarray
            A 2D array of illumination values between 0-1, where 0 is
            completely in shadow and 1 is completely illuminated.
        gư>r   r
   )dotr}  r  r>   r`   r   )r   Znormalsr  	intensityZiminZimaxr   r   r   r  3  s    zLightSource.shade_normalsNoverlayc          	   K   s   |dkr|  }|dkr | }|dkr4t||d}|||}| j|f|||||	|
d|}|dddf |dddf< |S )a  
        Combine colormapped data values with an illumination intensity map
        (a.k.a.  "hillshade") of the values.

        Parameters
        ----------
        data : 2D array-like
            The height values used to generate a shaded map.
        cmap : `~matplotlib.colors.Colormap`
            The colormap used to color the *data* array. Note that this must be
            a `~matplotlib.colors.Colormap` instance.  For example, rather than
            passing in ``cmap='gist_earth'``, use
            ``cmap=plt.get_cmap('gist_earth')`` instead.
        norm : `~matplotlib.colors.Normalize` instance, optional
            The normalization used to scale values before colormapping. If
            None, the input will be linearly scaled between its min and max.
        blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
            The type of blending used to combine the colormapped data
            values with the illumination intensity.  Default is
            "overlay".  Note that for most topographic surfaces,
            "overlay" or "soft" appear more visually realistic. If a
            user-defined function is supplied, it is expected to
            combine an MxNx3 RGB array of floats (ranging 0 to 1) with
            an MxNx1 hillshade array (also 0 to 1).  (Call signature
            ``func(rgb, illum, **kwargs)``) Additional kwargs supplied
            to this function will be passed on to the *blend_mode*
            function.
        vmin : float or None, optional
            The minimum value used in colormapping *data*. If *None* the
            minimum value in *data* is used. If *norm* is specified, then this
            argument will be ignored.
        vmax : float or None, optional
            The maximum value used in colormapping *data*. If *None* the
            maximum value in *data* is used. If *norm* is specified, then this
            argument will be ignored.
        vert_exag : number, optional
            The amount to exaggerate the elevation values by when calculating
            illumination. This can be used either to correct for differences in
            units between the x-y coordinate system and the elevation
            coordinate system (e.g. decimal degrees vs. meters) or to
            exaggerate or de-emphasize topography.
        dx : number, optional
            The x-spacing (columns) of the input *elevation* grid.
        dy : number, optional
            The y-spacing (rows) of the input *elevation* grid.
        fraction : number, optional
            Increases or decreases the contrast of the hillshade.  Values
            greater than one will cause intermediate values to move closer to
            full illumination or shadow (and clipping any values that move
            beyond 0 or 1). Note that this is not visually or mathematically
            the same as vertical exaggeration.
        Additional kwargs are passed on to the *blend_mode* function.

        Returns
        -------
        ndarray
            An MxNx4 array of floats ranging between 0-1.
        N)r  r  )r  
blend_moder  r  r  r  .rV   )r  r>   r   	shade_rgb)r   r   r   normr  r  r  r  r  r  r  r;   Zrgb0Zrgb1r   r   r   shadea  s    <zLightSource.shaderc  c          
   K   s   |  |||||}	|	dtjf }	| j| j| jd}
||
krN|
| ||	f|}nHy|||	f|}W n4 tk
r } ztd|
j	|W dd}~X Y nX tj
|	r|	jd }x,tdD ] }|d|f | |d|f |< qW |S )a  
        Use this light source to adjust the colors of the *rgb* input array to
        give the impression of a shaded relief map with the given *elevation*.

        Parameters
        ----------
        rgb : array-like
            An (M, N, 3) RGB array, assumed to be in the range of 0 to 1.
        elevation : array-like
            An (M, N) array of the height values used to generate a shaded map.
        fraction : number
            Increases or decreases the contrast of the hillshade.  Values
            greater than one will cause intermediate values to move closer to
            full illumination or shadow (and clipping any values that move
            beyond 0 or 1). Note that this is not visually or mathematically
            the same as vertical exaggeration.
        blend_mode : {'hsv', 'overlay', 'soft'} or callable, optional
            The type of blending used to combine the colormapped data values
            with the illumination intensity.  For backwards compatibility, this
            defaults to "hsv". Note that for most topographic surfaces,
            "overlay" or "soft" appear more visually realistic. If a
            user-defined function is supplied, it is expected to combine an
            MxNx3 RGB array of floats (ranging 0 to 1) with an MxNx1 hillshade
            array (also 0 to 1).  (Call signature
            ``func(rgb, illum, **kwargs)``)
            Additional kwargs supplied to this function will be passed on to
            the *blend_mode* function.
        vert_exag : number, optional
            The amount to exaggerate the elevation values by when calculating
            illumination. This can be used either to correct for differences in
            units between the x-y coordinate system and the elevation
            coordinate system (e.g. decimal degrees vs. meters) or to
            exaggerate or de-emphasize topography.
        dx : number, optional
            The x-spacing (columns) of the input *elevation* grid.
        dy : number, optional
            The y-spacing (rows) of the input *elevation* grid.
        Additional kwargs are passed on to the *blend_mode* function.

        Returns
        -------
        ndarray
            An (m, n, 3) array of floats ranging between 0-1.
        .)rc  Zsoftr  z*"blend_mode" must be callable or one of {}N).r   rV   )r  r`   rl  	blend_hsvblend_soft_lightblend_overlayrL   r8   r   keysra   rs   rt   rk  )r   ri  r  r  r  r  r  r  r;   r  lookupblendr   rt   re  r   r   r   r    s"    /

 zLightSource.shade_rgbc          	   C   sh  |dkr| j }|dkr| j}|dkr*| j}|dkr8| j}|d }d| d }t|ddddddf }t|dd\}}	}
t|	t|	dk|dk@ d| |	 ||   t|	t|	dk|dk @ d| |	 ||   t|
|dkd| |
 ||   t|
|dk d| |
 ||   tj	|ddddddf dd|ddddddf d	 t
|S )
a  
        Take the input data array, convert to HSV values in the given colormap,
        then adjust those color values to give the impression of a shaded
        relief map with a specified light source.  RGBA values are returned,
        which can then be used to plot the shaded image with imshow.

        The color of the resulting image will be darkened by moving the (s, v)
        values (in hsv colorspace) toward (hsv_min_sat, hsv_min_val) in the
        shaded regions, or lightened by sliding (s, v) toward (hsv_max_sat,
        hsv_max_val) in regions that are illuminated.  The default extremes are
        chose so that completely shaded points are nearly black (s = 1, v = 0)
        and completely illuminated points are nearly white (s = 0, v = 1).

        Parameters
        ----------
        rgb : ndarray
            An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
        intensity : ndarray
            An MxNx1 array of floats ranging from 0 to 1 (grayscale image).
        hsv_max_sat : number, default: 1
            The maximum saturation value that the *intensity* map can shift the
            output image to.
        hsv_min_sat : number, optional
            The minimum saturation value that the *intensity* map can shift the
            output image to. Defaults to 0.
        hsv_max_val : number, optional
            The maximum value ("v" in "hsv") that the *intensity* map can shift
            the output image to. Defaults to 1.
        hsv_min_val : number, optional
            The minimum value ("v" in "hsv") that the *intensity* map can shift
            the output image to. Defaults to 0.

        Returns
        -------
        ndarray
            An MxNx3 RGB array representing the combined images.
        N).r   rY   r
   r   rV   r\   g|=)r   )rw  ru  rv  rt  r`  r`   ZmoveaxisZputmaskr+  r   rj  )r   ri  r  rw  ru  rt  rv  rc  huesatr   r   r   r   r    s,    (>zLightSource.blend_hsvc             C   s    d| | dd|  |d   S )a  
        Combine an rgb image with an intensity map using "soft light" blending,
        using the "pegtop" formula.

        Parameters
        ----------
        rgb : ndarray
            An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
        intensity : ndarray
            An MxNx1 array of floats ranging from 0 to 1 (grayscale image).

        Returns
        -------
        ndarray
            An MxNx3 RGB array representing the combined images.
        rY   r
   r   )r   ri  r  r   r   r   r  =	  s    zLightSource.blend_soft_lightc             C   s6   d| | }ddd|  d|   }t |dk||S )a  
        Combine an rgb image with an intensity map using "overlay" blending.

        Parameters
        ----------
        rgb : ndarray
            An MxNx3 RGB array of floats ranging from 0 to 1 (color image).
        intensity : ndarray
            An MxNx1 array of floats ranging from 0 to 1 (grayscale image).

        Returns
        -------
        ndarray
            An MxNx3 RGB array representing the combined images.
        rY   r
   g      ?)r`   where)r   ri  r  lowhighr   r   r   r  P	  s    zLightSource.blend_overlay)rp  rq  r   r
   r
   r   )r
   r
   r
   r~  )r~  )Nr  NNr
   r
   r
   r
   )r~  rc  r
   r
   r
   )NNNN)r   r   r   r   r   r  r}  r  r  r  r  r  r  r  r   r   r   r   ro    s   	 

5
. 
J 
H 
Gro  rQ  c       	   
   C   s   t ddt ddt ddt ddd}tj||d || }t| d }||j |jpXd }t||krtd|dt|  d	| d
t| t|| |d}|dkr||d  n
|d |dkr|	|d  n
|	d ||_
t| |d}||fS )aw  
    A helper routine to generate a cmap and a norm instance which
    behave similar to contourf's levels and colors arguments.

    Parameters
    ----------
    levels : sequence of numbers
        The quantization levels used to construct the `BoundaryNorm`.
        Value ``v`` is quantized to level ``i`` if ``lev[i] <= v < lev[i+1]``.
    colors : sequence of colors
        The fill color to use for each level. If *extend* is "neither" there
        must be ``n_level - 1`` colors. For an *extend* of "min" or "max" add
        one extra color, and for an *extend* of "both" add two colors.
    extend : {'neither', 'min', 'max', 'both'}, optional
        The behaviour when a value falls out of range of the given levels.
        See `~.Axes.contourf` for details.

    Returns
    -------
    cmap : `~matplotlib.colors.Normalize`
    norm : `~matplotlib.colors.Colormap`
    r
   r\   Nr   )rS  r  r>   rQ  )rR  zWith extend == z and z levels, expected z colors, but got )r   )r  rS  rQ   )r>   rS  )rX  )slicer   Zcheck_in_listrJ   startstopr8   r   r   r   r   rP  )	ZlevelsrO   rR  Z	slice_mapZcolor_sliceZn_data_colorsZ
n_expectedr   r  r   r   r   from_levels_and_colorse	  s*    &

r  )N)N)N)F)r   )N)NNF)r   NNF)rQ  )Mr   r   collections.abcr   r   rx   r   r?  r   r   numbersr   r3   ZPILr   ZPIL.PngImagePluginr   rF   r   numpyr`   r   r   r	   Z_color_datar   r   r   r   dictr   r)   r   r:   r   r*   r0   r6   r9   r<   rC   r7   rM   r=   r|   r   ZcnamescompileZhexColorPatternZrgb2hexZ	hex2colorr   ZcolorConverterr   r   r   r   r   r   r  r'  r>  Z	FuncScalerF  r   ZLogScalerH  ZSymmetricalLogScalerL  rM  rP  rY  r`  rj  rn  ro  r  r   r   r   r   <module>(   s   






	
+
\
a


d  * $_ 9[a`"3}4R
   !