
    ^Mh                        d dl Z ddlmZ d dlZd dlmZmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZ d dlmZ d dlmZmZmZmZ d dlmZmZmZ d dlmZ dd	lm Z m!Z!m"Z" dd
l#m$Z$ ddl%m&Z& d dl'm(Z( g dZ)	 d'dZ*	 	 	 d(dZ+	 	 	 d)dZ,g dZ-g dZ.	 	 	 d*dZ/d Z0d Z1d Z2d Z3ddddej         ej        fddfddddZ4d+dZ5d  Z6d! Z7d" Z8d,d&Z9dS )-    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                    t           ||d |         f|z              }|t          |          |k    r|d         dk    rt          |          dk    r|d         dk    rt          |          S |  d| d}t          |dd           }	|	r
|d|	 dz  }n|dz  }|d	| d
t          |           dz  }t	          |          t          |j        t                    r|j        }
nt          t                    }
t          |          |
fS )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              Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_minpack_py.py_check_funcr8      s<   
WW:I:0479
:
:C uSzz\'A'AOq  <  1$$?a'' ::% 7 7#*7 7 7CT::I )I))))s
LlLLuSzzLLLLCC.. #)W%% Y5\\::r>     J P>d   c                      fdd_         |||||	|
|d}t          ||fd|i|j         _         |r3d         }fddD             }d         |d	<   ||d
         d         fS d
         }d         }|dk    rt          |          |dk    rn0|dv rt          j        |t
          d           nt          |          d         S )a  
    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                  .    xj         dz  c_          |  S )zc
        Wrapped `func` to track the number of times
        the function has been called.
        r   )nfev)fargs_wrapped_funcfuncs    r7   rA   zfsolve.<locals>._wrapped_func   s%    
 	atU|r9   r   )	col_derivxtolmaxfevbandepsfactordiagjacxc                 D    i | ]}|v |                     |          S r:   )get).0kr3   s     r7   
