
    79j                        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	m
Z
 g dZd Zd Zd Z G d	 d
      Z G d de      Z G d de      Z G d d      Zd Z G d de      Z G d d      Zed        Z G d d      Z G d d      Zd/dZd Zd Zd Zd0d Zd! Z d" Z!d# Z"d1d$Z#d% Z$d& Z%d' Z&d( Z'd) Z( ejR                         jT                  jV                  ejR                   ejX                         jT                  jV                  ejX                   ejZ                         jT                  jV                  ejZ                   ej\                         jT                  jV                  ej\                   ej^                         jT                  jV                  ejR                  d*ejX                  d+ej\                  iZ0d2d,Z1d- Z2d. Z3y)3    N)contextmanager   )all_warningswarn)deprecate_funcget_bound_method_classr   safe_as_intcheck_shape_equalitycheck_nDr   
reshape_ndidentityslice_at_axisdeprecate_parameter
DEPRECATEDc                 b    | }d}t        |d      r|j                  }|dz  }t        |d      r|S )a  Count the number of inner wrappers by unpacking ``__wrapped__``.

    If a wrapped function wraps another wrapped function, then we refer to the
    wrapping of the second function as an *inner wrapper*.

    For example, consider this code fragment:

    .. code-block:: python
        @wrap_outer
        @wrap_inner
        def foo():
            pass

    Here ``@wrap_inner`` applies a wrapper to ``foo``, and ``@wrap_outer``
    applies a wrapper to the result.

    Parameters
    ----------
    func : callable
        The callable of which to determine the number of inner wrappers.

    Returns
    -------
    count : int
        The number of times `func` has been wrapped.

    See Also
    --------
    count_global_wrappers
    r   __wrapped__r   )hasattrr   )func	unwrappedcounts      U/media/conek/DATA/Code/OCR/venv/lib/python3.12/site-packages/skimage/_shared/utils.pycount_inner_wrappersr      s?    > IE
)]
+))	
 )]
+ L    c                 V    t        |       }t        |       }||z
  dz   }t        |d      S )a  Find stacklevel of `func` relative to its global representation.

    Determine automatically with which stacklevel a warning should be raised.

    Parameters
    ----------
    func : Callable
        Tries to find the global version of `func` and counts the number of
        additional wrappers around `func`.

    Returns
    -------
    stacklevel : int
        The stacklevel. Minimum of 2.
    r      )r   count_global_wrappersmax)r   inner_wrapped_countglobal_wrapped_count
stacklevels       r   _warning_stacklevelr!   B   s7    " /t406%(;;a?Jz1r   c                     d| j                   v rd}t        |      | j                   j                  d      ^}}| j                  j	                  ||       }|D ]  }t        |||      } t        |      }|dk\  sJ |S )a  Count the total number of times a function as been wrapped globally.

    Similar to :func:`count_inner_wrappers`, this counts the number of times
    `func` has been wrapped. However, this function doesn't start counting
    from `func` but instead tries to access the "global representation" of
    `func`. This means that you could use this function from inside a wrapper
    that was applied first, and still count wrappers that were applied on
    top of it afterwards.

    E.g., `func` might be wrapped by multiple decorators that emit
    warnings. In that case, calling this function in the inner-most decorator
    will still return the total count of wrappers.

    Parameters
    ----------
    func : callable
        The callable of which to determine the number of wrappers. Can be a
        function or method of a class.

    Returns
    -------
    count : int
        The number of times `func` has been wrapped.

    See Also
    --------
    count_inner_wrappers
    z<locals>zuCannot determine stacklevel of a function defined in another function's local namespace. Set the stacklevel manually..r   )__qualname__
ValueErrorsplit__globals__getgetattrr   )r   msg
first_nameotherglobal_funcpartr   s          r   r   r   Z   s    : T&&&G 	 o**005J""&&z48K  >k4=> !-EA::Lr   c                   $    e Zd ZdZddddZd Zy)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.
    stacklevel : {None, int}, optional
        If None, the decorator attempts to detect the appropriate stacklevel for the
        deprecation warning automatically. This can fail, e.g., due to
        decorating a closure, in which case you can set the stacklevel manually
        here. The outermost decorator should have stacklevel 2, the next inner
        one stacklevel 3, etc.
    N)warning_msgr    c                J    || _         || _        || _        || _        || _        y N)arg_name	new_valuer1   changed_versionr    )selfr4   r5   r6   r1   r    s         r   __init__zchange_default_value.__init__   s)     !"&.$r   c                     t        j                        j                  }t        |j	                               j                   j                        | j                     j                  } j                  sd j                   d j                   d j                   d j                   d| d j                   d j                   d j                   d	 j                   d
 _        t        j                         f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                      t        |       dz   k  rej                  |j                         vrIj                  j                  n
