
    ^Mh              
           d dl Z d dlZd dlmc mZ d dlmZ d dl	m
Z
mZmZmZ dZd Zddddd	d
d ddd	dZd Zdddd	d
d ddZdddd	d
ddZdS )    N)_RichResult)array_namespacexp_signxp_copyxp_take_along_axisc                    t          |          }t          |           st          d          t          j        |          s|f}|i n|}|                    dd           }|                    dd           }d}t          j        ||nd||nd|g          }t          j        |j        t          j	                  rIt          j
        |dk               s1t          j
        t          j        |                    s|j        dk    rt          |          t          |d                   }t          |          }||k    s|dk    rt          d	          t          |          }||k    s|dk    rt          d
          |                    |          }|                    |          }|                    |||          }|\  }}}d}|	dvrt          |          |
t          |
          st          d          | ||||||||||	|
fS )Nz`f` must be callable.atolrtolz<Tolerances and step parameters must be non-negative scalars.   r   )      z%`maxiter` must be a positive integer.z#`order` must be a positive integer.z'`preserve_shape` must be True or False.>   FTz`callback` must be callable.)r   callable
ValueErrornpiterablegetasarray
issubdtypedtypenumberanyisnanshapefloatintbroadcast_arrays)fxargs
tolerancesmaxiterorderinitial_stepstep_factorstep_directionpreserve_shapecallbackxpr
   r   messagetolsmaxiter_int	order_inttemps                      b/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/differentiate/_differentiate.py_derivative_ivr0   
   s+    
		BA;; 20111;t w!)zJ>>&$''D>>&$''D MG:t/ttQ#/ttQ"$ % %D M$*bi00 "BF4!84D4D "vbhtnn%%")-t););!!!Q..Kg,,K+A@AAAE

IEUaZZ>???ZZ//N::l++Lq.,??D&*#A~|7G]**!!!HX$6$67888q$dKLC C     
            ?g       @F)	r    r!   r"   r#   r$   r%   r&   r'   r(   c       	           ' t          | |||||||||	|
          }|\  }}}}}}}}}}}	}
t          j        ||f||	          }|\  }}}}}}''                    |          }||j        n|}|
|j        dz  n|}|d         |d         } }'                    | 'j                  }'                    ||          }'	                    |d          }'
                    t          |          |          }'                    ||          }'	                    |d          }'
                    ||          }'                    'j        |          ||dk    <   '                    |t          j        'j                  }d\  }}|dk     }|dk    }|dk    }||z  }t          d&i d|d	|d
