
    ^Mh=                        U d dl Z d dlm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
Z
d dlmZmZ d dlZd dlmZmZmZ d dlmZmZ ee         ed<   ee         ed<   ee         ed	<   ej                            ej                  d
k    rd dlmZm Z m!Z!m"Z" nd dlmZm Z m!Z! e#Z"eed<   eed<   ej                            ej                  dk    rb	  ej$                    5   ej%        dde&           ej'        Z(ej)        Z*ddd           n# 1 swxY w Y   n'# e+$ r ej,        Z(ej-        Z*Y nw xY wej,        Z(ej-        Z*e.ej/        z  Z0e1ej2        z  ej/        z  Z3e4dz  ed<   ej                            ej                  dk    rdZ5n\ej                            ej                  dk     rdZ5n6	  ej6        dg          7                    d           dZ5n# e#$ r dZ5Y nw xY wej8        j9        ej8        j:        z  Z;eed<   e0e;z  dz  Z<eed<    ede;          Z=	 d dl>m9Z9 n# e?$ r  G d d          Z9Y nw xY wdKdZ@dLd ZAe1d!dfd"ZBd# ZCd$e.d%e1fd&ZDd'ZEddd(d)d*ZFd+ ZG	 	 	 dMd,ZHdNd-ZI ed.g d/          ZJd0 ZK G d1 d2          ZL G d3 d4          ZM	 	 dOd6ZNedPd8            ZOd9 ZPdQd:ZQd; ZRdRd<ZSdSddd>d?ZTdNd@ZUdA ZVddBdCZWdD ZXdE ZY G dF dGeZ          Z[dLdHZ\dI Z]dTdJZ^dS )U    N)contextmanager)
namedtuple)	TypeAliasTypeVar)array_namespaceis_numpyxp_size)FunctionDoc	Parameter	AxisErrorComplexWarningVisibleDeprecationWarningz1.25.0)r   r   r   DTypePromotionError)r   r   r   np_longnp_ulongz
2.0.0.dev0ignorez/.*In the future `np\.long` will be defined as.*copy_if_neededz2.0.0z1.28.0F   copy_RNGSeedTypeGeneratorType)bound)	Generatorc                       e Zd ZdS )r   N)__name__
__module____qualname__     P/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/_lib/_util.pyr   r   P   s        r!   r   c                 p    t           g|R  }||cxu rn ||t          d           |j         g|R  }|                    dg          j        }|                    |d         |d          |dd         c }|                     | fd|D                        }|t          |          t          t          t          t          hv r8t          j        d	
          5  ||z  j        }	ddd           n# 1 swxY w Y   n|                    |j        |          }	|                     j        |	|                    ||	                    }
n^  |                     |fd|D                        }|                    ||          }	|                     j        |	          }
||
<   ||
 <   |
S )a  Return elements chosen from two possibilities depending on a condition

    Equivalent to ``f(*arrays) if cond else fillvalue`` performed elementwise.

    Parameters
    ----------
    cond : array
        The condition (expressed as a boolean array).
    arrays : tuple of array
        Arguments to `f` (and `f2`). Must be broadcastable with `cond`.
    f : callable
        Where `cond` is True, output will be ``f(arr1[cond], arr2[cond], ...)``
    fillvalue : object
        If provided, value with which to fill output array where `cond` is
        not True.
    f2 : callable
        If provided, output will be ``f2(arr1[cond], arr2[cond], ...)`` where
        `cond` is not True.

    Returns
    -------
    out : array
        An array with elements from the output of `f` where `cond` is True
        and `fillvalue` (or elements from the output of `f2`) elsewhere. The
        returned array has data type determined by Type Promotion Rules
        with the output of `f` and `fillvalue` (or the output of `f2`).

    Notes
    -----
    ``xp.where(cond, x, fillvalue)`` requires explicitly forming `x` even where
    `cond` is False. This function evaluates ``f(arr1[cond], arr2[cond], ...)``
    onle where `cond` ``is True.

    Examples
    --------
    >>> import numpy as np
    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
    >>> def f(a, b):
    ...     return a*b
    >>> _lazywhere(a > 2, (a, b), f, np.nan)
    array([ nan,  nan,  21.,  32.])

    Nz1Exactly one of `fillvalue` or `f2` must be given.Tr   Fr   r   c              3   (   K   | ]}|         V  d S Nr    .0arrconds     r"   	<genexpr>z_lazywhere.<locals>.<genexpr>   s'      773t9777777r!   r   )invaliddtype)r-   
