U
    ?hc                     @   s  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mZ dddddd	d
dddg
Z	dd Z
dd Zdd ZG dd dZG dd deZG dd deZdd ZG dd deZG dd dZG d d deZd!d Zd;d#dZd$d Zd%d Zd&d Zd<d(d	Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Ze j j!eje" j j!ej"e# j j!ej#e$ j j!ej$e% j j!ejd3ej"d4ej$iZ&d=d6d7Z'd8d Z(d9d: Z)dS )>    N   )all_warningswarndeprecate_funcget_bound_method_classr   safe_as_intcheck_shape_equalitycheck_nDr   
reshape_ndidentityslice_at_axisc                 C   s   t | rdt| j S dS dS )z'Return function rank in the call stack.r   r   N)_is_wrapped_get_stack_rank__wrapped__func r   G/var/www/html/venv/lib/python3.8/site-packages/skimage/_shared/utils.pyr      s    r   c                 C   s   dt | kS )Nr   )dirr   r   r   r   r      s    r   c                 C   s   t | j| j| S )z"Return function call stack length.)r   __globals__get__name__r   r   r   r   _get_stack_length   s    r   c                   @   s   e Zd ZdZi Zdd ZdS )_DecoratorBaseClassa  Used to manage decorators' warnings stacklevel.

    The `_stack_length` class variable is used to store the number of
    times a function is wrapped by a decorator.

    Let `stack_length` be the total number of times a decorated
    function is wrapped, and `stack_rank` be the rank of the decorator
    in the decorators stack. The stacklevel of a warning is then
    `stacklevel = 1 + stack_length - stack_rank`.
    c                 C   s   | j |jt|S N)_stack_lengthr   r   r   )selfr   r   r   r   get_stack_length.   s    
z$_DecoratorBaseClass.get_stack_lengthN)r   
__module____qualname____doc__r   r   r   r   r   r   r       s   r   c                   @   s&   e Zd ZdZddddZdd ZdS )change_default_valuea  Decorator for changing the default value of an argument.

    Parameters
    ----------
    arg_name: str
        The name of the argument to be updated.
    new_value: any
        The argument new value.
    changed_version : str
        The package version in which the change will be introduced.
    warning_msg: str
        Optional warning message. If None, a generic warning message
        is used.

    N)warning_msgc                C   s   || _ || _|| _|| _d S r   )arg_name	new_valuer"   changed_version)r   r#   r$   r%   r"   r   r   r   __init__D   s    zchange_default_value.__init__c                    s   t j}t| j |j j}tj	d krdj dj
 dj dj d| dj dj dj
 d	j d
_	t fdd}|S )NzThe new recommended value for z is z. Until version z, the default z
 value is z. From version z, the z default value will be z/. To avoid this warning, please explicitly set z value.c                     sL   d   }t|  d k rBj| krBtjjt|d | |S Nr   
stacklevel)r   lenr#   keyswarningsr   r"   FutureWarningargskwargsr)   arg_idxr   r   
stack_rankr   r   
fixed_func[   s    
z1change_default_value.__call__.<locals>.fixed_func)inspect	signature
parameterslistr+   indexr#   defaultr   r"   r$   r%   	functoolswraps)r   r   r7   	old_valuer4   r   r1   r   __call__K   s    
Jzchange_default_value.__call__r   r   r   r    r&   r>   r   r   r   r   r!   3   s   r!   c                   @   s&   e Zd ZdZddddZdd ZdS )
remove_argaf  Decorator to remove an argument from function's signature.

    Parameters
    ----------
    arg_name: str
        The name of the argument to be removed.
    changed_version : str
        The package version in which the warning will be replaced by
        an error.
    help_msg: str
        Optional message appended to the generic warning message.

    N)help_msgc                C   s   || _ || _|| _d S r   )r#   rA   r%   )r   r#   r%   rA   r   r   r   r&   v   s    zremove_arg.__init__c                    s   t j}t| j j dj dj dj dj	d k	r^dj	 7 t