| dd'j        f         d'j        d|d'j        d'j        d|d|d|d|d|d|d|d|dz   dz  d|d|d|d|d|dt          g g d          } g d }!'fd!}"'fd"}#'fd#}$d$ }%d% }&t          j        | |
||||||"|#|$|%|&|!'|	          S )'a7  Evaluate the derivative of a elementwise, real scalar function numerically.

    For each element of the output of `f`, `derivative` approximates the first
    derivative of `f` at the corresponding element of `x` using finite difference
    differentiation.

    This function works elementwise when `x`, `step_direction`, and `args` contain
    (broadcastable) arrays.

    Parameters
    ----------
    f : callable
        The function whose derivative is desired. The signature must be::

            f(xi: ndarray, *argsi) -> ndarray

        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
        which may contain an arbitrary number of arrays that are broadcastable with
        ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
        must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
        ``xi`` or the arrays in ``argsi``.
    x : float array_like
        Abscissae at which to evaluate the derivative. Must be broadcastable with
        `args` and `step_direction`.
    args : tuple of array_like, optional
        Additional positional array arguments to be passed to `f`. Arrays
        must be broadcastable with one another and the arrays of `init`.
        If the callable for which the root is desired requires arguments that are
        not broadcastable with `x`, wrap that callable with `f` such that `f`
        accepts only `x` and broadcastable ``*args``.
    tolerances : dictionary of floats, optional
        Absolute and relative tolerances. Valid keys of the dictionary are:

        - ``atol`` - absolute tolerance on the derivative
        - ``rtol`` - relative tolerance on the derivative

        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
        `atol` is the smallest normal number of the appropriate dtype, and
        the default `rtol` is the square root of the precision of the
        appropriate dtype.
    order : int, default: 8
        The (positive integer) order of the finite difference formula to be
        used. Odd integers will be rounded up to the next even integer.
    initial_step : float array_like, default: 0.5
        The (absolute) initial step size for the finite difference derivative
        approximation.
    step_factor : float, default: 2.0
        The factor by which the step size is *reduced* in each iteration; i.e.
        the step size in iteration 1 is ``initial_step/step_factor``. If
        ``step_factor < 1``, subsequent steps will be greater than the initial
        step; this may be useful if steps smaller than some threshold are
        undesirable (e.g. due to subtractive cancellation error).
    maxiter : int, default: 10
        The maximum number of iterations of the algorithm to perform. See
        Notes.
    step_direction : integer array_like
        An array representing the direction of the finite difference steps (for
        use when `x` lies near to the boundary of the domain of the function.)
        Must be broadcastable with `x` and all `args`.
        Where 0 (default), central differences are used; where negative (e.g.
        -1), steps are non-positive; and where positive (e.g. 1), all steps are
        non-negative.
    preserve_shape : bool, default: False
        In the following, "arguments of `f`" refers to the array ``xi`` and
        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
        of `x` and all elements of `args` (which is conceptually
        distinct from ``xi` and ``argsi`` passed into `f`).

        - When ``preserve_shape=False`` (default), `f` must accept arguments
          of *any* broadcastable shapes.

        - When ``preserve_shape=True``, `f` must accept arguments of shape
          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
          abscissae at which the function is being evaluated.

        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
        Consequently, the shape of the output is always the shape of the input
        ``xi``.

        See Examples.
    callback : callable, optional
        An optional user-supplied function to be called before the first
        iteration and after each iteration.
        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
        similar to that returned by `derivative` (but containing the current
        iterate's values of all variables). If `callback` raises a
        ``StopIteration``, the algorithm will terminate immediately and
        `derivative` will return a result. `callback` must not mutate
        `res` or its attributes.

    Returns
    -------
    res : _RichResult
        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
        following attributes. The descriptions are written as though the values will
        be scalars; however, if `f` returns an array, the outputs will be
        arrays of the same shape.

        success : bool array
            ``True`` where the algorithm terminated successfully (status ``0``);
            ``False`` otherwise.
        status : int array
            An integer representing the exit status of the algorithm.

            - ``0`` : The algorithm converged to the specified tolerances.
            - ``-1`` : The error estimate increased, so iteration was terminated.
            - ``-2`` : The maximum number of iterations was reached.
            - ``-3`` : A non-finite value was encountered.
            - ``-4`` : Iteration was terminated by `callback`.
            - ``1`` : The algorithm is proceeding normally (in `callback` only).

        df : float array
            The derivative of `f` at `x`, if the algorithm terminated
            successfully.
        error : float array
            An estimate of the error: the magnitude of the difference between
            the current estimate of the derivative and the estimate in the
            previous iteration.
        nit : int array
            The number of iterations of the algorithm that were performed.
        nfev : int array
            The number of points at which `f` was evaluated.
        x : float array
            The value at which the derivative of `f` was evaluated
            (after broadcasting with `args` and `step_direction`).

    See Also
    --------
    jacobian, hessian

    Notes
    -----
    The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
    DERIVEST [3]_, but the implementation follows the theory of Taylor series
    more straightforwardly (and arguably naively so).
    In the first iteration, the derivative is estimated using a finite
    difference formula of order `order` with maximum step size `initial_step`.
    Each subsequent iteration, the maximum step size is reduced by
    `step_factor`, and the derivative is estimated again until a termination
    condition is reached. The error estimate is the magnitude of the difference
    between the current derivative approximation and that of the previous
    iteration.

    The stencils of the finite difference formulae are designed such that
    abscissae are "nested": after `f` is evaluated at ``order + 1``
    points in the first iteration, `f` is evaluated at only two new points
    in each subsequent iteration; ``order - 1`` previously evaluated function
    values required by the finite difference formula are reused, and two
    function values (evaluations at the points furthest from `x`) are unused.

    Step sizes are absolute. When the step size is small relative to the
    magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
    default initial step size of ``0.5`` cannot be resolved. Accordingly,
    consider using larger initial step sizes for large magnitudes of `x`.

    The default tolerances are challenging to satisfy at points where the
    true derivative is exactly zero. If the derivative may be exactly zero,
    consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
    improve convergence.

    References
    ----------
    .. [1] Hans Dembinski (@HDembinski). jacobi.
           https://github.com/HDembinski/jacobi
    .. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
           https://numdifftools.readthedocs.io/en/latest/
    .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
           https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
    .. [4] Numerical Differentition. Wikipedia.
           https://en.wikipedia.org/wiki/Numerical_differentiation

    Examples
    --------
    Evaluate the derivative of ``np.exp`` at several points ``x``.

    >>> import numpy as np
    >>> from scipy.differentiate import derivative
    >>> f = np.exp
    >>> df = np.exp  # true derivative
    >>> x = np.linspace(1, 2, 5)
    >>> res = derivative(f, x)
    >>> res.df  # approximation of the derivative
    array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
    >>> res.error  # estimate of the error
    array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
           1.94262384e-11])
    >>> abs(res.df - df(x))  # true error
    array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
           6.92779167e-14])

    Show the convergence of the approximation as the step size is reduced.
    Each iteration, the step size is reduced by `step_factor`, so for
    sufficiently small initial step, each iteration reduces the error by a
    factor of ``1/step_factor**order`` until finite precision arithmetic
    inhibits further improvement.

    >>> import matplotlib.pyplot as plt
    >>> iter = list(range(1, 12))  # maximum iterations
    >>> hfac = 2  # step size reduction per iteration
    >>> hdir = [-1, 0, 1]  # compare left-, central-, and right- steps
    >>> order = 4  # order of differentiation formula
    >>> x = 1
    >>> ref = df(x)
    >>> errors = []  # true error
    >>> for i in iter:
    ...     res = derivative(f, x, maxiter=i, step_factor=hfac,
    ...                      step_direction=hdir, order=order,
    ...                      # prevent early termination
    ...                      tolerances=dict(atol=0, rtol=0))
    ...     errors.append(abs(res.df - ref))
    >>> errors = np.array(errors)
    >>> plt.semilogy(iter, errors[:, 0], label='left differences')
    >>> plt.semilogy(iter, errors[:, 1], label='central differences')
    >>> plt.semilogy(iter, errors[:, 2], label='right differences')
    >>> plt.xlabel('iteration')
    >>> plt.ylabel('error')
    >>> plt.legend()
    >>> plt.show()
    >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
    (0.06215223140159822, 0.0625)

    The implementation is vectorized over `x`, `step_direction`, and `args`.
    The function is evaluated once before the first iteration to perform input
    validation and standardization, and once per iteration thereafter.

    >>> def f(x, p):
    ...     f.nit += 1
    ...     return x**p
    >>> f.nit = 0
    >>> def df(x, p):
    ...     return p*x**(p-1)
    >>> x = np.arange(1, 5)
    >>> p = np.arange(1, 6).reshape((-1, 1))
    >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
    >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
    >>> np.allclose(res.df, df(x, p))
    True
    >>> res.df.shape
    (3, 5, 4)
    >>> f.nit
    2

    By default, `preserve_shape` is False, and therefore the callable
    `f` may be called with arrays of any broadcastable shapes.
    For example:

    >>> shapes = []
    >>> def f(x, c):
    ...    shape = np.broadcast_shapes(x.shape, c.shape)
    ...    shapes.append(shape)
    ...    return np.sin(c*x)
    >>>
    >>> c = [1, 5, 10, 20]
    >>> res = derivative(f, 0, args=(c,))
    >>> shapes
    [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]

    To understand where these shapes are coming from - and to better
    understand how `derivative` computes accurate results - note that
    higher values of ``c`` correspond with higher frequency sinusoids.
    The higher frequency sinusoids make the function's derivative change
    faster, so more function evaluations are required to achieve the target
    accuracy:

    >>> res.nfev
    array([11, 13, 15, 17], dtype=int32)

    The initial ``shape``, ``(4,)``, corresponds with evaluating the
    function at a single abscissa and all four frequencies; this is used
    for input validation and to determine the size and dtype of the arrays
    that store results. The next shape corresponds with evaluating the
    function at an initial grid of abscissae and all four frequencies.
    Successive calls to the function evaluate the function at two more
    abscissae, increasing the effective order of the approximation by two.
    However, in later function evaluations, the function is evaluated at
    fewer frequencies because the corresponding derivative has already
    converged to the required tolerance. This saves function evaluations to
    improve performance, but it requires the function to accept arguments of
    any shape.

    "Vector-valued" functions are unlikely to satisfy this requirement.
    For example, consider

    >>> def f(x):
    ...    return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]

    This integrand is not compatible with `derivative` as written; for instance,
    the shape of the output will not be the same as the shape of ``x``. Such a
    function *could* be converted to a compatible form with the introduction of
    additional parameters, but this would be inconvenient. In such cases,
    a simpler solution would be to use `preserve_shape`.

    >>> shapes = []
    >>> def f(x):
    ...     shapes.append(x.shape)
    ...     x0, x1, x2, x3 = x
    ...     return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
    >>>
    >>> x = np.zeros(4)
    >>> res = derivative(f, x, preserve_shape=True)
    >>> shapes
    [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]

    Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
    function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
    and this is what we observe.

    )r'   Nr5   r   )r   r   )r   r   r   dffserrorhdf_last
error_lastfacr
   r   nitnfevstatusr   termsr   r   hdirilicirio
diff_state)centralrightr>   ))rA   rA   )r8   r8   )r:   r:   )r?   r?   )r@   r@   )r   r   c                    | j         }| j        ddj        f         }| j        }|dz  }| j        dk    rR||                    || j                  z  z  }                                        |d           |fd          }n#                    | |fd          ||dz
  z  z  }| j        dk    r&||                    d|z  | j                  z  z  }n%                    |||z  fd          ||dz
  z  z  }| j        dk    rd|z  nd}	                    | j
        j        d         |f| j                  }| j        | j        | j        }}
}	| j        |         ddj        f         ||         z   ||<   | j        |
         ddj        f         ||
         z   ||
<   | j        |	         ddj        f         ||	         z
  ||	<   |S )	a  Determine the abscissae at which the function needs to be evaluated.

        See `_derivative_weights` for a description of the stencil (pattern
        of the abscissae).

        In the first iteration, there is only one stored function value in
        `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
        subsequent iterations, we evaluate at two new points. Note that
        `work.x` is always flattened into a 1D array after broadcasting with
        all `args`, so we add a new axis at the end and evaluate all point
        in one call to the function.

        For improvement:
        - Consider measuring the step size actually taken, since ``(x + h) - x``
          is not identically equal to `h` with floating point arithmetic.
        - Adjust the step size automatically if `x` is too big to resolve the
          step.
        - We could probably save some work if there are no central difference
          steps or no one-sided steps.
        Nr5   r   r7   r   axisr   r   )rB   r;   newaxisr>   r?   aranger   concatflipzerosrC   r   rD   rE   rF   r   )worknr;   cdhchrn_newx_evalrD   rE   rF   r)   s               r/   pre_func_evalz!derivative.<locals>.pre_func_eval  s   * JF111bj=!HsF 8q==Q		!4:	6666BRWWRbW11126R@@BBQB7,,q1Q3x7B8q==Q		!A#TZ	8888BBAqs8"--AaC8Bx1}}!!49?1-u5TZHHWdgtwBVBZ2:.B7r