fill_valuec              3   (   K   | ]}|         V  d S r%   r    )r'   r(   nconds     r"   r*   z_lazywhere.<locals>.<genexpr>   s'      ==sE
======r!   )r   
ValueErrorbroadcast_arraysasarrayr-   astypetypeboolintfloatcomplexnperrstateresult_typefullshapeempty)r)   arraysf	fillvaluef2xpargs
bool_dtypetemp1r-   outtemp2r0   s   `           @r"   
_lazywhererJ   T   s.   X 
	'	'	'	'B
iR^	8MLMMM2t-f---DTF##)J99T!Wju9==tABBxLD&JJqq7777777899E	z
 	??tS%999X... 2 2*12 2 2 2 2 2 2 2 2 2 2 2 2 2 2 >>%+y995ggdj!#IU!C!C  E E 

22====f===>??ue,,hhtzh//E
CIJs   "C99C= C=c                   	 t          j        | }t          j        d |D                       }t          j        t          j        |d                   ||          }t          ||           D ]n\  }	t          j        	du           rt          j        	|d                   \  	}t          	fd|D                       }t          j        |	 ||            o|S )aZ  
    Mimic `np.select(condlist, choicelist)`.

    Notice, it assumes that all `arrays` are of the same shape or can be
    broadcasted together.

    All functions in `choicelist` must accept array arguments in the order
    given in `arrays` and must return an array of the same shape as broadcasted
    `arrays`.

    Examples
    --------
    >>> import numpy as np
    >>> x = np.arange(6)
    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
    array([  0,   1,   4,   0,  64, 125])

    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
    array([   0.,    1.,    4.,   0.,   64.,  125.])

    >>> a = -np.ones_like(x)
    >>> _lazyselect([x < 3, x > 3],
    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
    ...             (x, a), default=np.nan)
    array([   0.,    1.,    4.,   nan,  -64., -125.])

    c                 &    g | ]}|j         j        S r    )r-   char)r'   as     r"   
<listcomp>z_lazyselect.<locals>.<listcomp>   s    999QAGL999r!   r   r.   r-   Fc              3   B   K   | ]}t          j        |          V  d S r%   )r:   extractr&   s     r"   r*   z_lazyselect.<locals>.<genexpr>   s/      ==sRZc**======r!   )	r:   r2   mintypecoder=   r>   zipalltupleplace)
condlist
choicelistr@   defaulttcoderH   func_tempr)   s
            @r"   _lazyselectr_      s    8  &)FN99&999::E
'"(6!9%%'
G
G
GC*h// ) )
d6$%-   	%dF1I66a====f=====
dDD$K((((Jr!   Cc                    t          j        |          }||j        }t          | d          s| f} t	          j        t          j        |           |j        z  }t          j	        ||z   dz   t           j
                  }|j        d         d         |z  }|dk    r||z
  }||||z   dz            dd         }t          j        | |||          }|                    d           |S )zAllocate a new ndarray with aligned memory.

    Primary use case for this currently is working around a f2py issue
    in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
    not necessarily create arrays aligned up to it.

    N__len__r   datar   )order)r:   r-   	alignmenthasattr	functoolsreduceoperatormulitemsizer?   uint8__array_interface__ndarrayfill)r>   r-   re   alignsizebufoffsetrc   s           r"   _aligned_zerosru      s     HUOOE}5)$$ HL%005>AD
(4%<!#RX
.
.C$V,Q/%7F{{ fVD[]"
#CRC
(C:eUCu555DIIaLLLKr!   c                 l    | j         ,| j        | j         j        dz  k     r|                                 S | S )zReturn an array equivalent to the input array. If the input
    array is a view of a much larger array, copy its contents to a
    newly allocated array. Otherwise, return the input unchanged.
    N   )baserr   r   )arrays    r"   _prune_arrayrz      s4    
 z%*uz!/C"C"Czz||Lr!   nreturnc                 h    | dk     r!t          t          j        |                     nt          j        S )zlCompute the factorial and return as a float

    Returns infinity when result is too large for a double
       )r8   math	factorialr:   inf)r{   s    r"   float_factorialr      s+    
 ()3ww5""###BF:r!   a^  If `rng` is passed by keyword, types other than `numpy.random.Generator` are
    passed to `numpy.random.default_rng` to instantiate a ``Generator``.
    If `rng` is already a ``Generator`` instance, then the provided instance is
    used. Specify `rng` for repeatable function behavior.

    If this argument is passed by position or `{old_name}` is passed by keyword,
    legacy behavior for the argument `{old_name}` applies:

    - If `{old_name}` is None (or `numpy.random`), the `numpy.random.RandomState`
      singleton is used.
    - If `{old_name}` is an int, a new ``RandomState`` instance is used,
      seeded with `{old_name}`.
    - If `{old_name}` is already a ``Generator`` or ``RandomState`` instance then
      that instance is used.

    .. versionchanged:: 1.15.0
        As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
        transition from use of `numpy.random.RandomState` to
        `numpy.random.Generator`, this keyword was changed from `{old_name}` to `rng`.
        For an interim period, both keywords will continue to work, although only one
        may be specified at a time. After the interim period, function calls using the
        `{old_name}` keyword will emit warnings. The behavior of both `{old_name}` and
        `rng` are outlined above, but only the `rng` keyword should be used in new code.
        T)position_numend_versionreplace_docc          	      H     dd d d d  d	 fd}|S )ay  Example decorator to transition from old PRNG usage to new `rng` behavior

    Suppose the decorator is applied to a function that used to accept parameter
    `old_name='random_state'` either by keyword or as a positional argument at
    `position_num=1`. At the time of application, the name of the argument in the
    function signature is manually changed to the new name, `rng`. If positional
    use was allowed before, this is not changed.*

    - If the function is called with both `random_state` and `rng`, the decorator
      raises an error.
    - If `random_state` is provided as a keyword argument, the decorator passes
      `random_state` to the function's `rng` argument as a keyword. If `end_version`
      is specified, the decorator will emit a `DeprecationWarning` about the
      deprecation of keyword `random_state`.
    - If `random_state` is provided as a positional argument, the decorator passes
      `random_state` to the function's `rng` argument by position. If `end_version`
      is specified, the decorator will emit a `FutureWarning` about the changing
      interpretation of the argument.
    - If `rng` is provided as a keyword argument, the decorator validates `rng` using
      `numpy.random.default_rng` before passing it to the function.
    - If `end_version` is specified and neither `random_state` nor `rng` is provided
      by the user, the decorator checks whether `np.random.seed` has been used to set
      the global seed. If so, it emits a `FutureWarning`, noting that usage of
      `numpy.random.seed` will eventually have no effect. Either way, the decorator
      calls the function without explicitly passing the `rng` argument.

    If `end_version` is specified, a user must pass `rng` as a keyword to avoid
    warnings.

    After the deprecation period, the decorator can be removed, and the function
    can simply validate the `rng` argument by calling `np.random.default_rng(rng)`.

    * A `FutureWarning` is emitted when the PRNG argument is used by
      position. It indicates that the "Hinsen principle" (same
      code yielding different results in two versions of the software)
      will be violated, unless positional use is deprecated. Specifically:

      - If `None` is passed by position and `np.random.seed` has been used,
        the function will change from being seeded to being unseeded.
      - If an integer is passed by position, the random stream will change.
      - If `np.random` or an instance of `RandomState` is passed by position,
        an error will be raised.

      We suggest that projects consider deprecating positional use of
      `random_state`/`rng` (i.e., change their function signatures to
      ``def my_func(..., *, rng=None)``); that might not make sense
      for all projects, so this SPEC does not make that
      recommendation, neither does this decorator enforce it.

    Parameters
    ----------
    old_name : str
        The old name of the PRNG argument (e.g. `seed` or `random_state`).
    position_num : int, optional
        The (0-indexed) position of the old PRNG argument (if accepted by position).
        Maintainers are welcome to eliminate this argument and use, for example,
        `inspect`, if preferred.
    end_version : str, optional
        The full version number of the library when the behavior described in
        `DeprecationWarning`s and `FutureWarning`s will take effect. If left
        unspecified, no warnings will be emitted by the decorator.
    replace_doc : bool, default: True
        Whether the decorator should replace the documentation for parameter `rng` with
        `_rng_desc` (defined above), which documents both new `rng` keyword behavior
        and typical legacy `random_state`/`seed` behavior. If True, manually replace
        the first paragraph of the function's old `random_state`/`seed` documentation
        with the desired *final* `rng` documentation; this way, no changes to
        documentation are needed when the decorator is removed. Documentation of `rng`
        after the first blank line is preserved. Use False if the function's old
        `random_state`/`seed` behavior does not match that described by `_rng_desc`.

    rngz@To silence this warning and ensure consistent behavior in SciPy z", control the RNG using argument `z `. Arguments passed to keyword `z` will be validated by `np.random.default_rng`, so the behavior corresponding with a given value may change compared to use of `a+  `. For example, 1) `None` will result in unpredictable random numbers, 2) an integer will result in a different stream of random numbers, (with the same distribution), and 3) `np.random` or `RandomState` instances will result in an error. See the documentation of `default_rng` for more information.c                 X    t          j                   
 fd            }r t          |          }d |d         D             }d|v rd}t                              d          }|d         |                    d                   j        }d|v r ||                    d          dz   d          ng }|g|z   }t          d||          }	|	|d         |                    d          <   t          |          	                    d	d          d         }t          |          |_
        |S )
Nc            	         |v }
|v }d uot          |           dz   k    }d u}t          |          t          |          z   t          |          z   dk    r"j         d
 d
 d d}t          |          t          j        j        j        j        j	        d u }|rI|
                              |
<   |r.d d
 d d	 d
	z   }t          j        |t          d           n|r}|          }t          j        j        t          j        j        t          j        j        f}	||rt#          ||	          rn|r+d
 d d dz   }t          j        |t$          d           nT|r)t          j                            |
                   |
<   n)|r'|r%d dz   }t          j        |t$          d            | i |S )Nr   2() got multiple values for argument now known as `z`. Specify one of `z` or `z`.Use of keyword argument `!` is deprecated and replaced by ``.  Support for `` will be removed in SciPy z. rw   
stacklevelzPositional use of `z` (formerly known as `z`) is still allowed, but the behavior is changing: the argument will be normalized using `np.random.default_rng` beginning in SciPy zH, and the resulting `Generator` will be used to generate random numbers.zJThe NumPy global RNG was seeded by calling `np.random.seed`. Beginning in z2, this function will no longer use the global RNG.)lenr7   r   	TypeErrorr:   randommtrand_rand_bit_generator	_seed_seqpopwarningswarnDeprecationWarningr   SeedSequenceBitGenerator
isinstanceFutureWarningdefault_rng)rE   kwargsas_old_kwargas_new_kwarg
as_pos_argemit_warningmessageglobal_seed_setarg
ok_classesNEW_NAMEcmn_msgr   funold_namer   s             r"   wrapperz6_transition_to_rng.<locals>.decorator.<locals>.wrappern  s    $v-L#v-L%T1Sc$ii<RSCS6SJ&d2L <  3|#4#44s:FJJ| 5 5.65 5 5 5(05 5 5 
  ((( !i.4CMQUUO 4D#)::h#7#7x  M4H 4 47?4 4(04 4 %04 4 4   G M'+=!LLLL )D <(
 I'I*I*

 KKJsJ<W<WK! 	H*h * *$* * GR* * *   G M'=QGGGG D $&9#8#89I#J#Jx    D\ DB6AB B B 	
 g}CCCC3''''r!   c                     g | ]	}|j         
S r    )name)r'   params     r"   rO   z9_transition_to_rng.<locals>.decorator.<locals>.<listcomp>  s    IIIeuzIIIr!   
Parametersr   z/{None, int, `numpy.random.Generator`}, optionalz
{old_name} r   
)rh   wrapsr
   	_rng_descreplaceindexdescr   strsplit__doc__)r   r   docparameter_names_type_descold_docold_doc_keepnew_doc_rng_parameter_docr   r   r   r   r   r   s   `         r"   	decoratorz%_transition_to_rng.<locals>.decoratorm  sd   			I	( I	( I	( I	( I	( I	( I	( I	( I	( 
	I	(V  	+g&&CIIs<7HIIIO''I!)),AAl+O,A,A%,H,HINBD--ww}}R'8'81'<'='=>>UW 'L0%.ueW%E%E"BTL!/"7"7">">?#hhnnT1--a0"%c((r!   r    )r   r   r   r   r   r   r   s   ```` @@r"   _transition_to_rngr     s    T H		G		G 		G:B		G 		G		G 		G 			G 		G 		G Z Z Z Z Z Z Z Z Z Zx r!   c                 f   | | t           j        u rt           j        j        j        S t	          | t
          j        t           j        z            rt           j                            |           S t	          | t           j        j        t           j        j	        z            r| S t          d|  d          )a`  Turn `seed` into a `np.random.RandomState` instance.

    Parameters
    ----------
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Returns
    -------
    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
        Random number generator.

    N'z<' cannot be used to seed a numpy.random.RandomState instance)r:   r   r   r   r   numbersIntegralintegerRandomStater   r1   )seeds    r"   check_random_stater     s    & |try((y%%$(2:566 +y$$T***$	-	0CCDD 
 ! ! ! ! " " "r!   c                    |s/ddl }|j                            |           rd}t          |          |s.t          j                            |           rt          d          |rt          j        nt          j        } ||           } |s*| j	        t	          j	        d          u rt          d          |r;t	          j
        | j	        t          j                  s || t          j                  } | S )aA  
    Helper function for SciPy argument validation.

    Many SciPy linear algebra functions do support arbitrary array-like
    input arguments. Examples of commonly unsupported inputs include
    matrices containing inf/nan, sparse matrix representations, and
    matrices with complicated elements.

    Parameters
    ----------
    a : array_like
        The array-like input.
    check_finite : bool, optional
        Whether to check that the input matrices contain only finite numbers.
        Disabling may give a performance gain, but may result in problems
        (crashes, non-termination) if the inputs do contain infinities or NaNs.
        Default: True
    sparse_ok : bool, optional
        True if scipy sparse matrices are allowed.
    objects_ok : bool, optional
        True if arrays with dype('O') are allowed.
    mask_ok : bool, optional
        True if masked arrays are allowed.
    as_inexact : bool, optional
        True to convert the input array to a np.inexact dtype.

    Returns
    -------
    ret : ndarray
        The converted validated array.

    r   NzSparse arrays/matrices are not supported by this function. Perhaps one of the `scipy.sparse.linalg` functions would work instead.zmasked arrays are not supportedOzobject arrays are not supportedr,   )scipy.sparsesparseissparser1   r:   maisMaskedArrayasarray_chkfiniter3   r-   
issubdtypeinexactfloat64)	rN   check_finite	sparse_ok
objects_okmask_ok
as_inexactscipymsgtoarrays	            r"   _asarray_validatedr     s    F  "<  ## 	")C S//! @5q!! 	@>???&2Bb""
G

A @7bhsmm##>??? -}QWbj11 	-,,,AHr!   c                     	 t          j        |           } n!# t          $ r t          | d          dw xY w|| |k     rt          | d|           d| S )a  
    Validate a scalar integer.

    This function can be used to validate an argument to a function
    that expects the value to be an integer.  It uses `operator.index`
    to validate the value (so, for example, k=2.0 results in a
    TypeError).

    Parameters
    ----------
    k : int
        The value to be validated.
    name : str
        The name of the parameter.
    minimum : int, optional
        An optional lower bound.
    z must be an integer.Nz" must be an integer not less than )rj   r   r   r1   )kr   minimums      r"   _validate_intr   #  s    $AN1 A A A455566D@Aq7{{D + +!(+ + , ,15	6Hs    5FullArgSpec)rE   varargsvarkwdefaults
kwonlyargskwonlydefaultsannotationsc           	         t          j        |           }d |j                                        D             }d |j                                        D             }|r|d         nd}d |j                                        D             }|r|d         nd}t	          d |j                                        D                       pd}d |j                                        D             }d |j                                        D             }d	 |j                                        D             }t          ||||||pd|          S )
as  inspect.getfullargspec replacement using inspect.signature.

    If func is a bound method, do not list the 'self' parameter.

    Parameters
    ----------
    func : callable
        A callable to inspect

    Returns
    -------
    fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
                              kwonlydefaults, annotations)

        NOTE: if the first argument of `func` is self, it is *not*, I repeat
        *not*, included in fullargspec.args.
        This is done for consistency between inspect.getargspec() under
        Python 2.x, and inspect.signature() under Python 3.x.

    c                 n    g | ]2}|j         t          j        j        t          j        j        fv +|j        3S r    )kindinspectr   POSITIONAL_OR_KEYWORDPOSITIONAL_ONLYr   r'   ps     r"   rO   z*getfullargspec_no_self.<locals>.<listcomp>g  sO       6g'='79 9 9 	
9 9 9r!   c                 P    g | ]#}|j         t          j        j        k    |j        $S r    )r   r   r   VAR_POSITIONALr   r   s     r"   rO   z*getfullargspec_no_self.<locals>.<listcomp>l  s7       6W&555 	
555r!   r   Nc                 P    g | ]#}|j         t          j        j        k    |j        $S r    )r   r   r   VAR_KEYWORDr   r   s     r"   rO   z*getfullargspec_no_self.<locals>.<listcomp>q  s7       6W&222 	
222r!   c              3   t   K   | ]3}|j         t          j        j        k    r|j        |j        u*|j        V  4d S r%   )r   r   r   r   rZ   r?   r   s     r"   r*   z)getfullargspec_no_self.<locals>.<genexpr>v  sR        Fg'===IQW$$ 	
	$$$$ r!   c                 P    g | ]#}|j         t          j        j        k    |j        $S r    )r   r   r   KEYWORD_ONLYr   r   s     r"   rO   z*getfullargspec_no_self.<locals>.<listcomp>{  s7       6W&333 	
333r!   c                 x    i | ]7}|j         t          j        j        k    r|j        |j        u*|j        |j        8S r    )r   r   r   r   rZ   r?   r   r   s     r"   
<dictcomp>z*getfullargspec_no_self.<locals>.<dictcomp>  sI     , , ,Vw0===)17** &!)***r!   c                 D    i | ]}|j         |j        u|j        |j         S r    )
annotationr?   r   r   s     r"   r   z*getfullargspec_no_self.<locals>.<dictcomp>  s6     3 3 3Al!'11 61<111r!   )r   	signature
parametersvaluesrV   r   )	r\   sigrE   r   r   r   r   
kwdefaultsr   s	            r"   getfullargspec_no_selfr  Q  s   * 
D
!
!C --//  D
 --//  G $-gajjG --//  E 'E!HH4E  >0022      
	 
 --//  J, ,S^-B-B-D-D , , ,J3 31F1F1H1H 3 3 3KtWeXz!)T;8 8 8r!   c                       e Zd ZdZd Zd ZdS )_FunctionWrapperz?
    Object to wrap user's function, allowing picklability
    c                 *    || _         |g n|| _        d S r%   rA   rE   )selfrA   rE   s      r"   __init__z_FunctionWrapper.__init__  s    ,BBD			r!   c                 (     | j         |g| j        R  S r%   r
  )r  xs     r"   __call__z_FunctionWrapper.__call__  s    tva$$)$$$$r!   N)r   r   r   r   r  r  r    r!   r"   r  r    s<         1 1 1% % % % %r!   r  c                   >    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
S )
MapWrapperav  
    Parallelisation wrapper for working with map-like callables, such as
    `multiprocessing.Pool.map`.

    Parameters
    ----------
    pool : int or map-like callable
        If `pool` is an integer, then it specifies the number of threads to
        use for parallelization. If ``int(pool) == 1``, then no parallel
        processing is used and the map builtin is used.
        If ``pool == -1``, then the pool will utilize all available CPUs.
        If `pool` is a map-like callable that follows the same
        calling sequence as the built-in map function, then this callable is
        used for parallelization.
    r   c                    d | _         t          | _        d| _        t	          |          r|| _         | j         | _        d S ddlm} t          |          dk    r) |            | _         | j         j        | _        d| _        d S t          |          dk    rd S t          |          dk    r8 |t          |                    | _         | j         j        | _        d| _        d S t          d          )	NFr   )Poolrd   Tr   )	processeszUNumber of workers specified must be -1, an int >= 1, or an object with a 'map' method)	poolmap_mapfunc	_own_poolcallablemultiprocessingr  r7   RuntimeError)r  r  r  s      r"   r  zMapWrapper.__init__  s    	D>> 	-DI IDMMM,,,,,,4yyB DFF	 $	!%TaTQ D3t99555	 $	!%" $, - - -r!   c                     | S r%   r    r  s    r"   	__enter__zMapWrapper.__enter__  s    r!   c                 J    | j         r| j                                         d S d S r%   )r  r  	terminater  s    r"   r   zMapWrapper.terminate  s0    > 	"I!!!!!	" 	"r!   c                 J    | j         r| j                                         d S d S r%   )r  r  joinr  s    r"   r"  zMapWrapper.join  s.    > 	INN	 	r!   c                 J    | j         r| j                                         d S d S r%   )r  r  closer  s    r"   r$  zMapWrapper.close  s.    > 	IOO	 	r!   c                 |    | j         r4| j                                         | j                                         d S d S r%   )r  r  r$  r   )r  exc_type	exc_value	tracebacks       r"   __exit__zMapWrapper.__exit__  sB    > 	"IOOI!!!!!	" 	"r!   c                 t    	 |                      ||          S # t          $ r}t          d          |d }~ww xY w)Nz;The map-like callable must be of the form f(func, iterable))r  r   )r  r\   iterablees       r"   r  zMapWrapper.__call__  sT    	>==x000 	> 	> 	> 6 7 7<=>	>s    
727Nr   )r   r   r   r   r  r  r   r"  r$  r)  r  r    r!   r"   r  r    s         - - - -8  " " "    " " "
> > > > >r!   r  int64c                 <   t          | t                    r|                     |||||          S | t          j        j        j        } |r;||                     |dz   ||          S ||                     ||dz   ||          S |                     ||||          S )al  
    Return random integers from low (inclusive) to high (exclusive), or if
    endpoint=True, low (inclusive) to high (inclusive). Replaces
    `RandomState.randint` (with endpoint=False) and
    `RandomState.random_integers` (with endpoint=True).

    Return random integers from the "discrete uniform" distribution of the
    specified dtype. If high is None (the default), then results are from
    0 to low.

    Parameters
    ----------
    gen : {None, np.random.RandomState, np.random.Generator}
        Random number generator. If None, then the np.random.RandomState
        singleton is used.
    low : int or array-like of ints
        Lowest (signed) integers to be drawn from the distribution (unless
        high=None, in which case this parameter is 0 and this value is used
        for high).
    high : int or array-like of ints
        If provided, one above the largest (signed) integer to be drawn from
        the distribution (see above for behavior if high=None). If array-like,
        must contain integer values.
    size : array-like of ints, optional
        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
        samples are drawn. Default is None, in which case a single value is
        returned.
    dtype : {str, dtype}, optional
        Desired dtype of the result. All dtypes are determined by their name,
        i.e., 'int64', 'int', etc, so byteorder is not available and a specific
        precision may have different C types depending on the platform.
        The default value is 'int64'.
    endpoint : bool, optional
        If True, sample from the interval [low, high] instead of the default
        [low, high) Defaults to False.

    Returns
    -------
    out: int or ndarray of ints
        size-shaped array of random integers from the appropriate distribution,
        or a single such random int if size not provided.
    )highrr   r-   endpointNr   )rr   r-   )r0  rr   r-   )r   r   integersr:   r   r   r   randint)genlowr0  rr   r-   r1  s         r"   rng_integersr6    s    X #y!! C||CdU%-  / / 	/ ;)"(C 	O |{{37U{CCC{{3TAXD{NNN {{3TE{BBBr!   	   !E^1cuBn c              #      K   t           j        j        | ffd	t           j        _        	 dV  t           j        _        dS # t           j        _        w xY w)z0Context with a fixed np.random.default_rng seed.c                      |           S r%   r    r   orig_funs    r"   <lambda>z$_fixed_default_rng.<locals>.<lambda>"  s    hhtnn r!   N)r:   r   r   r:  s    @r"   _fixed_default_rngr=    s`       y$H(,<<<<<BI) (		((((s   A Ac                 T     t          j        dt           j                   fd}|S )a&  Rewrite the HTML rendering of ``np.random.default_rng``.

    This is intended to decorate
    ``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.

    Examples are only run by Sphinx when there are plot involved. Even so,
    it does not change the result values getting printed.
    z*np.random.default_rng\((0x[0-9A-F]+|\d+)\)c                  4     | i |}fd|D             }|S )Nc                 <    g | ]}t          j        d |          S )znp.random.default_rng())resub)r'   linepatterns     r"   rO   z7_rng_html_rewrite.<locals>._wrapped.<locals>.<listcomp>7  s8     
 
 
 F75t<<
 
 