t fdd}|S )Nz7 argument is deprecated and will be removed in version z/. To avoid this warning, please do not use the z argument. Please see z  documentation for more details. c                     sF   d   }t|  ks,j| kr<tjt|d | |S r'   )r   r*   r#   r+   r,   r   r-   r.   r2   r   r   r3   r"   r   r   r4      s    z'remove_arg.__call__.<locals>.fixed_func)r5   r6   r7   r8   r+   r9   r#   r%   r   rA   r   r;   r<   )r   r   r7   r4   r   rC   r   r>   {   s    "
zremove_arg.__call__r?   r   r   r   r   r@   g   s   r@   c                 C   s  | j dkrdS zddlm}m} W n tk
r<   | j  Y S X || }| D ]8\}}d| ddd| g}|d ||d	|d
 qNt|}	|	d}
|
dd }|d 	 s|
d q|
d}|d 	 r|d|
d 7 }q|d7 }|d| }ddd |dD }|S )a2  Add deprecated kwarg(s) to the "Other Params" section of a docstring.

    Parameters
    ----------
    func : function
        The function whose docstring we wish to update.
    kwarg_mapping : dict
        A dict containing {old_arg: new_arg} key/value pairs as used by
        `deprecate_kwarg`.
    deprecated_version : str
        A major.minor version string specifying when old_arg was
        deprecated.

    Returns
    -------
    new_doc : str
        The updated docstring. Returns the original docstring if numpydoc is
        not available.
    Nr   )FunctionDoc	ParameterzDeprecated in favor of `z`. z.. deprecated:: zOther ParametersZ
DEPRECATED)nametypedesc
r   z
    z

c                 S   s   g | ]}|  qS r   )rstrip).0liner   r   r   
<listcomp>   s     z-_docstring_add_deprecated.<locals>.<listcomp>)r    Znumpydoc.docscraperD   rE   ImportErroritemsappendstrsplitstrippopjoin)r   kwarg_mappingdeprecated_versionrD   rE   Docold_argnew_argrI   Znew_docstringrS   Z	no_headerdescrZfinal_docstringr   r   r   _docstring_add_deprecated   s@    



r]   c                   @   s"   e Zd ZdZdddZdd ZdS )deprecate_kwarga9  Decorator ensuring backward compatibility when argument names are
    modified in a function definition.

    Parameters
    ----------
    kwarg_mapping: dict
        Mapping between the function's old argument names and the new
        ones.
    deprecated_version : str
        The package version in which the argument was first deprecated.
    warning_msg: str
        Optional warning message. If None, a generic warning message
        is used.
    removed_version : str
        The package version in which the deprecated argument will be
        removed.

    Nc                 C   sR   || _ |d krBd| _|d k	r2|  jd| d7  _|  jd7  _n|| _|| _d S )Nz=`{old_arg}` is a deprecated argument name for `{func_name}`. zIt will be removed in version z. zPlease use `{new_arg}` instead.)rW   r"   rX   )r   rW   rX   r"   removed_versionr   r   r   r&      s    zdeprecate_kwarg.__init__c                    sF   t  t  fdd} jd k	rBt jj}||_|S )Nc                     sf   d    }j D ]>\}}||krtjjj| j|dt|d |	|||< q | |S )Nr   )rZ   	func_namer[   r(   )
r   rW   rP   r,   r   r"   formatr   r-   rU   )r/   r0   r)   rZ   r[   r   r   r3   r   r   r4      s    
 z,deprecate_kwarg.__call__.<locals>.fixed_func)r   r;   r<   r    r]   rW   rX   )r   r   r4   Znewdocr   rb   r   r>      s    
zdeprecate_kwarg.__call__)NNr?   r   r   r   r   r^      s
     
r^   c                   @   s"   e Zd ZdZd
ddZdd Zd	S )channel_as_last_axisa%  Decorator for automatically making channels axis last for all arrays.

    This decorator reorders axes for compatibility with functions that only
    support channels along the last axis. After the function call is complete
    the channels axis is restored back to its original position.

    Parameters
    ----------
    channel_arg_positions : tuple of int, optional
        Positional arguments at the positions specified in this tuple are
        assumed to be multichannel arrays. The default is to assume only the
        first argument to the function is a multichannel array.
    channel_kwarg_names : tuple of str, optional
        A tuple containing the names of any keyword arguments corresponding to
        multichannel arrays.
    multichannel_output : bool, optional
        A boolean that should be True if the output of the function is not a
        multichannel array and False otherwise. This decorator does not
        currently support the general case of functions with multiple outputs
        where some or all are multichannel.

    r   r   Tc                 C   s   t || _t || _|| _d S r   )setarg_positionskwarg_namesmultichannel_output)r   Zchannel_arg_positionsZchannel_kwarg_namesrh   r   r   r   r&   .  s    

