
    g)             
       ~   d Z ddlZddlmZ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mZmZ dd	lmZmZmZmZ  G d
 de       Z!i Z"e"jG                  e       e"jG                   ejH                         D  ci c]  \  } }d| v r| jK                  dd      | c}}        e"jG                  e       e"jG                  e       e"jG                   ejH                         D  ci c]  \  } }d| v r| jK                  dd      | c}}        e"jG                  e        e!e"      Z"dZ&dZ'd Z( G d de      Z) e)       Z*d Z+ ejX                  d      Z-d Z.d Z/d Z0d Z1d Z2dWdZ3dWdZ4dWdZ5d Z6dXdZ7eZ8 ejX                  d      Z9e7Z:e6Z; G d  d!      Z< e<       Z=dYd"Z> G d# d$      Z? G d% d&e?      Z@ G d' d(e?      ZA G d) d*      ZB G d+ d,      ZC G d- d.eC      ZD G d/ d0eC      ZE G d1 d2      ZF G d3 d4eF      ZG G d5 d6eF      ZHdWdd7d8ZIej                  d9        ZKd: ZLd; ZM eIej                  dZd<7       G d= d>eF             ZO  eI ej                  ej                  d?@            eF      ZRdAxeR_S        eR_T        dBeR_          eIej                  d[dCdDdE7       G dF dGeF             ZV eIej                  d\dH7       G dI dJeF             ZX G dK dLeF      ZY G dM dNeF      ZZ G dO dPeF      Z[dQ Z\dR Z]dS Z^ G dT dU      Z_d]dVZ`yc c}} w c c}} w )^a  
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::

  :ref:`colormap-manipulation` for examples of how to
  make colormaps and

  :ref:`colormaps` for a list of built-in colormaps.

  :ref:`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
:ref:`colors_def`.

.. _palettable: https://jiffyclub.github.io/palettable/
.. _xkcd color survey: https://xkcd.com/color/rgb/
    N)SizedSequenceMapping)Real)Image)PngInfo)_api_cmcbookscale_image   )BASE_COLORSTABLEAU_COLORSCSS4_COLORSXKCD_COLORSc                   2     e Zd Z fdZ fdZ fdZ xZS )_ColorMappingc                 2    t         |   |       i | _        y N)super__init__cache)selfmapping	__class__s     N/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/matplotlib/colors.pyr   z_ColorMapping.__init__>   s    !
    c                 Z    t         |   ||       | j                  j                          y r   )r   __setitem__r   clear)r   keyvaluer   s      r   r    z_ColorMapping.__setitem__B   s"    C'

r   c                 X    t         |   |       | j                  j                          y r   )r   __delitem__r   r!   )r   r"   r   s     r   r%   z_ColorMapping.__delitem__F   s     C 

r   )__name__
__module____qualname__r   r    r%   __classcell__r   s   @r   r   r   =   s     r   r   greygray)i   @      c                      t         S )z3Return the global mapping of names to named colors.)_colors_full_map r   r   get_named_colors_mappingr2   ]   s    r   c                   ^   e Zd ZdZej
                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                   ej"                  dZd Zd Zd Zd Zd Zd Zd	 Zy
)ColorSequenceRegistrya  
    Container for sequences of colors that are known to Matplotlib by name.

    The universal registry instance is `matplotlib.color_sequences`. There
    should be no need for users to instantiate `.ColorSequenceRegistry`
    themselves.

    Read access uses a dict-like interface mapping names to lists of colors::

        import matplotlib as mpl
        colors = mpl.color_sequences['tab10']

    The returned lists are copies, so that their modification does not change
    the global definition of the color sequence.

    Additional color sequences can be added via
    `.ColorSequenceRegistry.register`::

        mpl.color_sequences.register('rgb', ['r', 'g', 'b'])
    )tab10tab20tab20btab20cPastel1Pastel2PairedAccentDark2Set1Set2Set3	petroff10c                 *    i | j                   | _        y r   )_BUILTIN_COLOR_SEQUENCES_color_sequencesr   s    r   r   zColorSequenceRegistry.__init__   s     A4#@#@ Ar   c                 j    	 t        | j                  |         S # t        $ r t        |d      w xY w)Nz# is not a known color sequence name)listrD   KeyErrorr   items     r   __getitem__z!ColorSequenceRegistry.__getitem__   sB    	K--d344 	KdX%HIJJ	Ks    2c                 ,    t        | j                        S r   )iterrD   rE   s    r   __iter__zColorSequenceRegistry.__iter__   s    D))**r   c                 ,    t        | j                        S r   )lenrD   rE   s    r   __len__zColorSequenceRegistry.__len__   s    4(())r   c                 8    ddj                  d | D              z   S )Nz,ColorSequenceRegistry; available colormaps:
z, c              3   (   K   | ]
  }d | d   yw)'Nr1   ).0names     r   	<genexpr>z0ColorSequenceRegistry.__str__.<locals>.<genexpr>   s     7$AdV1+7s   )joinrE   s    r   __str__zColorSequenceRegistry.__str__   s!    ?		7$778 	9r   c                     || j                   v rt        |d      t        |      }|D ]  }	 t        |        || j                  |<   y# t        $ r t        |d      w xY w)a  
        Register a new color sequence.

        The color sequence registry stores a copy of the given *color_list*, so
        that future changes to the original list do not affect the registered
        color sequence. Think of this as the registry taking a snapshot
        of *color_list* at registration.

        Parameters
        ----------
        name : str
            The name for the color sequence.

        color_list : list of :mpltype:`color`
            An iterable returning valid Matplotlib colors when iterating over.
            Note however that the returned color sequence will always be a
            list regardless of the input type.

        z0 is a reserved name for a builtin color sequencez# is not a valid color specificationN)rC   
ValueErrorrG   to_rgbarD   )r   rV   
color_listcolors       r   registerzColorSequenceRegistry.register   s    ( 4000x (. . / / *%
 	EEE	E '1d#	  E iBCE EEs   AA#c                 t    || j                   v rt        d|      | j                  j                  |d       y)z
        Remove a sequence from the registry.

        You cannot remove built-in color sequences.

        If the name is not registered, returns with no error.
        z)Cannot unregister builtin color sequence N)rC   r[   rD   popr   rV   s     r   
unregisterz ColorSequenceRegistry.unregister   sA     4000;D8DF F!!$-r   N)r&   r'   r(   __doc__r
   _tab10_data_tab20_data_tab20b_data_tab20c_data_Pastel1_data_Pastel2_data_Paired_data_Accent_data_Dark2_data
_Set1_data
_Set2_data
_Set3_data_petroff10_datarC   r   rK   rN   rQ   rY   r_   rc   r1   r   r   r4   r4   b   s    , """"$$$$""""((  BK+*9 1D.r   r4   c                 f    | | S 	 | j                         }|S # t        $ r t        |       }Y |S w xY wr   )rJ   AttributeErrorfloat)exrets     r   _sanitize_extremarw      sB    	z	ggi J  BiJs    00z\AC[0-9]+\Zc                 P    t        | t              xr t        j                  |       S )zDReturn whether *c* can be interpreted as an item in the color cycle.)
isinstancestr_nth_color_rematchcs    r   _is_nth_colorr      s    a8-"5"5a"88r   c                 ^    t        |       ry	 t        |        y# t        t        f$ r Y yw xY w)z9Return whether *c* can be interpreted as an RGB(A) color.TF)r   r\   	TypeErrorr[   r}   s    r   is_color_liker      s9     Q
  z" s    ,,c                 D    t        | t               xr t        |       dk(  S )z4Return whether *c* is a color with an alpha channel.   )ry   rz   rP   r}   s    r   _has_alpha_channelr      s!     !S!!1c!fk1r   c                  l    | j                         D ]!  \  }}t        |      rt        |d| d       y)zS
    For each *key, value* pair in *kwargs*, check that *value* is color-like.
    z is not a valid value for a*  : supported inputs are (r, g, b) and (r, g, b, a) 0-1 float tuples; '#rrggbb', '#rrggbbaa', '#rgb', '#rgba' strings; named color strings; string reprs of 0-1 floats for grayscale values; 'C0', 'C1', ... strings for colors of the color cycle; and pairs combining one of the above with an alpha valueN)itemsr   r[   )kwargskvs      r   _check_color_liker      sN      	M1Q%1! 5K LM M	Mr   c                    t        |       } t        |      }t        | j                  d   d      }t        |j                  d   d      }||k7  rt        d      | j                  |j                  k(  xr | |k(  j	                         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shaper[   all)c1c2n1n2s       r   
same_colorr     sx     
r	B	r	B	RXXa[!	B	RXXa[!	B	Rx?@@ 88rxx4R2XNN$44r   c                    t        | t              rt        |       dk(  r|| \  } }n| d   } t        |       rQt        j
                  d   }|j                         j                  ddg      }|t        | dd       t        |      z     } 	 t        j                  | |f   }|$t        | |      }	 |t        j                  | |f<   |S |S # t        t        f$ r d}Y ;w xY w# t        $ r Y |S w xY w)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.
       Nr   zaxes.prop_cycler^   r   r   )ry   tuplerP   r   mplrcParamsby_keygetintr0   r   rH   r   _to_rgba_no_colorcycle)r~   alphaprop_cyclercolorsrgbas        r   r\   r\     s   0 !UA!=HAu!AQll#45##%))'C593qu:F+,%%ah/ |%a/	/3""1e8, K4K i    	K	s$   	C -C CC	C*)C*c                    |"d|cxk  rdk  st        d       t        d      | }| t        j                  j                  u ryt	        | t
              r| j                         dk(  ry	 t        |    } t	        | t
              rvt        j                  d|       }|r)t        d | dd	 | d	d
 | d
d fD              ||fz   S dfz   S t        j                  d|       }|r2t        d | d   dz  | d   dz  | d	   dz  fD              ||fz   S dfz   S t        j                  d|       }|r>| dd	 | d	d
 | d
d | dd fD cg c]  }t        |d      dz   }}|||d<   t        |      S t        j                  d|       }|rJ| d   dz  | d   dz  | d	   dz  | d   dz  fD cg c]  }t        |d      dz   }}|||d<   t        |      S 	 t        |       } d| cxk  rdk  sn t        d|d      | | | ||fS dfS t	        | t        j                        r2| j                   dk(  r#| j"                  d   dk(  r| j%                  d      } t        j&                  |       st        d|      t        |       dvrt        d      t)        d | D              st        d|      t        t+        t        |             } t        |       d	k(  r|d}|	| dd	 |fz   } t-        d | D              rt        d      | S # t        $ r: t        |      dk7  r(	 t        | j                            } n# t        $ r Y nw xY wY w xY wc c}w c c}w # t         $ r Y nw xY wt        d|      )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)``.
    Nr   r   *'alpha' must be between 0 and 1, inclusive        r   r   r   none\A#[a-fA-F0-9]{6}\Zc              3   :   K   | ]  }t        |d       dz    yw      Nr   rU   ns     r   rW   z)_to_rgba_no_colorcycle.<locals>.<genexpr>e  #      = a*s* =                  ?z\A#[a-fA-F0-9]{3}\Zc              3   :   K   | ]  }t        |d       dz    ywr   r   r   s     r   rW   z)_to_rgba_no_colorcycle.<locals>.<genexpr>k  r   r   r   z\A#[a-fA-F0-9]{8}\Z	   r   r   z\A#[a-fA-F0-9]{4}\Zr   zInvalid string grayscale value z . Value must be within 0-1 rangezInvalid RGBA argument: r   r   z'RGBA sequence should have length 3 or 4c              3   <   K   | ]  }t        |t                y wr   )ry   r   )rU   xs     r   rW   z)_to_rgba_no_colorcycle.<locals>.<genexpr>  s     .qz!T".s   c              3   4   K   | ]  }|d k  xs |dkD    yw)r   r   Nr1   )rU   elems     r   rW   z)_to_rgba_no_colorcycle.<locals>.<genexpr>  s      
.D4!8tax
.s   &RGBA values should be within 0-1 range)r[   npmamaskedry   rz   lowerr0   rH   rP   rer|   r   r   rt   ndarrayndimr   reshapeiterabler   mapany)r~   r   orig_cr|   r   r^   s         r   r   r   D  s    eqEFF "1EFFFBEELL!S779#	 #A !S/3 =$%aFAaFAaF#;= = % 1u;< =79;< = /3 =$%aDFAaDFAaDF#;= = % 1u;< =79;< = /3 1vq1vq1vq1v>@ BZ#% @E @ !b	</3 tAvqtAvqtAvqtAv>@ BZ#% @E @ !b	<		?aA KaK 5fZ @5 67 7 aU%6E>>B>> !RZZ 66Q;1771:?		"A;;q>26*=>>
1vVBCC.A.. 26*=>>c%mA
1v{u}bqEUH

.A
..ABBHI  	6{a(3A 		,@@  		 26*=>>sT   )	K5 :L;M M 5L8L%$L8%	L1.L80L11L87L8	MMc           	      	   t        | t              r.t        |       dk(  r t        | d   t              r|| \  } }n| d   } t	        j
                  |      r#t	        j                  |      j                         }t        | t        j                        r| j                  j                  dv r| j                  dk(  r| j                  d   dv rt        j                  j                  |       r| j                  j!                  d      nd}t        j                  j#                  |       } t	        j
                  |      rt| j                  d   dk(  r8|j                  d   dkD  r&t	        j$                  | |j                  d   df      } n*| j                  d   |j                  d   k7  rt'        d      | j                  d   d	k(  rAt	        j(                  | t	        j*                  t        |             g      }||nd
|dddf<   n-| j                  d   dk(  r| j-                         }|	||dddf<   |d|<   t	        j                   dk  |dkD  z        rt'        d      |S t/        j0                  | d      rt	        j*                  dt2              S 	 t	        j
                  |      r2t	        j4                  |D cg c]  }t7        | |       c}t2              S t	        j4                  t7        | |      gt2              S c c}w # t8        $ r Y n&t&        $ r}|j:                  dk(  r|Y d}~nd}~ww xY wt        | t<              rt'        | d      t        |       dk(  rt	        j*                  dt2              S t        | t>              r| D ch c]%  }t        |t@        t        f      rt        |      nd' nc c}w }}|d	hk(  r4t	        j(                  | t	        jB                  t        |             g      }n|dhk(  rt	        j4                  |       }net	        j4                  | D cg c]  }t7        |       nc c}w c}      }n2t	        j4                  | D cg c]  }t7        |       nc c}w c}      }|N||ddd	f<   t        | t>              r5| D cg c]  }t/        jD                  |d       nc c}w }	}d|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 `~numpy.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.
    r   r   Nr   ifr   axisz^The number of colors must match the number of alpha values if there are more than one of each.r   r   r   r   r   r   )r   r   )r   z is not a valid color value.)#ry   r   rP   r   r   r   asarrayravelr   dtypekindr   r   r   	is_maskedmaskr   getdatatiler[   column_stackzeroscopyr   _str_lower_equalrt   arrayr\   r   argsrz   r   rG   ones