t	              }t        j                  j                  t        |        | i |S )Nr   )r    )	lenr4   keysr    r!   warningsr   r1   FutureWarning)argskwargsr    arg_idxr   r7   s      r   
fixed_funcz1change_default_value.__call__.<locals>.fixed_func   sn    4y7Q;&4==+M 2 OO,T2  d..*U(((r   )inspect	signature
parameterslistr<   indexr4   defaultr1   r5   r6   	functoolswraps)r7   r   rE   	old_valuerB   rA   s   ``   @r   __call__zchange_default_value.__call__   s   &&t,77
z()//>t}}-55	#0t>>""243G3G2H I#}}oZ	{ C  $ 4 45VDMM? K))-(8 977;}}oWN  
			) 
		) r   __name__
__module__r$   __doc__r8   rL    r   r   r0   r0      s    , DHTX%r   r0   c                       e Zd ZdZd Zy)PatchClassReprz5Control class representations in rendered signatures.c                 "    d| j                    dS )N<>)rN   )clss    r   __repr__zPatchClassRepr.__repr__   s    3<<.""r   N)rN   rO   r$   rP   rX   rQ   r   r   rS   rS      s
    ?#r   rS   c                       e Zd ZdZy)r   a  Signal value to help with deprecating parameters that use None.

    This is a proxy object, used to signal that a parameter has not been set.
    This is useful if ``None`` is already used for a different purpose or just
    to highlight a deprecated parameter in the signature.
    NrN   rO   r$   rP   rQ   r   r   r   r      s    r   r   )	metaclassc                   4    e Zd ZdZeZdZdZddddddZd Zy)	r   a  Deprecate a parameter of a function.

    Parameters
    ----------
    deprecated_name : str
        The name of the deprecated parameter.
    start_version : str
        The package version in which the warning was introduced.
    stop_version : str
        The package version in which the warning will be replaced by
        an error / the deprecation is completed.
    template : str, optional
        If given, this message template is used instead of the default one.
    new_name : str, optional
        If given, the default message will recommend the new parameter name and an
        error will be raised if the user uses both old and new names for the
        same parameter.
    modify_docstring : bool, optional
        If the wrapped function has a docstring, add the deprecated parameters
        to the "Other Parameters" section.
    stacklevel : {None, int}, optional
        If None, the decorator attempts to detect the appropriate stacklevel for the
        deprecation warning automatically. This can fail, e.g., due to
        decorating a closure, in which case you can set the stacklevel manually
        here. The outermost decorator should have stacklevel 2, the next inner
        one stacklevel 3, etc.

    Notes
    -----
    Assign `DEPRECATED` as the new default value for the deprecated parameter.
    This marks the status of the parameter also in the signature and rendered
    HTML docs.

    This decorator can be stacked to deprecate more than one parameter.

    Examples
    --------
    >>> from skimage._shared.utils import deprecate_parameter, DEPRECATED
    >>> @deprecate_parameter(
    ...     "b", new_name="c", start_version="0.1", stop_version="0.3"
    ... )
    ... def foo(a, b=DEPRECATED, *, c=None):
    ...     return a, c

    Calling ``foo(1, b=2)``  will warn with::

        FutureWarning: Parameter `b` is deprecated since version 0.1 and will
        be removed in 0.3 (or later). To avoid this warning, please use the
        parameter `c` instead. For more details, see the documentation of
        `foo`.
    a	  Parameter `{deprecated_name}` is deprecated since version {deprecated_version} and will be removed in {changed_version} (or later). To avoid this warning, please do not use the parameter `{deprecated_name}`. For more details, see the documentation of `{func_name}`.a  Parameter `{deprecated_name}` is deprecated since version {deprecated_version} and will be removed in {changed_version} (or later). To avoid this warning, please use the parameter `{new_name}` instead. For more details, see the documentation of `{func_name}`.NT)templatenew_namemodify_docstringr    c                f    || _         || _        || _        || _        || _        || _        || _        y r3   )deprecated_namer^   r]   start_versionstop_versionr_   r    )r7   ra   rb   rc   r]   r^   r_   r    s           r   r8   zdeprecate_parameter.__init__  s9      /  *( 0$r   c                 B   	 t        j                        j                  }	 t        |j	                               j                   j                        d j                  r3	 t        |j	                               j                   j                        | j                     j                  t        ur t        d j                   dt        d       j                   j                  }n% j                   j                  }n j                  }|j                   j                   j                    j"                  j$                   j                        	t'        j(                         	fd       } j*                  r@j,                  4t/         j                   j                  i j                         }||_        |S # t        $ r}t         j                  d      |d }~ww xY w# t        $ r}t         j                  d      |d }~ww xY w)Nz not in parametersFz