r!   r    )rE   r   reslinesr\   rD  s       r"   _wrappedz#_rng_html_rewrite.<locals>._wrapped5  sF    dD#F##
 
 
 

 
 
 r!   )rA  compileI)r\   rG  rD  s   ` @r"   _rng_html_rewriterJ  )  s?     jFMMG      Or!   c                 f    t          j        | |          }|r|t          j        ||          }|S )z
    argmin with a `keepdims` parameter.

    See https://github.com/numpy/numpy/issues/8710

    If axis is not None, a.shape[axis] must be greater than 0.
    axis)r:   argminexpand_dims)rN   keepdimsrM  rE  s       r"   _argminrQ  @  s>     )AD
!
!
!C -D$nSt,,,Jr!   c                 x    t          t          j        |           |d          }t          j        | ||          S )a  
    Return the first non-nan value along the given axis.

    If a slice is all nan, nan is returned for that slice.

    The shape of the return value corresponds to ``keepdims=True``.

    Examples
    --------
    >>> import numpy as np
    >>> nan = np.nan
    >>> a = np.array([[ 3.,  3., nan,  3.],
                      [ 1., nan,  2.,  4.],
                      [nan, nan,  9., -1.],
                      [nan,  5.,  4.,  3.],
                      [ 2.,  2.,  2.,  2.],
                      [nan, nan, nan, nan]])
    >>> _first_nonnan(a, axis=0)
    array([[3., 3., 2., 3.]])
    >>> _first_nonnan(a, axis=1)
    array([[ 3.],
           [ 1.],
           [ 9.],
           [ 5.],
           [ 2.],
           [nan]])
    TrM  rP  rL  )rQ  r:   isnantake_along_axis)rN   rM  r   s      r"   _first_nonnanrV  N  s8    8 	$666Aa....r!   c                 j   |$| j         dk    rdS |                                 } d}nM| j        }||         dk    r:|d|         d|z  z   ||dz   d         z   }t          j        |dt
                    S t          | |          }|| k    t          j        |           z                      ||          S )	a  
    Determine if the values along an axis are all the same.

    nan values are ignored.

    `a` must be a numpy array.

    `axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.

    For an axis of length 0, the result is True.  That is, we adopt the
    convention that ``allsame([])`` is True. (There are no values in the
    input that are different.)

    `True` is returned for slices that are all nan--not because all the
    values are the same, but because this is equivalent to ``allsame([])``.

    Examples
    --------
    >>> from numpy import nan, array
    >>> a = array([[ 3.,  3., nan,  3.],
    ...            [ 1., nan,  2.,  4.],
    ...            [nan, nan,  9., -1.],
    ...            [nan,  5.,  4.,  3.],
    ...            [ 2.,  2.,  2.,  2.],
    ...            [nan, nan, nan, nan]])
    >>> _nan_allsame(a, axis=1, keepdims=True)
    array([[ True],
           [False],
           [False],
           [False],
           [ True],
           [ True]])
    Nr   Tr-  r   rP   rL  rS  )	rr   ravelr>   r:   r=   r6   rV  rT  rU   )rN   rM  rP  shpa0s        r"   _nan_allsamer[  n  s    D |6Q;;4GGIIgt9>>ete*tH},s4!899~=C734t<<<<	qt	$	$	$B1W#((dX(FFFr!   	propagate)xp_omit_okayrD   c                   |t          |           }t          |           }|h d}||vr t          dt          |           d          t	          |           dk    rd}nf|                    | j        d          r*|                    |                    |                     }n!|                    | j        d          rx|                    |                    |	                    |                               |                    |                    |
                    |                               z  }nt          |          r}t          j        | j        t                    r^d}|                                 D ]F}t          j        t          |          t          j                  rt          j        |          rd} nGnd}|r|d	k    rt          d
          |s|r|r|dk    rd}t          |          ||fS )N>   omitraiser\  znan_policy must be one of .r   Fzreal floatingzcomplex floatingTr`  zThe input contains nan valuesr_  z9`nan_policy='omit' is incompatible with non-NumPy arrays.)r   r   r1   setr	   isdtyper-   rT  maxrealimagr:   r   objectrX  r5   number)	rN   