<dictcomp>zfsolve.<locals>.<dictcomp>   s8     O O OQ#XX 3771::EMXXr9   )r?   njevfjacrqtffunfvecstatusmessager   )            rY   
stacklevel)r?   
_root_hybrr*   warningswarnRuntimeWarning)rB   r/   r0   fprimefull_outputrC   rD   rE   rF   epsfcnrH   rI   optionsrK   inforW   r4   rA   r3   s   `                @@r7   r!   r!   -   sJ   V      M% G ]B
D
D&
DG
D
DC!CH HO O O OAO O O5zV$Hs9~55X)nQ;;C.. q[[|##M#~!<<<<<C.. 3xr9   c                 R   t          |           |}t          |                                          }t          |          }t	          |t
                    s|f}t          dd| ||||f          \  }}|t          |          j        }|}|B|d\  }}n|dd         \  }}|dk    rd|dz   z  }t          j
        | ||d||||||	|
          }nBt          dd	||||||f           |dk    rd
|dz   z  }t          j        | |||d||||	|

  
        }|d         |d         }}ddd|z  d|dddddd}|d         }|                    d          |d<   t          ||dk    |d          }|                    |           	 ||         |d<   n# t          $ r |d         |d<   Y nw xY w|S )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!   rB   N)ri   rY   r      r   rc   r<   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   rY   rZ   r[   r\   unknownrV   rU   hybr)rK   successrW   methodrX   rn   )r   r   flattenr(   
isinstancetupler8   r   rG   r   _hybrd_hybrjpopr   updateKeyError)rB   r/   r0   rJ   rC   rD   rE   rF   rG   rH   rI   unknown_optionsre   nr   r   DfunmlmuretvalrK   rW   errorsrg   sols                            r7   r_   r_      sC   L ?+++F					BBAdE"" wxr4QDIILE5~u!D|<FB"1"XFBQ;;AE]Fr4D&!#R? ? 	Hhb$Aq6BBBaKKAE]FtRq!*D&&$H H q	6":vA:*)+12?G ? ? ?*$ ./ /F !9D((6""DK
1v{F &( ( (CJJt+I + + +	*I+ Js    F F$#F$r   rY   rZ   r[   )r\            F        c                    t          |                                          }t          |          }t          |t                    s|f}t          dd| |||          \  }}|d         }||k    rt          d| d|           |
t          |          j        }
|-|	dk    rd|dz   z  }	t          j
        | |||||||	|
||          }n^|rt          dd	||||||f           nt          dd	||||||f           |	dk    rd
|dz   z  }	t          j        | |||||||||	||          }dt          gd|ddgd|ddgd|dd|ddgd|dddgd|	z  t          gd|ddt          gd|ddt          gd|ddt          gd	}|d         }|rd}|t          v r|d         d         }t          |          }t          t          |d         d                   d|ddf                   }t!          j        d|f          }	  ||          \  }}|dk    rt%          d|           |                                ||<   ||j        z  }n# t$          t          f$ r Y nw xY w|d         |f|dd         z   ||         d         |fz   S |t*          v r)t-          j        ||         d         t0          d            n)|dk    r# ||         d         ||         d                   |d         |fS )!a  
    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"   rB   r   z+Improper input: func input vector length N=z- must not exceed func output vector length M=Nrj   r   r|   r<   zImproper input parameters.zRBoth actual and predicted relative reductions in the sum of squares
  are at most rm   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.rl   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   rY   rZ   r[   r\   r   r   r   rk   ipvtrR   trtriztrtri returned info rY   r]   )r   rr   r(   rs   rt   r8   r*   r   rG   r   _lmdif_lmder
ValueErrorLEASTSQ_SUCCESSr   r   r   get_lapack_funcsr   copyTLEASTSQ_FAILUREr`   ra   rb   )rB   r/   r0   r|   rd   rC   ftolrD   gtolrE   re   rH   rI   r{   r   r   mr   r   rg   cov_xpermrS   inv_triuinvR
trtri_infos                             r7   r"   r"   #  s?   D 
				BBAdE"" wy&$D!DDLE5aA1uu Ga G GCDG G H H 	H ~u!|Q;;!a%[Fr4dD!%vvvtE E  	F	64T1q!fEEEE	64T1q!fEEEQ;;AE]FtR{!*D$f!'/ / /	:C:>BC CDHJ2)-12 237967;H6 6 .256 6 8<=#:>F# # #$(*!#)*+57:$F : : :=$K = = =E$N E E EFPR)S SF0 ":D ?"" !9V$DD		AYvay011"1"aaa%899A.w==H#+8A;; j??%&IZ&I&IJJJ!YY[[T
tv,   q	5!F1R4L0F4LOT3JJJ?""M&,q/>aHHHHHQYY!&,q/&,q/222ay$s   AI	 	IIc                 @      fdd _         d _        d_        S )Nc                     j         r |           S t          j        j        | k              rj        S j        d_          |           }j         t          j        |           _        |_        |S )NT)skip_lookupnpalllast_paramslast_valr   )paramsval_memoized_funcrm   s     r7   r   z-_lightweight_memoizer.<locals>._memoized_func  s    % 	1V996.,677 	.!**'3)-N&aii%-)+N&&)N#
r9   F)r   r   r   )rm   r   s   `@r7   _lightweight_memoizerr     sB         " "&N"N!&Nr9   c                 p      fd}n'j         dk    sj        dk    r	 fd}n fd}|S )Nc                      g| R  z
  S Nr:   )r   rB   xdataydatas    r7   func_wrappedz _wrap_func.<locals>.func_wrapped  s     4''''%//r9   r   c                 "     g| R  z
  z  S r   r:   r   rB   	transformr   r   s    r7   r   z _wrap_func.<locals>.func_wrapped  s%    U 4V 4 4 4u <==r9   c                 <    t           g| R  z
  d          S NTlower)r   r   s    r7   r   z _wrap_func.<locals>.func_wrapped(  s0    #IttE/CF/C/C/Ce/KSWXXXXr9   )sizendim)rB   r   r   r   r   s   ```` r7   
_wrap_funcr     s    	0 	0 	0 	0 	0 	0 	0 	0	1			! 3 3	> 	> 	> 	> 	> 	> 	> 	> 	>	Y 	Y 	Y 	Y 	Y 	Y 	Y 	Yr9   c                 R      fd}nj         dk    r fd}n fd}|S )Nc                      g| R  S r   r:   )r   rJ   r   s    r7   jac_wrappedz_wrap_jac.<locals>.jac_wrapped/  s    3u&v&&&&r9   r   c                 h    d d t           j        f         t          j         g| R            z  S r   )r   newaxisr   r   rJ   r   r   s    r7   r   z_wrap_jac.<locals>.jac_wrapped2  s9    QQQ
]+bjU9LV9L9L9L.M.MMMr9   c           	      Z    t          t          j         g| R            d          S r   )r   r   r   r   s    r7   r   z_wrap_jac.<locals>.jac_wrapped5  s>    #I$&Jss5/B6/B/B/B$C$C*.0 0 0 0r9   )r   )rJ   r   r   r   s   ``` r7   	_wrap_jacr   -  s    	' 	' 	' 	' 	' 	' 	'	1			N 	N 	N 	N 	N 	N 	N 	N	0 	0 	0 	0 	0 	0 	0 r9   c                    t          j        |           }t          j        |           }t          j        |          }||z  }d| |         ||         z   z  ||<   || z  }| |         dz   ||<   | |z  }||         dz
  ||<   |S )N      ?r   )r   	ones_likeisfinite)lbubp0	lb_finite	ub_finitemasks         r7   _initialize_feasibler   <  s    	b		BBIBIy DbhD)*BtH	z!D$x!|BtH:	!D$x!|BtHIr9   )rd   