Expected `z` to have the value z2 to indicate its status in the rendered signature.)ra   deprecated_versionr6   	func_namer^   c                     t         }t         }t        |       kD  r'|    }j                  | d  t         fz   | dz   d  z   } j                  |j	                         v r.|j                     }j                  t         |j                  <   durt        |       kD  r|    }j                  r+j                  |j	                         v r|j                     }|t         urj
                  j
                  n
t              }t        j                  	t        |       |t         ur&t        dj                   dj                   d      j                  ||j                  <    | i |S )Nr   Fcategoryr    zBoth deprecated parameter `z` and new parameter `z<` are used. Use only the latter to avoid conflicting values.)r   r;   r^   ra   r<   r    r!   r=   r   r>   r%   )
r?   r@   deprecated_valuer5   r    deprecated_idxr   new_idxr7   warning_messages
        r   rB   z0deprecate_parameter.__call__.<locals>.fixed_funcS  s   )"I 4y>)#'#7 ==,_n-%-(~1345 
 ##v{{}4#)$*>*>#? ==,3=F4//0 e#D	G(; M	}}&++-!?"4==1	z1 2 OO,T2 
 #m
 J.$5d6J6J5K L..2mm_ =GH 
 ]].,<F4==)(((r   )rC   rD   rE   rF   r<   rG   ra   r%   r^   rH   r   RuntimeErrorr]   replace_parameter_templateremove_parameter_templateformatrb   rc   r$   rI   rJ   r_   rP   _docstring_add_deprecated)
r7   r   rE   er]   rB   newdocrk   rl   rm   s
   ``     @@@r   rL   zdeprecate_parameter.__call__1  s   &&t,77
	S!*//"34::4;O;OPN ==Pz0177F d**+33:ET1122Fzn UD E 
 ==$}}H]]&66H55H"// 00#11 --'']] * 
 
	.	) 