_str_equal)
r~   r   r   resultaecclensr   	none_masks
             r   r   r     s   : !UA!
1Q40F=HAu!A 
{{5

5!'')1bjj!agglld&:!
f 4%'UU__Q%7qvvzzqz!TEEMM!;;uwwqzQ5;;q>A#5GGAA23u{{1~-  "- . . 771:?__a#a&)9%:;F%*%6EBF1b5MWWQZ1_VVXF  %q"uF4L666A:&1*-.EFF
 a(xx&&
;;u88E:qWQ]:EBB88WQ./77 ;   66EEG F !SA5 <=>>
1v{xx&& !XKLMR:b4-8Bb@MMMA3;??Arwws1v#78DaS[88A;D8815RWR[556Dxxq1112QT
a" ABB"))"f5BBIB$%DAJy!KsN   (L =LL $L L 	L4L4L//L4*N<,P?Q2R;c                     t        |       dd S )zAConvert *c* to an RGB color, silently dropping the alpha channel.Nr   )r\   r}   s    r   to_rgbr     s    1:bq>r   c                 \    t        |       } |s| dd } ddj                  d | D              z   S )a@  
    Convert *c* to a hex color.

    Parameters
    ----------
    c : :ref:`color <colors_def>` 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
    Nr   # c              3   L   K   | ]  }t        t        |d z        d        yw)r   02xN)formatround)rU   vals     r   rW   zto_hex.<locals>.<genexpr>&  s      FScCi 0%8Fs   "$)r\   rX   )r~   
keep_alphas     r   to_hexr     s5      	
AbqEFAFFFFr   r   c                   \    e Zd ZdZeZej                  Z ee      Z ee	      Z	 ee
      Z
y)ColorConverterz
    A class only kept for backwards compatibility.

    Its functionality is entirely provided by module-level functions.
    N)r&   r'   r(   rd   r0   r   r   staticmethodr   r\   r   r1   r   r   r   r   2  s7    
 F""E&!F7#G /Mr   r   c                    t        |      rRt        j                  dd|       |z  }t        j                  t        j                   ||      t
              dd      }|S 	 t        j                  |      }t        j                  d|       |dddf   }|dddf   }|dddf   }	|d   d	k7  s|d
   dk7  rt        d      t        j                  |      dk  j                         rt        d      | dk(  rt        j                  |d
         }n|| dz
  z  }| dz
  t        j                  dd|       |z  z  }t        j                  ||      dd
 }
|dd
 ||
dz
     z
  ||
   ||
dz
     z
  z  }t        j                  |	d   g|||
   |	|
dz
     z
  z  |	|
dz
     z   |d
   gg      }t        j                  |d	d      S # t        $ r}t        d      |d}~ww xY w)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   r   z$data must be convertible to an arrayN)Nr   )datar   r   r   r   z8data mapping points must start with x=0 and end with x=1z3data mapping points must have x in increasing order)callabler   linspaceclipr   rt   	Exceptionr   r	   check_shaper[   diffr   searchsortedconcatenate)Nr   gammaxindlutadataerrr   y0y1inddistances               r   _create_lookup_tabler	  E  s   v ~{{1a#u,ggbhhtDz7A>
I 	YU+adA	q!tB	q!tBtrzQrUc\FH 	H

QNOOAvhhr"vQKAQ1-66ooa&q,2J37+#370CDnnUG3"S1W+-.C!G<VH
  773S!!;  I>?SHIs   F= =	GGGc                       e Zd ZdZddZddZddZd Zd Zd Z	dd	Z
d
 ZddZd ZddZdddddZdddddZd Zd Zd Zd ZddZd Zd Zd Zy)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                     || _         t        |      | _        d| _        d| _        d| _        | j                  | _        | j                  dz   | _        | j                  dz   | _        d| _	        d| _
        d| _        y)z
        Parameters
        ----------
        name : str
            The name of the colormap.
        N : int
            The number of RGB quantization levels.
        r   Nr   r   F)rV   r   r   	_rgba_bad_rgba_under
_rgba_over_i_under_i_over_i_bad_isinit
n_variatescolorbar_extend)r   rV   r   s      r   r   zColormap.__init__  sm     	Q-vvzffqj
  %r   Nc                 t    | j                  |||      \  }}t        j                  |      st        |      }|S )a  
        Parameters
        ----------
        X : float or int, `~numpy.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, default: False
            If False (default), the returned RGBA values will be floats in the
            interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s 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, )``.
        )r   bytes)_get_rgba_and_maskr   r   r   )r   Xr   r  r   r   s         r   __call__zColormap.__call__  s8    . ,,Qe5,I
d{{1~;Dr   c                    | j                   s| j                          t        j                  |d      }|j                  j
                  s7|j                         j                  |j                  j                               }|j                  j                  dk(  r.|| j                  z  }| j                  dz
  ||| j                  k(  <   |dk  }|| j                  k\  }t        j                  j                  |      r|j                  nt        j                  |      }t        j                  d      5  |j!                  t"              }ddd       | j$                  ||<   | j&                  ||<   | j(                  ||<   | j*                  }|r"|d	z  j!                  t        j,                        }|j/                  |dd
      }	|}t        j0                  |dd      }|r|d	z  }|j2                  d|j2                  fvr%t5        d|j2                   d|j2                         ||	d<   |d   dk(  j7                         rd|	|<   |	|fS # 1 sw Y   xY w)a=  
        Parameters
        ----------
        X : float or int, `~numpy.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, default: False
            If False (default), the returned RGBA values will be floats in the
            interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
            interval ``[0, 255]``.

        Returns
        -------
        colors : np.ndarray
            Array of RGBA values with a shape of ``X.shape + (4, )``.
        mask : np.ndarray
            Boolean array with True where the input is ``np.nan`` or masked.
        Tr   fr   r   ignoreinvalidNr   r   )r   moder1   "alpha is array-like but its shape z does not match that of X .r   r   r   r   r   r   )r  _initr   r   r   isnativebyteswapviewnewbyteorderr   r   r   r   r   isnanerrstateastyper   r  r  r  _lutuint8taker   r   r[   r   )
r   r  r   r  xa
mask_under	mask_overmask_badr  r   s
             r   r  zColormap._get_rgba_and_mask  s   2 ||JJLXXad#xx  ##BHH$9$9$;<B88==C$&&LB#vvzBrTVV| !V
$&&L	UU__Q/166RXXb\[[* 	 3B	  :9{{8ii9$$RXX.Cxxx0GGE1a(E{{2rxx.0 8 F++-88*67 7 "DMB1!!#!-XX~5	  	 s   2IIc                     | j                   }|j                  |      }|j                  j                  | j                         | j                  r$t        j                  | j                        |_        |S r   )r   __new____dict__updater  r   r   r-  r   cls
cmapobjects      r   __copy__zColormap.__copy__.  sR    nn[[%
""4==1<< ggdii0JOr   c                    t        |t              r| j                  |j                  k7  ry| j                  s| j	                          |j                  s|j	                          t        j                  | j                  |j                        S NF)ry   r  r  r  r%  r   array_equalr-  r   others     r   __eq__zColormap.__eq__6  s\    5(+$$(=(==||JJL}}KKM~~dii44r   c                     | j                   s| j                          t        j                  | j                  | j
                           S z Get the color for masked values.)r  r%  r   r   r-  r  rE   s    r   get_badzColormap.get_badA  s.    ||JJLxx		$++.//r   c                 `    t        ||      | _        | j                  r| j                          yy)z Set the color for masked values.N)r\   r  r  _set_extremesr   r^   r   s      r   set_badzColormap.set_badG  s(     .<<  r   c                     | j                   s| j                          t        j                  | j                  | j
                           S )z*Get the color for low out-of-range values.)r  r%  r   r   r-  r  rE   s    r   	get_underzColormap.get_underM  s.    ||JJLxx		$--011r   c                 `    t        ||      | _        | j                  r| j                          yy)z*Set the color for low out-of-range values.N)r\   r  r  rF  rG  s      r   	set_underzColormap.set_underS  s)    "5%0<<  r   c                     | j                   s| j                          t        j                  | j                  | j
                           S )z+Get the color for high out-of-range values.)r  r%  r   r   r-  r  rE   s    r   get_overzColormap.get_overY  s.    ||JJLxx		$,,/00r   c                 `    t        ||      | _        | j                  r| j                          yy)z+Set the color for high out-of-range values.N)r\   r  r  rF  rG  s      r   set_overzColormap.set_over_  s(    !%/<<  r   badunderoverc                x    || j                  |       || j                  |       || j                  |       yy)z
        Set the colors for masked (*bad*) values and, when ``norm.clip =
        False``, low (*under*) and high (*over*) out-of-range values.
        N)rH  rL  rP  )r   rR  rS  rT  s       r   set_extremeszColormap.set_extremese  s>    
 ?LLNN5!MM$ r   c                N    | j                         }|j                  |||       |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.
        rQ  )r   rV  )r   rR  rS  rT  new_cms        r   with_extremeszColormap.with_extremesq  s)     5t<r   c                    | j                   r$| j                   | j                  | j                  <   n&| j                  d   | j                  | j                  <   | j                  r$| j                  | j                  | j                  <   n3| j                  | j
                  dz
     | j                  | j                  <   | j                  | j                  | j                  <   y )Nr   r   )r  r-  r  r  r  r   r  r  rE   s    r   rF  zColormap._set_extremes{  s    '+'7'7DIIdmm$'+yy|DIIdmm$??&*ooDIIdll#&*ii
&;DIIdll#!%		$++r   c                     t        d      z)Generate the lookup table, ``self._lut``.zAbstract class onlyNotImplementedErrorrE   s    r   r%  zColormap._init      !"788r   c                 &   | j                   s| j                          t        j                  | j                  dddf   | j                  dddf   k(        xr: t        j                  | j                  dddf   | j                  dddf   k(        S )z)Return whether the colormap is grayscale.Nr   r   r   )r  r%  r   r   r-  rE   s    r   is_grayzColormap.is_gray  sn    ||JJLtyyA$))AqD/9: ;tyyA$))AqD/9:	<r   c                     t        | d      r3t        j                  dt        |        d       | j	                  |      S t               )-Return a new colormap with *lutsize* entries.	_resamplezHThe ability to resample a color map is now public API However the class zX still only implements the previous private _resample method.  Please update your class.)hasattrr	   warn_externaltyperd  r^  )r   lutsizes     r   	resampledzColormap.resampled  sL    4%%%)$ZL 1 >>'**!##r   c                     t               )a  
        Return a reversed instance of the Colormap.

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

        Parameters
        ----------
        name : str, optional
            The name for the reversed colormap. If None, the
            name is set to ``self.name + "_r"``.

        See Also
        --------
        LinearSegmentedColormap.reversed
        ListedColormap.reversed
        r]  rb   s     r   reversedzColormap.reversed  s    " "##r   c                    t        j                  t        j                  ddt        d         t        d   df      } | |d      }t	        j
                         }| j                  dz   }dt        j                   d}t               }|j                  d|       |j                  d	|       |j                  d