nan_policyc
                    |Kt          |           }|j        }t          |          dk     rt          d          t          |          dz
  }nt	          j        |          }|j        }t          |t                    r|j	        |j
        }}nt          ||          \  }}|t          ||          }t	          j        |t          j         k    |t          j        k     z            }||rd}nd}|dk    r|rt          d          ||dnd	}|rt	          j        |t                     }nt	          j        |t                     }t          |t$          t&          t          j        f          r7|rt	          j        |t                     }nt	          j        |t                     }|j        d
k    rt          d          |s||dk    rt          d          g d}t+          |||          \  }}t+          |||          \  }}|s|r|dk    rt	          j        |          }|                    t'          t/          |j        dz
                                }|t	          j        |          z  }|d| f         }||          }|Nt	          j        |          }|j        dk    r
||          }n%|j        dk    r|| ddf         }|dd| f         }|t	          j        |          }|j        dk    s|j        |j        fk    rd|z  }n]|j        |j        |j        fk    r5	 t5          |d          }n3# t6          $ r}t          d          |d}~ww xY wt          d          d}t9          t;          | |||                    }t=          |	          rt9          t?          |	||                    }	n
|	|dk    rd}	d|v rt          d          |dk    r|j        dk    r%||j        k    rtA          d| d|j                   tC          ||f|	dd|}|\  }}}}}t          |d                   } t	          j"        |d         dz            }!|dvrtG          d|z             n1d |vr|$                    d!d          |d <   tK          ||f|	||d"|}|j&        stG          d|j'        z             tQ          |j)        |j*        #          }|j+        }|j'        }t          |j*                  } d|j,        z  }!|j-        }t]          |j/        d	$          \  }"}#}$t	          j0        t                     j1        te          |j/        j                  z  |#d
         z  }%|#|#|%k             }#|$d|#j                 }$t	          j3        |$j4        |#dz  z  |$          }d	}&|&t	          j        |                                          rOtk          t          |          t          |          ft           %          }|6                    t                     d}&n<|s:| |j        k    r|!| |j        z
  z  }'||'z  }n|6                    t                     d}&|&rto          j8        d&tr          d'           |