.	)`   T\\%=.t++T]];T=O=OF "(Jk  	S 4 477IJKQRR	S  P DMM#44F!GHaOPs/   2G '2G7 	G4G//G47	H HH)	rN   rO   r$   rP   r   rp   ro   r8   rL   rQ   r   r   r   r      s=    2h J	 	M  %&Yr   r   c                 X   | j                   y	 ddlm}m}  ||       }|j                         D ][  \  }}g }||j                  d| d       n|j                  d| d       |dd	| gz  }|d
   j                   ||d|             ] t        |      }	|	j                  d      }
|
dd }|d   j                         s%|j                  d       |d   j                         s%|j                  d      }|d   j                         r+|d|j                  d      z   z  }|d   j                         r+|dz  }|dj                  |      z   }dj                  |j                  d      D cg c]  }|j                          c}      }|S # t        $ r | j                   cY S w xY wc c}w )a0  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, see
        `deprecate_parameter`.
    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	Parameter`z` is deprecated.zDeprecated in favor of `z`. z.. deprecated:: zOther Parametersr   )nametypedesc
r   z
    z

)rP   numpydoc.docscraperv   rw   ImportErroritemsappendstrr&   strippopjoinrstrip)r   kwarg_mappingre   rv   rw   Docold_argnew_argr|   new_docstringr&   	no_headerdescrfinal_docstringlines                  r   rr   rr     s   ( ||=
 d
C)//1 

?KK!G9$456KK27)2>?'(:';<==&&7DA	


 HM %Eab	Il  "a l  " MM!E
A,


IMM!,,, A,


	VOEhmmI66Oii?;P;PQU;V W4 WXOO  ||L !Xs   F ,F'F$#F$c                       e Zd ZdZy)FailedEstimationAccessErrorzError from use of failed estimation instance

    This error arises from attempts to use an instance of
    :class:`FailedEstimation`.
    NrZ   rQ   r   r   r   r     s    r   r   c                   <    e Zd ZdZeZdZd Zd Zd Z	d Z
d Zd Zy	)
FailedEstimationa  Class to indicate a failed transform estimation.

    The ``from_estimate`` class method of each transform type may return an
    instance of this class to indicate some failure in the estimation process.

    Parameters
    ----------
    message : str
        Message indicating reason for failed estimation.

    Attributes
    ----------
    message : str
        Message above.

    Raises
    ------
    FailedEstimationAccessError
        Exception raised for missing attributes or if the instance is used as a
        callable.
    zYou can check for a failed estimation by truth testing the returned object. For failed estimations, `bool(estimation_result)` will be `False`. E.g.

    if not estimation_result:
        raise RuntimeError(f'Failed estimation: {estimation_result}')c                     || _         y r3   message)r7   r   s     r   r8   zFailedEstimation.__init__  s	    r   c                      y)NFrQ   r7   s    r   __bool__zFailedEstimation.__bool__  s    r   c                 L    t        |       j                   d| j                  dS )N())r{   rN   r   r   s    r   rX   zFailedEstimation.__repr__  s%    t*%%&a'7q99r   c                     | j                   S r3   r   r   s    r   __str__zFailedEstimation.__str__  s    ||r   c                     t        |       j                   d| j                   d| j                   }| j	                  |      )Nz is not callable. 

Hint: r{   rN   r   hint	error_cls)r7   r?   r@   r*   s       r   rL   zFailedEstimation.__call__  sG    Dz""##5dll^ DYYK! 	 nnS!!r   c                     t        |       j                   d|d| j                   d| j                   }| j	                  |      )Nz has no attribute z. r   r   )r7   rz   r*   s      r   __getattr__zFailedEstimation.__getattr__  sM    Dz""##5dXR~ NYYK! 	 nnS!!r   N)rN   rO   r$   rP   r   r   r   r8   r   rX   r   rL   r   rQ   r   r   r   r     s7    , ,I	P 	:""r   r   c               #      K   t        j                         5  t        j                  dt        dd       d ddd       y# 1 sw Y   yxY ww)zmFilter warnings about the deprecated `estimate` method.

    Use either as decorator or context manager.
    ignorez`estimate` is deprecatedskimage)actionri   r   moduleN)r=   catch_warningsfilterwarningsr>   rQ   r   r   #_ignore_deprecated_estimate_warningr     sG      
	 	 	" ".		
 	  s   A"A	AAAc                   $    e Zd ZdZ	 	 	 ddZd Zy)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.

    c                 R    t        |      | _        t        |      | _        || _        y r3   )setarg_positionskwarg_namesmultichannel_output)r7   channel_arg_positionschannel_kwarg_namesr   s       r   r8   zchannel_as_last_axis.__init__;  s(     !!6723#6 r   c                 F     t        j                         fd       }|S )Nc                  ~   |j                  dd       }| | i |S t        j                  |      r|f}t        |      dkD  rt	        d      |dk(  s|dk(  r | i |S 	j
                  rjg }t        |       D ]N  \  }}|	j
                  v r*|j                  t        j                  ||d   d             >|j                  |       P t        |      }n| }	j                  D ]"  }t        j                  ||   |d   d      ||<   $ d|d<    |i |}	j                  rt        j                  |d|d         }|S )Nchannel_axisr   z1only a single channel axis is currently supported)r   r   )r(   npisscalarr;   r%   r   	enumerater   moveaxistupler   r   )
r?   r@   r   new_argsposargrz   outr   r7   s
           r   rB   z1channel_as_last_axis.__call__.<locals>.fixed_funcF  sX   !::nd;L#T,V,,
 {{<( ,< 1$ !TUUu$(:T,V,,!! )$ -HCd000 Ca"(MN ,	-
 !?(( N!{{6$<a"MtN
 &(F>" +F+C''kk#r<?;Jr   )rI   rJ   )r7   r   rB   s   `` r   rL   zchannel_as_last_axis.__call__E  s'    		'	 
'	R r   N))r   rQ   TrM   rQ   r   r   r   r   #  s    2 # 	7+r   r   c                   &    e Zd ZdZdddddZd Zy)r   a  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."
    stacklevel :  {None, int}, optional
        If None, the decorator attempts to detect the appropriate stacklevel for the
        deprecation warning automatically. This can fail, e.g., due to
        decorating a closure, in which case you can set the stacklevel manually
        here. The outermost decorator should have stacklevel 2, the next inner
        one stacklevel 3, etc.

    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)removed_versionr   r    c                <    || _         || _        || _        || _        y r3   re   r   r   r    )r7   re   r   r   r    s        r   r8   zdeprecate_func.__init__  s"     #5.	$r   c                 ~    dj                    d j                    j                  rd j                   dz   j                  r"d j                  j	                  d       dz  t        j                         fd       }d }|j                  	||_        |S |dz   |j                  z   |_        |S )	Nrx   z` is deprecated since version z  and will be removed in version r#    c                      j                   j                   n