zchannel_as_last_axis.__init__c                    s   t   fdd}|S )Nc                     s
  | dd }|d kr | |S t|r.|f}t|dkrBtd|dksR|dkr\ | |S jrg }t| D ]6\}}|jkr|t||d d qn|| qnt	|}n| }j
D ]}t|| |d d||< qd|d<  ||}jrt|d|d }|S )Nchannel_axisr   z1only a single channel axis is currently supported)rj   r   )r   npZisscalarr*   
ValueErrorrf   	enumeraterQ   Zmoveaxistuplerg   rh   )r/   r0   ri   new_argsposargrG   outr   r   r   r   r4   6  s4    






z1channel_as_last_axis.__call__.<locals>.fixed_func)r;   r<   )r   r   r4   r   rs   r   r>   4  s    +zchannel_as_last_axis.__call__N)rd   r   Tr?   r   r   r   r   rc     s
     
rc   c                   @   s(   e Zd ZdZdddddZdd ZdS )r   av  Decorate a deprecated function and warn when it is called.

    Adapted from <http://wiki.python.org/moin/PythonDecoratorLibrary>.

    Parameters
    ----------
    deprecated_version : str
        The package version when the deprecation was introduced.
    removed_version : str
        The package version in which the deprecated function will be removed.
    hint : str, optional
        A hint on how to address this deprecation,
        e.g., "Use `skimage.submodule.alternative_func` instead."

    Examples
    --------
    >>> @deprecate_func(
    ...     deprecated_version="1.0.0",
    ...     removed_version="1.2.0",
    ...     hint="Use `bar` instead."
    ... )
    ... def foo():
    ...     pass

    Calling ``foo`` will warn with::

        FutureWarning: `foo` is deprecated since version 1.0.0
        and will be removed in version 1.2.0. Use `bar` instead.
    N)r_   hintc                C   s   || _ || _|| _d S r   )rX   r_   rt   )r   rX   r_   rt   r   r   r   r&     s    zdeprecate_func.__init__c                    s   d j  dj jr,dj d7 jrJdjd d7 t t  fdd}d }|jd kr||_n|d	 |j |_|S )
N`z` is deprecated since version z  and will be removed in version .rB   c                     s,   d    }tjt|d  | |S )Nr   )categoryr)   )r   r,   r   r-   r.   r   messager   r3   r   r   wrapped  s    z(deprecate_func.__call__.<locals>.wrappedz**Deprecated:** z

    )	r   rX   r_   rt   rK   r   r;   r<   r    )r   r   rz   docr   rx   r   r>     s    


zdeprecate_func.__call__r?   r   r   r   r   r   e  s   c                 C   s   t jdk r| jS | jjS )z*Return the class for a bound method.

    3)sysversionZim_class__self__	__class__)mr   r   r   r     s    MbP?c                 C   s   t | d }|jdkr*|dkrBd| }nd||dk  ||dk< zt jj|d|d W n$ tk
r|   td|  dY nX t | t j	S )a  
    Attempt to safely cast values to integer format.

    Parameters
    ----------
    val : scalar or iterable of scalars
        Number or container of numbers which are intended to be interpreted as
        integers, e.g., for indexing purposes, but which may not carry integer
        type.
    atol : float
        Absolute tolerance away from nearest integer to consider values in
        ``val`` functionally integers.

    Returns
    -------
    val_int : NumPy scalar or ndarray of dtype `np.int64`
        Returns the input value(s) coerced to dtype `np.int64` assuming all
        were within ``atol`` of the nearest integer.

    Notes
    -----
    This operation calculates ``val`` modulo 1, which returns the mantissa of
    all values. Then all mantissas greater than 0.5 are subtracted from one.
    Finally, the absolute tolerance from zero is calculated. If it is less
    than ``atol`` for all value(s) in ``val``, they are rounded and returned
    in an integer array. Or, if ``val`` was a scalar, a NumPy scalar type is
    returned.

    If any value(s) are outside the specified tolerance, an informative error
    is raised.

    Examples
    --------
    >>> safe_as_int(7.0)
    7

    >>> safe_as_int([9, 4, 2.9999999999])
    array([9, 4, 3])

    >>> safe_as_int(53.1)
    Traceback (most recent call last):
        ...
    ValueError: Integer argument required but received 53.1, check inputs.

    >>> safe_as_int(53.01, atol=0.01)
    53

    r   r   g      ?)atolz'Integer argument required but received z, check inputs.)