VBZ2:.B7r
VBZ2:.B7r
r1   c                    |j         }|j        dk    r|nd}|j        |j        |j        }}}||         ddd|f         |j        |         ||         dd| df         f}                    |d          }|j        dk    r|}	nD|ddd|f         |dd||dz   f         |dd| df         f}	                    |	d          }	                    |j        |         ||         fd          }
|j        dk    r|
}n4                    |
ddddf         |
ddd|z  df         fd          }                    |j        d         |j        j        d         d|z  z   f|j	                  |_        ||j        |<   |
|j        |<   t          ||          \  }}                    |j        d	
          |_        |	|z  |j        |         z  |j        |<   ||z  |j        |         z  |j        |<   |j        |xx         dz  cc<   |xj        |j        z  c_        |j        |_                            |j        |j        z
            |_        dS )a   Estimate the derivative and error from the function evaluations

        As in `pre_func_eval`: in the first iteration, there is only one stored
        function value in `work.fs`, `f(x)`, so we need to add the `order` new
        points. In subsequent iterations, we add two new points. The tricky
        part is getting the order to match that of the weights, which is
        described in `_derivative_weights`.

        For improvement:
        - Change the order of the weights (and steps in `pre_func_eval`) to
          simplify `work_fc` concatenation and eliminate `fc` concatenation.
        - It would be simple to do one-step Richardson extrapolation with `df`
          and `df_last` to increase the order of the estimate and/or improve
          the error estimate.
        - Process the function evaluations in a more numerically favorable
          way. For instance, combining the pairs of central difference evals
          into a second-order approximation and using Richardson extrapolation
          to produce a higher order approximation seemed to retain accuracy up
          to very high order.
        - Alternatively, we could use `polyfit` like Jacobi. An advantage of
          fitting polynomial to more points than necessary is improved noise
          tolerance.
        r   r   Nr   rL   r   r7   T)copy)rB   r?   rD   rE   rG   r9   rP   rR   r   r   _derivative_weightsr   r8   r<   r;   r>   r:   r=   abs)r   r   rS   rT   rY   rD   rE   rG   work_fcfcwork_fofowcwor)   s                 r/   post_func_evalz"derivative.<locals>.post_func_eval  sk   0 JX]]WdgtwB
 R5FUF#TWR[!B%E677
