a
    ߙfb5                     @   s   d Z ddlZddlZddlm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mZmZ z$ddlZddlmZ ddlmZ W n  ey   G d	d
 d
ZY n0 g dZddgiZG dd deZdddZeeZdddZdS )zK
Normalization class for Matplotlib that can be used to produce
colorbars.
    N)ma   )PercentileIntervalAsymmetricPercentileIntervalManualIntervalMinMaxIntervalBaseInterval)LinearStretchSqrtStretchPowerStretch
LogStretchAsinhStretchBaseStretch)	Normalize)pyplotc                   @   s   e Zd Zdd ZdS )r   c                 O   s   t dd S )Nz2matplotlib is required in order to use this class.)ImportError)selfargskwargs r   Blib/python3.9/site-packages/astropy/visualization/mpl_normalize.py__init__   s    zNormalize.__init__N)__name__
__module____qualname__r   r   r   r   r   r      s   r   )ImageNormalizesimple_normimshow_norm*
matplotlibc                       sN   e Zd ZdZdddde ddf fdd	Zdd Zdd	d
ZdddZ  Z	S )r   a  
    Normalization class to be used with Matplotlib.

    Parameters
    ----------
    data : ndarray, optional
        The image array.  This input is used only if ``interval`` is
        also input.  ``data`` and ``interval`` are used to compute the
        vmin and/or vmax values only if ``vmin`` or ``vmax`` are not
        input.
    interval : `~astropy.visualization.BaseInterval` subclass instance, optional
        The interval object to apply to the input ``data`` to determine
        the ``vmin`` and ``vmax`` values.  This input is used only if
        ``data`` is also input.  ``data`` and ``interval`` are used to
        compute the vmin and/or vmax values only if ``vmin`` or ``vmax``
        are not input.
    vmin, vmax : float, optional
        The minimum and maximum levels to show for the data.  The
        ``vmin`` and ``vmax`` inputs override any calculated values from
        the ``interval`` and ``data`` inputs.
    stretch : `~astropy.visualization.BaseStretch` subclass instance
        The stretch object to apply to the data.  The default is
        `~astropy.visualization.LinearStretch`.
    clip : bool, optional
        If `True`, data values outside the [0:1] range are clipped to
        the [0:1] range.
    invalid : None or float, optional
        Value to assign NaN values generated by this class.  NaNs in the
        input ``data`` array are not changed.  For matplotlib
        normalization, the ``invalid`` value should map to the
        matplotlib colormap "under" value (i.e., any finite value < 0).
        If `None`, then NaN values are not replaced.  This keyword has
        no effect if ``clip=True``.
    NF      c                    s   t  j|||d || _|| _|d u r.tdt|ts@td|| _|d ur`t|t	s`td|| _