rk   asarrayndimZtestingZassert_allcloseAssertionErrorrl   roundastypeZint64)valr   modr   r   r   r     s    1

c                     s2   | d  t  fdd| dd D s.tddS )z)Check that all images have the same shaper   c                 3   s   | ]} j |j kV  qd S r   )shape)rL   imageZimage0r   r   	<genexpr>  s     z'check_shape_equality.<locals>.<genexpr>r   Nz+Input images must have the same dimensions.)allrl   )Zimagesr   r   r   r     s    c                 C   s   t df| | f d S )a   
    Construct tuple of slices to slice an array in the given dimension.

    Parameters
    ----------
    sl : slice
        The slice for the given dimension.
    axis : int
        The axis to which `sl` is applied. All other dimensions are left
        "unsliced".

    Returns
    -------
    sl : tuple of slices
        A tuple with slices matching `shape` in length.

    Examples
    --------
    >>> slice_at_axis(slice(None, 3, -1), 1)
    (slice(None, None, None), slice(None, 3, -1), Ellipsis)
    N).)slice)slZaxisr   r   r   r     s    c                 C   s0   | j dkrtddg| }d||< t| |S )a  Reshape a 1D array to have n dimensions, all singletons but one.

    Parameters
    ----------
    arr : array, shape (N,)
        Input array
    ndim : int
        Number of desired dimensions of reshaped array.
    dim : int
        Which dimension/axis will not be singleton-sized.

    Returns
    -------
    arr_reshaped : array, shape ([1, ...], N, [1,...])
        View of `arr` reshaped to the desired shape.

    Examples
    --------
    >>> rng = np.random.default_rng()
    >>> arr = rng.random(7)
    >>> reshape_nd(arr, 2, 0).shape
    (7, 1)
    >>> reshape_nd(arr, 3, 1).shape
    (1, 7, 1)
    >>> reshape_nd(arr, 4, -1).shape
    (1, 1, 1, 7)
    r   zarr must be a 1D arrayrj   )r   rl   rk   Zreshape)Zarrr   dimZ	new_shaper   r   r   r
     s
    

r   c                 C   sf   t | } d}d}t|tr"|g}| jdkr8t|| | j|krbt||ddd |D f dS )aJ  
    Verify an array meets the desired ndims and array isn't empty.

    Parameters
    ----------
    array : array-like
        Input array to be validated
    ndim : int or iterable of ints
        Allowable ndim or ndims for the array.
    arg_name : str, optional
        The name of the array in the original function.

    z1The parameter `%s` must be a %s-dimensional arrayz+The parameter `%s` cannot be an empty arrayr   z-or-c                 S   s   g | ]}t |qS r   )rR   )rL   nr   r   r   rN   O  s     zcheck_nD.<locals>.<listcomp>N)rk   Z
asanyarray
isinstanceintsizerl   r   rV   )arrayr   r#   Zmsg_incorrect_dimZmsg_empty_arrayr   r   r   r	   8  s    



c                 C   sL   | j tjkr| tjS |r4| j jdkrH| t} nddlm} || } | S )a  Convert input image to float image with the appropriate range.

    Parameters
    ----------
    image : ndarray
        Input image.
    preserve_range : bool
        Determines if the range of the image should be kept or transformed
        using img_as_float. Also see
        https://scikit-image.org/docs/dev/user_guide/data_types.html

    Notes
    -----
    * Input images with `float32` data type are not upcast.

    Returns
    -------
    image : ndarray
        Transformed version of the input.

    Zdf   )img_as_float)	dtyperk   float16r   float32charfloatZ
