
    (ph                        S SK r SSKJr  S SKrS SKJrJrJrJrJ	r	J
r
JrJrJrJrJrJrJr  S SKJr  S SKJrJrJrJr  S SKJrJrJr  S SKJr  SS	KJ r J!r!J"r"  SS
K#J$r$  SSK%J&r&  S SK'J(r(  / SQr) S S jr*   S!S jr+   S"S jr,/ SQr-/ SQr.   S#S jr/S r0S r1S r2S r3SSSS\R                  * \R                  4SS4SSS.S jjr4S$S jr5S r6S r7S r8S%S jr9g)&    N   )_minpack)
atleast_1dtriushape	transposezerosprodgreaterasarrayinffinfoinexact
issubdtypedtype)linalg)svdcholeskysolve_triangularLinAlgError)_asarray_validated
_lazywhere_contains_nan)getfullargspec_no_self)OptimizeResult_check_unknown_optionsOptimizeWarning)least_squares)prepare_bounds)Bounds)fsolveleastsqfixed_point	curve_fitc                    [        U" US U 4U-   6 5      nUb  [        U5      U:w  aw  US   S:w  an  [        U5      S:  a  US   S:X  a  [        U5      $ U  SU S3n[        USS 5      n	U	(       a
  USU	 S3-  nOUS-  nUS	U S
[        U5       S3-  n[	        U5      e[        UR                  [        5      (       a  UR                  n
O[        [        5      n
[        U5      U
4$ )Nr   r   zA: there is a mismatch between the input and output shape of the 'z
' argument__name__z 'z'..zShape should be z but it is )	r   r   lengetattr	TypeErrorr   r   r   float)checkerargnamethefuncx0args	numinputsoutput_shaperesmsg	func_namedts              M/var/www/html/venv/lib/python3.13/site-packages/scipy/optimize/_minpack_py.py_check_funcr8      s    
W:I0479
:C uSz\'AOq < 1$?a' :%I ##*):7CT:II;b))s
%l^;uSzl!LLCC. #))W%%YY5\:r>    c                   ^ ^ UU 4S jmSTl         UUUUU	U
US.n[        TX4SU0UD6nTR                   Ul         U(       aA  US   nS Vs0 s H  oU;   d  M
  XR                  U5      _M     nnUS   US'   UUUS	   US
   4$ US	   nUS
   nUS:X  a  [        U5      eUS:X  a   US   $ US;   a  [        R
                  " U[        SS9  US   $ [        U5      es  snf )aA  
Find the roots of a function.

Return the roots of the (non-linear) equations defined by
``func(x) = 0`` given a starting estimate.

Parameters
----------
func : callable ``f(x, *args)``
    A function that takes at least one (possibly vector) argument,
    and returns a value of the same length.
x0 : ndarray
    The starting estimate for the roots of ``func(x) = 0``.
args : tuple, optional
    Any extra arguments to `func`.
fprime : callable ``f(x, *args)``, optional
    A function to compute the Jacobian of `func` with derivatives
    across the rows. By default, the Jacobian will be estimated.
full_output : bool, optional
    If True, return optional outputs.
col_deriv : bool, optional
    Specify whether the Jacobian function computes derivatives down
    the columns (faster, because there is no transpose operation).
xtol : float, optional
    The calculation will terminate if the relative error between two
    consecutive iterates is at most `xtol`.
maxfev : int, optional
    The maximum number of calls to the function. If zero, then
    ``100*(N+1)`` is the maximum where N is the number of elements
    in `x0`.
band : tuple, optional
    If set to a two-sequence containing the number of sub- and
    super-diagonals within the band of the Jacobi matrix, the
    Jacobi matrix is considered banded (only for ``fprime=None``).
epsfcn : float, optional
    A suitable step length for the forward-difference
    approximation of the Jacobian (for ``fprime=None``). If
    `epsfcn` is less than the machine precision, it is assumed
    that the relative errors in the functions are of the order of
    the machine precision.
factor : float, optional
    A parameter determining the initial step bound
    (``factor * || diag * x||``). Should be in the interval
    ``(0.1, 100)``.
diag : sequence, optional
    N positive entries that serve as a scale factors for the
    variables.

Returns
-------
x : ndarray
    The solution (or the result of the last iteration for
    an unsuccessful call).
infodict : dict
    A dictionary of optional outputs with the keys:

    ``nfev``
        number of function calls
    ``njev``
        number of Jacobian calls
    ``fvec``
        function evaluated at the output
    ``fjac``
        the orthogonal matrix, q, produced by the QR
        factorization of the final approximate Jacobian
        matrix, stored column wise
    ``r``
        upper triangular matrix produced by QR factorization
        of the same matrix
    ``qtf``
        the vector ``(transpose(q) * fvec)``

ier : int
    An integer flag.  Set to 1 if a solution was found, otherwise refer
    to `mesg` for more information.
mesg : str
    If no solution is found, `mesg` details the cause of failure.

See Also
--------
root : Interface to root finding algorithms for multivariate
       functions. See the ``method='hybr'`` in particular.

Notes
-----
``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms.

Examples
--------
Find a solution to the system of equations:
``x0*cos(x1) = 4,  x1*x0 - x1 = 5``.

>>> import numpy as np
>>> from scipy.optimize import fsolve
>>> def func(x):
...     return [x[0] * np.cos(x[1]) - 4,
...             x[1] * x[0] - x[1] - 5]
>>> root = fsolve(func, [1, 1])
>>> root
array([6.50409711, 0.90841421])
>>> np.isclose(func(root), [0.0, 0.0])  # func(root) should be almost 0.0.
array([ True,  True])

c                  8   > T=R                   S-  sl         T" U 6 $ )zK
Wrapped `func` to track the number of times
the function has been called.
r   )nfev)fargs_wrapped_funcfuncs    r7   r>   fsolve.<locals>._wrapped_func   s     
 	aU|r9   r   )	col_derivxtolmaxfevbandepsfactordiagjacx)r<   njevfjacrqtffunfvecstatusmessager   )            rR   
stacklevel)r<   
_root_hybrgetr*   warningswarnRuntimeWarning)r?   r/   r0   fprimefull_outputrA   rB   rC   rD   epsfcnrF   rG   optionsr3   rI   kinforP   r4   r>   s   `                  @r7   r!   r!   -   s%   V M%G ]B
D&
DG
DC!!CHHAOA#X 771:A 	 O5zV$Hs9~55X)nQ;C. q[
 3x	 |#MM#~!< 3x C. Os   	CCc                    [        U5        Un[        U5      R                  5       n[        U5      n[	        U[
        5      (       d  U4n[        SSXX-U45      u  pUc  [        U5      R                  nUnUc=  Uc  Su  nnOUSS u  nnUS:X  a  SUS-   -  n[        R                  " XUSXVUUXU
5      nO;[        SS	UXXU45        US:X  a  S
US-   -  n[        R                  " U UXSXEXiU
5
      nUS   US   nnSSSU-  SUS S3SSSS.nUS   nUR                  S5      US'   [        UUS:H  USS9nUR                  U5         UU   US'   U$ ! [         a    US   US'    U$ f = f)a  
Find the roots of a multivariate function using MINPACK's hybrd and
hybrj routines (modified Powell method).

Options
-------
col_deriv : bool
    Specify whether the Jacobian function computes derivatives down
    the columns (faster, because there is no transpose operation).
xtol : float
    The calculation will terminate if the relative error between two
    consecutive iterates is at most `xtol`.
maxfev : int
    The maximum number of calls to the function. If zero, then
    ``100*(N+1)`` is the maximum where N is the number of elements
    in `x0`.
band : tuple
    If set to a two-sequence containing the number of sub- and
    super-diagonals within the band of the Jacobi matrix, the
    Jacobi matrix is considered banded (only for ``jac=None``).
eps : float
    A suitable step length for the forward-difference
    approximation of the Jacobian (for ``jac=None``). If
    `eps` is less than the machine precision, it is assumed
    that the relative errors in the functions are of the order of
    the machine precision.
factor : float
    A parameter determining the initial step bound
    (``factor * || diag * x||``). Should be in the interval
    ``(0.1, 100)``.
diag : sequence
    N positive entries that serve as a scale factors for the
    variables.

r!   r?   N)rd   rR   r      r   r]   d   z'Improper input parameters were entered.zThe solution converged.z8The number of calls to function has reached maxfev = %d.xtol=fzO is too small, no further improvement in the approximate
 solution is possible.ztThe iteration is not making good progress, as measured by the 
 improvement from the last five Jacobian evaluations.ziThe iteration is not making good progress, as measured by the 
 improvement from the last ten iterations.zAn error occurred.)r   r   rR   rS   rT   rU   unknownrO   rN   hybr)rI   successrP   methodrQ   rj   )r   r   flattenr(   
isinstancetupler8   r   rE   r   _hybrd_hybrjpopr   updateKeyError)r?   r/   r0   rH   rA   rB   rC   rD   rE   rF   rG   unknown_optionsr_   nr   r   DfunmlmuretvalrI   rP   errorsrb   sols                            r7   rX   rX      s   L ?+F				BBAdE""wx4QDILE~u!!D|<FB"1XFBQ;AE]F4D!#R? 	Hhbq6BaKAE]FtRq!*&$H q	6":vA:*)+12a !? ?*$ ./F !9D((6"DK
1v{F &(CJJt+I J  +	*IJ+s   E E'&E'r   rR   rS   rT   )rU            Fc                    [        U5      R                  5       n[        U5      n[        U[        5      (       d  U4n[        SSXX-5      u  pUS   nUU:  a  [        SU SU 35      eU
c  [        U5      R                  n
Uc*  U	S:X  a  SUS-   -  n	[        R                  " XX$XgXXU5      nOTU(       a  [        SS	X1X-UU45        O[        SS	X1X-UU45        U	S:X  a  S
US-   -  n	[        R                  " XXUXVXxU	X5      nS[        /SUS 3S/SUS 3S/SUS SUS 3S/SUS S3S/SU	-  [        /SUS S3[        /SUS S3[        /SUS S3[        /S.	nUS   nU(       a  SnU[        ;   a  US   S   n[        U5      n[        [        US   S   5      SU2SS24   5      n[         R"                  " SU45      n U" U5      u  nnUS:w  a  [%        SU 35      eUR'                  5       UU'   UUR(                  -  nUS   U4USS -   UU   S   U4-   $ U[*        ;   a!  [,        R.                  " UU   S   [0        SS 9  OUS:X  a  UU   S   " UU   S   5      eUS   U4$ ! [$        [        4 a     Nvf = f)!a5  
Minimize the sum of squares of a set of equations.

::

    x = arg min(sum(func(y)**2,axis=0))
             y

Parameters
----------
func : callable
    Should take at least one (possibly length ``N`` vector) argument and
    returns ``M`` floating point numbers. It must not return NaNs or
    fitting might fail. ``M`` must be greater than or equal to ``N``.
x0 : ndarray
    The starting estimate for the minimization.
args : tuple, optional
    Any extra arguments to func are placed in this tuple.
Dfun : callable, optional
    A function or method to compute the Jacobian of func with derivatives
    across the rows. If this is None, the Jacobian will be estimated.
full_output : bool, optional
    If ``True``, return all optional outputs (not just `x` and `ier`).
col_deriv : bool, optional
    If ``True``, specify that the Jacobian function computes derivatives
    down the columns (faster, because there is no transpose operation).
ftol : float, optional
    Relative error desired in the sum of squares.
xtol : float, optional
    Relative error desired in the approximate solution.
gtol : float, optional
    Orthogonality desired between the function vector and the columns of
    the Jacobian.
maxfev : int, optional
    The maximum number of calls to the function. If `Dfun` is provided,
    then the default `maxfev` is 100*(N+1) where N is the number of elements
    in x0, otherwise the default `maxfev` is 200*(N+1).
epsfcn : float, optional
    A variable used in determining a suitable step length for the forward-
    difference approximation of the Jacobian (for Dfun=None).
    Normally the actual step length will be sqrt(epsfcn)*x
    If epsfcn is less than the machine precision, it is assumed that the
    relative errors are of the order of the machine precision.
factor : float, optional
    A parameter determining the initial step bound
    (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
diag : sequence, optional
    N positive entries that serve as a scale factors for the variables.

Returns
-------
x : ndarray
    The solution (or the result of the last iteration for an unsuccessful
    call).
cov_x : ndarray
    The inverse of the Hessian. `fjac` and `ipvt` are used to construct an
    estimate of the Hessian. A value of None indicates a singular matrix,
    which means the curvature in parameters `x` is numerically flat. To
    obtain the covariance matrix of the parameters `x`, `cov_x` must be
    multiplied by the variance of the residuals -- see curve_fit. Only
    returned if `full_output` is ``True``.
infodict : dict
    a dictionary of optional outputs with the keys:

    ``nfev``
        The number of function calls
    ``fvec``
        The function evaluated at the output
    ``fjac``
        A permutation of the R matrix of a QR
        factorization of the final approximate
        Jacobian matrix, stored column wise.
        Together with ipvt, the covariance of the
        estimate can be approximated.
    ``ipvt``
        An integer array of length N which defines
        a permutation matrix, p, such that
        fjac*p = q*r, where r is upper triangular
        with diagonal elements of nonincreasing
        magnitude. Column j of p is column ipvt(j)
        of the identity matrix.
    ``qtf``
        The vector (transpose(q) * fvec).

    Only returned if `full_output` is ``True``.
mesg : str
    A string message giving information about the cause of failure.
    Only returned if `full_output` is ``True``.
ier : int
    An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
    found. Otherwise, the solution was not found. In either case, the
    optional output variable 'mesg' gives more information.

See Also
--------
least_squares : Newer interface to solve nonlinear least-squares problems
    with bounds on the variables. See ``method='lm'`` in particular.

Notes
-----
"leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms.

cov_x is a Jacobian approximation to the Hessian of the least squares
objective function.
This approximation assumes that the objective function is based on the
difference between some observed target data (ydata) and a (non-linear)
function of the parameters `f(xdata, params)` ::

       func(params) = ydata - f(xdata, params)

so that the objective function is ::

       min   sum((ydata - f(xdata, params))**2, axis=0)
     params

The solution, `x`, is always a 1-D array, regardless of the shape of `x0`,
or whether `x0` is a scalar.

Examples
--------
>>> from scipy.optimize import leastsq
>>> def func(x):
...     return 2*(x-3)**2+1
>>> leastsq(func, 0)
(array([2.99999999]), 1)

r"   r?   r   z+Improper input: func input vector length N=z- must not exceed func output vector length M=Nre   r   rx   rf   zImproper input parameters.zRBoth actual and predicted relative reductions in the sum of squares
  are at most ri   z?The relative error between two consecutive iterates is at most zG and the relative error between two consecutive iterates is at 
  most zTThe cosine of the angle between func(x) and any column of the
  Jacobian is at most z in absolute valuez4Number of calls to function has reached maxfev = %d.zftol=zH is too small, no further reduction in the sum of squares
  is possible.rh   zP is too small, no further improvement in the approximate
  solution is possible.zgtol=z[ is too small, func(x) is orthogonal to the columns of
  the Jacobian to machine precision.)	r   r   rR   rS   rT   rU   r   r   r   rg   ipvtrK   trtriztrtri returned info rR   rV   )r   rn   r(   ro   rp   r8   r*   r   rE   r   _lmdif_lmder
ValueErrorLEASTSQ_SUCCESSr   r   r   get_lapack_funcsr   copyTLEASTSQ_FAILURErZ   r[   r\   )r?   r/   r0   rx   r^   rA   ftolrB   gtolrC   r_   rF   rG   rw   r   r   mr{   r|   rb   cov_xpermrL   inv_triuinvR
trtri_infos                             r7   r"   r"   #  sn   D 
			BBAdE""wy&$DDLEaA1uEaS ICCD#G H 	H ~u!!|Q;!a%[F4d!%vtE 	64Tq!fE	64Tq!fEQ;AE]FR{!*$f!'/ /	:::>qCDHJ))-a237977;Ah ?--1!H6 8<=::>q B##$(*!#)*+57$q ": : $q "= = $q "E EFPR)SF0 ":D?" !9V$DD	AYvay01"1"a%89A..w=H#+A; j?%(<ZL&IJJ!YY[T
tvv q	5!F1RL0F4LOT3JJJ?"MM&,q/>aHQY,q/&,q/22ay$  , s   AI' 'I:9I:c                 B   ^ ^ UU 4S jmS Tl         S Tl        STl        T$ )Nc                 8  > TR                   (       a  T" U 5      $ [        R                  " TR                  U :H  5      (       a  TR                  $ TR                  b  STl         T" U 5      nTR                  c"  [        R
                  " U 5      Tl        UTl        U$ )NT)skip_lookupnpalllast_paramslast_valr   )paramsval_memoized_funcri   s     r7   r   -_lightweight_memoizer.<locals>._memoized_func  s    %%V966.,,677!***''3)-N&i%%-)+N&&)N#
r9   F)r   r   r   )ri   r   s   `@r7   _lightweight_memoizerr     s(    " "&N"N!&Nr9   c                    ^ ^^^ Tc
  U UU4S jnU$ TR                   S:X  d  TR                  S:X  a  U UUU4S jnU$ U UUU4S jnU$ )Nc                    > T" T/U Q76 T-
  $ N )r   r?   xdataydatas    r7   func_wrapped _wrap_func.<locals>.func_wrapped  s    ''%//r9   r   c                 "   > TT" T/U Q76 T-
  -  $ r   r   r   r?   	transformr   r   s    r7   r   r     s    U 4V 4u <==r9   c                 .   > [        TT" T/U Q76 T-
  SS9$ NTlower)r   r   s    r7   r   r   (  s"    #ItE/CF/Ce/KSWXXr9   )sizendim)r?   r   r   r   r   s   ```` r7   
_wrap_funcr     sS    	0   
1		! 3	> 	> 	Y 	Yr9   c                 h   ^ ^^ Tc	  U U4S jnU$ TR                   S:X  a
  U UU4S jnU$ U UU4S jnU$ )Nc                    > T" T/U Q76 $ r   r   )r   rH   r   s    r7   jac_wrapped_wrap_jac.<locals>.jac_wrapped/  s    u&v&&r9   r   c                 n   > TS S 2[         R                  4   [         R                  " T" T/U Q76 5      -  $ r   )r   newaxisr   r   rH   r   r   s    r7   r   r   2  s.    Q

]+bjjU9LV9L.MMMr9   c           	      P   > [        T[        R                  " T" T/U Q76 5      SS9$ r   )r   r   r   r   s    r7   r   r   5  s+    #I$&JJs5/B6/B$C*.0 0r9   )r   )rH   r   r   r   s   ``` r7   	_wrap_jacr   -  s?    	'  
1		N 		0 r9   c                     [         R                  " U 5      n[         R                  " U 5      n[         R                  " U5      nX4-  nSX   X   -   -  X%'   X4) -  nX   S-   X%'   U) U-  nX   S-
  X%'   U$ )N      ?r   )r   	ones_likeisfinite)lbubp0	lb_finite	ub_finitemasks         r7   _initialize_feasibler   <  s|    	b	BBIBI Dbh)*BHz!Dx!|BH:	!Dx!|BHIr9   )r^   
nan_policyc
                ~   Uc@  [        U 5      nUR                  n[        U5      S:  a  [        S5      e[        U5      S-
  nO"[        R
                  " U5      nUR                  n[        U[        5      (       a  UR                  UR                  nnO[        X5      u  nnUc  [        UU5      n[        R                  " U[        R                  * :  U[        R                  :  -  5      nUc  U(       a  SnOSnUS:X  a  U(       a  [        S5      eUc  Uc  SOS	nU(       a  [        R                  " U[         5      nO[        R"                  " U[         5      n[        U[$        [&        [        R(                  45      (       a>  U(       a  [        R                  " U[         5      nO[        R"                  " U[         5      nUR                  S
:X  a  [        S5      eU(       Gd  UGb  US:X  a  [        S5      e/ SQn[+        XUS9u  nn[+        X+US9u  nnU(       d  U(       a  US:X  a  [        R,                  " U5      nUR                  ['        [/        UR0                  S-
  5      5      S9nU[        R,                  " U5      -  nUSU) 4   nUU)    nUbQ  [        R"                  " U5      nUR0                  S:X  a  UU)    nO$UR0                  S:X  a  UU) SS24   nUSS2U) 4   nUb  [        R"                  " U5      nUR                  S:X  d  UR2                  UR                  4:X  a  SU-  nO?UR2                  UR                  UR                  4:X  a   [5        USS9nO[        S5      eSn[9        [;        XUU5      5      n[=        U	5      (       a  [9        [?        XU5      5      n	OU	c  US:w  a  Sn	SU;   a  [        S5      eUS:X  a  UR                  S:w  a*  XR                  :  a  [A        SU SUR                   35      e[C        UU4U	SS.UD6nUu  nnnnn[        US   5      n [        RD                  " US   S-  5      n!US;  a  [G        SU-   5      eGOZS U;  a  URI                  S!S5      US '   [K        UU4XUS".UD6nURL                  (       d  [G        SURN                  -   5      e[Q        URR                  URT                  S#9nURV                  nURN                  n[        URT                  5      n SURX                  -  n!URZ                  n[]        UR^                  S	S$9u  n"n#n$[        R`                  " [         5      Rb                  [e        UR^                  R2                  5      -  U#S
   -  n%U#U#U%:     n#U$SU#R                   n$[        Rf                  " U$Rh                  U#S-  -  U$5      nS	n&Ub)  [        R,                  " U5      R                  5       (       a:  [k        [        U5      [        U5      4[         S%9nURm                  [        5        Sn&OFU(       d?  U UR                  :  a  U!U UR                  -
  -  n'UU'-  nOURm                  [        5        Sn&U&(       a  [n        Rp                  " S&[r        SS'9  U
(       a  UUUUU4$ UU4$ ! [6         a  n[        S5      UeSnAff = f)(a/  
Use non-linear least squares to fit a function, f, to data.

Assumes ``ydata = f(xdata, *params) + eps``.

Parameters
----------
f : callable
    The model function, f(x, ...). It must take the independent
    variable as the first argument and the parameters to fit as
    separate remaining arguments.
xdata : array_like
    The independent variable where the data is measured.
    Should usually be an M-length sequence or an (k,M)-shaped array for
    functions with k predictors, and each element should be float
    convertible if it is an array like object.
ydata : array_like
    The dependent data, a length M array - nominally ``f(xdata, ...)``.
p0 : array_like, optional
    Initial guess for the parameters (length N). If None, then the
    initial values will all be 1 (if the number of parameters for the
    function can be determined using introspection, otherwise a
    ValueError is raised).
sigma : None or scalar or M-length sequence or MxM array, optional
    Determines the uncertainty in `ydata`. If we define residuals as
    ``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma`
    depends on its number of dimensions:

    - A scalar or 1-D `sigma` should contain values of standard deviations of
      errors in `ydata`. In this case, the optimized function is
      ``chisq = sum((r / sigma) ** 2)``.

    - A 2-D `sigma` should contain the covariance matrix of
      errors in `ydata`. In this case, the optimized function is
      ``chisq = r.T @ inv(sigma) @ r``.

      .. versionadded:: 0.19

    None (default) is equivalent of 1-D `sigma` filled with ones.
absolute_sigma : bool, optional
    If True, `sigma` is used in an absolute sense and the estimated parameter
    covariance `pcov` reflects these absolute values.

    If False (default), only the relative magnitudes of the `sigma` values matter.
    The returned parameter covariance matrix `pcov` is based on scaling
    `sigma` by a constant factor. This constant is set by demanding that the
    reduced `chisq` for the optimal parameters `popt` when using the
    *scaled* `sigma` equals unity. In other words, `sigma` is scaled to
    match the sample variance of the residuals after the fit. Default is False.
    Mathematically,
    ``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)``
check_finite : bool, optional
    If True, check that the input arrays do not contain nans of infs,
    and raise a ValueError if they do. Setting this parameter to
    False may silently produce nonsensical results if the input arrays
    do contain nans. Default is True if `nan_policy` is not specified
    explicitly and False otherwise.
bounds : 2-tuple of array_like or `Bounds`, optional
    Lower and upper bounds on parameters. Defaults to no bounds.
    There are two ways to specify the bounds:

    - Instance of `Bounds` class.

    - 2-tuple of array_like: Each element of the tuple must be either
      an array with the length equal to the number of parameters, or a
      scalar (in which case the bound is taken to be the same for all
      parameters). Use ``np.inf`` with an appropriate sign to disable
      bounds on all or some parameters.

method : {'lm', 'trf', 'dogbox'}, optional
    Method to use for optimization. See `least_squares` for more details.
    Default is 'lm' for unconstrained problems and 'trf' if `bounds` are
    provided. The method 'lm' won't work when the number of observations
    is less than the number of variables, use 'trf' or 'dogbox' in this
    case.

    .. versionadded:: 0.17
jac : callable, string or None, optional
    Function with signature ``jac(x, ...)`` which computes the Jacobian
    matrix of the model function with respect to parameters as a dense
    array_like structure. It will be scaled according to provided `sigma`.
    If None (default), the Jacobian will be estimated numerically.
    String keywords for 'trf' and 'dogbox' methods can be used to select
    a finite difference scheme, see `least_squares`.

    .. versionadded:: 0.18
full_output : boolean, optional
    If True, this function returns additional information: `infodict`,
    `mesg`, and `ier`.

    .. versionadded:: 1.9
nan_policy : {'raise', 'omit', None}, optional
    Defines how to handle when input contains nan.
    The following options are available (default is None):

    * 'raise': throws an error
    * 'omit': performs the calculations ignoring nan values
    * None: no special handling of NaNs is performed
      (except what is done by check_finite); the behavior when NaNs
      are present is implementation-dependent and may change.

    Note that if this value is specified explicitly (not None),
    `check_finite` will be set as False.

    .. versionadded:: 1.11
**kwargs
    Keyword arguments passed to `leastsq` for ``method='lm'`` or
    `least_squares` otherwise.

Returns
-------
popt : array
    Optimal values for the parameters so that the sum of the squared
    residuals of ``f(xdata, *popt) - ydata`` is minimized.
pcov : 2-D array
    The estimated approximate covariance of popt. The diagonals provide
    the variance of the parameter estimate. To compute one standard
    deviation errors on the parameters, use
    ``perr = np.sqrt(np.diag(pcov))``. Note that the relationship between
    `cov` and parameter error estimates is derived based on a linear
    approximation to the model function around the optimum [1]_.
    When this approximation becomes inaccurate, `cov` may not provide an
    accurate measure of uncertainty.

    How the `sigma` parameter affects the estimated covariance
    depends on `absolute_sigma` argument, as described above.

    If the Jacobian matrix at the solution doesn't have a full rank, then
    'lm' method returns a matrix filled with ``np.inf``, on the other hand
    'trf'  and 'dogbox' methods use Moore-Penrose pseudoinverse to compute
    the covariance matrix. Covariance matrices with large condition numbers
    (e.g. computed with `numpy.linalg.cond`) may indicate that results are
    unreliable.
infodict : dict (returned only if `full_output` is True)
    a dictionary of optional outputs with the keys:

    ``nfev``
        The number of function calls. Methods 'trf' and 'dogbox' do not
        count function calls for numerical Jacobian approximation,
        as opposed to 'lm' method.
    ``fvec``
        The residual values evaluated at the solution, for a 1-D `sigma`
        this is ``(f(x, *popt) - ydata)/sigma``.
    ``fjac``
        A permutation of the R matrix of a QR
        factorization of the final approximate
        Jacobian matrix, stored column wise.
        Together with ipvt, the covariance of the
        estimate can be approximated.
        Method 'lm' only provides this information.
    ``ipvt``
        An integer array of length N which defines
        a permutation matrix, p, such that
        fjac*p = q*r, where r is upper triangular
        with diagonal elements of nonincreasing
        magnitude. Column j of p is column ipvt(j)
        of the identity matrix.
        Method 'lm' only provides this information.
    ``qtf``
        The vector (transpose(q) * fvec).
        Method 'lm' only provides this information.

    .. versionadded:: 1.9
mesg : str (returned only if `full_output` is True)
    A string message giving information about the solution.

    .. versionadded:: 1.9
ier : int (returned only if `full_output` is True)
    An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
    found. Otherwise, the solution was not found. In either case, the
    optional output variable `mesg` gives more information.

    .. versionadded:: 1.9

Raises
------
ValueError
    if either `ydata` or `xdata` contain NaNs, or if incompatible options
    are used.

RuntimeError
    if the least-squares minimization fails.

OptimizeWarning
    if covariance of the parameters can not be estimated.

See Also
--------
least_squares : Minimize the sum of squares of nonlinear functions.
scipy.stats.linregress : Calculate a linear least squares regression for
                         two sets of measurements.

Notes
-----
Users should ensure that inputs `xdata`, `ydata`, and the output of `f`
are ``float64``, or else the optimization may return incorrect results.

With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm
through `leastsq`. Note that this algorithm can only deal with
unconstrained problems.

Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to
the docstring of `least_squares` for more information.

Parameters to be fitted must have similar scale. Differences of multiple
orders of magnitude can lead to incorrect results. For the 'trf' and
'dogbox' methods, the `x_scale` keyword argument can be used to scale
the parameters.

References
----------
.. [1] K. Vugrin et al. Confidence region estimation techniques for nonlinear
       regression in groundwater flow: Three case studies. Water Resources
       Research, Vol. 43, W03423, :doi:`10.1029/2005WR004804`

Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.optimize import curve_fit

>>> def func(x, a, b, c):
...     return a * np.exp(-b * x) + c

Define the data to be fit with some noise:

>>> xdata = np.linspace(0, 4, 50)
>>> y = func(xdata, 2.5, 1.3, 0.5)
>>> rng = np.random.default_rng()
>>> y_noise = 0.2 * rng.normal(size=xdata.size)
>>> ydata = y + y_noise
>>> plt.plot(xdata, ydata, 'b-', label='data')

Fit for the parameters a, b, c of the function `func`:

>>> popt, pcov = curve_fit(func, xdata, ydata)
>>> popt
array([2.56274217, 1.37268521, 0.47427475])
>>> plt.plot(xdata, func(xdata, *popt), 'r-',
...          label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

Constrain the optimization to the region of ``0 <= a <= 3``,
``0 <= b <= 1`` and ``0 <= c <= 0.5``:

>>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
>>> popt
array([2.43736712, 1.        , 0.34463856])
>>> plt.plot(xdata, func(xdata, *popt), 'g--',
...          label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))

>>> plt.xlabel('x')
>>> plt.ylabel('y')
>>> plt.legend()
>>> plt.show()

For reliable results, the model `func` should not be overparametrized;
redundant parameters can cause unreliable covariance matrices and, in some
cases, poorer quality fits. As a quick check of whether the model may be
overparameterized, calculate the condition number of the covariance matrix:

>>> np.linalg.cond(pcov)
34.571092161547405  # may vary

The value is small, so it does not raise much concern. If, however, we were
to add a fourth parameter ``d`` to `func` with the same effect as ``a``:

>>> def func2(x, a, b, c, d):
...     return a * d * np.exp(-b * x) + c  # a and d are redundant
>>> popt, pcov = curve_fit(func2, xdata, ydata)
>>> np.linalg.cond(pcov)
1.13250718925596e+32  # may vary

Such a large value is cause for concern. The diagonal elements of the
covariance matrix, which is related to uncertainty of the fit, gives more
information:

>>> np.diag(pcov)
array([1.48814742e+29, 3.78596560e-02, 5.39253738e-03, 2.76417220e+28])  # may vary

Note that the first and last terms are much larger than the other elements,
suggesting that the optimal values of these parameters are ambiguous and
that only one of these parameters is needed in the model.

If the optimal parameters of `f` differ by multiple orders of magnitude, the
resulting fit can be inaccurate. Sometimes, `curve_fit` can fail to find any
results:

>>> ydata = func(xdata, 500000, 0.01, 15)
>>> try:
...     popt, pcov = curve_fit(func, xdata, ydata, method = 'trf')
... except RuntimeError as e:
...     print(e)
Optimal parameters not found: The maximum number of function evaluations is
exceeded.

If parameter scale is roughly known beforehand, it can be defined in
`x_scale` argument:

>>> popt, pcov = curve_fit(func, xdata, ydata, method = 'trf',
...                        x_scale = [1000, 1, 1])
>>> popt
array([5.00000000e+05, 1.00000000e-02, 1.49999999e+01])
NrR   z-Unable to determine number of fit parameters.r   trflmzQMethod 'lm' only works for unconstrained problems. Use 'trf' or 'dogbox' instead.TFr   z`ydata` must not be empty!	propagatez;`nan_policy='propagate'` is not supported by this function.)Nraiseomit)policiesr   axis.g      ?r   z"`sigma` must be positive definite.z`sigma` has incorrect shape.z2-pointr0   z+'args' is not a supported keyword argument.zThe number of func parameters=z+ must not exceed the number of data points=)rx   r^   rO   r~   zOptimal parameters not found: max_nfevrC   )rH   boundsrm   )r<   rO   )full_matrices)r   z3Covariance of the parameters could not be estimated)categoryrW   ):_getfullargspecr0   r(   r   r   r   r   ro   r    r   r   r   r   anyr   asarray_chkfiniter+   r   listrp   ndarrayr   isnanranger   r   r   r   r   r   callabler   r*   r"   sumRuntimeErrorrs   r   rl   rQ   dictr<   rN   rP   costrI   r   rH   r   rE   maxdotr   r	   fillrZ   r[   r   )(ri   r   r   r   sigmaabsolute_sigmacheck_finiter   rm   rH   r^   r   kwargssigr0   rw   r   r   bounded_problemr   x_contains_nany_contains_nanhas_nanr   er?   r3   poptpcovinfodicterrmsgierysizer   _sVT	thresholdwarn_covs_sqs(                                           r7   r$   r$   M  s   f	 
za xxt9q=LMMIM]]2GG&&!!FIIBB*B	z!"b)ffbBFF7lrBFF{;<O~FF~/ : ; 	; )1tu $$UE2

5%(%$rzz233 ((6EJJue,EzzQ566 J2$ 1 2 2 +%25<D&F"
%25<D&F"
 n*2FhhuoGkkuU7<<>-B'CkDGrxx&G#x-(E7(OE  

5)::?!7(OEZZ1_!7(A+.E!!gX+.E 

5! ::?ekkejj]:eI [[UZZ44N$U$7	 ;<<	 AeY!GHD}}#Ic)$DE	4 FGG~::?q::~<QC @AAFN O OdBBSaB6B,/)dHfcHV$%vvhv&!+,l"?&HII # V#!'Hd!;F:D" &#V &$& {{?#++MNNSXXCGG4jjCGG388|uu swwe41bHHUO''#cggmm*<<qtC	a)m[vvbddQTk2&H|rxx~))++c$iT+59		#277?5277?+D$;DIIcNHK.1	> T8VS00Tz]  N !EFAMNs   
Z! !
Z<+Z77Z<c                 H   [        U5      n[        U5      nUR                  U45      n[        U " U/UQ76 5      n[        U5      nUR                  U45      nUn	[        U" U/UQ76 5      n
U
R                  X45      n
US:X  a  [        U
5      n
[	        U4[
        5      n[	        U4[
        5      nSn[        R                  " XXWXXSU5
        [        U " U/UQ76 5      nUR                  U45      n[        R                  " XXWXXSU5
        [        [        US5      SS9nX4$ )z=Perform a simple check on the gradient for correctness.

    r   Nr   rR   r   r   )
r   r(   reshaper   r	   r+   r   _chkderr
   r   )fcnDfcnr/   r0   rA   rI   rw   rO   r   ldfjacrK   xperrfvecpgoods                  r7   check_gradientr  .  s   
 	2AAA			1$Ac!mdm$DD	A<<DFd1ntn%D<<DA~	tU	B
e
CEQ1D"QDs2~~&EMM1$EQ1D"QDc"+D;r9   c                 >    U [         R                  " X-
  5      U-  -
  $ r   )r   square)r   p1ds      r7   _del2r	  M  s    		"'"Q&&&r9   c                     X-
  U-  $ r   r   )actualdesireds     r7   _relerrr  Q  s    ''r9   c                 ^   Un[        U5       H  nU " U/UQ76 nU(       a*  U " U/UQ76 n	U	SU-  -
  U-   n
[        U
S:g  XhU
4[        U	S9nOUn[        US:g  X4[        US9n[        R
                  " [        R                  " U5      U:  5      (       a  Us  $ UnM     SUW4-  n[        U5      e)Ng       @r   )ri   	fillvaluez3Failed to converge after %d iterations, value is %s)r   r   r	  r  r   r   absr   )r?   r/   r0   rB   maxiter	use_accelr   ir  p2r  prelerrr4   s                 r7   _fixed_point_helperr  U  s    	B7^"_t_b4BS2X"A16BA;%2FAAB!GaW1E66"&&.4'((H  @7A,
NC
s
r9   c                 @    SSS.U   n[        USS9n[        XX#XF5      $ )a  
Find a fixed point of the function.

Given a function of one or more variables and a starting point, find a
fixed point of the function: i.e., where ``func(x0) == x0``.

Parameters
----------
func : function
    Function to evaluate.
x0 : array_like
    Fixed point of function.
args : tuple, optional
    Extra arguments to `func`.
xtol : float, optional
    Convergence tolerance, defaults to 1e-08.
maxiter : int, optional
    Maximum number of iterations, defaults to 500.
method : {"del2", "iteration"}, optional
    Method of finding the fixed-point, defaults to "del2",
    which uses Steffensen's Method with Aitken's ``Del^2``
    convergence acceleration [1]_. The "iteration" method simply iterates
    the function until convergence is detected, without attempting to
    accelerate the convergence.

References
----------
.. [1] Burden, Faires, "Numerical Analysis", 5th edition, pg. 80

Examples
--------
>>> import numpy as np
>>> from scipy import optimize
>>> def func(x, c1, c2):
...    return np.sqrt(c1/(x+c2))
>>> c1 = np.array([10,12.])
>>> c2 = np.array([3, 5.])
>>> optimize.fixed_point(func, [1.2, 1.3], args=(c1,c2))
array([ 1.4920333 ,  1.37228132])

TF)del2	iteration)
as_inexact)r   r  )r?   r/   r0   rB   r  rm   r  s          r7   r#   r#   g  s/    T E26:I	B4	0BtWHHr9   r   )
r   Nr   r   J P>r   NNrf   N)	r   Nr   r  r   NNrf   N)r   NFFr  r  g        r   Nrf   N)r   r   )r   g:0yE>i  r  ):rZ    r   numpyr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   scipyr   scipy.linalgr   r   r   r   scipy._lib._utilr   r   r   r   r   	_optimizer   r   r   _lsqr   _lsq.least_squaresr   scipy.optimize._minimizer    __all__r8   r!   rX   r   r   r"   r   r   r   r   r$   r  r	  r  r  r#   r   r9   r7   <module>r'     s      6 6 6 6  E E J J F N N  . +
; "0 898<)-Qh '+GK $[|  7<3=>BWt6*" #'d5"&&"&&(9$^',^B>'($,Ir9   