|j| _|| _|| _|d ur| | d S )N)vminvmaxclipzstretch must be inputz5stretch must be an instance of a BaseStretch subclassz7interval must be an instance of a BaseInterval subclass)superr   r!   r"   
ValueError
isinstancer   	TypeErrorstretchr   intervalinverseinverse_stretchr#   invalid_set_limits)r   datar)   r!   r"   r(   r#   r,   	__class__r   r   r   D   s     
zImageNormalize.__init__c                 C   s   | j d ur| jd urd S | jd u rd| j d u rBt|t| | _ | jd u rt|t| | _n0| j|\}}| j d u r|| _ | jd u r|| _d S )N)r!   r"   r)   npminZisfinitemax
get_limits)r   r.   Z_vminZ_vmaxr   r   r   r-   `   s    




zImageNormalize._set_limitsc                 C   s   |du r| j }|du r| j}t|tjrF|r2d}n|j}|| j}nd}t	|rftj
|gtd}ntj
|dtd}| | tj|| j|d tj|| j| j |d |rtj |dd|d}| jjr| j||d|d	}n| j||dd
}tj
||dS )ar  
        Transform values using this normalization.

        Parameters
        ----------
        values : array-like
            The input values.
        clip : bool, optional
            If `True`, values outside the [0:1] range are clipped to the
            [0:1] range.  If `None` then the ``clip`` value from the
            `ImageNormalize` instance is used (the default of which is
            `False`).
        invalid : None or float, optional
            Value to assign NaN values generated by this class.  NaNs in
            the input ``data`` array are not changed.  For matplotlib
            normalization, the ``invalid`` value should map to the
            matplotlib colormap "under" value (i.e., any finite value <
            0).  If `None`, then the `ImageNormalize` instance value is
            used.  This keyword has no effect if ``clip=True``.
        NF)dtypeT)copyr5   )out              ?)r7   r#   r,   )r7   r#   )mask)r#   r,   r&   r   ZMaskedArrayr:   Zfilledr"   r1   ZisscalarZarrayfloatr-   subtractr!   Ztrue_divider(   _supports_invalid_kw)r   valuesr#   r,   r:   r   r   r   __call__q   s0    


zImageNormalize.__call__c                 C   s>   | j jr| j |d|d}n| j |dd}|| j| j  | j S )NF)r#   r,   )r#   )r+   r=   r"   r!   )r   r>   r,   Zvalues_normr   r   r   r*      s    zImageNormalize.inverse)NN)N)
r   r   r   __doc__r	   r   r-   r?   r*   __classcell__r   r   r/   r   r       s   #
Ar   linearr9   皙?F  r    c                 C   s   |durt |}nF|dus"|dur6t|p*d|p0d}n"|dusF|durRt||}nt }|dkrht }nV|dkrxt }nF|dkrt|}n4|dkrt|
}n"|dkrt|}nt	d	| d
|
| \}}t||||	|dS )a2  
    Return a Normalization class that can be used for displaying images
    with Matplotlib.

    This function enables only a subset of image stretching functions
    available in `~astropy.visualization.mpl_normalize.ImageNormalize`.

    This function is used by the
    ``astropy.visualization.scripts.fits2bitmap`` script.

    Parameters
    ----------
    data : ndarray
        The image array.

    stretch : {'linear', 'sqrt', 'power', log', 'asinh'}, optional
        The stretch function to apply to the image.  The default is
        'linear'.

    power : float, optional
        The power index for ``stretch='power'``.  The default is 1.0.

    asinh_a : float, optional
        For ``stretch='asinh'``, the value where the asinh curve
        transitions from linear to logarithmic behavior, expressed as a
        fraction of the normalized image.  Must be in the range between
        0 and 1.  The default is 0.1.

    min_cut : float, optional
        The pixel value of the minimum cut level.  Data values less than
        ``min_cut`` will set to ``min_cut`` before stretching the image.
        The default is the image minimum.  ``min_cut`` overrides
        ``min_percent``.

    max_cut : float, optional
        The pixel value of the maximum cut level.  Data values greater
        than ``min_cut`` will set to ``min_cut`` before stretching the
        image.  The default is the image maximum.  ``max_cut`` overrides
        ``max_percent``.

    min_percent : float, optional
        The percentile value used to determine the pixel value of
        minimum cut level.  The default is 0.0.  ``min_percent``
        overrides ``percent``.

    max_percent : float, optional
        The percentile value used to determine the pixel value of
        maximum cut level.  The default is 100.0.  ``max_percent``
        overrides ``percent``.

    percent : float, optional
        The percentage of the image values used to determine the pixel
        values of the minimum and maximum cut levels.  The lower cut
        level will set at the ``(100 - percent) / 2`` percentile, while
        the upper cut level will be set at the ``(100 + percent) / 2``
        percentile.  The default is 100.0.  ``percent`` is ignored if
        either ``min_percent`` or ``max_percent`` is input.

    clip : bool, optional
        If `True`, data values outside the [0:1] range are clipped to
        the [0:1] range.

    log_a : float, optional
        The log index for ``stretch='log'``. The default is 1000.

    invalid : None or float, optional
        Value to assign NaN values generated by the normalization.  NaNs
        in the input ``data`` array are not changed.  For matplotlib
        normalization, the ``invalid`` value should map to the
        matplotlib colormap "under" value (i.e., any finite value < 0).
        If `None`, then NaN values are not replaced.  This keyword has
        no effect if ``clip=True``.

    Returns
    -------
    result : `ImageNormalize` instance
        An `ImageNormalize` instance that can be used for displaying
        images with Matplotlib.
    Nr8   g      Y@rB   ZsqrtpowerlogZasinhzUnknown stretch: .)r!   r"   r(   r#   r,   )r   r   r   r   r	   r
   r   r   r   r%   r4   r   )r.   r(   rE   Zasinh_aZmin_cutZmax_cutZmin_percentZmax_percentZpercentr#   Zlog_ar,   r)   r!   r"   r   r   r   r      s0    S




r   c                 K   s   d|v rt dd|v r t dt|}d| i}tjD ]}||v r6||||< q6tf i ||d< |du rtj| fi |}n|j| fi |}||d fS )a+   A convenience function to call matplotlib's `matplotlib.pyplot.imshow`
    function, using an `ImageNormalize` object as the normalization.

    Parameters
    ----------
    data : 2D or 3D array-like
        The data to show. Can be whatever `~matplotlib.pyplot.imshow` and
        `ImageNormalize` both accept. See `~matplotlib.pyplot.imshow`.
    ax : None or `~matplotlib.axes.Axes`, optional
        If None, use pyplot's imshow.  Otherwise, calls ``imshow`` method of
        the supplied axes.
    **kwargs : dict, optional
        All other keyword arguments are parsed first by the
        `ImageNormalize` initializer, then to
        `~matplotlib.pyplot.imshow`.

    Returns
    -------
    result : tuple
        A tuple containing the `~matplotlib.image.AxesImage` generated
        by `~matplotlib.pyplot.imshow` as well as the `ImageNormalize`
        instance.

    Notes
    -----
    The ``norm`` matplotlib keyword is not supported.

    Examples
    --------
    .. plot::
        :include-source:

        import numpy as np
        import matplotlib.pyplot as plt
        from astropy.visualization import (imshow_norm, MinMaxInterval,
                                           SqrtStretch)

        # Generate and display a test image
        image = np.arange(65536).reshape((256, 256))
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        im, norm = imshow_norm(image, ax, origin='lower',
                               interval=MinMaxInterval(),
                               stretch=SqrtStretch())
        fig.colorbar(im)
    Xz#Cannot give both ``X`` and ``data``ZnormzoThere is no point in using imshow_norm if you give the ``norm`` keyword - use imshow directly if you want that.r.   N)r%   dict	_norm_sig
parameterspopr   pltZimshow)r.   Zaxr   Zimshow_kwargsZnorm_kwargsZpnameZimshow_resultr   r   r   r   2  s    /
r   )rB   r9   rC   NNNNNFrD   r    )N)r@   inspectZnumpyr1   r   r)   r   r   r   r   r   r(   r	   r
   r   r   r   r   r   Zmatplotlib.colorsr   r   rM   r   __all__Z__doctest_requires__r   r   Z	signaturerJ   r   r   r   r   r   <module>   s*    
    
q