r|||||fS ||fS )(a2  
    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])
    NrY   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=)r|   rd   rV   r   zOptimal parameters not found: max_nfevrE   )rJ   boundsrq   )r?   rV   )full_matrices)r   z3Covariance of the parameters could not be estimated)categoryr^   ):_getfullargspecr0   r(   r   r   r   r   rs   r    r   r   r   r   anyr   asarray_chkfiniter+   r   listrt   ndarrayr   isnanranger   r   r   r   r   r   callabler   r*   r"   sumRuntimeErrorrw   r   rp   rX   dictr?   rU   rW   costrK   r   rJ   r   rG   maxdotr   r	   fillr`   ra   r   )(rm   r   r   r   sigmaabsolute_sigmacheck_finiter   rq   rJ   rd   r   kwargssigr0   r{   r   r   bounded_problemr   x_contains_nany_contains_nanhas_nanr   erB   r3   poptpcovinfodicterrmsgierysizer   _sVT	thresholdwarn_covs_sqs(                                           r7   r$   r$   M  s8   f	 
za  xt99q==LMMMIIM]2G&&!! +FIB**B	z!"b))fbBF7lrBF{;<<O~ 	FFF~~/~ : ; ; 	; )1ttu  )$UE22
5%((%$rz233 -  	-(66EEJue,,EzQ5666  /J2$$ 1 2 2 2 +**%25*<D&F &F &F"
%25*<D&F &F &F"
  	/n 	/*2F2FhuooGkkuU7<>-B-B'C'CkDDGrx&G#x-(E7(OE  
5)):??!7(OEEZ1__!7(AAA+.E!!!!gX+.E 
5!! :??ekej]::eII [UZ444N$U$777		 N N N !EFFAMN ;<<<	 AueY!G!GHHD}} #Ic5)$D$DEE	4 FGGG~~:??q5:~~ NQ N NAFN N O O OdBBSaBB6BB,/)dHfcHV$%%vhv&!+,,l""?&HIII # V##!'Hd!;!;F:D" &#fV & &$& & { 	O?#+MNNNSXCG444jCG38|u swe4441bHUOO'#cgm*<*<<qtC	a)m[vbdQTk2&&H|rx~~))++|c$iiT+5999		# 27??527?+D$;DDIIcNNNH >K.1	> 	> 	> 	>  T8VS00Tzs   'L9 9
MMMc                    t          |          }t          |          }|                    |f          }t           | |g|R            }t          |          }|                    |f          }|}	t           ||g|R            }
|
                    ||f          }
|dk    rt          |
          }
t	          |ft
                    }t	          |ft
                    }d}t          j        |||||
|	||d|
  
         t           | |g|R            }|                    |f          }t          j        |||||
|	||d|
  
         t          t          |d          d          }||fS )z=Perform a simple check on the gradient for correctness.

    r   Nr   rY   r   r   )
r   r(   reshaper   r	   r+   r   _chkderr
   r   )fcnDfcnr/   r0   rC   rK   r{   rV   r   ldfjacrR   xperrfvecpgoods                  r7   check_gradientr  .  sn   
 	2AAA			1$Acc!mdmmm$$DD		A<<DFdd1ntnnn%%D<<ADA~~	tU		B
e

CEQ1dD&"eQDDDss2~~~~&&EMM1$EQ1dD&"eQDDDc""+++D#;r9   c                 <    | t          j        || z
            |z  z
  S r   )r   square)r   p1ds      r7   _del2r
  M  s     	"r'""Q&&&r9   c                     | |z
  |z  S r   r:   )actualdesireds     r7   _relerrr  Q  s    W''r9   c                 t   |}t          |          D ]} | |g|R  }|r4 | |g|R  }	|	d|z  z
  |z   }
t          |
dk    |||
ft          |	          }n|}t          |dk    ||ft          |          }t	          j        t	          j        |          |k               r|c S |}d||fz  }t          |          )Ng       @r   )rm   	fillvaluez3Failed to converge after %d iterations, value is %s)r   r   r
  r  r   r   absr   )rB   r/   r0   rD   maxiter	use_accelr   ir  p2r	  prelerrr4   s                 r7   _fixed_point_helperr  U  s    	B7^^  T"_t___ 	b4BS2X"A16BA;%2FFFAAAB!GaW1EEE6"&..4'(( 	HHH
?7A,
NC
s

r9   :0yE>  del2c                 b    ddd|         }t          |d          }t          | |||||          S )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)r  	iteration)
as_inexact)r   r  )rB   r/   r0   rD   r  rq   r  s          r7   r#   r#   g  sA    T E226:I	B4	0	0	0BtRtWiHHHr9   r   )
r:   Nr   r   r;   r   NNr<   N)	r:   Nr   r;   r   NNr<   N)r:   NFFr;   r;   r   r   Nr<   N)r:   r   )r:   r  r  r  ):r`    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!   r_   r   r   r"   r   r   r   r   r$   r  r
  r  r  r#   r:   r9   r7   <module>r)     s             6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6       E E E E E E E E E E E E J J J J J J J J J J F F F F F F N N N N N N N N N N       . . . . . . + + + + + +
;
;
; "   0 898<)-Q Q Q Qh '+GK $[ [ [ [| ,,,, 7<3=>BW W W Wt  6  *    " #'d5"&"&(9$^',^ ^ ^ ^ ^B   >' ' '( ( (  $,I ,I ,I ,I ,I ,Ir9   