2CD))G")--8q==BB!!!RaR%.'!!!QqsU("3WQQQV_EB2B''B ))TWR[!B%0r)::8q==BBGAAAqsFOWQQQ1X->?bIIB((BHQKr):QuW)DETZ(XX$T1b11Bzz$'z552gr
*2gr
*r$(* VVDGdl233


r1   c                 *                                            | j                  j                  }| j        | j        | j        t          | j                  z  z   k     }t          j	        | j
        |<   d||<   | j        dk    rb                    | j                                      | j                  z  |z   }j        t          j        c| j        |<   | j
        |<   d||<   | j        | j        dz  k    | z  }t"          | j
        |<   d||<   |S )zBTerminate due to convergence, non-finite values, or error increaseTr   r3   )astype
zeros_liker8   boolr:   r
   r   r`   eim_ECONVERGEDrA   r?   isfiniter   nan
_EVALUEERRr=   _EERRORINCREASE)rS   stopir)   s      r/   check_terminationz%derivative.<locals>.check_termination(  s    yytw//99JTYs47||%;;;AQ8a<<;;tv&&TW)=)==EFA)+&DGAJADG Z$/",,5(AQr1   c                     d S Nr2   )rS   s    r/   post_termination_checkz*derivative.<locals>.post_termination_checkB  s    r1   c                     |S rv   r2   )resr   s     r/   customize_resultz$derivative.<locals>.customize_resultE  s    r1   r2   )r0   rl   _initializefinfosmallest_normaleps	full_likero   broadcast_toreshaperi   r   r   _EINPROGRESSint32r   rN   _loop)(r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   ry   funcr
   r   h0r>   rC   r.   xsr9   r   r   r|   r8   rA   r?   r@   rD   rE   rF   rG   rS   res_work_pairsr[   rg   rt   rw   rz   r)   s(                                          @r/   
derivativer   ;   s   |	 AtZ%'S SC 14.T1dD$dNH ?4!tNKKKD+/(D"b$ubHHUOOE$(L5  dD!\59c>>tDa5"Q%qA	a	 	 B ??4''D::dE""D99WT]]E**D	U	#	#B	B		B	2u		B**RV5*11BrQwK\\!S-RX\>>FIC	B	B	B	bB  O O O Orr Oa2:&6&6 Obff O O!vvO24&&O>AcO DO'+tO14O;?4O %fO -2EO ;@'AO !D	O &(R	O -/B	O 462	O ;="	O #.b"M"M"M"MODD D DN, , , , ,\A4 A4 A4 A4 A4F    4     9T8UGT4"N4E+-=~) ) )r1   c                 >   t          | j                  }| j        }||j        k    rg |_        g |_        ||_        t          |j                  d|z  dz   k    rt          j        | |dz             }t          j        |          dz
  }t          j	        |          }|||z  z  }t          j
        |d          j        }	t          j        d|z  dz             }
d|
d<   t          j                            |	|
          }d||<   t          |          D ]}||          || dz
  <   ||_        t          j        d|z  dz             }|dz
  }t          j	        |          }|t          j        |          |z  z  }t          j
        |d          j        }	t          j        d|z  dz             }
d|
d<   t          j                            |	|
          }||_        |                    |j        | j                  |                    |j        | j                  fS )Nr   r         ?T)
increasingr   r7   )r   r>   rH   rI   rJ   lenr   rO   r`   signvanderTrR   linalgsolverangesqrtr   r   )rS   rT   r)   r>   rH   rs   psr;   Abweightss               r/   r_   r_   N  s   @ //C J
jn