|       |j                  d|       t        j                  |      j                  |d|       |j                         S ).Generate a PNG representation of the Colormap.r   r   Tr  z	 colormapMatplotlib v, https://matplotlib.orgTitleDescriptionAuthorSoftwarepngr   pnginfo)r   r   r   _REPR_PNG_SIZEioBytesIOrV   r   __version__r   add_textr   	fromarraysavegetvalue)r   r  pixels	png_bytestitleauthorrw  s          r   
_repr_png_zColormap._repr_png_  s    GGBKK1nQ&78#A&*,at$JJL			K'00HI)%(.6*V,$$Yug$N!!##r   c                 n   | j                         }t        j                  |      j                  d      }d }d| j                   d| j                   d| j                   d| dt
        d   d	z    d
 || j                                d || j                                d || j                                dS )0Generate an HTML representation of the Colormap.asciic                 .    t        | 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   r^   	hex_colors     r   color_blockz)Colormap._repr_html_.<locals>.color_block  -    u6I"9+ .) *39> ?r   -<div style="vertical-align: middle;"><strong>,</strong> </div><div class="cmap"><img alt="z colormap" title="=" style="border: 1px solid #555;" src="data:image/png;base64,7"></div><div style="vertical-align: middle; max-width: r   r   Npx; 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 </div></div>)	r  base64	b64encodedecoderV   rx  rJ  rD  rN  r   r  
png_base64r  s       r   _repr_html_zColormap._repr_html_  s    OO%	%%i077@
	?99+ & 		{ #)) %..8\ :,Q/12 3- t~~/01 2 #4<<>23#DMMO45' 	r   c                 "    | j                         S zReturn a copy of the colormap.r;  rE   s    r   r   zColormap.copy      }}r   )r.   r=  )r   Nr   )r&   r'   r(   rd   r   r  r  r;  rA  rD  rH  rJ  rL  rN  rP  rV  rY  rF  r%  ra  ri  rk  r  r  r   r1   r   r   r  r    s    	%28DL	50!2!1! #'d 
  $(t$ 	09<$$&$ "Hr   r  c                   `     e Zd ZdZd	 fd	Zd Zd Zed	d       Zd Z	ed        Z
d
dZ x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.
    c                 P    d| _         t        | 	  ||       || _        || _        y)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   rV   segmentdatar   r   r   s        r   r   z LinearSegmentedColormap.__init__  s+    Z  q!'r   c                    t        j                  | j                  dz   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                  v r5t        | j                  | j                  d
   d      | j                  d ddf<   d| _        | j                          y )Nr   r   redr   greenr   bluer   r   T)
r   r   r   rt   r-  r	  r  r  r  rF  rE   s    r   r%  zLinearSegmentedColormap._init%  s   GGTVVaZOU3	0FFD%%e,dkk;		#2#q&0FFD%%g.=		#2#q&0FFD%%f-t{{<		#2#q&d''' 4))'2A!7DIIcrc1fr   c                 2    || _         | j                          y)z.Set a new gamma value and regenerate colormap.N)r  r%  )r   r   s     r   	set_gammaz!LinearSegmentedColormap.set_gamma3  s    

r   c                    t        j                  |      st        d      t        |d   t              r0t        |d         dk(  rt        |d   t              st        | \  }}n t        j                  ddt        |            }t        |      j                  \  }}}}t        j                  |||g      t        j                  |||g      t        j                  |||g      t        j                  |||g      d}	t        | |	||      S )a  
        Create a `LinearSegmentedColormap` from a list of colors.

        Parameters
        ----------
        name : str
            The name of the colormap.
        colors : list of :mpltype:`color` or list 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   r   r   )r  r  r  r   )r   r   r[   ry   r   rP   rz   zipr   r   Tr   r  )
rV   r   r   r   valsrgbr   cdicts
             r   	from_listz!LinearSegmentedColormap.from_list8  s    & {{6"677vay%(S^q-@"6!9c2<LD&;;q!S[1D"6*,,
1a??D!Q<0__dAq\2OOT1aL1__dAq\2	
 'tUAu==r   c                     t        | j                  | j                  |      }| j                  |_        | j                  |_        | j
                  |_        |S )rc  )r  rV   r  r  r  r  )r   rh  new_cmaps      r   ri  z!LinearSegmentedColormap.resampled_  sH    *499d6G6G+24"oo#//!^^r   c                      | d|z
        S )Nr   r1   )funcr   s     r   	_reverserz!LinearSegmentedColormap._reverseri  s    AE{r   c                    || j                   dz   }| j                  j                         D ci c]X  \  }}|t        |      r t	        j
                  | j                  |      n&t        |      D cg c]  \  }}}d|z
  ||f c}}}Z }}}}}}t        ||| j                  | j                        }| j                  |_        | j                  |_        | j                  |_        |S c c}}}w c c}}}}}w )aS  
        Return a reversed instance of the Colormap.

        Parameters
        ----------
        name : str, optional
            The name for the reversed colormap. If None, the
            name is set to ``self.name + "_r"``.

        Returns
        -------
        LinearSegmentedColormap
            The reversed colormap.
        _rr   )rV   r  r   r   	functoolspartialr  rk  r  r   r  r  r  r  )	r   rV   r"   r   r   r  r  data_rr  s	            r   rk  z LinearSegmentedColormap.reversedm  s     <99t#D $(#4#4#:#:#<> >  c4 #D> "))$..$?<DTNKKyq"b#'2r*KL > >
 +4M"..#!^^ L>s   AC35C,C3,C3)r.   r   r   )r&   r'   r(   rd   r   r%  r  r   r  ri  r  rk  r)   r*   s   @r   r  r    sK    0d
 $> $>L  r   r  c                   8     e Zd ZdZd fd	Zd Zd ZddZ x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
        Sequence of Matplotlib color specifications (color names or RGB(A)
        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.
    c                    d| _         ||| _        t        |      }nt        |t              r|g|z  | _        d| _         nt        j                  |      rMt        |      dk(  rd| _         t        t        j                  t        j                  |      |            | _        n	 t        |      }|g|z  | _        d| _         t        | 9  ||       y # t        $ r Y #w xY w)NFTr   )r  r   rP   ry   rz   r   r   rG   	itertoolsislicecyclert   r   r   r   )r   r   rV   r   r,   r   s        r   r   zListedColormap.__init__  s    9 DKFA&#&%hl"&V$v;!#&*DO"$$Y__V%<a@B- =D $(&1*DK"&q! ! s   $C 	CCc                     t        j                  | j                  dz   dft              | _        t        | j                        | j                  d d d| _        | j                          y )Nr   r   r  T)	r   r   r   rt   r-  r   r   r  rF  rE   s    r   r%  zListedColormap._init  sK    HHdffqj!_e4	&t{{3		#2r   c                      | t        j                  dd|            }t        || j                        }| j                  |_        | j
                  |_        | j                  |_        |S )rc  r   r   rV   )r   r   r  rV   r  r  r  )r   rh  r   r  s       r   ri  zListedColormap.resampled  sT    bkk!Q01!&tyy9"oo#//!^^r   c                     || j                   dz   }t        t        | j                              }t	        ||| j
                        }| j                  |_        | j                  |_        | j                  |_        |S )aX  
        Return a reversed instance of the Colormap.

        Parameters
        ----------
        name : str, optional
            The name for the reversed colormap. If None, the
            name is set to ``self.name + "_r"``.

        Returns
        -------
        ListedColormap
            A reversed instance of the colormap.
        r  rV   r   )	rV   rG   rk  r   r  r   r  r  r  )r   rV   colors_rr  s       r   rk  zListedColormap.reversed  sg     <99t#D-.!(@"..#!^^r   )r  Nr   )	r&   r'   r(   rd   r   r%  ri  rk  r)   r*   s   @r   r  r    s    6"0r   r  c                       e Zd ZdZddZddZd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd ZdddddZed        Zd Zd Zy)MultivarColormapzz
    Class for holding multiple `~matplotlib.colors.Colormap` for use in a
    `~matplotlib.cm.ScalarMappable` object
    c                    || _         t        j                  |      rt        |      dk(  st	        |t
              rt        d      t        |      }t        |      D ]G  \  }}t	        |t
              rt        j                  |   ||<   -t	        |t              r>t        d       || _        t        j                  ddg|       || _        t        |      | _        d| _        y)	a;  
        Parameters
        ----------
        colormaps: list or tuple of `~matplotlib.colors.Colormap` objects
            The individual colormaps that are combined
        combination_mode: str, 'sRGB_add' or 'sRGB_sub'
            Describe how colormaps are combined in sRGB space

            - If 'sRGB_add' -> Mixing produces brighter colors
              `sRGB = sum(colors)`
            - If 'sRGB_sub' -> Mixing produces darker colors
              `sRGB = 1 - sum(1 - colors)`
        name : str, optional
            The name of the colormap family.
        r   z4A MultivarColormap must have more than one colormap.zdcolormaps must be a list of objects that subclass Colormap or a name found in the colormap registry.sRGB_addsRGB_sub)combination_moder   N)rV   r   r   rP   ry   rz   r[   rG   	enumerater   	colormapsr  
_colormapsr	   check_in_list_combination_moder  r  )r   r  r  rV   icmaps         r   r   zMultivarColormap.__init__  s      	{{9%)n!C(STTO	 + 	XGAt$$"}}T2	!h/  "W X X		X $J
3FVW!1i.-r   Nc           	         t        |      t        |       k7  r#t        dt        |        dt        |             | d   j                  |d   d      \  }}t        | dd |dd       D ]H  \  }}|j                  |d      \  }	}
|ddd	fxx   |	ddd	f   z  cc<   |d
xx   |	d
   z  cc<   ||
z  }J | j                  dk(  r|ddd	fxx   t        |       dz
  z  cc<   | j                         ||<   |rt        j                  |dd      }||rt        j                  |dd      }t        j                  |      dt        j                  |d         fvr:t        dt        j                  |       dt        j                  |d                |dxx   |z  cc<   |r!|st        d      |dz  j                  d      }t        j                  |d         st        |      }|S )a  
        Parameters
        ----------
        X : tuple (X0, X1, ...) of length equal to the number of colormaps
            X0, X1 ...:
            float or int, `~numpy.ndarray` or scalar
            The data value(s) to convert to RGBA.
            For floats, *Xi...* should be in the interval ``[0.0, 1.0]`` to
            return the RGBA values ``X*100`` percent along the Colormap line.
            For integers, *Xi...*  should be in the interval ``[0, self[i].N)`` to
            return RGBA values *indexed* from colormap [i] with index ``Xi``, where
            self[i] is colormap i.
        alpha : float or array-like or None
            Alpha must be a scalar between 0 and 1, a sequence of such
            floats with shape matching *Xi*, or None.
        bytes : bool, default: False
            If False (default), the returned RGBA values will be floats in the
            interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s in the
            interval ``[0, 255]``.
        clip : bool, default: True
            If True, clip output to 0 to 1

        Returns
        -------
        Tuple of RGBA values if X[0] is scalar, otherwise an array of
        RGBA values with a shape of ``X.shape + (4, )``.
        z?For the selected colormap the data must have a first dimension z, not r   Frn  r   N.r   ).r   r  r1   r"   does not match that of X[0] r#  z_clip cannot be false while bytes is true as uint8 does not support values below 0 or above 255.r   r.  )rP   r[   r  r  r  rD  r   r   r   r,  r   r   )r   r  r   r  r   r   r3  r~   xxsub_rgbasub_mask_bads              r   r  zMultivarColormap.__call__  s   : q6SYQt9+VCF8-. . a33AaD3Fhab1QR5) 	%EAr%&%9%9"E%9%J"HlbqbMXc2A2g..MLHV,,L$H		%   J.bqbMSY]*MX774A&Dq!,xxr288AaD>&:: 8%8I J..0hhqtn-=?@ @ MU"M %& & 3J&&w/D{{1Q4 ;Dr   c                 "    | j                         S )z&Return a copy of the multivarcolormap.r  rE   s    r   r   zMultivarColormap.copy[  r  r   c                 6   | j                   }|j                  |      }|j                  j                  | j                         | j                  D cg c]  }|j                          c}|_        t        j
                  | j                        |_        |S c c}w r   )r   r5  r6  r7  r  r   r   r  )r   r9  r:  cms       r   r;  zMultivarColormap.__copy___  so    nn[[%
""4==159__ Er E
!wwt~~6
 !Fs   Bc                    t        |t              syt        |       t        |      k7  ryt        | |      D ]  \  }}||k7  s y t	        | j
                  |j
                  k(        sy| j                  |j                  k7  ryyNFT)ry   r  rP   r  r   r  r  )r   r@  c0r   s       r   rA  zMultivarColormap.__eq__g  s{    %!12t9E
"$& 	FBRx	 4>>U__45  E$:$::r   c                      | j                   |   S r   r  rI   s     r   rK   zMultivarColormap.__getitem__u  s    t$$r   c              #   6   K   | j                   D ]  }|  y wr   r  r   r~   s     r   rN   zMultivarColormap.__iter__x  s      	AG	s   c                 ,    t        | j                        S r   )rP   r  rE   s    r   rQ   zMultivarColormap.__len__|  s    4??##r   c                     | j                   S r   r  rE   s    r   rY   zMultivarColormap.__str__  s    yyr   c                 @    t        j                  | j                        S rC  )r   r   r  rE   s    r   rD  zMultivarColormap.get_bad  s    xx''r   c                    t        j                  |      rt        |      t        |       k7  rt        dt        |              | j	                         }t        |      D ])  \  }}|	| |   j                  |      |j                  |<   + |S )a  
        Return a new colormap with *lutshape* entries.

        Parameters
        ----------
        lutshape : tuple of (`int`, `None`)
            The tuple must have a length matching the number of variates.
            For each element in the tuple, if `int`, the corresponding colorbar
            is resampled, if `None`, the corresponding colorbar is not resampled.

        Returns
        -------
        MultivarColormap
        zlutshape must be of length )r   r   rP   r[   r   r  ri  r  )r   lutshaper  r  ss        r   ri  zMultivarColormap.resampled  s      {{8$HT(B:3t9+FGG99;h' 	>DAq})-a):):1)=##A&	> r   rQ  c                   | j                         }|t        |      |_        |it        j                  |      rt        |      t        |      k7  rt        dt        |       d      t        ||      D ]  \  }}|j                  |        |it        j                  |      rt        |      t        |      k7  rt        dt        |       d      t        ||      D ]  \  }}|j                  |        |S )a  
        Return a copy of the `MultivarColormap` with modified out-of-range attributes.

        The *bad* keyword modifies the copied `MultivarColormap` while *under* and
        *over* modifies the attributes of the copied component colormaps.
        Note that *under* and *over* colors are subject to the mixing rules determined
        by the *combination_mode*.

        Parameters
        ----------
        bad: :mpltype:`color`, default: None
            If Matplotlib color, the bad value is set accordingly in the copy

        under tuple of :mpltype:`color`, default: None
            If tuple, the `under` value of each component is set with the values
            from the tuple.

        over tuple of :mpltype:`color`, default: None
            If tuple, the `over` value of each component is set with the values
            from the tuple.

        Returns
        -------
        MultivarColormap
            copy of self with attributes set

        zH*under* must contain a color for each scalar colormap i.e. be of length .zG*over* must contain a color for each scalar colormap i.e. be of length )
r   r\   r  r   r   rP   r[   r  rL  rP  )r   rR  rS  rT  rX  r~   r  s          r   rY  zMultivarColormap.with_extremes  s    8 ?&s|F;;u%Us6{)B  "77:6{m1"F G G  . #DAqKKN#;;t$D	S[(@  "77:6{m1"F G G  - "DAqJJqM"r   c                     | j                   S r   )r  rE   s    r   r  z!MultivarColormap.combination_mode  s    %%%r   c                    t        j                  t        j                  ddt        d         t        d   df      }t        j                  t        d   t        |       z  t        d   dft         j                        }t        |       D ]/  \  }} ||d      ||t        d   z  |dz   t        d   z  ddf<   1 t        j                         }| j                  dz   }d	t        j                   d
}t               }|j                  d|       |j                  d|       |j                  d|       |j                  d|       t        j                   |      j#                  |d|       |j%                         S )rm  r   r   r   r   Trn  Nz multivariate colormapro  rp  rq  rr  rs  rt  ru  rv  )r   r   r   rx  r   rP   r.  r  ry  rz  rV   r   r{  r   r|  r   r}  r~  r  )	r   r  r  r  r~   r  r  r  rw  s	            r   r  zMultivarColormap._repr_png_  sQ   GGBKK1nQ&78!/!2A 68>!,SY6q8I1M "*dO 	VDAqEFqPTEUF1^A&&!^A->'>>AB	VJJL			4400HI)%(.6*V,$$Yug$N!!##r   c                 z    dj                  | j                  D cg c]  }|j                          c}      S c c}w )z8Generate an HTML representation of the MultivarColormap.r   )rX   r  r  r  s     r   r  zMultivarColormap._repr_html_  s)    wwAAABBAs   8)zmultivariate colormapr  )r&   r'   r(   rd   r   r  r   r;  rA  rK   rN   rQ   rY   rD  ri  rY  propertyr  r  r  r1   r   r   r  r    so    ".HDL%$(0 $(t$ -^ & &$&Cr   r  c                       e Zd ZdZ	 	 ddZddZed        Zd Zd Z	d Z
d	 Zdd
ZddZd ZddddddZd Zed        Zed        Zd Zd Zd Zd Zd Zy)BivarColormapz
    Base class for all bivariate to RGBA mappings.

    Designed as a drop-in replacement for Colormap when using a 2D
    lookup table. To be used with `~matplotlib.cm.ScalarMappable`.
    c                    || _         t        |      | _        t        |      | _        t	        j
                  g d|       || _        d| _        d| _        d| _	        d| _
        t        |d         t        |d         f| _        y	)