nan_policypoliciesr]  rD   	not_numpycontains_nanelr   s	            r"   _contains_nanrn    s    
zQRLL I111!!Fc(mmFFFGGGqzzQ	AG_	-	-  xxq		**	AG/	0	0  xxrwwqzz 2 233bhhrvvbggajj?Q?Q6R6RR	" 	"-88 	'')) 	 	B}T"XXry11 bhrll #  :
g--8999 "I ", ":v;M;MM!!!##r!   c                       fd}|S )a  
    Generate decorator for backward-compatible keyword renaming.

    Apply the decorator generated by `_rename_parameter` to functions with a
    recently renamed parameter to maintain backward-compatibility.

    After decoration, the function behaves as follows:
    If only the new parameter is passed into the function, behave as usual.
    If only the old parameter is passed into the function (as a keyword), raise
    a DeprecationWarning if `dep_version` is provided, and behave as usual
    otherwise.
    If both old and new parameters are passed into the function, raise a
    DeprecationWarning if `dep_version` is provided, and raise the appropriate
    TypeError (function got multiple values for argument).

    Parameters
    ----------
    old_name : str
        Old name of parameter
    new_name : str
        New name of parameter
    dep_version : str, optional
        Version of SciPy in which old parameter was deprecated in the format
        'X.Y.Z'. If supplied, the deprecation message will indicate that
        support for the old parameter will be removed in version 'X.Y+2.Z'

    Notes
    -----
    Untested with functions that accept *args. Probably won't work as written.

    c                 N     t          j                    fd            }|S )Nc            	         |v rr}                     d          }t          t          |d                   dz             |d<   d                    |          }d d d d| d	}t	          j        |t          d           |v rj         d	 d
}t          |          |	                              |<    | i |S )Nra  r   rw   r   r   r   r   r   r   `)
r   r   r7   r"  r   r   r   r   r   r   )rE   r   r   r   dep_versionr   new_namer   s       r"   r   z5_rename_parameter.<locals>.decorator.<locals>.wrapper  s$   6!! M"-"3"3C"8"8K%([^)<)<q)@%A%AKN"%((;"7"7K :8  :  :>F :  :/7 :  : ,7 :  :  :G M'+=!LLLLv%%"%,  E  E9A E  E  EG#G,,,#)::h#7#7x 3''''r!   )rh   r   )r   r   rs  rt  r   s   ` r"   r   z$_rename_parameter.<locals>.decorator  sH    				( 	( 	( 	( 	( 	( 	( 
		(" r!   r    )r   rt  rs  r   s   ``` r"   _rename_parameterru    s1    @      ( r!   c                 f    | j         j        }fd|                    |          D             }|S )Nc                 z    g | ]7}t           j                             t                    |                    8S r    )r:   r   r   r5   )r'   child_ssbgs     r"   rO   z_rng_spawn.<locals>.<listcomp>  sI     8 8 8 )%%hd2hhx&8&899 8 8 8r!   )r   r   spawn)r   