:!A#')) Iqb!a%  F1IINGAJJqLIaD)))+HQqS1W!)//!Q'' 
q 	( 	(A$QZKGQBqDMM %

 IacAgFGAJJ!!IaD)))+HQUQY!)//!Q''"
JJz)J<<JJz'tzJ::< <r1   )r!   r"   r#   r$   r%   r&   c                    t          |                              |          }                    |j        d          }|r/                    |                    d          j                  n|j        dk     rd}	t          |	          j        d                                        fd}
t          |
||||||d|		  	        }|`	|S )
a!  Evaluate the Jacobian of a function numerically.

    Parameters
    ----------
    f : callable
        The function whose Jacobian is desired. The signature must be::

            f(xi: ndarray) -> ndarray

        where each element of ``xi`` is a finite real. If the function to be
        differentiated accepts additional arguments, wrap it (e.g. using
        `functools.partial` or ``lambda``) and pass the wrapped callable
        into `jacobian`. `f` must not mutate the array ``xi``. See Notes
        regarding vectorization and the dimensionality of the input and output.
    x : float array_like
        Points at which to evaluate the Jacobian. Must have at least one dimension.
        See Notes regarding the dimensionality and vectorization.
    tolerances : dictionary of floats, optional
        Absolute and relative tolerances. Valid keys of the dictionary are:

        - ``atol`` - absolute tolerance on the derivative
        - ``rtol`` - relative tolerance on the derivative

        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
        `atol` is the smallest normal number of the appropriate dtype, and
        the default `rtol` is the square root of the precision of the
        appropriate dtype.
    maxiter : int, default: 10
        The maximum number of iterations of the algorithm to perform. See
        Notes.
    order : int, default: 8
        The (positive integer) order of the finite difference formula to be
        used. Odd integers will be rounded up to the next even integer.
    initial_step : float array_like, default: 0.5
        The (absolute) initial step size for the finite difference derivative
        approximation. Must be broadcastable with `x` and `step_direction`.
    step_factor : float, default: 2.0
        The factor by which the step size is *reduced* in each iteration; i.e.
        the step size in iteration 1 is ``initial_step/step_factor``. If
        ``step_factor < 1``, subsequent steps will be greater than the initial
        step; this may be useful if steps smaller than some threshold are
        undesirable (e.g. due to subtractive cancellation error).
    step_direction : integer array_like
        An array representing the direction of the finite difference steps (e.g.
        for use when `x` lies near to the boundary of the domain of the function.)
        Must be broadcastable with `x` and `initial_step`.
        Where 0 (default), central differences are used; where negative (e.g.
        -1), steps are non-positive; and where positive (e.g. 1), all steps are
        non-negative.

    Returns
    -------
    res : _RichResult
        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
        following attributes. The descriptions are written as though the values will
        be scalars; however, if `f` returns an array, the outputs will be
        arrays of the same shape.

        success : bool array
            ``True`` where the algorithm terminated successfully (status ``0``);
            ``False`` otherwise.
        status : int array
            An integer representing the exit status of the algorithm.

            - ``0`` : The algorithm converged to the specified tolerances.
            - ``-1`` : The error estimate increased, so iteration was terminated.
            - ``-2`` : The maximum number of iterations was reached.
            - ``-3`` : A non-finite value was encountered.

        df : float array
            The Jacobian of `f` at `x`, if the algorithm terminated
            successfully.
        error : float array
            An estimate of the error: the magnitude of the difference between
            the current estimate of the Jacobian and the estimate in the
            previous iteration.
        nit : int array
            The number of iterations of the algorithm that were performed.
        nfev : int array
            The number of points at which `f` was evaluated.

        Each element of an attribute is associated with the corresponding
        element of `df`. For instance, element ``i`` of `nfev` is the
        number of points at which `f` was evaluated for the sake of
        computing element ``i`` of `df`.

    See Also
    --------
    derivative, hessian

    Notes
    -----
    Suppose we wish to evaluate the Jacobian of a function
    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
    ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
    respectively, and let ``...`` represent an arbitrary tuple of integers.
    If we wish to evaluate the Jacobian at a single point, then:

    - argument `x` must be an array of shape ``(m,)``
    - argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
      The first axis represents the :math:`m` inputs of :math:`f`; the remainder
      are for evaluating the function at multiple points in a single call.
    - argument `f` must return an array of shape ``(n, ...)``. The first
      axis represents the :math:`n` outputs of :math:`f`; the remainder
      are for the result of evaluating the function at multiple points.
    - attribute ``df`` of the result object will be an array of shape ``(n, m)``,
      the Jacobian.

    This function is also vectorized in the sense that the Jacobian can be
    evaluated at ``k`` points in a single call. In this case, `x` would be an
    array of shape ``(m, k)``, `f` would accept an array of shape
    ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
    attribute of the result would have shape ``(n, m, k)``.

    Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
    only accept an array of shape ``(m,)``. A simple solution to satisfy the required
    interface is to wrap ``f_not_vectorized`` as follows::

        def f(x):
            return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)

    Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
    only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
    consider::

        def f(x):
            m, batch = x.shape[0], x.shape[1:]  # x.shape is (m, ...)
            x = np.reshape(x, (m, -1))  # `-1` is short for q = prod(batch)
            res = f_vec_q(x)  # pass shape (m, q) to function
            n = res.shape[0]
            return np.reshape(res, (n,) + batch)  # return shape (n, ...)

    Then pass the wrapped callable ``f`` as the first argument of `jacobian`.

    References
    ----------
    .. [1] Jacobian matrix and determinant, *Wikipedia*,
           https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant

    Examples
    --------
    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
    array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
    to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
    at ``[0.5, 0.5, 0.5]``.

    >>> import numpy as np
    >>> from scipy.differentiate import jacobian
    >>> from scipy.optimize import rosen, rosen_der
    >>> m = 3
    >>> x = np.full(m, 0.5)
    >>> res = jacobian(rosen, x)
    >>> ref = rosen_der(x)  # reference value of the gradient
    >>> res.df, ref
    (array([-51.,  -1.,  50.]), array([-51.,  -1.,  50.]))

    As an example of a function with multiple outputs, consider Example 4
    from [1]_.

    >>> def f(x):
    ...     x1, x2, x3 = x
    ...     return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]

    The true Jacobian is given by:

    >>> def df(x):
    ...         x1, x2, x3 = x
    ...         one = np.ones_like(x1)
    ...         return [[one, 0*one, 0*one],
    ...                 [0*one, 0*one, 5*one],
    ...                 [0*one, 8*x2, -2*one],
    ...                 [x3*np.cos(x1), 0*one, np.sin(x1)]]

    Evaluate the Jacobian at an arbitrary point.

    >>> rng = np.random.default_rng(389252938452)
    >>> x = rng.random(size=3)
    >>> res = jacobian(f, x)
    >>> ref = df(x)
    >>> res.df.shape == (4, 3)
    True
    >>> np.allclose(res.df, ref)
    True

    Evaluate the Jacobian at 10 arbitrary points in a single call.

    >>> x = rng.random(size=(3, 10))
    >>> res = jacobian(f, x)
    >>> ref = df(x)
    >>> res.df.shape == (4, 3, 10)
    True
    >>> np.allclose(res.df, ref)
    True

    integralr   r7   r   z"Argument `x` must be at least 1-D.r   c                 \   | j         j         k    rdn| j        d         f}fj        dd          z   |z   }                    d          }| j         j         k    r                    |d          }t                              ||                    }| |f<    |          S )Nr2   r   r   rL   )r)   )ndimr   expand_dimsr   r   )	r   r   	new_shapexphr   rs   mx0r)   s	       r/   wrappedzjacobian.<locals>.wrapped  s    &BG##BB!'"+FRXabb\)A-	nnRan((6RW..2...Cbooc955"===AqD	qvvr1   T)r!   r"   r#   r$   r%   r'   r&   )
r   r   isdtyper   r   r   r   rO   r   r   )r   r   r!   r"   r#   r$   r%   r&   	int_dtyper*   r   ry   rs   r   r   r)   s   `           @@@@r/   jacobianr     s   L 
		B