a~  
        Parameters
        ----------
        N : int, default: 256
            The number of RGB quantization levels along the first axis.
        M : int, default: 256
            The number of RGB quantization levels along the second axis.
        shape : {'square', 'circle', 'ignore', 'circleignore'}

            - 'square' each variate is clipped to [0,1] independently
            - 'circle' the variates are clipped radially to the center
              of the colormap, and a circular mask is applied when the colormap
              is displayed
            - 'ignore' the variates are not clipped, but instead assigned the
              'outside' color
            - 'circleignore' a circular mask is applied, but the data is not
              clipped and instead assigned the 'outside' color

        origin : (float, float), default: (0,0)
            The relative origin of the colormap. Typically (0, 0), for colormaps
            that are linear on both axis, and (.5, .5) for circular colormaps.
            Used when getting 1D colormaps from 2D colormaps.
        name : str, optional
            The name of the colormap.
        squarecircler  circleignorer   r   )r   r   r   r   Fr   r   r   N)rV   r   r   Mr	   r  _shaper  _rgba_outsider  r  rt   _origin)r   r   r  r   originrV   s         r   r   zBivarColormap.__init__  sz    8 	QQIQVW-1fQi(%q	*:;	(r   Nc                    t        |      dk7  rt        dt        |             | j                  s| j                          t        j
                  j                  |d   d      }t        j
                  j                  |d   d      }| j                  ||f       |j                  j                  s7|j                         j                  |j                  j                               }|j                  j                  s7|j                         j                  |j                  j                               }|j                  j                  dk(  r.|| j                  z  }| j                  dz
  ||| j                  k(  <   |j                  j                  dk(  r.|| j                  z  }| j                  dz
  ||| j                  k(  <   |dk  |dk  z  || j                  k\  z  || j                  k\  z  }t        j
                  j!                  |      r|j"                  nt	        j$                  |      }t        j
                  j!                  |      r|j"                  nt	        j$                  |      }||z  }	t	        j&                  d	      5  |j)                  t*              }|j)                  t*              }d
d
d
       ||fD ]  }
d|
|<   d|
|	<    | j,                  ||f   }t	        j.                  |d         rt	        j0                  |      }| j2                  ||<   | j4                  ||	<   |r"|dz  j)                  t        j6                        }|t	        j8                  |dd      }|r|dz  }t	        j:                  |      dt	        j:                  |      fvr7t        dt	        j:                  |       dt	        j:                  |             ||d<   t	        j                  | j4                        dk(  j=                         rd||	<   t	        j>                  |d         stA        |      }|S # 1 sw Y   xY w)a  
        Parameters
        ----------
        X : tuple (X0, X1), X0 and X1: float or int `~numpy.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.
            - 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, default: None
            Alpha must be a scalar between 0 and 1, a sequence of such
            floats with shape matching X0, or None.
        bytes : bool, default: False
            If False (default), the returned RGBA values will be floats in the
            interval ``[0, 1]`` otherwise they will be `numpy.uint8`\s 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, )``.
        r   zBFor a `BivarColormap` the data must have a first dimension 2, not r   Tr  r   r  r  r  Nr   r1   r"  r  r#  r$  )!rP   r[   r  r%  r   r   r   _clipr   r&  r'  r(  r)  r   r   r  r   r   r*  r+  r,  r   r-  isscalarr   r  r  r.  r   r   r   r   r   )r   r  r   r  X0X1mask_outside
mask_bad_0
mask_bad_1r3  X_partr   s               r   r  zBivarColormap.__call__  se   4 q6Q;a&#$ $ ||JJLUU[[1D[)UU[[1D[)

B8 xx  ##BHH$9$9$;<Bxx  ##BHH$9$9$;<B88==C$&&LB#vvzBrTVV|88==C$&&LB#vvzBrTVV| Q26*bDFFl;rTVV|L " 3RWW"
 " 3RWW"

*[[* 	 3B3B	  2h 	!F#$F<  F8	! yyR ;;qt774=D!//\X3J&&rxx0DGGE1a(Exxr288B<&88 8%8I J..0hhrl^=> > "DM(A-224!-X{{1Q4 ;DC	  	 s   +P33P=c                    | j                   s| j                          t        j                  | j                        }| j
                  dk(  s| j
                  dk(  rt        j                  dd| j                        }t        j                  dd| j                        }|dz  ddt        j                  f   |dz  t        j                  ddf   z   }|dkD  }d||df<   |S )	a  
        For external access to the lut, i.e. for displaying the cmap.
        For circular colormaps this returns a lut with a circular mask.

        Internal functions (such as to_rgb()) should use _lut
        which stores the lut without a circular mask
        A lut without the circular mask is needed in to_rgb() because the
        conversion from floats to ints results in some some pixel-requests
        just outside of the circular mask

        r  r  r   r   r   Nr   r   )
r  r%  r   r   r-  r   r   r   r  newaxis)r   r  r   m	radii_sqrr  s         r   r  zBivarColormap.lut~  s     ||JJLggdii ::!TZZ>%AB466*AB466*AAq"**}-Arzz1}0EEI$q=L#$Ca 
r   c                    | j                   }|j                  |      }|j                  j                  | j                         t	        j
                  | j                        |_        t	        j
                  | j                        |_        | j                  |_	        | j                  r$t	        j
                  | j                        |_        |S r   )r   r5  r6  r7  r   r   r  r  r   r  r  r-  r8  s      r   r;  zBivarColormap.__copy__  s    nn[[%
""4==1#%774+=+=#>
 !wwt~~6
 JJ
<< ggdii0JOr   c                    t        |t              sy| j                  s| j                          |j                  s|j                          t	        j
                  | j                  |j                        syt	        j
                  | j                  |j                        syt	        j
                  | j                  |j                        sy| j                  |j                  k7  ryyr  )
ry   r  r  r%  r   r>  r-  r  r  r   r?  s     r   rA  zBivarColormap.__eq__  s    %/||JJL}}KKM~~dii4~~dnneoo>~~d00%2E2EF::$r   c                     | j                   S rC  )r  rE   s    r   rD  zBivarColormap.get_bad  s    ~~r   c                     | j                   S )z&Get the color for out-of-range values.)r  rE   s    r   get_outsidezBivarColormap.get_outside  s    !!!r   c           	      x   t        j                  |      rt        |      dk7  rt        d      |d   |d   g}|d   |d   dk(  r| j                  |d<   |d   |d   dk(  r| j
                  |d<   ddg}|d   dk  r%d|d<   |d    |d<   |d   dk(  r| j                  |d<   |d   dk  r%d|d<   |d    |d<   |d   dk(  r| j
                  |d<   t         j                  dd|d   dz  dd|d   dz  f   \  }}|d   r|ddd	ddf   }|d   r|ddddd	f   }| j                  }d
| _        |r4 | ||f      }t        || j                  || j                  ddd	         }n- | ||f      }t        || j                  || j                        }|| _        | j                  |_        | j                  |_        |S )a  
        Return a new colormap with *lutshape* entries.

        Note that this function does not move the origin.

        Parameters
        ----------
        lutshape : tuple of ints or None
            The tuple must be of length 2, and each entry is either an int or None.

            - If an int, the corresponding axis is resampled.
            - If negative the corresponding axis is resampled in reverse
            - If -1, the axis is inverted
            - If 1 or None, the corresponding axis is not resampled.

        transposed : bool, default: False
            if True, the axes are swapped after resampling

        Returns
        -------
        BivarColormap
        r   zlutshape must be of length 2r   r   NFTy              ?r   r  )rV   r   r   )r   r   rP   r[   r   r  mgridr  BivarColormapFromImagerV   r   r  r  )	r   r  
transposedinvertedx_0x_1shape_memorynew_lutr  s	            r   ri  zBivarColormap.resampled  s   0 {{8$H(:;<<QK!-A;(1+"2&&HQKA;(1+"2&&HQK5>A;?HQK#A;,HQK{a"ffA;?HQK#A;,HQK{a"ff88Aa!r!12Aa!r9I4JJKSA;ddAg,CA;a2g,C
 {{C:&G-gDII4@59[[25FHH C:&G-gDII4@59[[BH #!^^!%!3!3r   c                 @    |rdnd}|rdnd}| j                  ||f      S )z3
        Reverses both or one of the axis.
        r   r   ri  )r   axis_0axis_1r_0r_1s        r   rk  zBivarColormap.reversed  s)     bb~~sCj))r   c                 (    | j                  dd      S )zK
        Transposes the colormap by swapping the order of the axis
        NNT)r  r  rE   s    r   r  zBivarColormap.transposed
  s     ~~lt~<<r   )rR  outsider   r   c                    | j                         }|t        |      |_        |t        |      |_        | t	        j
                  g d|       ||_        |!t        |d         t        |d         f|_        |S )a  
        Return a copy of the `BivarColormap` with modified attributes.

        Note that the *outside* color is only relevant if `shape` = 'ignore'
        or 'circleignore'.

        Parameters
        ----------
        bad : None or :mpltype:`color`
            If Matplotlib color, the *bad* value is set accordingly in the copy

        outside : None or :mpltype:`color`
            If Matplotlib color and shape is 'ignore' or 'circleignore', values
            *outside* the colormap are colored accordingly in the copy

        shape : {'square', 'circle', 'ignore', 'circleignore'}

            - If 'square' each variate is clipped to [0,1] independently
            - If 'circle' the variates are clipped radially to the center
              of the colormap, and a circular mask is applied when the colormap
              is displayed
            - If 'ignore' the variates are not clipped, but instead assigned the
              *outside* color
            - If 'circleignore' a circular mask is applied, but the data is not
              clipped and instead assigned the *outside* color

        origin : (float, float)
            The relative origin of the colormap. Typically (0, 0), for colormaps
            that are linear on both axis, and (.5, .5) for circular colormaps.
            Used when getting 1D colormaps from 2D colormaps.

        Returns
        -------
        BivarColormap
            copy of self with attributes set
        r  r  r   r   )	r   r\   r  r  r	   r  r  rt   r  )r   rR  r$  r   r   rX  s         r   rY  zBivarColormap.with_extremes  s~    J ?&s|F#*7#3F M%*,!FM#F1I.fQi0@AFNr   c                     t        d      r\  r]  rE   s    r   r%  zBivarColormap._initC  r_  r   c                     | j                   S r   )r  rE   s    r   r   zBivarColormap.shapeG  s    {{r   c                     | j                   S r   )r  rE   s    r   r   zBivarColormap.originK  s    ||r   c                 X   | j                   dk(  r`t        || j                  | j                  f      D ]:  \  }}d||dk  <   |j                  j
                  dk(  r	d||dkD  <   0|dz
  |||k\  <   < y| j                   dk(  r]t        || j                  | j                  f      D ]7  \  }}d||dk  <   |j                  j
                  dk(  r	d||dkD  <   0d|||k\  <   9 y| j                   dk(  s| j                   dk(  r|D ]&  }|j                  j
                  dk7  st        d	       |d   d
z
  dz  |d   d
z
  dz  z   }|dkD  }| j                   dk(  rJdt        j                  ||         z  }|d   |   d