t              }t        j                  t        |        | i |S )Nrh   )r    r!   r=   r   r>   )r?   r@   r    r   r   r7   s      r   wrappedz(deprecate_func.__call__.<locals>.wrapped  sG     ??. (. 
 MM'MjQ(((r   z**Deprecated:** z

    )rN   re   r   r   r   rI   rJ   rP   )r7   r   r   docr   s   ``  @r   rL   zdeprecate_func.__call__  s    <T=T=T<UV 	 9$:N:N9OqQQG99499++C0133G			) 
	) !	*??"!GO  "J.@GOr   rM   rQ   r   r   r   r   s  s    "J 6:QU%r   r   c                 x    || j                   j                  d      d   n|} t        ddd| dd      |       S )	zDeprecate ``estimate`` method.r#   r   z0.26z2.2zPlease use `z*.from_estimate` class constructor instead.r   r   )r$   r&   r   )r   
class_names     r   _deprecate_estimater     sU    4>4F""((-a0JJ>!J<'QR	
  r   c                     d }t        | d      j                  }|j                  |_        t        j                  |      |_        t        || j                        | _        | S )zDeprecate inherited ``estimate`` instance method.

    This needs a class decorator so we can correctly specify the class of the
    `from_estimate` class method in the deprecation message.
    c                 *     | j                   |i |d u S r3   )	_estimate)r7   r?   r@   s      r   estimatez/_deprecate_inherited_estimate.<locals>.estimate  s    t~~t.v.$66r   r   )	r)   r   rP   rC   rD   __signature__r   rN   r   )rW   r   inherited_meths      r   _deprecate_inherited_estimater     sS    7 S*-99N%--H$..~>H&x>CLJr   c                    t        | d      fd}j                  j                  d      d   }j                  j	                  || j
                        |_        t        j                        |_        t        |      | _
        | S )a3  Fix docstring for inherited ``from_estimate`` class method.

    Even for classes that inherit the `from_estimate` method, and do not
    override it, we nevertheless need to change the *docstring* of the
    `from_estimate` method to point the user to the current (inheriting) class,
    rather than the class in which the method is defined (the inherited class).

    This needs a class decorator so we can modify the docstring of the new
    class method.  CPython currently does not allow us to modify class method
    docstrings by updating ``__doc__``.
    from_estimatec                      |i |S r3   rQ   )rW   r?   r@   inherited_cmeths      r   r   z6_update_from_estimate_docstring.<locals>.from_estimate  s    ///r   r#   )r)   r$   r&   rP   replacerN   rC   rD   r   classmethodr   )rW   r   inherited_class_namer   s      @r   _update_from_estimate_docstringr     s}     c?3O0 +77==cB2F+33;;cllM #*"3"3O"DM#M2CJr   c                 l    t         j                  dk  r| j                  S | j                  j                  S )z$Return the class for a bound method.3)sysversionim_class__self__	__class__)ms    r   r   r     s&    s*1::D

0D0DDr   c                 :   t        j                  |       dz  }|j                  dk(  r|dkD  rd|z
  }nd||dkD     z
  ||dkD  <   t        j                  |d|      st	        d|  d      t        j
                  |       j                  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.)r   asarrayndimallcloser%   roundastypeint64)valr   mods      r   r	   r	     s    b **S/A