util.dtyper   )r   Zpreserve_ranger   r   r   r   convert_to_floatS  s    r   c                 C   sL   |dkr| t krdS dS |dk s(|dkr0td| t krH|dkrHtd|S )a3  Validate and return spline interpolation's order.

    Parameters
    ----------
    image_dtype : dtype
        Image dtype.
    order : int, optional
        The order of the spline interpolation. The order has to be in
        the range 0-5. See `skimage.transform.warp` for detail.

    Returns
    -------
    order : int
        if input order is None, returns 0 if image_dtype is bool and 1
        otherwise. Otherwise, image_dtype is checked and input order
        is validated accordingly (order > 0 is not supported for bool
        image dtype)

    Nr   r      z6Spline interpolation order has to be in the range 0-5.zInput image dtype is bool. Interpolation is not defined with bool data type. Please set order to 0 or explicitly cast input image to another data type.)boolrl   )Zimage_dtypeorderr   r   r   _validate_interpolation_orderv  s    r   c                 C   s"   t dddd}| |kr||  } | S )z7Convert padding modes from `ndi.correlate` to `np.pad`.edge	symmetricreflect)nearestr   mirror)dictmodeZmode_translation_dictr   r   r   _to_np_mode  s    r   c                 C   s6   t dddddd}| |kr*td|  dt||  S )	zEConvert from `numpy.pad` mode name to the corresponding ndimage mode.constantr   r   r   wrap)r   r   r   r   r   zUnknown mode: 'z', or cannot translate mode. The mode should be one of 'constant', 'edge', 'symmetric', 'reflect', or 'wrap'. See the documentation of numpy.pad for more info.)r   rl   _fix_ndimage_moder   r   r   r   _to_ndimage_mode  s     
r   c                 C   s   ddd}| | | S )Nzgrid-constantz	grid-wrap)r   r   )r   )r   Z
grid_modesr   r   r   r     s    
r   gGFc                 C   sN   t | trtjdd | D  S t| } |s>| jdkr>tdt| j	tj
S )a  Return an appropriate floating-point dtype for a given dtype.

    float32, float64, complex64, complex128 are preserved.
    float16 is promoted to float32.
    complex256 is demoted to complex128.
    Other types are cast to float64.

    Parameters
    ----------
    input_dtype : np.dtype or tuple of np.dtype
        The input dtype. If a tuple of multiple dtypes is provided, each
        dtype is first converted to a supported floating point type and the
        final dtype is then determined by applying `np.result_type` on the
        sequence of supported floating point types.
    allow_complex : bool, optional
        If False, raise a ValueError on complex-valued inputs.

    Returns
    -------
    float_type : dtype
        Floating-point dtype for the image.
    c                 s   s   | ]}t |V  qd S r   )_supported_float_type)rL   dr   r   r   r     s     z(_supported_float_type.<locals>.<genexpr>cz%complex valued input is not supported)r   rn   rk   Zresult_typer   kindrl   new_float_typer   r   float64)Zinput_dtypeZallow_complexr   r   r   r     s    

r   c                 O   s   | S )z&Returns the first argument unmodified.r   )r   r/   r0   r   r   r   r     s    c                C   sF   t | } | jtkr8t | dk| dk@ r8t| dt j| tdS )zReturn `array` as a numpy.ndarray of dtype bool.

    Raises
    ------
    ValueError:
        An error including the given `variable_name` if `array` can not be
        safely cast to a boolean array.
    r   r   zo array is not of dtype boolean or contains values other than 0 and 1 so cannot be safely cast to boolean array.)r   )rk   r   r   r   anyrl   )r   Zvariable_namer   r   r   as_binary_ndarray  s    	

r   )r   )r   )F)*r;   r5   r}   r,   numpyrk   	_warningsr   r   __all__r   r   r   r   r!   r@   r]   r^   rc   r   r   r   r   r   r
   r	   r   r   r   r   r   r   r   r   r   Z	complex64Z
complex128r   r   r   r   r   r   r   r   r   <module>   sj        4/B?NE
C#
#%		
 
 
 
 
   