z
  |z  d
z   |d   |<   |d   |   d
z
  |z  d
z   |d   |<   yd|d   |<   d|d   |<   yy)a  
        For internal use when applying a BivarColormap to data.
        i.e. cm.ScalarMappable().to_rgba()
        Clips X[0] and X[1] according to 'self.shape'.
        X is modified in-place.

        Parameters
        ----------
        X: np.array
            array of floats or ints to be clipped
        shape : {'square', 'circle', 'ignore', 'circleignore'}

            - If 'square' each variate is clipped to [0,1] independently
            - If 'circle' the variates are clipped radially to the center
              of the colormap.
              It is assumed that a circular mask is applied when the colormap
              is displayed
            - If 'ignore' the variates are not clipped, but instead assigned the
              'outside' color
            - If 'circleignore' a circular mask is applied, but the data is not clipped
              and instead assigned the 'outside' color

        r  r   r  r   r  r   r  r  zJCircular bivariate colormaps are only implemented for use with with floats      ?r   g      ?N)	r   r  r   r  r   r   r^  r   sqrt)r   r  r	  mxr  r  
overextends          r   r  zBivarColormap._clipO  s   0 ::!!!dffdff%56 2
%&vz"<<$$+)*F6A:&+-6F6R<(2 ZZ8#!!dffdff%56 .
%'vz"<<$$+)+F6A:&+-F6R<(. ZZ8#tzz^'C A<<$$+-@A AA
 1a1Q4#:/9I$t+LzzX%<)@!AA
&'d<&83&>*%Ls%R!\"&'d<&83&>*%Ls%R!\"%'!\"%'!\" (Dr   c                    | j                   s| j                          |dk(  rt        | j                  d   | j                  z        }|| j                  dz
  kD  r| j                  dz
  }| j
                  dd|f   }t        || j                   d| j                        }n|dk(  rt        | j                  d   | j                  z        }|| j                  dz
  kD  r| j                  dz
  }| j
                  |ddf   }t        || j                   d| j                        }nt        d|      | j                  |_
        | j                  dv r6|j                  | j                         |j                  | j                         |S )	z6Creates and returns a colorbar along the selected axisr   r   N_0r  _1z2only 0 or 1 are valid keys for BivarColormap, not )r  r  )r  r%  r   r  r  r-  r  rV   r   rH   r  r   rP  r  rL  )r   rJ   origin_1_as_int	one_d_lutr  origin_0_as_ints         r   rK   zBivarColormap.__getitem__  sV   ||JJL19!$,,q/$&&"89O)"&&&(		!_"45I%i26F$&&QHQY!$,,q/$&&"89O)"&&&(		/1"45I%i26F$&&QH AAEJ K K!^^::33d001t112r   c                 \   | j                   s| j                          | j                  }|j                  d   t        k  r5t        j                  |t        |j                  d   z  d      ddddf   }|j                  d   t        k  r5t        j                  |t        |j                  d   z  d      ddddf   }|dddddddf   dz  j                  t
        j                        }t        j                         }| j                  dz   }d	t        j                   d
}t               }|j                  d|       |j                  d|       |j                  d|       |j                  d|       t!        j"                  |      j%                  |d|       |j'                         S )z3Generate a PNG representation of the BivarColormap.r   )repeatsr   Nr.   r   r   r   z BivarColormapro  rp  rq  rr  rs  rt  ru  rv  )r  r%  r  r   _BIVAR_REPR_PNG_SIZEr   repeatr,  r.  ry  rz  rV   r   r{  r   r|  r   r}  r~  r  )r   r  r  r  r  rw  s         r   r  zBivarColormap._repr_png_  sq   ||JJL<<?11YYv';V\\!_'L$%''+tQw0F <<?11YYv';V\\!_'L$%''($3$w0F 2q!$s*22288<JJL			,,00HI)%(.6*V,$$Yug$N!!##r   c                 :   | j                         }t        j                  |      j                  d      }d }d| j                   d| j                   d| j                   d| dt
        dz    d	 || j                                d
 || j                                dS )r  r  c                 .    t        | d      }d| d| dS r  r  r  s     r   r  z.BivarColormap._repr_html_.<locals>.color_block  r  r   r  r  z BivarColormap" title="r  r  r   r  z- outside</div><div style="float: right;">bad r  )r  r  r  r  rV   r6  r  rD  r  s       r   r  zBivarColormap._repr_html_  s    OO%	%%i077@
	?99+ & 		{ #)) %..8\ :2145 6- t//123 4 #4<<>23! 	 r   c                 "    | j                         S r  r  rE   s    r   r   zBivarColormap.copy  r  r   )r.   r.   r  r   r   zbivariate colormapr=  F)TT)r&   r'   r(   rd   r   r  r  r  r;  rA  rD  r  ri  rk  r  rY  r%  r   r   r  rK   r  r  r   r1   r   r   r  r    s     =C**(X_B  .
$"DL*= $(T$ 1f9    6(p4$2 @r   r  c                   .     e Zd ZdZ	 	 d fd	Zd Z xZS )SegmentedBivarColormapaL  
    BivarColormap object generated by supersampling a regular grid.

    Parameters
    ----------
    patch : np.array
        Patch is required to have a shape (k, l, 3), and will get supersampled
        to a lut of shape (N, N, 4).
    N : int
        The number of RGB quantization levels along each axis.
    shape : {'square', 'circle', 'ignore', 'circleignore'}

        - If 'square' each variate is clipped to [0,1] independently
        - If 'circle' the variates are clipped radially to the center
          of the colormap, and a circular mask is applied when the colormap
          is displayed
        - If 'ignore' the variates are not clipped, but instead assigned the
          'outside' color
        - If 'circleignore' a circular mask is applied, but the data is not clipped

    origin : (float, float)
        The relative origin of the colormap. Typically (0, 0), for colormaps
        that are linear on both axis, and (.5, .5) for circular colormaps.
        Used when getting 1D colormaps from 2D colormaps.

    name : str, optional
        The name of the colormap.
    c                 j    t        j                  d|       || _        t        |   |||||       y )N)NNr   )patchr  )r	   r   r@  r   r   )r   r@  r   r   r   rV   r   s         r   r   zSegmentedBivarColormap.__init__  s2    6
Auf48r   c                 R   | j                   j                  }t        j                  |d   |d   df      }| j                   |d d d d d df<   d|d d d d df<   t        j
                  j                         j                  dd      j                  | j                  |d   dz
  z  | j                  |d   dz
  z        }t        j                  | j                  | j                  df      | _
        t        j                  || j                  |t        j                  dd       d| _        y )	Nr   r   r   r   g      F)resampler   T)r@  r   r   emptyr   