C xx1}9c'CSs^+C#I;;sAD)B3%WXX88C=))r   c                  T    | d   t        fd| dd D              st        d      y)z)Check that all images have the same shaper   c              3   P   K   | ]  }j                   |j                   k(    y wr3   )shape).0imageimage0s     r   	<genexpr>z'check_shape_equality.<locals>.<genexpr>A  s     Cuv||u{{*Cs   #&r   Nz+Input images must have the same dimensions.)allr%   )imagesr   s    @r   r
   r
   >  s/    AYFCqr
CCFGG
r   c                 .    t        d      f|z  | fz   dz   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)slaxiss     r   r   r   F  s!    , $K>D B5(611r   c                 x    | j                   dk7  rt        d      dg|z  }d||<   t        j                  | |      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 arrayr   )r   r%   r   reshape)arrr   dim	new_shapes       r   r   r   _  s@    8 xx1}122d
IIcN::c9%%r   c                 (   t        j                  |       } d}d}t        |t              r|g}| j                  dk(  rt        ||z        | j                  |vr6t        ||dj                  |D cg c]  }t        |       c}      fz        yc c}w )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-N)	r   
asanyarray
isinstanceintsizer%   r   r   r   )arrayr   r4   msg_incorrect_dimmsg_empty_arrayns         r   r   r     s     MM% EKCO$vzzQH566zz6;;7M1A7M+N OO
 	
 7Ms   .Bc                     | j                   t        j                  k(  r| j                  t        j                        S |r/| j                   j
                  dvr| j                  t              } | S 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.

    dfr   )img_as_float)	dtyper   float16r   float32charfloat
util.dtyper  )r   preserve_ranger  s      r   convert_to_floatr    sg    , {{bjj ||BJJ'' ;;4'LL'E
 L 	.U#Lr   c                     || t         k(  rdS dS |dk  s|dkD  rt        d      | t         k(  r|dk7  rt        d      |S )a  Validate and return spline interpolation's order.

    Parameters
    ----------
    image_dtype : dtype
        Image dtype.
    order : {None, int}, optional
        The order of the spline interpolation. The order has to be in the range
        0-5. If ``None`` assume order 0 for Boolean images, otherwise 1. 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)

    r   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.)boolr%   )image_dtypeorders     r   _validate_interpolation_orderr    s[    , }4'q.Q.qyEAIQRRduz5
 	
 Lr   c                 4    t        ddd      }| |v r||    } | S )z7Convert padding modes from `ndi.correlate` to `np.pad`.edge	symmetricreflect)nearestr!  mirror)dictmodemode_translation_dicts     r   _to_np_moder(    s)     YW$$$T*Kr   c                 d    t        ddddd      }| |v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$  r%   _fix_ndimage_moder%  s     r   _to_ndimage_moder-    sX      ((dV $ 
 	
 24899r   c                 0    ddd}|j                  | |       S )Nzgrid-constantz	grid-wrap)r*  r+  )r(   )r&  
grid_modess     r   r,  r,    s     .{CJ>>$%%r   gGc                    t        | t              rt        j                  d | D         S t        j                  |       } |s| j
                  dk(  rt        d      t        j                  | 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              3   2   K   | ]  }t        |        y wr3   )_supported_float_type)r   ds     r   r   z(_supported_float_type.<locals>.<genexpr>.  s     NQ 5a 8Ns   cz%complex valued input is not supported)r  r   r   result_typer  kindr%   new_float_typer(   r  float64)input_dtypeallow_complexs     r   r4  r4    sj    . +u%~~N+NOO((;'K[--4@AAk..

;;r   c                     | S )z&Returns the first argument unmodified.rQ   )r   r?   r@   s      r   r   r   5  s    Lr   c                    t        j                  |       } | j                  t        k7  r,t        j                  | dk7  | dk7  z        rt        | d      t        j                  | t              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  )r   r   r  r  anyr%   )r	  variable_names     r   as_binary_ndarrayrA  :  sf     JJuE{{d665A:%1*-. / "0 1 
 ::e4((r   r3   )gMbP?)r   )F)4rI   rC   r   r=   
contextlibr   numpyr   	_warningsr   r   __all__r   r!   r   r0   r{   rS   r   r   rr   AttributeErrorr   r   r   r   r   r   r   r   r   r	   r
   r   r   r   r  r  r(  r-  r,  r  r  r  r:  	complex64
complex128r  r9  r4  r   rA  rQ   r   r   <module>rI     s     
  %  ) $N0.b: :z#T #> r rj?D. 9" 9"x  M M`H HV&:E
=*@22 &F
6!H#L:&& BJJLRZZBJJLRZZBLLNr||BMMOBJJLRZZ
<>
)r   