1A

17J//I7@	GARZZ__2	3	3	3aB	w{{6!!!
A
		!A	 	 	 	 	 	 	 	 	 WaJ$E!,T$24 4 4C
 	Jr1   )r!   r"   r#   r$   r%   c                `    t          ||||          |i n|}|                    dd          |                    dd          t          |          }|                    |          }|                    |j        d          s|j        n|                    d          j        }|                    |          }	
|	j        dz  n|	j        dz  }
d	d
|
 d}dcxk     r|
k     r!n nt          j	        |t          d           |
 fd}g t          ||fd|i}|                    |                              d          |                    |j        |j        df         |j                  }t%          |d          d         |_        |j        |_        |`|`|S )aL  Evaluate the Hessian of a function numerically.

    Parameters
    ----------
    f : callable
        The function whose Hessian is desired. The signature must be::

            f(xi: ndarray) -> ndarray

        where each element of ``xi`` is a finite real. If the function to be
        differentiated accepts additional arguments, wrap it (e.g. using
        `functools.partial` or ``lambda``) and pass the wrapped callable
        into `hessian`. `f` must not mutate the array ``xi``. See Notes
        regarding vectorization and the dimensionality of the input and output.
    x : float array_like
        Points at which to evaluate the Hessian. Must have at least one dimension.
        See Notes regarding the dimensionality and vectorization.
    tolerances : dictionary of floats, optional
        Absolute and relative tolerances. Valid keys of the dictionary are:

        - ``atol`` - absolute tolerance on the derivative
        - ``rtol`` - relative tolerance on the derivative

        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
        `atol` is the smallest normal number of the appropriate dtype, and
        the default `rtol` is the square root of the precision of the
        appropriate dtype.
    order : int, default: 8
        The (positive integer) order of the finite difference formula to be
        used. Odd integers will be rounded up to the next even integer.
    initial_step : float, default: 0.5
        The (absolute) initial step size for the finite difference derivative
        approximation.
    step_factor : float, default: 2.0
        The factor by which the step size is *reduced* in each iteration; i.e.
        the step size in iteration 1 is ``initial_step/step_factor``. If
        ``step_factor < 1``, subsequent steps will be greater than the initial
        step; this may be useful if steps smaller than some threshold are
        undesirable (e.g. due to subtractive cancellation error).
    maxiter : int, default: 10
        The maximum number of iterations of the algorithm to perform. See
        Notes.

    Returns
    -------
    res : _RichResult
        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
        following attributes. The descriptions are written as though the values will
        be scalars; however, if `f` returns an array, the outputs will be
        arrays of the same shape.

        success : bool array
            ``True`` where the algorithm terminated successfully (status ``0``);
            ``False`` otherwise.
        status : int array
            An integer representing the exit status of the algorithm.

            - ``0`` : The algorithm converged to the specified tolerances.
            - ``-1`` : The error estimate increased, so iteration was terminated.
            - ``-2`` : The maximum number of iterations was reached.
            - ``-3`` : A non-finite value was encountered.

        ddf : float array
            The Hessian of `f` at `x`, if the algorithm terminated
            successfully.
        error : float array
            An estimate of the error: the magnitude of the difference between
            the current estimate of the Hessian and the estimate in the
            previous iteration.
        nfev : int array
            The number of points at which `f` was evaluated.

        Each element of an attribute is associated with the corresponding
        element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
        number of points at which `f` was evaluated for the sake of
        computing element ``[i, j]`` of `ddf`.

    See Also
    --------
    derivative, jacobian

    Notes
    -----
    Suppose we wish to evaluate the Hessian of a function
    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
    ``m`` the positive integer value of :math:`m`. If we wish to evaluate
    the Hessian at a single point, then:

    - argument `x` must be an array of shape ``(m,)``
    - argument `f` must be vectorized to accept an array of shape
      ``(m, ...)``. The first axis represents the :math:`m` inputs of
      :math:`f`; the remaining axes indicated by ellipses are for evaluating
      the function at several abscissae in a single call.
    - argument `f` must return an array of shape ``(...)``.
    - attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
      the Hessian.

    This function is also vectorized in the sense that the Hessian can be
    evaluated at ``k`` points in a single call. In this case, `x` would be an
    array of shape ``(m, k)``, `f` would accept an array of shape
    ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
    attribute of the result would have shape ``(m, m, k)``. Note that the
    axis associated with the ``k`` points is included within the axes
    denoted by ``(...)``.

    Currently, `hessian` is implemented by nesting calls to `jacobian`.
    All options passed to `hessian` are used for both the inner and outer
    calls with one exception: the `rtol` used in the inner `jacobian` call
    is tightened by a factor of 100 with the expectation that the inner
    error can be ignored. A consequence is that `rtol` should not be set
    less than 100 times the precision of the dtype of `x`; a warning is
    emitted otherwise.

    References
    ----------
    .. [1] Hessian matrix, *Wikipedia*,
           https://en.wikipedia.org/wiki/Hessian_matrix

    Examples
    --------
    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
    array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
    wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.

    >>> import numpy as np
    >>> from scipy.differentiate import hessian
    >>> from scipy.optimize import rosen, rosen_hess
    >>> m = 3
    >>> x = np.full(m, 0.5)
    >>> res = hessian(rosen, x)
    >>> ref = rosen_hess(x)  # reference value of the Hessian
    >>> np.allclose(res.ddf, ref)
    True

    `hessian` is vectorized to evaluate the Hessian at multiple points
    in a single call.

    >>> rng = np.random.default_rng(4589245925010)
    >>> x = rng.random((m, 10))
    >>> res = hessian(rosen, x)
    >>> ref = [rosen_hess(xi) for xi in x.T]
    >>> ref = np.moveaxis(ref, 0, -1)
    >>> np.allclose(res.ddf, ref)
    True

    )r"   r#   r$   r%   Nr
   r   r   r   r5   d   zThe specified `rtol=z@`, but error estimates are likely to be unreliable when `rtol < z`.r   r   )