transformsAffine2D	translater   r   r-  r   rB  BILINEARr  )r   r  _patch	transforms       r   r%  zSegmentedBivarColormap._init  s    JJ1Q41q/*::q!RaRxq!QwNN++-77dC!&tvv1':DFFadQh<O!P 	HHdffdffa01			9foo!&a	1r   )r.   r  r;  zsegmented bivariate colormapr&   r'   r(   rd   r   r%  r)   r*   s   @r   r>  r>    s    : =C49r   r>  c                   *     e Zd ZdZd fd	Zd Z xZS )r  a  
    BivarColormap object generated by supersampling a regular grid.

    Parameters
    ----------
    lut : nparray of shape (N, M, 3) or (N, M, 4)
        The look-up-table
    shape: {'square', 'circle', 'ignore', 'circleignore'}

        - If 'square' each variate is clipped to [0,1] independently
        - If 'circle' the variates are clipped radially to the center
          of the colormap, and a circular mask is applied when the colormap
          is displayed
        - If 'ignore' the variates are not clipped, but instead assigned the
          'outside' color
        - If 'circleignore' a circular mask is applied, but the data is not clipped

    origin: (float, float)
        The relative origin of the colormap. Typically (0, 0), for colormaps
        that are linear on both axis, and (.5, .5) for circular colormaps.
        Used when getting 1D colormaps from 2D colormaps.
    name : str, optional
        The name of the colormap.

    c                 L   t        j                  |d      }|j                  dk7  s|j                  d   dvrt	        dd      |j
                  t         j                  k(  r"|j                  t         j                        dz  }|j                  d   dk(  rZt        j                  |j                  d	   |j                  d
   df|j
                        }||d d d d d df<   d|d d d d df<   |}|| _
        t        | 1  |j                  d	   |j                  d
   |||       y )NTr  r   r   r   z8The lut must be an array of shape (n, m, 3) or (n, m, 4)z& or a PIL.image encoded as RGB or RGBAr   r   r   r   r   r   r  )r   r   r   r   r[   r   r.  r,  float32rC  r-  r   r   )r   r  r   r   rV   r  r   s         r   r   zBivarColormapFromImage.__init__,  s     hhs&88q=CIIaL6WEG G 99 **RZZ(,C99Q<1hh		!ciilA>ciiPG #GAq"1"H!GAq!GC	1syy|UFNr   c                     d| _         y )NT)r  rE   s    r   r%  zBivarColormapFromImage._initB  s	    r   )r  r;  z
from imagerJ  r*   s   @r   r  r    s    4O,r   r  c                       e Zd ZdZddZed        Zej                  d        Zed        Zej                  d        Zed        Z	e	j                  d	        Z	d
 Z
ed        ZddZd Zd Zd Zd Zy)	Normalizea  
    A class which, when called, maps values within the interval
    ``[vmin, vmax]`` linearly to the interval ``[0.0, 1.0]``. The mapping of
    values outside ``[vmin, vmax]`` depends on *clip*.

    Examples
    --------
    ::

        x = [-2, -1, 0, 1, 2]

        norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=False)
        norm(x)  # [-0.5, 0., 0.5, 1., 1.5]
        norm = mpl.colors.Normalize(vmin=-1, vmax=1, clip=True)
        norm(x)  # [0., 0., 0.5, 1., 1.]

    See Also
    --------
    :ref:`colormapnorms`
    Nc                     t        |      | _        t        |      | _        || _        d| _        t        j                  dg      | _        y)ad  
        Parameters
        ----------
        vmin, vmax : float or None
            Values within the range ``[vmin, vmax]`` from the input data will be
            linearly mapped to ``[0, 1]``. If either *vmin* or *vmax* is not
            provided, they default to the minimum and maximum values of the input,
            respectively.

        clip : bool, default: False
            Determines the behavior for mapping values outside the range
            ``[vmin, vmax]``.

            If clipping is off, values outside the range ``[vmin, vmax]`` are
            also transformed, resulting in values outside ``[0, 1]``.  This
            behavior is usually desirable, as colormaps can mark these *under*
            and *over* values with specific colors.

            If clipping is on, values below *vmin* are mapped to 0 and values
            above *vmax* are mapped to 1. Such values become indistinguishable
            from regular boundary values, which may cause misinterpretation of
            the data.

        Notes
        -----
        If ``vmin == vmax``, input data will be mapped to 0.
        Nchanged)signals)rw   _vmin_vmaxr  _scaler   CallbackRegistry	callbacks)r   vminvmaxr   s       r   r   zNormalize.__init__\  s>    8 't,
&t,

//Dr   c                     | j                   S r   rT  rE   s    r   rY  zNormalize.vmin~      zzr   c                 h    t        |      }|| j                  k7  r|| _        | j                          y y r   )rw   rT  _changedr   r#   s     r   rY  zNormalize.vmin  -    !%(DJJDJMMO r   c                     | j                   S r   rU  rE   s    r   rZ  zNormalize.vmax  r]  r   c                 h    t        |      }|| j                  k7  r|| _        | j                          y y r   )rw   rU  r_  r`  s     r   rZ  zNormalize.vmax  ra  r   c                     | j                   S r   )r  rE   s    r   r   zNormalize.clip  r]  r   c                 R    || j                   k7  r|| _         | j                          y y r   )r  r_  r`  s     r   r   zNormalize.clip  s#    DJJDJMMO r   c                 :    | j                   j                  d       y)z~
        Call this whenever the norm is changed to notify all the
        callback listeners to the 'changed' signal.
        rR  N)rX  processrE   s    r   r_  zNormalize._changed  s    
 	y)r   c                    t        j                  |        }|r| g} t        j                  |       }t        j                  |t         j                        s|j
                  t         j                  u r$t        j                  |t         j                        }t         j                  j                  |       }t        j                  |       }t         j                  j                  |||d      }||fS )a  
        Homogenize the input *value* for easy and efficient normalization.

        *value* can be a scalar or sequence.

        Parameters
        ----------
        value
            Data to normalize.

        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)r   r   r   )r   r   min_scalar_type
issubdtypeintegerrg  bool_promote_typesrM  r   getmaskr   r   )r#   	is_scalarr   r   r   r   s         r   process_valuezNormalize.process_value  s    4 E**	GE""5)==

+uzzRXX/E$$UBJJ7E uu}}U#zz% TEEy  r   c                    || j                   }| j                  |      \  }}| j                  | j                  | j	                  |       | j                  | j                        \  \  }}| j                  | j                        \  \  }}||k(  r|j                  d       n||kD  rt        d      |rdt        j                  j                  |      }t        j                  j                  t        j                   |j                  |      ||      |      }|j                  }	|	|z  }	|	||z
  z  }	t        j                  j                  |	|j                  d      }|r|d   }|S )a  
        Normalize the data and return the normalized data.

        Parameters
        ----------
        value
            Data to normalize.
        clip : bool, optional
            See the description of the parameter *clip* in `.Normalize`.

            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)``.
        r   /minvalue must be less than or equal to maxvaluer   Fr   r   )r   rq  rY  rZ  autoscale_Nonefillr[   r   r   ro  r   filledr   r   )
r   r#   r   r   rp  rY  _rZ  r   resdats
             r   r  zNormalize.__call__  s7   & <99D ..u5	99		 1'''		2
''		2
4<KKND[NOOuu}}V,RWWV]]4-@$%M*. % 0 [[FdNFtd{#FUU[[fkk[FFAYFr   c                 L   | j                         st        d      | j                  | j                        \  \  }}| j                  | j                        \  \  }}t        j                  |      r*t
        j                  j                  |      }||||z
  z  z   S ||||z
  z  z   S )z
        Maps the normalized value (i.e., index in the colormap) back to image
        data value.

        Parameters
        ----------
        value
            Normalized value.
        /Not invertible until both vmin and vmax are set)	scaledr[   rq  rY  rZ  r   r   r   r   )r   r#   rY  ry  rZ  r   s         r   inversezNormalize.inverse  s     {{}NOO''		2
''		2
;;u%%--&C#---%4$;///r   c                     | j                   j                         5  dx| _        | _        | j	                  |       ddd       | j                          y# 1 sw Y   xY w)z&Set *vmin*, *vmax* to min, max of *A*.N)rX  blockedrY  rZ  rv  r_  r   As     r   	autoscalezNormalize.autoscale	  sP    ^^##% 	# %)(DI	"		#
 		# 	#s    AAc                    t        j                  |      }t        |t         j                  j                        r0|j
                  du s|j
                  j                  s|j                  }| j                  !|j                  r|j                         | _        | j                  #|j                  r|j                         | _        yyy)zDIf *vmin* or *vmax* are not set, use the min/max of *A* to set them.FN)r   
asanyarrayry   r   MaskedArrayr   r   r   rY  sizeminrZ  r   r  s     r   rv  zNormalize.autoscale_None	  s    MM!a**+vvaffllFF99DI99DI "(r   c                 >    | j                   duxr | j                  duS )z.Return whether *vmin* and *vmax* are both set.NrY  rZ  rE   s    r   r}  zNormalize.scaled(	  s    yy$>$)>>r   NNFr   )r&   r'   r(   rd   r   r  rY  setterrZ  r   r_  r   rq  r  r~  r  rv  r}  r1   r   r   rP  rP  F  s    * ED   
[[    
[[    
[[ 
* %! %!N-^0* ?r   rP  c                   l     e Zd Zd fd	Zed        Zej                  d        Z fdZddZd Z	 xZ
S )	TwoSlopeNormc                     t         |   ||       || _        ||||k\  rt        d      ||||k  rt        d      yyy)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  Nz2vmin, vcenter, and vmax must be in ascending order)r   r   _vcenterr[   )r   vcenterrY  rZ  r   s       r   r   zTwoSlopeNorm.__init__.	  sq    @ 	d.4#34 / 0 04#34 / 0 0 9H#3r   c                     | j                   S r   r  rE   s    r   r  zTwoSlopeNorm.vcenterW	      }}r   c                 R    || j                   k7  r|| _         | j                          y y r   )r  r_  r`  s     r   r  zTwoSlopeNorm.vcenter[	  s#    DMM!!DMMMO "r   c                 6   t         |   |       | j                  | j                  k\  r+| j                  | j                  | j                  z
  z
  | _        | j                  | j                  k  r,| j                  | j                  | j                  z
  z   | _        yy)z
        Get vmin and vmax.

        If vcenter isn't in the range [vmin, vmax], either vmin or vmax
        is expanded so that vcenter lies in the middle of the modified range
        [vmin, vmax].
        N)r   rv  rY  r  rZ  )r   r  r   s     r   rv  zTwoSlopeNorm.autoscale_Nonea	  sq     	q!99$		DLL(@ADI99$tyy(@ADI %r   c           	      0   | j                  |      \  }}| j                  |       | j                  | j                  cxk  r| j                  k  st        d       t        d      t        j                  j                  t        j                  || j                  | j                  | j                  gg dt        j                   t        j                        t        j                  j                  |            }|rt        j                  |      d   }|S )zR
        Map value to the interval [0, 1]. The *clip* argument is unused.
        z/vmin, vcenter, vmax must increase monotonicallyr   r*  r   leftrightrt  r   )rq  rv  rY  r  rZ  r[   r   r   masked_arrayinterpinfro  
atleast_1d)r   r#   r   r   rp  s        r   r  zTwoSlopeNorm.__call__o	  s     !..u5	F#yyDLL5DII5NOO 6NOO##IIftyy$,,		B!rvv?v& $ ( ]]6*1-Fr   c                 t   | j                         st        d      | j                  | j                        \  \  }}| j                  | j                        \  \  }}| j                  | j
                        \  \  }}t        j                  |g d|||gt        j                   t        j                        }|S )Nr|  r  r  )	r}  r[   rq  rY  rZ  r  r   r  r  )r   r#   rY  ry  rZ  r  r   s          r   r~  zTwoSlopeNorm.inverse	  s    {{}NOO''		2
''		2
**4<<8
A5+gt/D!#rvv7r   r#  r   )r&   r'   r(   r   r  r  r  rv  r  r~  r)   r*   s   @r   r  r  -	  sE    '0R   ^^ 
B$r   r  c                        e Zd Zd fd	Zd Zd Zed        Zej                  d        Zed        Z	e	j                  d        Z	ed        Z
e
j                  d	        Z
ed
        Zej                  d        Z xZS )CenteredNormc                 F    t         |   dd|       || _        || _        y)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.
        clip : bool, default: False
            Determines the behavior for mapping values outside the range
            ``[vmin, vmax]``.

            If clipping is off, values outside the range ``[vmin, vmax]`` are
            also transformed, resulting in values outside ``[0, 1]``.  This
            behavior is usually desirable, as colormaps can mark these *under*
            and *over* values with specific colors.

            If clipping is on, values below *vmin* are mapped to 0 and values
            above *vmax* are mapped to 1. Such values become indistinguishable
            from regular boundary values, which may cause misinterpretation of
            the data.

        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rY  rZ  r   )r   r   r  	halfrange)r   r  r  r   r   s       r   r   zCenteredNorm.__init__	  s(    \ 	dD9"r   c                     t        j                  |      }t        | j                  |j	                         z
  |j                         | j                  z
        | _        y)zY
        Set *halfrange* to ``max(abs(A-vcenter))``, then set *vmin* and *vmax*.
        N)r   r  r   r  r  r  r  s     r   r  zCenteredNorm.autoscale	  sA     MM!T]]15572UUWT]]24r   c                     t        j                  |      }| j                  |j                  r| j	                  |       yyy)zSet *vmin* and *vmax*.N)r   r  r  r  r  r  s     r   rv  zCenteredNorm.autoscale_None	  s4    MM!>>!affNN1 '-!r   c                     | j                   S r   r\  rE   s    r   rY  zCenteredNorm.vmin	  r]  r   c                     t        |      }|| j                  k7  r/|| _        d| j                  z  |z
  | _        | j	                          y y Nr   )rw   rT  r  rU  r_  r`  s     r   rY  zCenteredNorm.vmin	  A    !%(DJJDJ4<<%/DJMMO r   c                     | j                   S r   rc  rE   s    r   rZ  zCenteredNorm.vmax	  r]  r   c                     t        |      }|| j                  k7  r/|| _        d| j                  z  |z
  | _        | j	                          y y r  )rw   rU  r  rT  r_  r`  s     r   rZ  zCenteredNorm.vmax	  r  r   c                     | j                   S r   r  rE   s    r   r  zCenteredNorm.vcenter	  r  r   c                 t    || j                   k7  r)|| _         | j                  | _        | j                          y y r   )r  r  r_  )r   r  s     r   r  zCenteredNorm.vcenter	  s.    dmm##DM!^^DNMMO	 $r   c                 l    | j                   | j                  y | j                  | j                   z
  dz  S r  r  rE   s    r   r  zCenteredNorm.halfrange	  s0    99		 1		DII%**r   c                     |d | _         d | _        y | j                  t        |      z
  | _         | j                  t        |      z   | _        y r   )rY  rZ  r  abs)r   r  s     r   r  zCenteredNorm.halfrange	  s>    DIDIs9~5DIs9~5DIr   )r   NF)r&   r'   r(   r   r  rv  r  rY  r  rZ  r  r  r)   r*   s   @r   r  r  	  s    1#f4   
[[    
[[    ^^  + +
 6 6r   r  initc          	      B   |t        j                  t        | |      S t        | t         j                        r<| j                  }t        | j                  j                               }| j                  } ndx}}|dd}t        | |||t        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.
    r  r1   c                      y r   r1   r  s      r   r  z"make_norm_from_scale.<locals>.init,
      r   r  )r  r  make_norm_from_scalery   r   r   keywordsr   r  _make_norm_from_scaleinspect	signature)	scale_clsbase_norm_clsr  
scale_argsscale_kwargs_itemss        r   r  r  
  s    >   !5ytLL)Y../^^
"9#5#5#;#;#=>NN	*,,
'|8 :1w((.0 0r   c                      G  fdd      }t         u r) j                   d|_         j                   d|_        n"j                  |_        j                  |_        j                  |_        j                  |_        |S )a  
    Helper for `make_norm_from_scale`.

    This function is split out to enable caching (in particular so that
    different unpickles reuse the same class).  In order to do so,

    - ``functools.partial`` *scale_cls* is expanded into ``func, args, kwargs``
      to allow memoizing returned norms (partial instances always compare
      unequal, but we can check identity based on ``func, args, kwargs``;
    - *init* is replaced by *init_signature*, as signatures are picklable,
      unlike to arbitrary lambdas.
    c                       e Zd ZfdZ fdZW j                   ej                  dej                  j                        gW j                  j                               e_        ddZd Z fdZ xZS )	#_make_norm_from_scale.<locals>.Normc                    t        |       }	 |t        t        j                  |j                        |j
                        u rt        |ft        |       fS 	 t        ft        |       fS # t        t        f$ r Y (w xY wr   )rg  getattr	importlibimport_moduler'   r(   _create_empty_object_of_classvarsImportErrorrs   _picklable_norm_constructor)r   r9  r  bound_init_signaturer  r  r  s     r   
__reduce__z._make_norm_from_scale.<locals>.Norm.__reduce__F
  s    t*C')"9"9#.."I"%"2"24 49C64:NN4
 0
,>"$8:J     0 s   AA. .B ?B c                 r    j                   |i |}|j                          t        |   di dD ci c]  }||j                  j                  |        c}  t        j                  gi t        	      ddd i|j                  | _	        | j                  j                         | _        y c c}w )Nr  r   r1   )bindapply_defaultsr   r   	argumentsra   r  r  dictrV  get_transform_trf)
r   r   r   bar   r   r  r  r  r  s
        r   r   z,_make_norm_from_scale.<locals>.Norm.__init__Y
  s    *%**D;F;BG N3KLa1bll&&q))LND)++D&D*./A*BD //!#/DK 113DI	 Ms   #B4r   )
parametersc                 H   | j                  |      \  }}| j                  | j                  | j                  |       | j                  | j                  kD  rt	        d      | j                  | j                  k(  rt        j                  |d      S || j                  }|r+t        j                  || j                  | j                        }| j                  j                  |      j                  t        j                  |            }| j                  j                  | j                  | j                  g      \  }}t        j                  ||g      j                         st	        d      ||z  }|||z
  z  }t
        j                  j                  |d      }|r|d   S |S )N"vmin must be less or equal to vmaxr   Invalid vmin or vmaxFr  )rq  rY  rZ  rv  r[   r   	full_liker   r  rI  r   r   isfiniter   r   masked_invalid)r   r#   r   rp  t_valuet_vmint_vmaxs          r   r  z,_make_norm_from_scale.<locals>.Norm.__call__g
  sT   #11%8E9yy DII$5##E*yy499$ !EFFyyDII%||E1--|yytyy$))<ii))%088%IG!YY00$))TYY1GHNFF;;/0446 !788vG(Gee**7*?G!*71:77r   c                 2   | j                         st        d      | j                  | j                  kD  rt        d      | j                  j                  | j                  | j                  g      \  }}t        j                  ||g      j                         st        d      | j                  |      \  }}|||z
  z  }||z  }| j                  j                         j                  |      j                  t        j                  |            }|r|d   S |S )NNot invertible until scaledr  r  r   )r}  r[   rY  rZ  r  rI  r   r  r   rq  r  r   r   )r   r#   r  r  rp  rescaleds         r   r~  z+_make_norm_from_scale.<locals>.Norm.inverse|
  s    ;;= !>??yy499$ !EFF!YY00$))TYY1GHNFF;;/0446 !788#11%8E90HHYYhji)gbhhuo.   )583e3r   c                     t        j                  t        j                  | j                  j	                  |            |      }|j
                  dk(  rt         j                  j                  }t        | %  |      S )Nr   )
r   extractr  r  rI  r  r   r   r   rv  )r   r  in_trf_domainr   s      r   rv  z2_make_norm_from_scale.<locals>.Norm.autoscale_None
  sV    JJr{{4993F3Fq3I'JANM!!Q& "7)-88r   r   )r&   r'   r(   r  r   replacer  	ParameterPOSITIONAL_OR_KEYWORDr  values__signature__r  r~  rv  r)   )r   r  r  r  r  r  s   @r   Normr  E
  s    	  	 &	4 	4 "6!=!=Gfg&7&7&M&MNJ7!,,335J7!= "8	8*	4"	9 	9r   r  )rP  r&   r(   r'   rd   )r  r  r  r  r  r  s   ````` r   r  r  3
  s    $M9 M9} M9^ 	!$--.d3(556d;%..)66#..DO ((DLKr   c                 $    | j                  |       S r   )r5  )r9  s    r   r  r  
  s    ;;sr   c                  $    t        t        |        S r   )r  r  )r   s    r   r  r  
  s    ()>)EFFr   c                      y r   r1   )	functionsrY  rZ  r   s       r   <lambda>r  
  r  r   c                       e Zd ZdZy)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
        Determines the behavior for mapping values outside the range
        ``[vmin, vmax]``.

        If clipping is off, values outside the range ``[vmin, vmax]`` are also
        transformed by the function, resulting in values outside ``[0, 1]``.
        This behavior is usually desirable, as colormaps can mark these *under*
        and *over* values with specific colors.

        If clipping is on, values below *vmin* are mapped to 0 and values above
        *vmax* are mapped to 1. Such values become indistinguishable from
        regular boundary values, which may cause misinterpretation of the data.
    N)r&   r'   r(   rd   r1   r   r   r  r  
  s    r   r  r   )nonpositiveLogNormz8Normalize a given value to the 0-1 range on a log scale.
   )basec                     	 y r   r1   )	linthreshlinscalerY  rZ  r   r  s         r   r  r  
  s
     r   c                   D    e Zd ZdZed        Zej                  d        Zy)
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                 .    | j                   j                  S r   rV  r  rE   s    r   r  zSymLogNorm.linthresh
  s    {{$$$r   c                 &    || j                   _        y r   r  r`  s     r   r  zSymLogNorm.linthresh
  s     %r   N)r&   r'   r(   rd   r  r  r  r1   r   r   r  r  
  s5    
0 % % & &r   r  c                      y r   r1   )linear_widthrY  rZ  r   s       r   r  r  
  r  r   c                   D    e Zd ZdZed        Zej                  d        Zy)	AsinhNormai  
    The inverse hyperbolic sine scale is approximately linear near
    the origin, but becomes logarithmic for larger positive
    or negative values. Unlike the `SymLogNorm`, the transition between
    these linear and logarithmic regions is smooth, which may reduce
    the risk of visual artifacts.

    .. note::

       This API is provisional and may be revised in the future
       based on early user feedback.

    Parameters
    ----------
    linear_width : float, default: 1
        The effective width of the linear region, beyond which
        the transformation becomes asymptotically logarithmic
    c                 .    | j                   j                  S r   rV  r   rE   s    r   r   zAsinhNorm.linear_width  s    {{'''r   c                 &    || j                   _        y r   r  r`  s     r   r   zAsinhNorm.linear_width  s    #( r   N)r&   r'   r(   rd   r  r   r  r1   r   r   r  r  
  s5    & ( ( ) )r   r  c                   2     e Zd ZdZd fd	ZddZd Z xZS )	PowerNorma2  
    Linearly map a given value to the 0-1 range and then apply
    a power-law normalization over that range.

    Parameters
    ----------
    gamma : float
        Power law exponent.
    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
        Determines the behavior for mapping values outside the range
        ``[vmin, vmax]``.

        If clipping is off, values above *vmax* are transformed by the power
        function, resulting in values above 1, and values below *vmin* are linearly
        transformed resulting in values below 0. This behavior is usually desirable, as
        colormaps can mark these *under* and *over* values with specific colors.

        If clipping is on, values below *vmin* are mapped to 0 and values above
        *vmax* are mapped to 1. Such values become indistinguishable from
        regular boundary values, which may cause misinterpretation of the data.

    Notes
    -----
    The normalization formula is

    .. math::

        \left ( \frac{x - v_{min}}{v_{max}  - v_{min}} \right )^{\gamma}

    For input values below *vmin*, gamma is set to one.
    c                 6    t         |   |||       || _        y r   )r   r   r   )r   r   rY  rZ  r   r   s        r   r   zPowerNorm.__init__=  s    tT*
r   c                    || j                   }| j                  |      \  }}| j                  |       | j                  }| j                  | j
                  }}||kD  rt        d      ||k(  r|j                  d       n|rdt        j                  j                  |      }t        j                  j                  t        j                   |j                  |      ||      |      }|j                  }	|	|z  }	|	||z
  z  }	t        j                  |	|	dkD     |      |	|	dkD  <   t        j                  j                  |	|j                  d      }|r|d   }|S )Nrs  r   rt  Fru  )r   rq  rv  r   rY  rZ  r[   rw  r   r   ro  r   rx  r   powerr   )
r   r#   r   r   rp  r   rY  rZ  r   rz  s
             r   r  zPowerNorm.__call__A  s(   <99D ..u5	F#

YY		d$;NOOT\KKNuu}}V,RWWV]]4-@$%M*. % 0[[FdNFtd{#F!#&!*<e!DF6A:UU[[fkk[FFAYFr   c                    | j                         st        d      | j                  |      \  }}| j                  }| j                  | j
                  }}|j                  }t        j                  ||dkD     d|z        ||dkD  <   |||z
  z  }||z  }t        j                  j                  ||j                  d      }|r|d   }|S )Nr  r   r   Fru  )r}  r[   rq  r   rY  rZ  r   r   r
  r   r   r   )r   r#   r   rp  r   rY  rZ  rz  s           r   r~  zPowerNorm.inverse]  s    {{}:;; ..u5	

YY		dXXfVaZ&8!e)Dvz4$;$V&++EBAYFr   r  r   r&   r'   r(   rd   r   r  r~  r)   r*   s   @r   r  r    s    "F8r   r  c                   8     e Zd ZdZddd fdZddZd Z xZS )	BoundaryNormz
    Generate a colormap index based on discrete intervals.

    Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
    instead of to the interval 0-1.
    neitherextendc                8   |r|dk7  rt        d      t        | 	  |d   |d   |       t        j                  |      | _        t        | j
                        | _        | j                  dk  rt        d|      || _        || _	        d| _
        | j                  d	z
  | _        d| _        |d
v r| xj                  d	z  c_        d	| _        |dv r| xj                  d	z  c_        | j                  | j                  kD  rt        d| j                   d| d      y)ao  
        Parameters
        ----------
        boundaries : array-like
            Monotonically increasing sequence of at least 2 bin edges:  data
            falling in the n-th bin will be mapped to the n-th color.

        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.

        Notes
        -----
        If there are fewer bins (including extensions) than colors, then the
        color index is chosen by linearly interpolating the ``[0, nbins - 1]``
        range onto the ``[0, ncolors - 1]`` range, effectively skipping some
        colors in the middle of the colormap.
        r  z+'clip=True' is not compatible with 'extend'r   r   r  r   zDYou must provide at least 2 boundaries (1 region) but you passed in Nr   r  bothr   r  z
There are z0 color bins including extensions, but ncolors = z1; ncolors must equal or exceed the number of bins)r[   r   r   r   r   
boundariesrP   r   Ncmapr  rV  
_n_regions_offset)r   r  ncolorsr   r  r   s        r   r   zBoundaryNorm.__init__}  s"   J Fi'JKKjm*R.tL**Z0T__%66A: ==GNL M M
&&1*_$OOq ODL_$OOq O??TZZ'z$//): ;D 'y ).. / / (r   c                    || j                   }| j                  |      \  }}t        j                  j	                  |      }t        j
                  |j                  | j                  dz               }|r=t        j                   || j                  | j                  |       | j                  dz
  }n| j                  }t        j                  || j                        dz
  | j                  z   }| j                  | j                  kD  rJ| j                  dk(  r| j                  dz
  dz  ||dk(  <   n"| j                  dz
  | j                  dz
  z  |z  }|j                  t        j                        }d||| j                  k  <   |||| j                  k\  <   t        j                  j!                  ||      }|rt#        |d         }|S )z
        This method behaves similarly to `.Normalize.__call__`, except that it
        returns integers or arrays of int16.
        r   outr   r   r   rt  )r   rq  r   r   getmaskarrayr  rx  rZ  rY  r  digitizer  r  r  r,  int16r   r   )	r   r#   r   r  rp  r   max_coliretrv   s	            r   r  zBoundaryNorm.__call__  sk   
 <99D**51Iuu!!"%]]299TYY]34GGB		499"5jj1nGjjG {{2t/!3dllB ::'!##'::>a"7TQY 

Q4??Q+>?$F{{288$!R$))^ 'R499_eekk$Tk*c!f+C
r   c                     t        d      )z
        Raises
        ------
        ValueError
            BoundaryNorm is not invertible, so calling this method will always
            raise an error
        zBoundaryNorm is not invertible)r[   r`  s     r   r~  zBoundaryNorm.inverse  s     9::r   r<  r   r  r*   s   @r   r  r  q  s     =/) =/~(T;r   r  c                       e Zd ZdZddZd Zy)NoNormz
    Dummy replacement for `Normalize`, for the case where we want to use
    indices directly in a `~matplotlib.cm.ScalarMappable`.
    Nc                 n    t        j                  |      rt         j                  j                  |      S |S r   r   r   r   r   )r   r#   r   s      r   r  zNoNorm.__call__  &    ;;u55;;u%%r   c                 n    t        j                  |      rt         j                  j                  |      S |S r   r'  r`  s     r   r~  zNoNorm.inverse  r(  r   r   )r&   r'   r(   rd   r  r~  r1   r   r   r%  r%    s    
r   r%  c                    t        j                  |       } | j                  d   dk7  rt        d| j                   d      | j                  }t        j                  | dt        j
                  | j                  t         j                        d      } t        j                  |       }| j                  d      }t        j                  |dkD        rt        d	|j                                | j                         d
k  rt        d| j                                |d
kD  }t        j                  | d      }t        j                  |      }||   ||   z  ||<   |d
kD  }| d   |k(  |z  }| |df   | |df   z
  ||   z  ||d
f<   | d   |k(  |z  }d| |df   | |d
f   z
  ||   z  z   ||d
f<   | d   |k(  |z  }d| |d
f   | |df   z
  ||   z  z   ||d
f<   |d   dz  dz  |d<   ||d<   ||d<   |j                  |      S )a+  
    Convert an array of float RGB values (in the range [0, 1]) to HSV values.

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

    Returns
    -------
    (..., 3) `~numpy.ndarray`
       Colors converted to HSV values in range [0, 1]
    r   r   /Last dimension of input array must be 3; shape  was found.Fr   r   r   ndminr   zBInput array must be in the range [0, 1]. Found a maximum value of r   zBInput array must be in the range [0, 1]. Found a minimum value of .r   .r   g       @.r   g      @      @r   )r   r   r   r[   r   rn  r   rM  
zeros_liker   r   r  ptpr   )arrin_shaper  arr_maxiposdeltar  idxs           r   
rgb_to_hsvr;    sA    **S/C yy} ""%))K9 : 	: yyH
((%syy"**5C --
CggbkG	vvgk((/8
 	

 wwy1}((+	{4
 	

 Q;DFF3OE
eADkGDM)AdG19Dv;'!T
)CsAv;S!V,c
:CQKv;'!T
)CCFc#q&k1U3Z??CQKv;'!T
)CCFc#q&k1U3Z??CQKv;$+CKCKCK;;x  r   c                 4   t        j                  |       } | j                  d   dk7  rt        d| j                   d      | j                  }t        j                  | dt        j
                  | j                  t         j                        d      } | d   }| d	   }| d
   }t        j                  |      }t        j                  |      }t        j                  |      }|dz  j                  t              }|dz  |z
  }	|d|z
  z  }
|d||	z  z
  z  }|d|d|	z
  z  z
  z  }|dz  dk(  }||   ||<   ||   ||<   |
|   ||<   |dk(  }||   ||<   ||   ||<   |
|   ||<   |dk(  }|
|   ||<   ||   ||<   ||   ||<   |dk(  }|
|   ||<   ||   ||<   ||   ||<   |dk(  }||   ||<   |
|   ||<   ||   ||<   |dk(  }||   ||<   |
|   ||<   ||   ||<   |dk(  }||   ||<   ||   ||<   ||   ||<   t        j                  |||gd      }|j                  |      S )z
    Convert HSV values to RGB.

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

    Returns
    -------
    (..., 3) `~numpy.ndarray`
       Colors converted to RGB values in range [0, 1]
    r   r   r+  r,  Fr   r-  r/  r0  r1  r2  r      r   r   r   r   r   )r   r   r   r[   r   rn  r   rM  
empty_liker,  r   stackr   )hsvr6  hr  r   r  r  r  r  r  pqtr:  rgbs                  r   
hsv_to_rgbrF  B  s    **S/C yy} ""%))K9 : 	: yyH
((%syy"**5C 	FAFAFA
aA
aA
aA	
SA	
SAA	S1WA	S1q5[A	S1a= !A
a%1*CsVAcFsVAcFsVAcF
q&CsVAcFsVAcFsVAcF
q&CsVAcFsVAcFsVAcF
q&CsVAcFsVAcFsVAcF
q&CsVAcFsVAcFsVAcF
q&CsVAcFsVAcFsVAcF
q&CsVAcFsVAcFsVAcF
((Aq!92
&C;;x  r   c                     d}t        | j                  d         D ]  }|| d|t        j                  f   dz  z  }  t        j                  |      S )Nr   r   .r   )ranger   r   r  r+  )r5  sum_sqr  s      r   _vector_magnituderJ    sR     F399R=! /#c1bjj()Q../776?r   c                   l    e Zd ZdZ	 	 ddZed        ZddZddZ	 	 ddZ		 	 ddZ
	 	 dd	Zd
 Zd Zy)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.
    c                 X    || _         || _        || _        || _        || _        || _        y)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.
        hsv_min_val : number, default: 0
            The minimum value ("v" in "hsv") that the *intensity* map can shift the
            output image to.
        hsv_max_val : number, default: 1
            The maximum value ("v" in "hsv") that the *intensity* map can shift the
            output image to.
        hsv_min_sat : number, default: 1
            The minimum saturation value that the *intensity* map can shift the output
            image to.
        hsv_max_sat : number, default: 0
            The maximum saturation value that the *intensity* map can shift the output
            image to.

        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   rN  rO  rP  rQ  rR  rS  s          r   r   zLightSource.__init__  s3    H 
&&&&r   c                 ~   t        j                  d| j                  z
        }t        j                  | j                        }t        j                  t        j
                  |      t        j
                  |      z  t        j                  |      t        j
                  |      z  t        j                  |      g      S )z3The unit vector direction towards the light source.Z   )r   radiansrN  rO  r   cossin)r   azalts      r   	directionzLightSource.direction  s}    
 ZZTZZ(jj%xxFF2J$FF2J$FF3K
  	r   c                    | }t        j                  ||z  ||      \  }}t        j                  |j                  dz         j	                  t        |            }| |d<   | |d<   d|d<   |t        |      z  }| j                  ||      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
        -------
        `~numpy.ndarray`
            A 2D array of illumination values between 0-1, where 0 is
            completely in shadow and 1 is completely illuminated.
        )r   r/  r0  r   r1  )r   gradientrC  r   r(  rg  rJ  shade_normals)	r   	elevation	vert_exagdxdyfractione_dye_dxnormals	            r   	hillshadezLightSource.hillshade  s    N S [[Y!6B?
d )//D0166tIGvvv#F++!!&(33r   c                     |j                  | j                        }|j                         |j                         }}||z  }||z
  dkD  r||z  }|||z
  z  }t	        j
                  |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
        -------
        `~numpy.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   normalsrc  	intensityiminimaxs         r   r^  zLightSource.shade_normals  sw    4 KK/	 ]]_immodX	
 4K4
 I$+&IGGIq!,	r   Nc           
          ||j                         }||j                         }|t        ||      } | ||            } | 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 (M, N, 3) RGB array of floats (ranging 0 to 1) with
            an (M, N, 1) 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.
        **kwargs
            Additional kwargs are passed on to the *blend_mode* function.

        Returns
        -------
        `~numpy.ndarray`
            An (M, N, 4) array of floats ranging between 0-1.
        Nr  )r_  
blend_moder`  ra  rb  rc  .r   )r  r   rP  	shade_rgb)r   r   r  normro  rY  rZ  r`  ra  rb  rc  r   rgb0rgb1s                 r   shadezLightSource.shadeD  s    z <88:D<88:D<$T2DDJt~~d ;dz(1bR'/;39; S"1"WS"1"Wr   c                    | j                  |||||      }	|	dt        j                  f   }	| j                  | j                  | j
                  d}
||
v r |
|   ||	fi |}n	  |||	fi |}t        j                  j                  |	      r1|	j                  d   }t        d      D ]  }|d|f   |   |d|f   |<    |S # t        $ r}t        d|
j                         |d}~ww xY w)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
            (M, N, 3) RGB array of floats (ranging 0 to 1) with an (M, N, 1)
            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.
        **kwargs
            Additional kwargs are passed on to the *blend_mode* function.

        Returns
        -------
        `~numpy.ndarray`
            An (m, n, 3) array of floats ranging between 0-1.
        .)r@  softoverlayz("blend_mode" must be callable or one of Nr/  r   )rg  r   r  	blend_hsvblend_soft_lightblend_overlayr   r[   keysr   r   r   rH  )r   rE  r_  rc  ro  r`  ra  rb  r   rk  lookupblendr  r   r  s                  r   rp  zLightSource.shade_rgb  s   ` NN9iRJ	c2::o.	 ~~----
 &F:&sI@@E<"3	<V< 55??9%>>&)D1X 8&)#q&k$&7c1fd#8   < !K$*KK="2 38;<<s   "
B> >	C%C  C%c           
         || j                   }|| j                  }|| j                  }|| j                  }|d   }d|z  dz
  }t	        |ddddddf         }t        j                  |dd      \  }}	}
t        j                  |	t        j                  |	      dkD  |dkD  z  d|z
  |	z  ||z  z          t        j                  |	t        j                  |	      dkD  |dk  z  d|z   |	z  ||z  z
         t        j                  |
|dkD  d|z
  |
z  ||z  z          t        j                  |
|dk  d|z   |
z  ||z  z
         t        j                  |ddddddf   dd|ddddddf   	       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 : `~numpy.ndarray`
            An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
        intensity : `~numpy.ndarray`
            An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).
        hsv_max_sat : number, optional
            The maximum saturation value that the *intensity* map can shift the output
            image to. If not provided, use the value provided upon initialization.
        hsv_min_sat : number, optional
            The minimum saturation value that the *intensity* map can shift the output
            image to. If not provided, use the value provided upon initialization.
        hsv_max_val : number, optional
            The maximum value ("v" in "hsv") that the *intensity* map can shift the
            output image to. If not provided, use the value provided upon
            initialization.
        hsv_min_val : number, optional
            The minimum value ("v" in "hsv") that the *intensity* map can shift the
            output image to. If not provided, use the value provided upon
            initialization.

        Returns
        -------
        `~numpy.ndarray`
            An (M, N, 3) RGB array representing the combined images.
        Nr/  r   r   r   r   r   g|=r  )rS  rQ  rR  rP  r;  r   moveaxisputmaskr  r   rF  )r   rE  rk  rS  rQ  rP  rR  r@  huesatr   s              r   rx  zLightSource.blend_hsv  s   T **K**K**K**K f%		MA%	 Q1Q3Y(CQ/S# 	

3v-)a-@	MS(9{+BB	D


3v-)a-@	MS(9{+BB	D


3	A	MS(9{+BB	D


3	A	MS(9{+BB	D
Aq!"Hq!Q12X7 #r   c                 0    d|z  |z  dd|z  z
  |dz  z  z   S )a  
        Combine an RGB image with an intensity map using "soft light" blending,
        using the "pegtop" formula.

        Parameters
        ----------
        rgb : `~numpy.ndarray`
            An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
        intensity : `~numpy.ndarray`
            An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).

        Returns
        -------
        `~numpy.ndarray`
            An (M, N, 3) RGB array representing the combined images.
        r   r   r1   )r   rE  rk  s      r   ry  zLightSource.blend_soft_light$  s*    " 9}s"a!i-&736%AAAr   c                 h    d|z  |z  }ddd|z
  z  d|z
  z  z
  }t        j                  |dk  ||      S )a  
        Combine an RGB image with an intensity map using "overlay" blending.

        Parameters
        ----------
        rgb : `~numpy.ndarray`
            An (M, N, 3) RGB array of floats ranging from 0 to 1 (color image).
        intensity : `~numpy.ndarray`
            An (M, N, 1) array of floats ranging from 0 to 1 (grayscale image).

        Returns
        -------
        ndarray
            An (M, N, 3) RGB array representing the combined images.
        r   r   r*  )r   where)r   rE  rk  lowhighs        r   rz  zLightSource.blend_overlay7  sE      )mc!1I&!c'22xxs
C..r   )i;  -   r   r   r   r   )r   r   r   r   r   )Nrw  NNr   r   r   r   )r   r@  r   r   r   )NNNN)r&   r'   r(   rd   r   r  r[  rg  r^  rt  rp  rx  ry  rz  r1   r   r   rL  rL    su     IJ,-)'V 
 
34j,\ GK;<JX AF()HT GK04HTB&/r   rL  c                 Z   t        dd      t        dd      t        dd      t        dd      d}t        j                  ||       ||   }t        |       dz
  }||j                  z   |j
                  xs dz
  }t        |      |k7  r)t        d|dt        |        d	| d
t        |             t        ||   |      }|dv r|j                  |d          n|j                  d       |dv r|j                  |d          n|j                  d       ||_
        t        | |      }||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.Colormap`
    norm : `~matplotlib.colors.Normalize`
    r   r   Nr   )r  r  r   r  r  zWith extend == z and z levels, expected z colors, but got )r   r  r   r  )r  )slicer	   r  rP   startstopr[   r  rL  rP  r  r  )	levelsr   r  	slice_mapcolor_slicen_data_colors
n_expectedr  rq  s	            r   from_levels_and_colorsr  L  s8   0 aQ~Q|D>	I 	y0F#KK!OM!2!22k6F6F6K!LJ
6{j fZuS[M :"|#4S[MCD 	D &-?D vay!v fRj!f!D6D:r   r   r<  r  r  )r   NNF)r   NNF)r  )ard   r  collections.abcr   r   r   r  r  r  ry  r  numbersr   r   PILr   PIL.PngImagePluginr   
matplotlibr   numpyr   r	   r
   r   r   r   _color_datar   r   r   r   r  r   r0   r7  r   r  rx  r6  r2   r4   rD   rw   compiler{   r   r   r   r   r   r\   r   r   r   r   cnameshexColorPatternrgb2hex	hex2colorr   colorConverterr	  r  r  r  r  r  r>  r  rP  r  r  r  r   r  r  r  	FuncScaler  r  LogScaler  r&   r(   SymmetricalLogScaler  
AsinhScaler  r  r  r%  r;  rF  rJ  rL  r  )r   r   s   00r   <module>r     s  'R  4 4    	   	  &   6 6 N ND       $   %6[%6%6%8)!Q"aK 662A5 ) *    $    '   %9^%9%9%;)!Q"aK 662A5 ) *    $ !12  
f.G f.R )*  

>*9

2M 5&,^[|iX
G2 
"**34
	
0 
0  !_"D@ @F
`h `F\X \~zC zCzs sl/] /d2] 2jd? d?N\9 \~s69 s6l.0 .0b i iXG 	OO	ACy CD;
Ienn&9;;DF*3 3 7'L 	

& &	&D 		FH)	 )H):U	 Up};9 };@Y  >!BO!dk/ k/\6}o)
)s   !L3
!L9