n_childrenss
child_rngsry  s       @r"   
_rng_spawnr~    sL    		B	B8 8 8 8"$((:"6"68 8 8Jr!   )rD   c                       	t          | n   fd|D             }	 t           d j                  }  j        g ||R  }n# t          $ r
  j        }Y nw xY w                      j        |          d         S )Nc                 :    g | ]}                     |          S r    )r3   )r'   itemrD   s     r"   rO   z_get_nan.<locals>.<listcomp>  s%    ...BJJt...r!   float16r,   r    )r   getattrfloat32r<   r   r   r3   nan)rD   rc   	min_floatr-   s   `   r"   _get_nanr    s    #%:$		2B.......DB	2:66	00i000   
 ::bfE:**2..s   %A AAc                 d    | | k     s| |k    rd|  d| }t          |          | dk     r| |z   } | S )Nzaxis z) is out of bounds for array of dimension r   )r   )rM  ndimr   s      r"   normalize_axis_indexr    sM    te||tt||KdKKTKKnnaxxd{Kr!   c                 V    | dS 	  | |           dS # t           $ r d| _        Y dS w xY w)aY  Call wrapped callback; return True if algorithm should stop.

    Parameters
    ----------
    callback : callable or None
        A user-provided callback wrapped with `_wrap_callback`
    res : OptimizeResult
        Information about the current iterate

    Returns
    -------
    halt : bool
        True if minimization should stop

    NFT)StopIterationstop_iteration)callbackrE  s     r"   _call_callback_maybe_haltr  %  sP      uu   "&tts    ((c                   @    e Zd ZdZd Zej        Zej        Z	d Z
d ZdS )_RichResultz5 Container for multiple outputs with pretty-printing c                 X    	 | |         S # t           $ r}t          |          |d }~ww xY wr%   )KeyErrorAttributeError)r  r   r,  s      r"   __getattr__z_RichResult.__getattr__A  s@    	.: 	. 	. 	. &&A-	.s   
 
)$)c                     g dt          | d          h dfdfdfd}|                                 rt          | |          S | j        j        dz   S )	N)r   successstatusr   funlr  xlcol_indnitloweruppereqlinineqlin	convergedflagfunction_calls
iterationsroot_order_keys>   conslackr  crossover_nitc                     	                      | d                                                   S # t          $ r t          j        cY S w xY wNr   )r   r  r1   r:   r   )r  
order_keyss    r"   keyz!_RichResult.__repr__.<locals>.keyT  sN    !''Q888   vs   ,0 A	A	c              3   4   K   | D ]}|d         v r|V  d S r  r    )itemsr  	omit_keyss     r"   omit_redundantz,_RichResult.__repr__.<locals>.omit_redundantZ  s=        7i''



 r!   c                 \    t           |                                                     S )N)r  )sortedr  )dr  r  s    r"   item_sorterz)_RichResult.__repr__.<locals>.item_sorter`  s(    ..33====r!   )sorterz())r  keys_dict_formatter	__class__r   )r  r  r  r  r  r  s     @@@@r"   __repr__z_RichResult.__repr__J  s      
 T=*==
 EDD		 	 	 	 		 	 	 	 		> 	> 	> 	> 	> 	> 99;; 	2"4<<<<>*T11r!   c                 D    t          |                                           S r%   )listr  r  s    r"   __dir__z_RichResult.__dir__h  s    DIIKK   r!   N)r   r   r   r   r  dict__setitem____setattr____delitem____delattr__r  r  r    r!   r"   r  r  ?  sY        ??. . . "K"K2 2 2<! ! ! ! !r!   r  c                 f    |                      d          }d|z  }d|z                       |          S )zQ
    Ensures that lines after the first are indented by the specified amount
    r    )r   r"  )sr{   r   indents       r"   	_indenterr  l  s4     GGDMMEUF6M&&&r!   c                     t          j        |           rdS t          j        |           rdS t          j        |           rdS t          j        | ddd          S )zP
    Returns a string representation of a float with exactly ten characters
    z
       infz
      -infz
       nan   rw   F)	precisionpad_leftunique)r:   isposinfisneginfrT  format_float_scientific)r  s    r"   _float_formatter_10r  u  s]     
{1~~ |	Q |	! |%a1qOOOOr!   c           	         t          | t                    rqt          t          t          t          |                                                               |z   d                    fd |           D                       }nIt          j	        dz
  dddt          i          5  t          |           }ddd           n# 1 swxY w Y   |S )	z
    Pretty printer for dictionaries

    `n` keeps track of the starting indentation;
    lines are indented by this much after a line break.
    `mplus` is additional left padding applied to keys
    r   c                     g | ]G\  }}|                               d z   t          t          |z   dz   d          dz             z   HS )z: rw   r   )rjustr  r  )r'   r   vmr{   r  s      r"   rO   z#_dict_formatter.<locals>.<listcomp>  si     . . .1a wwqzzD( AaCE1f!E!EqsKKL . . .r!   L   rw      