stacklevelc                     t          dz            }t          | fd|i}                    t                    dk    r|j        n|j                            d                     |j        S )Nr   )r   r
   r!   r   r   rL   )dictr   appendr   r@   sumr8   )r   r!   r.   r
   r   kwargsr@   r   s      r/   r8   zhessian.<locals>.dfY  sr    tCxd333
1>>>v>>TaDIITY]]]5K5KLLLwr1   r!   rL   .)r   r   r   r   r   r   r|   r~   warningswarnRuntimeWarningr   cumulative_sumstackri   r?   rN   int64r   r@   r8   ddf)r   r   r!   r"   r#   r$   r%   r)   r   r|   rtol_minr*   r8   ry   res_nitr
   r   r@   r   s   `              @@@@r/   hessianr     s   r '\)+ + +F!)zJ>>&$''D>>&$''D			B


1A::agz::TAGG

2@TEHHUOOE!\59c>>tD y3H7 7 7*27 7 7G4(g~!<<<<         D
2q
:
:Z
:6
:
:CRXXd^^!44Dii
C0"(;;G!$a888;CHfCGJr1   )r   numpyr   (scipy._lib._elementwise_iterative_method_lib_elementwise_iterative_methodrl   scipy._lib._utilr   scipy._lib._array_apir   r   r   r   rq   r0   r   r_   r   r   r2   r1   r/   <module>r      s3        6 6 6 6 6 6 6 6 6 ( ( ( ( ( ( W W W W W W W W W W W W.C .C .Cb  D"ScP) P) P) P) P)fu< u< u<p "&rQc c c c cL !%b#3} } } } } } }r1   