
    doi                     J   S SK r S SKrS SKrS SKrS SKJrJrJr  S SKJ	r	J
r
JrJrJrJr  S SKrS SKrS SKJr  S SKJrJr  S SKJr  SSKJrJr  S S	K Jr  S S
KJr  S SKJr  / SQr  " S S\!5      r"S r#S r$S r%S r&\'" \" S5      RQ                  5       \" S5      RQ                  5       S9r)S r*    S<S jr+\*" \+5          S=S jr, " S S5      r- " S S5      r. " S S5      r/S r0 " S  S!\.5      r1 " S" S#5      r2\" S$5      RQ                  5       \)S%'    " S& S'\15      r3 " S( S)\35      r4 " S* S+\15      r5 " S, S-\15      r6 " S. S/\15      r7 " S0 S1\15      r8 " S2 S3\.5      r9S4 r:\:" S5\35      r;\:" S6\45      r<\:" S7\55      r=\:" S8\75      r>\:" S9\65      r?\:" S:\85      r@\:" S;\95      rAg)>    N)asarraydotvdot)normsolveinvqrsvdLinAlgError)get_blas_funcs)copy_if_needed_dedent_for_py313)getfullargspec_no_self   )scalar_search_wolfe1scalar_search_armijo)	signature)get_close_matches)GenericAlias)broyden1broyden2andersonlinearmixingdiagbroydenexcitingmixingnewton_krylovBroydenFirstKrylovJacobianInverseJacobianNoConvergencec                       \ rS rSrSrSrg)r    !   zXException raised when nonlinear solver fails to converge within the specified
`maxiter`. N)__name__
__module____qualname____firstlineno____doc____static_attributes__r#       R/var/www/html/land-ocr/venv/lib/python3.13/site-packages/scipy/optimize/_nonlin.pyr    r    !   s
    r*   r    c                 J    [         R                  " U 5      R                  5       $ N)npabsolutemaxxs    r+   maxnormr3   '   s    ;;q>r*   c                     [        U 5      n [        R                  " U R                  [        R                  5      (       d  [        U [        R
                  S9$ U $ )z:Return `x` as an array, of either floats or complex floatsdtype)r   r.   
issubdtyper6   inexactfloat64r1   s    r+   _as_inexactr:   +   s:    
A=="**--q

++Hr*   c                     [         R                  " U [         R                  " U5      5      n [        USU R                  5      nU" U 5      $ )z;Return ndarray `x` as same array subclass and shape as `x0`__array_wrap__)r.   reshapeshapegetattrr<   )r2   x0wraps      r+   _array_likerB   3   s8    


1bhhrl#A2')9)9:D7Nr*   c                     [         R                  " U 5      R                  5       (       d$  [         R                  " [         R                  5      $ [        U 5      $ r-   )r.   isfiniteallarrayinfr   )vs    r+   
_safe_normrI   :   s5    ;;q>xx7Nr*   z
    F : function(x) -> f
        Function whose root to find; should take and return an array-like
        object.
    xin : array_like
        Initial guess for the solution
    a  
    iter : int, optional
        Number of iterations to make. If omitted (default), make as many
        as required to meet tolerances.
    verbose : bool, optional
        Print status to stdout on every iteration.
    maxiter : int, optional
        Maximum number of iterations to make. If more are needed to
        meet convergence, `NoConvergence` is raised.
    f_tol : float, optional
        Absolute tolerance (in max-norm) for the residual.
        If omitted, default is 6e-6.
    f_rtol : float, optional
        Relative tolerance for the residual. If omitted, not used.
    x_tol : float, optional
        Absolute minimum step size, as determined from the Jacobian
        approximation. If the step size is smaller than this, optimization
        is terminated as successful. If omitted, not used.
    x_rtol : float, optional
        Relative minimum step size. If omitted, not used.
    tol_norm : function(vector) -> scalar, optional
        Norm to use in convergence check. Default is the maximum norm.
    line_search : {None, 'armijo' (default), 'wolfe'}, optional
        Which type of a line search to use to determine the step size in the
        direction given by the Jacobian approximation. Defaults to 'armijo'.
    callback : function, optional
        Optional callback function. It is called on every iteration as
        ``callback(x, f)`` where `x` is the current solution and `f`
        the corresponding residual.

    Returns
    -------
    sol : ndarray
        An array (of similar array type as `x0`) containing the final solution.

    Raises
    ------
    NoConvergence
        When a solution was not found.

    )params_basicparams_extrac                 X    U R                   (       a  U R                   [        -  U l         g g r-   )r(   
_doc_parts)objs    r+   _set_docrO   x   s    
{{kkJ. r*   c           
      Z  ^ ^ U
c  [         OU
n
[        XgXX:S9n[        T5      mU U4S jnTR                  5       n[        R
                  " U[        R                  5      nU" U5      n[        U5      n[        U5      nUR                  UR                  5       UU5        Uc  Ub  US-   nOSUR                  S-   -  nUSL a  SnOUSL a  SnUS	;  a  [        S
5      eSnSnSnSn[        U5       GH^  nUR                  UUU5      nU(       a    GO`[        UUU-  5      nUR!                  UUS9* n[        U5      S:X  a  [        S5      eU(       a  [#        UUUUU5      u  nnnnOSnUU-   nU" U5      n[        U5      nUR%                  UR                  5       U5        U(       a	  U" UU5        UUS-  -  US-  -  nUUS-  -  U:  a  [        UU5      nO[        U['        UUUS-  -  5      5      nUnU(       d  GM  [(        R*                  R-                  U SU
" U5      S SUS S35        [(        R*                  R/                  5         GMa     U(       a  [1        [3        UT5      5      eSnU(       a)  UR4                  UUUS:H  SSS.U   S.n[3        UT5      U4$ [3        UT5      $ )a>  
Find a root of a function, in a way suitable for large-scale problems.

Parameters
----------
%(params_basic)s
jacobian : Jacobian
    A Jacobian approximation: `Jacobian` object or something that
    `asjacobian` can transform to one. Alternatively, a string specifying
    which of the builtin Jacobian approximations to use:

        krylov, broyden1, broyden2, anderson
        diagbroyden, linearmixing, excitingmixing

%(params_extra)s
full_output : bool
    If true, returns a dictionary `info` containing convergence
    information.
raise_exception : bool
    If True, a `NoConvergence` exception is raise if no solution is found.

See Also
--------
asjacobian, Jacobian

Notes
-----
This algorithm implements the inexact Newton method, with
backtracking or full line searches. Several Jacobian
approximations are available, including Krylov and Quasi-Newton
methods.

References
----------
.. [KIM] C. T. Kelley, "Iterative Methods for Linear and Nonlinear
   Equations". Society for Industrial and Applied Mathematics. (1995)
   https://archive.siam.org/books/kelley/fr16/

N)f_tolf_rtolx_tolx_rtoliterr   c                 V   > [        T" [        U T5      5      5      R                  5       $ r-   )r:   rB   flatten)zFr@   s    r+   funcnonlin_solve.<locals>.func   s#    1[B/0199;;r*   r   d   TarmijoF)Nr]   wolfezInvalid line searchg?gH.?g?gMbP?)tolr   z[Jacobian inversion yielded zero vector. This indicates a bug in the Jacobian approximation.      ?   z:  |F(x)| = gz; step 
z0A solution was found at the specified tolerance.z:The maximum number of iterations allowed has been reached.)r   ra   )nitfunstatussuccessmessage)r3   TerminationConditionr:   rW   r.   	full_likerG   r   
asjacobiansetupcopysize
ValueErrorrangecheckminr   _nonlin_line_searchupdater0   sysstdoutwriteflushr    rB   	iteration) rY   r@   jacobianrU   verbosemaxiterrQ   rR   rS   rT   tol_normline_searchcallbackfull_outputraise_exception	conditionrZ   r2   dxFxFx_normgammaeta_maxeta_tresholdetanrf   r_   sFx_norm_neweta_Ainfos    ``                              r+   nonlin_solver   }   s   Z #*wH$5+0*.?I 
RB<


A	a	 B	aB2hG(#HNN1668R&QhG166!8nGd		33.// EGL
C7^Q+ #s7{#nnRSn))8q= . / /
 $7aR8C%E!Aq"k ABAaBr(K"%QO Q&!336>L(gu%Cgs5%Q,78C 7JJs,x|A.>gaU"MNJJS V Ar 233F ** !Q; , 3 %	&		 1b!4''1b!!r*   c                 h  ^ ^^^^^^^^ S/mU/m[        U5      S-  /m[        T5      [        T5      -  mSUU UUUU4S jjmUUU4S jnUS:X  a  [        TUTS   SUS9u  pn
OUS:X  a  [        TTS   TS   * US	9u  pWc  S
nTUT-  -   mUTS   :X  a  TS   nOT " T5      n[        U5      nUTX+4$ )Nr   ra   c                    > U T	S   :X  a  TS   $ T
U T-  -   nT" U5      n[        U5      S-  nU(       a  U T	S'   UTS'   UTS'   U$ )Nr   ra   )rI   )r   storextrH   pr   rZ   tmp_Fxtmp_phitmp_sr2   s        r+   phi _nonlin_line_search.<locals>.phi  s_    a=1:2XHqM1E!HGAJF1Ir*   c                 V   > [        U 5      T-   S-   T-  nT" X-   SS9T" U 5      -
  U-  $ )Nr   F)r   )abs)r   dsr   rdiffs_norms     r+   derphi#_nonlin_line_search.<locals>.derphi%  s7    !fvo!U*AD&Q/255r*   r^   {Gz?)xtolaminr]   )r   r`   )T)r   r   r   )rZ   r2   r   r   search_typer   sminr   r   phi1phi0r   r   r   r   r   r   s   `` ` `      @@@@@r+   rs   rs     s    CETFBx{mG!WtBxF
 
6 g,S&'!*26TC		 &sGAJ,02 	y 	AbDAE!H}AY!W2hGar*   c                   4    \ rS rSrSrSSSSS\4S jrS rSrg)ri   i?  z
Termination condition for an iteration. It is terminated if

- |F| < f_rtol*|F_0|, AND
- |F| < f_tol

AND

- |dx| < x_rtol*|x|, AND
- |dx| < x_tol

Nc                 B   Uc1  [         R                  " [         R                  5      R                  S-  nUc  [         R                  nUc  [         R                  nUc  [         R                  nX0l        X@l        Xl        X l        X`l	        XPl
        S U l        SU l        g )NgUUUUUU?r   )r.   finfor9   epsrG   rS   rT   rQ   rR   r   rU   f0_normry   )selfrQ   rR   rS   rT   rU   r   s          r+   __init__TerminationCondition.__init__L  s|     =HHRZZ(,,6E>VVF=FFE>VVF

		r*   c                    U =R                   S-  sl         U R                  U5      nU R                  U5      nU R                  U5      nU R                  c  X@l        US:X  a  gU R                  b  SU R                   U R                  :  -  $ [	        X@R
                  :*  =(       a    X@R                  -  U R                  :*  =(       a&    X`R                  :*  =(       a    X`R                  -  U:*  5      $ )Nr   r   ra   )	ry   r   r   rU   intrQ   rR   rS   rT   )r   fr2   r   f_normx_normdx_norms          r+   rq   TerminationCondition.checkd  s    !11))B-<<!LQ;99 233 Fjj( ;{{*dll:;::- :#KK/69< 	<r*   )r   rR   rQ   rU   ry   r   rT   rS   )	r$   r%   r&   r'   r(   r3   r   rq   r)   r#   r*   r+   ri   ri   ?  s!     "$d40<r*   ri   c                   J    \ rS rSrSr\" \5      rS rS r	S
S jr
S rS rSrg	)Jacobiani  a.  
Common interface for Jacobians or Jacobian approximations.

The optional methods come useful when implementing trust region
etc., algorithms that often require evaluating transposes of the
Jacobian.

Methods
-------
solve
    Returns J^-1 * v
update
    Updates Jacobian to point `x` (where the function has residual `Fx`)

matvec : optional
    Returns J * v
rmatvec : optional
    Returns A^H * v
rsolve : optional
    Returns A^-H * v
matmat : optional
    Returns A * V, where V is a dense matrix with dimensions (N,K).
todense : optional
    Form the dense Jacobian matrix. Necessary for dense trust region
    algorithms, and useful for testing.

Attributes
----------
shape
    Matrix dimensions (M, N)
dtype
    Data type of the matrix.
func : callable, optional
    Function the Jacobian corresponds to

c                     / SQnUR                  5        H+  u  p4X2;  a  [        SU 35      eUc  M  [        XX   5        M-     [        U S5      (       a  SS jng g )N)	r   rt   matvecrmatvecrsolvematmattodenser>   r6   zUnknown keyword argument r   c                 D    Ub  [        SU 35      eU R                  5       $ )Nz`dtype` must be None, was )ro   r   )r   r6   rm   s      r+   	__array__$Jacobian.__init__.<locals>.__array__  s'    $$'A%%IJJ||~%r*   NN)itemsro   setattrhasattr)r   kwnamesnamevaluer   s         r+   r   Jacobian.__init__  s_    888:KD  #<TF!CDD BH-	 & 4##& $r*   c                     [        U 5      $ r-   )r   r   s    r+   aspreconditionerJacobian.aspreconditioner  s    t$$r*   c                     [         er-   NotImplementedErrorr   rH   r_   s      r+   r   Jacobian.solve      !!r*   c                     g r-   r#   r   r2   rY   s      r+   rt   Jacobian.update      r*   c                     X0l         UR                  UR                  4U l        UR                  U l        U R                  R
                  [        R
                  L a  U R                  X5        g g r-   )rZ   rn   r>   r6   	__class__rl   r   rt   r   r2   rY   rZ   s       r+   rl   Jacobian.setup  sM    	ffaff%
WW
>>8>>1KK 2r*   )r6   rZ   r>   Nr   )r$   r%   r&   r'   r(   classmethodr   __class_getitem__r   r   r   rt   rl   r)   r#   r*   r+   r   r     s.    #L $L1& %"r*   r   c                   N    \ rS rSrSr\" \5      rS r\	S 5       r
\	S 5       rSrg)r   i  aG  
A simple wrapper that inverts the Jacobian using the `solve` method.

.. legacy:: class

    See the newer, more consistent interfaces in :mod:`scipy.optimize`.

Parameters
----------
jacobian : Jacobian
    The Jacobian to invert.

Attributes
----------
shape
    Matrix dimensions (M, N)
dtype
    Data type of the matrix.

c                     Xl         UR                  U l        UR                  U l        [	        US5      (       a  UR
                  U l        [	        US5      (       a  UR                  U l        g g )Nrl   r   )rz   r   r   rt   r   rl   r   r   )r   rz   s     r+   r   InverseJacobian.__init__  sR     nnoo8W%%!DJ8X&&#??DL 'r*   c                 .    U R                   R                  $ r-   )rz   r>   r   s    r+   r>   InverseJacobian.shape      }}"""r*   c                 .    U R                   R                  $ r-   )rz   r6   r   s    r+   r6   InverseJacobian.dtype  r   r*   )rz   r   r   rl   rt   N)r$   r%   r&   r'   r(   r   r   r   r   propertyr>   r6   r)   r#   r*   r+   r   r     sA    , $L1+ # # # #r*   r   c                   ^ ^ [         R                  R                  R                  m[	        T [
        5      (       a  T $ [        R                  " T 5      (       a  [        T [
        5      (       a  T " 5       $ [	        T [        R                  5      (       a  T R                  S:  a  [        S5      e[        R                  " [        R                  " T 5      5      m T R                  S   T R                  S   :w  a  [        S5      e[        U 4S jU 4S jSU 4S jjSU 4S	 jjT R                   T R                  S
9$ [         R                  R#                  T 5      (       ac  T R                  S   T R                  S   :w  a  [        S5      e[        U 4S jU 4S jSU U4S jjSU U4S jjT R                   T R                  S
9$ [%        T S5      (       a  [%        T S5      (       aq  [%        T S5      (       a`  [        ['        T S5      ['        T S5      T R(                  ['        T S5      ['        T S5      ['        T S5      T R                   T R                  S9$ [+        T 5      (       a   " U U4S jS[
        5      nU" 5       $ [	        T [,        5      (       a3  [/        [0        [2        [4        [6        [8        [:        [<        S9T    " 5       $ [?        S5      e)z=
Convert given object to one suitable for use as a Jacobian.
ra   zarray must have rank <= 2r   r   zarray must be squarec                    > [        TU 5      $ r-   )r   rH   Js    r+   <lambda>asjacobian.<locals>.<lambda>  s    Qr*   c                 L   > [        TR                  5       R                  U 5      $ r-   )r   conjTr   s    r+   r   r     s    #affhjj!*<r*   c                    > [        TU 5      $ r-   )r   rH   r_   r   s     r+   r   r     s    uQ{r*   c                 L   > [        TR                  5       R                  U 5      $ r-   )r   r   r   r   s     r+   r   r     s    affhjj!0Dr*   )r   r   r   r   r6   r>   zmatrix must be squarec                    > TU -  $ r-   r#   r   s    r+   r   r     s	    Qr*   c                 >   > TR                  5       R                  U -  $ r-   r   r   r   s    r+   r   r     s    !&&(**q.r*   c                    > T" TU 5      $ r-   r#   rH   r_   r   spsolves     r+   r   r     s    wq!}r*   c                 F   > T" TR                  5       R                  U 5      $ r-   r   r   s     r+   r   r     s    

A0Fr*   r>   r6   r   r   r   r   rt   rl   )r   r   r   r   rt   rl   r6   r>   c                   X   > \ rS rSrS rS	U U4S jjrU 4S jrS	U U4S jjrU 4S jrSr	g)
asjacobian.<locals>.Jaci  c                     Xl         g r-   r1   r   s      r+   rt   asjacobian.<locals>.Jac.update  s    r*   c                    > T" U R                   5      n[        U[        R                  5      (       a  [	        X15      $ [
        R                  R                  U5      (       a  T" X15      $ [        S5      eNzUnknown matrix type)	r2   
isinstancer.   ndarrayr   scipysparseissparsero   r   rH   r_   mr   r   s       r+   r   asjacobian.<locals>.Jac.solve!  sV    dffIa,, ;&\\**1--"1=($%:;;r*   c                    > T" U R                   5      n[        U[        R                  5      (       a  [	        X!5      $ [
        R                  R                  U5      (       a  X!-  $ [        S5      er  )	r2   r  r.   r  r   r  r  r  ro   r   rH   r  r   s      r+   r   asjacobian.<locals>.Jac.matvec*  sS    dffIa,,q9$\\**1--5L$%:;;r*   c                 N  > T" U R                   5      n[        U[        R                  5      (       a$  [	        UR                  5       R                  U5      $ [        R                  R                  U5      (       a!  T" UR                  5       R                  U5      $ [        S5      er  )r2   r  r.   r  r   r   r   r  r  r  ro   r  s       r+   r   asjacobian.<locals>.Jac.rsolve3  sp    dffIa,, Q//\\**1--"1668::q11$%:;;r*   c                 F  > T" U R                   5      n[        U[        R                  5      (       a$  [	        UR                  5       R                  U5      $ [        R                  R                  U5      (       a  UR                  5       R                  U-  $ [        S5      er  )r2   r  r.   r  r   r   r   r  r  r  ro   r  s      r+   r   asjacobian.<locals>.Jac.rmatvec<  sm    dffIa,,qvvxzz1--\\**1--668::>)$%:;;r*   r1   Nr   )
r$   r%   r&   r'   rt   r   r   r   r   r)   )r   r   s   r+   Jacr     s+    < <<< << <r*   r  )r   r   r   r   r   r   krylovz#Cannot convert object to a Jacobianr   ) r  r  linalgr   r  r   inspectisclass
issubclassr.   r  ndimro   
atleast_2dr   r>   r6   r  r   r?   r   callablestrdictr   BroydenSecondAndersonDiagBroydenLinearMixingExcitingMixingr   	TypeError)r   r  r   s   ` @r+   rk   rk     s!    ll!!))G!X			
1h 7 7s
	Arzz	"	"66A:899MM"**Q-(771:#3442 <:DggQWW	6 	6
 
		q	!	!771:#455 8<FggQWW	6 	6
 
G		G!4!4G9L9Lwq(3 '9 5gg&q(3&q(3%a1gggg' 	' 
!&	< &	<( &	<N u	As		\*% +!-#1)+ ,-. 0 	0 =>>r*   c                   6    \ rS rSr\" \5      rS rS rS r	Sr
g)GenericBroydeniU  c                     [         R                  XX#5        X l        Xl        [	        U S5      (       aI  U R
                  c;  [        U5      nU(       a!  S[        [        U5      S5      -  U-  U l        g SU l        g g g )Nalpha      ?r   r`   )r   rl   last_flast_xr   r%  r   r0   )r   r@   f0rZ   normf0s        r+   rl   GenericBroyden.setupY  si    t*4!!djj&8 "XF T"Xq!11F:
 
 '9!r*   c                     [         er-   r   r   r2   r   r   dfr   df_norms          r+   _updateGenericBroyden._updateg  r   r*   c           
          X R                   -
  nXR                  -
  nU R                  XXC[        U5      [        U5      5        X l         Xl        g r-   )r'  r(  r0  r   )r   r2   r   r.  r   s        r+   rt   GenericBroyden.updatej  s<    __Q248T"X6r*   )r%  r'  r(  N)r$   r%   r&   r'   r   r   r   rl   r0  rt   r)   r#   r*   r+   r#  r#  U  s    #L1!"r*   r#  c                       \ rS rSrSr\" \5      rS r\	S 5       r
\	S 5       rS rS rSS jrSS	 jrS
 rSS jrS rS rS rSS jrSrg)LowRankMatrixir  z
A matrix represented as

.. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger

However, if the rank of the matrix reaches the dimension of the vectors,
full matrix representation will be used thereon.

c                 R    Xl         / U l        / U l        X l        X0l        S U l        g r-   )r%  csr   r   r6   	collapsed)r   r%  r   r6   s       r+   r   LowRankMatrix.__init__  s&    

r*   c                     [        / SQUS S U /-   5      u  pEnX-  n[        X#5       H!  u  pU" X5      n
U" XUR                  U
5      nM#     U$ )N)axpyscaldotcr   )r   ziprn   )rH   r%  r7  r   r;  r<  r=  wcdas              r+   _matvecLowRankMatrix._matvec  s\    )*B*,Ra&A3,8DIKDAQ
AQ1661%A   r*   c           	      6   [        U5      S:X  a  X-  $ [        SS/USS U /-   5      u  pEUS   nU[        R                  " [        U5      UR                  S9-  n[        U5       H-  u  p[        U5       H  u  pXxU
4==   U" X5      -  ss'   M     M/     [        R                  " [        U5      UR                  S9n[        U5       H  u  pU" X5      X'   M     X-  n[        X|5      nX-  n[        X,5       H  u  pU" XUR                  U* 5      nM     U$ )Evaluate w = M^-1 vr   r;  r=  Nr   r5   )
lenr   r.   identityr6   	enumeratezerosr   r>  rn   )rH   r%  r7  r   r;  r=  c0AirA  jr@  qr?  qcs                  r+   _solveLowRankMatrix._solve  s    r7a<7N $VV$4b!fslC
UBKKBrxx88bMDA!"A#$q*$ & " HHSWBHH-bMDA:AD "	
!KGZEAQ166B3'A   r*   c                     U R                   b!  [        R                  " U R                   U5      $ [        R	                  XR
                  U R                  U R                  5      $ )zEvaluate w = M v)r8  r.   r   r5  rC  r%  r7  r   r   rH   s     r+   r   LowRankMatrix.matvec  sB    >>%66$..!,,$$Q

DGGTWWEEr*   c                 "   U R                   b9  [        R                  " U R                   R                  R	                  5       U5      $ [
        R                  U[        R                  " U R                  5      U R                  U R                  5      $ )zEvaluate w = M^H v)
r8  r.   r   r   r   r5  rC  r%  r   r7  rT  s     r+   r   LowRankMatrix.rmatvec  s\    >>%66$..**//1155$$Q

(;TWWdggNNr*   c                     U R                   b  [        U R                   U5      $ [        R                  XR                  U R
                  U R                  5      $ )rF  )r8  r   r5  rQ  r%  r7  r   r   s      r+   r   LowRankMatrix.solve  s>    >>%++##Azz477DGGDDr*   c                    U R                   b.  [        U R                   R                  R                  5       U5      $ [        R                  U[        R                  " U R                  5      U R                  U R                  5      $ )zEvaluate w = M^-H v)
r8  r   r   r   r5  rQ  r.   r%  r   r7  r   s      r+   r   LowRankMatrix.rsolve  sX    >>%))..0!44##Arwwtzz':DGGTWWMMr*   c                 \   U R                   b5  U =R                   US S 2S 4   US S S 24   R                  5       -  -  sl         g U R                  R                  U5        U R                  R                  U5        [        U R                  5      UR                  :  a  U R                  5         g g r-   )r8  r   r7  appendr   rG  rn   collapse)r   r@  rA  s      r+   r]  LowRankMatrix.append  s{    >>%NNa$i!DF)..*:::Nqqtww<!&& MMO !r*   Nc                    Ub  [         R                  " SU S3SS9  Ub  [         R                  " SU S3SS9  U R                  b  U R                  $ U R                  [        R
                  " U R                  U R                  S9-  n[        U R                  U R                  5       H(  u  pEX4S S 2S 4   US S S 24   R                  5       -  -  nM*     U$ )NzJLowRankMatrix is scipy-internal code, `dtype` should only be None but was z (not handled)   )
stacklevelzILowRankMatrix is scipy-internal code, `copy` should only be None but was r5   )warningswarnr8  r%  r.   rH  r   r6   r>  r7  r   r   )r   r6   rm   Gmr@  rA  s         r+   r   LowRankMatrix.__array__  s    MM 99>~O%&( MM 99=nN%&( >>%>>!ZZDFF$**==)DAAdF)Ad1fINN,,,B *	r*   c                 j    [         R                  " U [        S9U l        SU l        SU l        SU l        g)z0Collapse the low-rank matrix to a full-rank one.)rm   N)r.   rF   r   r8  r7  r   r%  r   s    r+   r^  LowRankMatrix.collapse  s)    $^<
r*   c                     U R                   b  gUS:  d   e[        U R                  5      U:  a  U R                  SS2	 U R                  SS2	 gg)z8
Reduce the rank of the matrix by dropping all vectors.
Nr   r8  rG  r7  r   r   ranks     r+   restart_reduceLowRankMatrix.restart_reduce  sG     >>%axxtww<$

 r*   c                     U R                   b  gUS:  d   e[        U R                  5      U:  a6  U R                  S	 U R                  S	 [        U R                  5      U:  a  M5  gg)z;
Reduce the rank of the matrix by dropping oldest vectors.
Nr   rj  rk  s     r+   simple_reduceLowRankMatrix.simple_reduce  sT     >>%axx$''lT!

 $''lT!r*   c                    U R                   b  gUnUb  UnOUS-
  nU R                  (       a"  [        U[        U R                  S   5      5      n[	        S[        XCS-
  5      5      n[        U R                  5      nXS:  a  g[
        R                  " U R                  5      R                  n[
        R                  " U R                  5      R                  n[        USS9u  px[        XhR                  R                  5       5      n[        USS9u  pn[        U[        U5      5      n[        X{R                  R                  5       5      n[        U5       HK  nUSS2U4   R                  5       U R                  U'   USS2U4   R                  5       U R                  U'   MM     U R                  US2	 U R                  US2	 g)	al  
Reduce the rank of the matrix by retaining some SVD components.

This corresponds to the "Broyden Rank Reduction Inverse"
algorithm described in [1]_.

Note that the SVD decomposition can be done by solving only a
problem whose size is the effective rank of this matrix, which
is viable even for large problems.

Parameters
----------
max_rank : int
    Maximum rank of this matrix after reduction.
to_retain : int, optional
    Number of SVD components to retain when reduction is done
    (ie. rank > max_rank). Default is ``max_rank - 2``.

References
----------
.. [1] B.A. van der Rotten, PhD thesis,
   "A limited memory Broyden method to solve high-dimensional
   systems of nonlinear equations". Mathematisch Instituut,
   Universiteit Leiden, The Netherlands (2003).

   https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf

Nra   r   r   economic)modeF)full_matrices)r8  r7  rr   rG  r0   r.   rF   r   r   r	   r   r   r
   r   rp   rm   )r   max_rank	to_retainr   rO  r  CDRUSWHks                r+   
svd_reduceLowRankMatrix.svd_reduce  sW   : >>% AAA77As4771:'A3qA#;L5HHTWWHHTWW!*%3388:q.b3r7O4499;qA1Q3DGGAJ1Q3DGGAJ  GGABKGGABKr*   )r%  r8  r7  r   r6   r   r   r   r-   )r$   r%   r&   r'   r(   r   r   r   r   staticmethodrC  rQ  r   r   r   r   r]  r   r^  rm  rp  r  r)   r#   r*   r+   r5  r5  r  sw     $L1    6FOEN	"		?r*   r5  a  
    alpha : float, optional
        Initial guess for the Jacobian is ``(-1/alpha)``.
    reduction_method : str or tuple, optional
        Method used in ensuring that the rank of the Broyden matrix
        stays low. Can either be a string giving the name of the method,
        or a tuple of the form ``(method, param1, param2, ...)``
        that gives the name of the method and values for additional parameters.

        Methods available:

        - ``restart``: drop all matrix columns. Has no extra parameters.
        - ``simple``: drop oldest matrix column. Has no extra parameters.
        - ``svd``: keep only the most significant SVD components.
          Takes an extra parameter, ``to_retain``, which determines the
          number of SVD components to retain when rank reduction is done.
          Default is ``max_rank - 2``.

    max_rank : int, optional
        Maximum rank for the Broyden matrix.
        Default is infinity (i.e., no rank reduction).
    broyden_paramsc                   T    \ rS rSrSrSS jrS rS rSS jrS r	SS	 jr
S
 rS rSrg)r   iY  a  
Find a root of a function, using Broyden's first Jacobian approximation.

This method is also known as "Broyden's good method".

Parameters
----------
%(params_basic)s
%(broyden_params)s
%(params_extra)s

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

Notes
-----
This algorithm implements the inverse Jacobian Quasi-Newton update

.. math:: H_+ = H + (dx - H df) dx^\dagger H / ( dx^\dagger H df)

which corresponds to Broyden's first Jacobian update

.. math:: J_+ = J + (df - J dx) dx^\dagger / dx^\dagger dx


References
----------
.. [1] B.A. van der Rotten, PhD thesis,
   "A limited memory Broyden method to solve high-dimensional
   systems of nonlinear equations". Mathematisch Instituut,
   Universiteit Leiden, The Netherlands (2003).
   https://math.leidenuniv.nl/scripties/Rotten.pdf

Examples
--------
The following functions define a system of nonlinear equations

>>> def fun(x):
...     return [x[0]  + 0.5 * (x[0] - x[1])**3 - 1.0,
...             0.5 * (x[1] - x[0])**3 + x[1]]

A solution can be obtained as follows.

>>> from scipy import optimize
>>> sol = optimize.broyden1(fun, [0, 0])
>>> sol
array([0.84116396, 0.15883641])

Nc                 f  ^ ^ [         R                  T 5        UT l        S T l        Uc  [        R
                  nUT l        [        U[        5      (       a  SmO
USS  mUS   nUS-
  4T-   mUS:X  a  UU 4S jT l	        g US:X  a  UU 4S jT l	        g US:X  a  UU 4S	 jT l	        g [        S
U S35      e)Nr#   r   r   r
   c                  6   > TR                   R                  " T 6 $ r-   )re  r  reduce_paramsr   s   r+   r   'BroydenFirst.__init__.<locals>.<lambda>  s    477#5#5}#Er*   simplec                  6   > TR                   R                  " T 6 $ r-   )re  rp  r  s   r+   r   r    s    477#8#8-#Hr*   restartc                  6   > TR                   R                  " T 6 $ r-   )re  rm  r  s   r+   r   r    s    477#9#9=#Ir*   zUnknown rank reduction method '')r#  r   r%  re  r.   rG   rv  r  r  _reducero   )r   r%  reduction_methodrv  r  s   `   @r+   r   BroydenFirst.__init__  s    %
vvH &,,M,QR0M/2!A-7u$EDL)HDL*IDL>?O>PPQRSSr*   c                     [         R                  XX#5        [        U R                  * U R                  S   U R
                  5      U l        g )Nr   )r#  rl   r5  r%  r>   r6   re  r   s       r+   rl   BroydenFirst.setup  s4    Ta.TZZ]DJJGr*   c                 ,    [        U R                  5      $ r-   )r   re  r   s    r+   r   BroydenFirst.todense  s    477|r*   c                 &   U R                   R                  U5      n[        R                  " U5      R	                  5       (       dL  U R                  U R                  U R                  U R                  5        U R                   R                  U5      $ U$ r-   )	re  r   r.   rD   rE   rl   r(  r'  rZ   )r   r   r_   rs       r+   r   BroydenFirst.solve  s_    GGNN1{{1~!!##JJt{{DKK;77>>!$$r*   c                 8    U R                   R                  U5      $ r-   )re  r   r   r   s     r+   r   BroydenFirst.matvec  s    ww}}Qr*   c                 8    U R                   R                  U5      $ r-   )re  r   r   r   r_   s      r+   r   BroydenFirst.rsolve  s    wwq!!r*   c                 8    U R                   R                  U5      $ r-   )re  r   r  s     r+   r   BroydenFirst.rmatvec  s    ww~~a  r*   c                     U R                  5         U R                  R                  U5      nX0R                  R                  U5      -
  nU[	        XG5      -  n	U R                  R                  X5        g r-   )r  re  r   r   r   r]  
r   r2   r   r   r.  r   r/  rH   r@  rA  s
             r+   r0  BroydenFirst._update  sO    GGOOB##ROqr*   )re  r  r%  rv  )Nr  Nr   )r$   r%   r&   r'   r(   r   rl   r   r   r   r   r   r0  r)   r#   r*   r+   r   r   Y  s2    2hT2H "!r*   r   c                       \ rS rSrSrS rSrg)r  i  a  
Find a root of a function, using Broyden's second Jacobian approximation.

This method is also known as "Broyden's bad method".

Parameters
----------
%(params_basic)s
%(broyden_params)s
%(params_extra)s

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

Notes
-----
This algorithm implements the inverse Jacobian Quasi-Newton update

.. math:: H_+ = H + (dx - H df) df^\dagger / ( df^\dagger df)

corresponding to Broyden's second method.

References
----------
.. [1] B.A. van der Rotten, PhD thesis,
   "A limited memory Broyden method to solve high-dimensional
   systems of nonlinear equations". Mathematisch Instituut,
   Universiteit Leiden, The Netherlands (2003).

   https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf

Examples
--------
The following functions define a system of nonlinear equations

>>> def fun(x):
...     return [x[0]  + 0.5 * (x[0] - x[1])**3 - 1.0,
...             0.5 * (x[1] - x[0])**3 + x[1]]

A solution can be obtained as follows.

>>> from scipy import optimize
>>> sol = optimize.broyden2(fun, [0, 0])
>>> sol
array([0.84116365, 0.15883529])

c                     U R                  5         UnX0R                  R                  U5      -
  nXvS-  -  n	U R                  R                  X5        g Nra   )r  re  r   r]  r  s
             r+   r0  BroydenSecond._update  s@    ##
Nqr*   r#   N)r$   r%   r&   r'   r(   r0  r)   r#   r*   r+   r  r    s    0dr*   r  c                   8    \ rS rSrSrS	S jrS
S jrS rS rSr	g)r  i	  az  
Find a root of a function, using (extended) Anderson mixing.

The Jacobian is formed by for a 'best' solution in the space
spanned by last `M` vectors. As a result, only a MxM matrix
inversions and MxN multiplications are required. [Ey]_

Parameters
----------
%(params_basic)s
alpha : float, optional
    Initial guess for the Jacobian is (-1/alpha).
M : float, optional
    Number of previous vectors to retain. Defaults to 5.
w0 : float, optional
    Regularization parameter for numerical stability.
    Compared to unity, good values of the order of 0.01.
%(params_extra)s

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

References
----------
.. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).

Examples
--------
The following functions define a system of nonlinear equations

>>> def fun(x):
...     return [x[0]  + 0.5 * (x[0] - x[1])**3 - 1.0,
...             0.5 * (x[1] - x[0])**3 + x[1]]

A solution can be obtained as follows.

>>> from scipy import optimize
>>> sol = optimize.anderson(fun, [0, 0])
>>> sol
array([0.84116588, 0.15883789])

Nc                 |    [         R                  U 5        Xl        X0l        / U l        / U l        S U l        X l        g r-   )r#  r   r%  Mr   r.  r   w0)r   r%  r  r  s       r+   r   Anderson.__init__P  s4    %

r*   c                    U R                   * U-  n[        U R                  5      nUS:X  a  U$ [        R                  " XAR
                  S9n[        U5       H  n[        U R                  U   U5      XV'   M       [        U R                  U5      n[        U5       H7  nX7U   U R                  U   U R                   U R                  U   -  -   -  -  nM9     U$ ! [         a#    U R                  S S 2	 U R                  S S 2	 Us $ f = fNr   r5   )r%  rG  r   r.   emptyr6   rp   r   r.  r   rB  r   )	r   r   r_   r   r   df_fr~  r   r  s	            r+   r   Anderson.solveY  s    jj[]L6Ixx)qA4771:q)DG 	$&&$'E qA(DGGAJDGGAJ)>>??B 	  	

I		s   :C *DDc           
      D   U* U R                   -  n[        U R                  5      nUS:X  a  U$ [        R                  " X1R
                  S9n[        U5       H  n[        U R                  U   U5      XE'   M      [        R                  " X34UR
                  S9n[        U5       H  n[        U5       H  n[        U R                  U   U R                  U   5      XgU4'   Xx:X  d  M4  U R                  S:w  d  MF  XgU4==   [        U R                  U   U R                  U   5      U R                  S-  -  U R                   -  -  ss'   M     M     [        Xd5      n	[        U5       H7  n
X)U
   U R                  U
   U R                  U
   U R                   -  -   -  -  nM9     U$ )Nr   r5   ra   )r%  rG  r   r.   r  r6   rp   r   r.  r  r   )r   r   r   r   r  r~  brM  rN  r   r  s              r+   r   Anderson.matvecp  sO   R

]L6Ixx)qA4771:q)DG  HHaV177+qA1Xdggaj$''!*5A#6dgglcFd4771:twwqz:477A:EdjjPPF  
 aqA(DGGAJDJJ)>>??B 	r*   c                 >   U R                   S:X  a  g U R                  R                  U5        U R                  R                  U5        [	        U R                  5      U R                   :  a[  U R                  R                  S5        U R                  R                  S5        [	        U R                  5      U R                   :  a  M[  [	        U R                  5      n[        R                  " Xw4UR                  S9n[        U5       H\  n	[        X5       HJ  n
X:X  a  U R                  S-  nOSnSU-   [        U R                  U	   U R                  U
   5      -  XU
4'   ML     M^     U[        R                  " US5      R                  R                  5       -  nXl        g )Nr   r5   ra   r   )r  r   r]  r.  rG  popr.   rJ  r6   rp   r  r   triur   r   rB  )r   r2   r   r   r.  r   r/  r   rB  rM  rN  wds               r+   r0  Anderson._update  s#   66Q;rr$''lTVV#GGKKNGGKKN $''lTVV# LHHaV177+qA1[6!BBB$TWWQZ <<A# !  	
RWWQ]__!!##r*   )r  rB  r%  r.  r   r   r  )Nr      r   )
r$   r%   r&   r'   r(   r   r   r   r0  r)   r#   r*   r+   r  r  	  s    +L..r*   r  c                   T    \ rS rSrSrSS jrS rSS jrS rSS jr	S	 r
S
 rS rSrg)r  i  a  
Find a root of a function, using diagonal Broyden Jacobian approximation.

The Jacobian approximation is derived from previous iterations, by
retaining only the diagonal of Broyden matrices.

.. warning::

   This algorithm may be useful for specific problems, but whether
   it will work may depend strongly on the problem.

Parameters
----------
%(params_basic)s
alpha : float, optional
    Initial guess for the Jacobian is (-1/alpha).
%(params_extra)s

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

Examples
--------
The following functions define a system of nonlinear equations

>>> def fun(x):
...     return [x[0]  + 0.5 * (x[0] - x[1])**3 - 1.0,
...             0.5 * (x[1] - x[0])**3 + x[1]]

A solution can be obtained as follows.

>>> from scipy import optimize
>>> sol = optimize.diagbroyden(fun, [0, 0])
>>> sol
array([0.84116403, 0.15883384])

Nc                 :    [         R                  U 5        Xl        g r-   r#  r   r%  r   r%  s     r+   r   DiagBroyden.__init__      %
r*   c                     [         R                  XX#5        [        R                  " U R                  S   4SU R
                  -  U R                  S9U l        g )Nr   r   r5   )r#  rl   r.   fullr>   r%  r6   rA  r   s       r+   rl   DiagBroyden.setup  s=    Ta.$**Q-)1tzz>Lr*   c                 "    U* U R                   -  $ r-   rA  r  s      r+   r   DiagBroyden.solve      rDFF{r*   c                 "    U* U R                   -  $ r-   r  r  s     r+   r   DiagBroyden.matvec  r  r*   c                 >    U* U R                   R                  5       -  $ r-   rA  r   r  s      r+   r   DiagBroyden.rsolve      rDFFKKM!!r*   c                 >    U* U R                   R                  5       -  $ r-   r  r  s     r+   r   DiagBroyden.rmatvec  r  r*   c                 D    [         R                  " U R                  * 5      $ r-   )r.   diagrA  r   s    r+   r   DiagBroyden.todense  s    wwwr*   c                 ^    U =R                   X@R                   U-  -   U-  US-  -  -  sl         g r  r  r-  s          r+   r0  DiagBroyden._update  s(    2r	>2%gqj00r*   )r%  rA  r-   r   r$   r%   r&   r'   r(   r   rl   r   r   r   r   r   r0  r)   r#   r*   r+   r  r    s1    &PM"" 1r*   r  c                   N    \ rS rSrSrSS jrSS jrS rSS jrS r	S	 r
S
 rSrg)r  i  a  
Find a root of a function, using a scalar Jacobian approximation.

.. warning::

   This algorithm may be useful for specific problems, but whether
   it will work may depend strongly on the problem.

Parameters
----------
%(params_basic)s
alpha : float, optional
    The Jacobian approximation is (-1/alpha).
%(params_extra)s

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

Nc                 :    [         R                  U 5        Xl        g r-   r  r  s     r+   r   LinearMixing.__init__   r  r*   c                 "    U* U R                   -  $ r-   r%  r  s      r+   r   LinearMixing.solve      r$**}r*   c                 "    U* U R                   -  $ r-   r  r  s     r+   r   LinearMixing.matvec  r  r*   c                 J    U* [         R                  " U R                  5      -  $ r-   r.   r   r%  r  s      r+   r   LinearMixing.rsolve
      r"''$**%%%r*   c                 J    U* [         R                  " U R                  5      -  $ r-   r  r  s     r+   r   LinearMixing.rmatvec  r  r*   c                     [         R                  " [         R                  " U R                  S   SU R                  -  5      5      $ )Nr   )r.   r  r  r>   r%  r   s    r+   r   LinearMixing.todense  s,    wwrwwtzz!}bm<==r*   c                     g r-   r#   r-  s          r+   r0  LinearMixing._update  r   r*   r  r-   r   )r$   r%   r&   r'   r(   r   r   r   r   r   r   r0  r)   r#   r*   r+   r  r    s*    ,&&>r*   r  c                   T    \ rS rSrSrSS jrS rSS jrS rSS jr	S	 r
S
 rS rSrg)r   i  a  
Find a root of a function, using a tuned diagonal Jacobian approximation.

The Jacobian matrix is diagonal and is tuned on each iteration.

.. warning::

   This algorithm may be useful for specific problems, but whether
   it will work may depend strongly on the problem.

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

Parameters
----------
%(params_basic)s
alpha : float, optional
    Initial Jacobian approximation is (-1/alpha).
alphamax : float, optional
    The entries of the diagonal Jacobian are kept in the range
    ``[alpha, alphamax]``.
%(params_extra)s
Nc                 T    [         R                  U 5        Xl        X l        S U l        g r-   )r#  r   r%  alphamaxbeta)r   r%  r  s      r+   r   ExcitingMixing.__init__2  s!    %
 	r*   c                     [         R                  XX#5        [        R                  " U R                  S   4U R
                  U R                  S9U l        g r  )r#  rl   r.   r  r>   r%  r6   r  r   s       r+   rl   ExcitingMixing.setup8  s9    Ta.GGTZZ],djj

K	r*   c                 "    U* U R                   -  $ r-   r  r  s      r+   r   ExcitingMixing.solve<      r$))|r*   c                 "    U* U R                   -  $ r-   r  r  s     r+   r   ExcitingMixing.matvec?  r  r*   c                 >    U* U R                   R                  5       -  $ r-   r  r   r  s      r+   r   ExcitingMixing.rsolveB      r$)).."""r*   c                 >    U* U R                   R                  5       -  $ r-   r  r  s     r+   r   ExcitingMixing.rmatvecE  r  r*   c                 H    [         R                  " SU R                  -  5      $ )Nr  )r.   r  r  r   s    r+   r   ExcitingMixing.todenseH  s    wwr$))|$$r*   c                    X R                   -  S:  nU R                  U==   U R                  -  ss'   U R                  U R                  U) '   [        R                  " U R                  SU R
                  U R                  S9  g )Nr   )out)r'  r  r%  r.   clipr  )r   r2   r   r   r.  r   r/  incrs           r+   r0  ExcitingMixing._updateK  sZ    }q 		$4::%::		4%
		1dmm;r*   )r%  r  r  )Nr`   r   r  r#   r*   r+   r   r     s0    4L##%<r*   r   c                   H    \ rS rSrSr  SS jrS rS rSS jrS r	S	 r
S
rg)r   iV  a\  
Find a root of a function, using Krylov approximation for inverse Jacobian.

This method is suitable for solving large-scale problems.

Parameters
----------
%(params_basic)s
rdiff : float, optional
    Relative step size to use in numerical differentiation.
method : str or callable, optional
    Krylov method to use to approximate the Jacobian.  Can be a string,
    or a function implementing the same interface as the iterative
    solvers in `scipy.sparse.linalg`. If a string, needs to be one of:
    ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``,
    ``'tfqmr'``.

    The default is `scipy.sparse.linalg.lgmres`.
inner_maxiter : int, optional
    Parameter to pass to the "inner" Krylov solver: maximum number of
    iterations. Iteration will stop after maxiter steps even if the
    specified tolerance has not been achieved.
inner_M : LinearOperator or InverseJacobian
    Preconditioner for the inner Krylov iteration.
    Note that you can use also inverse Jacobians as (adaptive)
    preconditioners. For example,

    >>> from scipy.optimize import BroydenFirst, KrylovJacobian
    >>> from scipy.optimize import InverseJacobian
    >>> jac = BroydenFirst()
    >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac))

    If the preconditioner has a method named 'update', it will be called
    as ``update(x, f)`` after each nonlinear step, with ``x`` giving
    the current point, and ``f`` the current function value.
outer_k : int, optional
    Size of the subspace kept across LGMRES nonlinear iterations.
    See `scipy.sparse.linalg.lgmres` for details.
inner_kwargs : kwargs
    Keyword parameters for the "inner" Krylov solver
    (defined with `method`). Parameter names must start with
    the `inner_` prefix which will be stripped before passing on
    the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details.
%(params_extra)s

See Also
--------
root : Interface to root finding algorithms for multivariate
       functions. See ``method='krylov'`` in particular.
scipy.sparse.linalg.gmres
scipy.sparse.linalg.lgmres

Notes
-----
This function implements a Newton-Krylov solver. The basic idea is
to compute the inverse of the Jacobian with an iterative Krylov
method. These methods require only evaluating the Jacobian-vector
products, which are conveniently approximated by a finite difference:

.. math:: J v \approx (f(x + \omega*v/|v|) - f(x)) / \omega

Due to the use of iterative matrix inverses, these methods can
deal with large nonlinear problems.

SciPy's `scipy.sparse.linalg` module offers a selection of Krylov
solvers to choose from. The default here is `lgmres`, which is a
variant of restarted GMRES iteration that reuses some of the
information obtained in the previous Newton steps to invert
Jacobians in subsequent steps.

For a review on Newton-Krylov methods, see for example [1]_,
and for the LGMRES sparse inverse method, see [2]_.

References
----------
.. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method,
       SIAM, pp.57-83, 2003.
       :doi:`10.1137/1.9780898718898.ch3`
.. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004).
       :doi:`10.1016/j.jcp.2003.08.010`
.. [3] A.H. Baker and E.R. Jessup and T. Manteuffel,
       SIAM J. Matrix Anal. Appl. 26, 962 (2005).
       :doi:`10.1137/S0895479803422014`

Examples
--------
The following functions define a system of nonlinear equations

>>> def fun(x):
...     return [x[0] + 0.5 * x[1] - 1.0,
...             0.5 * (x[1] - x[0]) ** 2]

A solution can be obtained as follows.

>>> from scipy import optimize
>>> sol = optimize.newton_krylov(fun, [0, 0])
>>> sol
array([0.66731771, 0.66536458])

Nc           	      \   X@l         Xl        [        [        R                  R
                  R                  [        R                  R
                  R                  [        R                  R
                  R                  [        R                  R
                  R                  [        R                  R
                  R                  [        R                  R
                  R                  S9R                  X"5      U l        [        X0R                   S9U l        U R                  [        R                  R
                  R                  L a;  X0R                  S'   SU R                  S'   U R                  R                  SS5        GOTU R                  [        R                  R
                  R                   [        R                  R
                  R                  [        R                  R
                  R                  4;   a  U R                  R                  SS5        OU R                  [        R                  R
                  R                  L a  XPR                  S'   SU R                  S'   U R                  R                  S	/ 5        U R                  R                  S
S5        U R                  R                  SS5        U R                  R                  SS5        [#        U R                  5      R$                   Vs/ s H  nUS;  d  M  UPM     nnUR'                  5        H  u  pU	R)                  S5      (       d  [+        SU	 35      eU	SS  U;  aG  [-        U	SS  USS9nU(       a
  SUS    S3nOSn[.        R0                  " SU	 SU S3U-   S[2        S9  My  XR                  U	SS  '   M     g s  snf )N)bicgstabgmreslgmrescgsminrestfqmr)r|   r  r  r   r|   atolr   outer_kouter_vprepend_outer_vTstore_outer_AvF)r   argskwargsinner_zUnknown parameter    )r   z Did you mean 'z'? zOption 'z#' is invalid for the inner method: zO. It will be ignored.Please check inner method documentation for valid options.ra  )rb  category)preconditionerr   r  r  r  r  r  r  r  r  r	  r
  getmethod	method_kw
setdefaultgcrotmkr   
parametersr   
startswithro   r   rc  rd  UserWarning)r   r   r  inner_maxiterinner_Mr  r   r~  valid_inner_paramskeyr   inner_param_suggestionssuggestion_msgs                r+   r   KrylovJacobian.__init__  s   %
 \\((11,,%%++<<&&--##''<<&&--,,%%++ c&! 	 m7J7JK;;%,,--333(5NN9%()DNN9%NN%%fa0[[U\\0088"\\0099"\\00446 6 NN%%fa0[[ELL//666(/NN9%()DNN9%NN%%i4NN%%&7> NN%%&6>NN%%fa0 !-88
8!22 8 	 

 ((*JC>>(++ #5cU!;<<12w00*;CG<N>?+A' +(7)@)C(DB'HN &(N se#Fvh OQ Q %%  !(	 &+NN3qr7#7 %
s   4
N)N)c                     [        U R                  5      R                  5       n[        U R                  5      R                  5       nU R                  [        SU5      -  [        SU5      -  U l        g )Nr   )r   r@   r0   r)  r   omega)r   mxmfs      r+   _update_diff_step KrylovJacobian._update_diff_step	  sO    \\ZZ#a*,s1bz9
r*   c                    [        U5      nUS:X  a  SU-  $ U R                  U-  nU R                  U R                  X1-  -   5      U R                  -
  U-  n[
        R                  " [
        R                  " U5      5      (       d:  [
        R                  " [
        R                  " U5      5      (       a  [        S5      eU$ )Nr   z$Function returned non-finite results)	r   r'  rZ   r@   r)  r.   rE   rD   ro   )r   rH   nvscr  s        r+   r   KrylovJacobian.matvec  s    !W7Q3JZZ"_YYtww~&0B6vvbkk!n%%"&&Q*@*@CDDr*   c                     SU R                   ;   a,  U R                  " U R                  U40 U R                   D6u  p4U$ U R                  " U R                  U4SU0U R                   D6u  p4U$ )Nrtol)r  r  op)r   rhsr_   solr   s        r+   r   KrylovJacobian.solve  s_    T^^#DGGSCDNNCIC 
 DGGSMsMdnnMIC
r*   c                     Xl         X l        U R                  5         U R                  b8  [	        U R                  S5      (       a  U R                  R                  X5        g g g )Nrt   )r@   r)  r*  r  r   rt   )r   r2   r   s      r+   rt   KrylovJacobian.update  sW      *t**H55##**10 6 +r*   c                    [         R                  XX#5        Xl        X l        [        R
                  R                  R                  U 5      U l        U R                  c2  [        R                  " UR                  5      R                  S-  U l	        U R                  5         U R                  b9  [!        U R                  S5      (       a  U R                  R                  XU5        g g g )Nr&  rl   )r   rl   r@   r)  r  r  r  aslinearoperatorr2  r   r.   r   r6   r   r*  r  r   )r   r2   r   rZ   s       r+   rl   KrylovJacobian.setup)  s    t(,,%%66t<::!''*..48DJ  *t**G44##))!5 5 +r*   )r)  r  r  r'  r2  r  r   r@   )Nr     N
   r   )r$   r%   r&   r'   r(   r   r*  r   r   rt   rl   r)   r#   r*   r+   r   r   V  s3    cJ CE')K,Z:
16r*   r   c           	      f   [        UR                  5      nUu  p4pVpxn	[        [        U[	        U5      * S U5      5      n
SR                  U
 VVs/ s H  u  pU SU< 3PM     snn5      nU(       a  SU-   nSR                  U
 VVs/ s H  u  pU SU 3PM     snn5      nU(       a  US-   nU(       a  [        SU 35      eSnU[        XUR                  US9-  n0 nUR                  [        5       5        [        UU5        UU    nUR                  Ul        [        U5        U$ s  snnf s  snnf )z
Construct a solver wrapper with given name and Jacobian approx.

It inspects the keyword arguments of ``jac.__init__``, and allows to
use the same arguments in the wrapper function, in addition to the
keyword arguments of `nonlin_solve`

Nz, =zUnexpected signature a  
def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None,
             f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
             tol_norm=None, line_search='armijo', callback=None, **kw):
    jac = %(jac)s(%(kwkw)s **kw)
    return nonlin_solve(F, xin, jac, iter, verbose, maxiter,
                        f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search,
                        callback)
)r   r   jackwkw)_getfullargspecr   listr>  rG  joinro   r  r$   rt   globalsexecr(   rO   )r   r?  r   r  varargsvarkwdefaults
kwonlyargs
kwdefaults_r  r~  rH   kw_strkwkw_strwrappernsrZ   s                     r+   _nonlin_wrapperrP  >  s*     -I@I=D5JA#dCM>?+X67FYY81#Qqe89Fyy8QCq*89Hd?0<==G $s||"*, ,G	BIIgi"d8D;;DLTNK; 9 9s   D'
D-
r   r   r   r   r   r   r   )r  NFNNNNNNr]   NFT)r]   g:0yE>r   )Br  ru   rc  numpyr.   r   r   r   scipy.linalgr   r   r   r	   r
   r   scipy.sparse.linalgr  scipy.sparser   scipy._lib._utilr   r   r   rA  _linesearchr   r   r   difflibr   typesr   __all__	Exceptionr    r3   r:   rB   rI   r  striprM   rO   r   rs   ri   r   r   rk   r#  r5  r   r  r  r  r  r   r   rP  r   r   r   r   r   r   r   r#   r*   r+   <module>r\     s    
   $ $ ? ?   ' > F C  % J	I 	  " $ 	 
" ($ (	P 
a1
h/
 ?DKO?C48O"d 	  FJ!*Z9< 9<@H HV(# (#VY?@X :L L^  1 2  	* 
+  0m> m`9L 9@U~ UxA1. A1H+> +\8<^ 8<~a6X a6P)X :|4:}5:x0~|<m[9 !1>B@r*   