float_kind)	linewidth	edgeitems	threshold	formatterN)r   r  rd  r  r   r  r  r"  r:   printoptionsr  r   )r  r{   mplusr  r  r  s    ` ` @r"   r  r    s&    !T Caffhh(())E1II . . . . . .#)6!99. . . / / _r!tqB(46I'JL L L 	 	AA	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 Hs   ,CCC)NN)r   )TFFFFr%   )NNr.  F)r7  )FN)F)r\  N)r   r   N)_rA  
contextlibr   rh   rj   r   r   collectionsr   r   r   typingr   r   numpyr:   scipy._lib._array_apir   r   r	   scipy._lib._docscraper
   r   r5   	Exception__annotations__WarninglibNumpyVersion__version__numpy.exceptionsr   r   r   r   r   catch_warningsfilterwarningsr   longr   ulongr   r  int_uintr7   r   	IntNumberr8   floatingDecimalNumberr6   r   ry   	__array__r   r   r   r   r   r   numpy.randomImportErrorrJ   r_   ru   rz   r   r   r   r   r   r   r   r  r  r  r6  r=  rJ  rQ  rV  r[  rn  ru  r~  r  r  r  r  r  r  r  r  r    r!   r"   <module>r     s    					 % % % % % %        " " " " " "   % % % % % % % %     D D D D D D D D D D 8 8 8 8 8 8 8 8 	?   W   = ( ( (6r~&&(22            
          $	
6r~&&,66$X$&& 	  	 #H#B  
 gGxH	  	  	  	  	  	  	  	  	  	  	  	  	  	  	     gGwHHH gGwH"*	#bj0t   6r~&&'11NNV((833NN!T***    )%	(==i = = =$&-) - - -t4443333333            
L L L L^% % % %P !&S    4  ;s ;u ; ; ; ; 
: 264#'u u u u ur" " "< (,BG"'5 5 5 5p   R jI I IJ J
48 48 48n	% 	% 	% 	% 	% 	% 	% 	%G> G> G> G> G> G> G> G>T 8?=C =C =C =C@ ) ) ) )  .   / / /@-G -G -G -G`,$$,$ ,$ ,$ ,$ ,$^4 4 4 4n    
/ 
/ 
/ 
/ 
/    4*! *! *! *! *!$ *! *! *!Z' ' ' '
P 
P 
P     sZ   D "!DD DD DD D10D13'G G%$G%!H( (H=<H=