
    -i                        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  S SKJr  SSKJr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RK                  5       SRK                  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 r- " S S \+5      r. " S! S"5      r/S#RK                  5       \&S$'    " S% S&\.5      r0 " S' S(\05      r1 " S) S*\.5      r2 " S+ S,\.5      r3 " S- S.\.5      r4 " S/ S0\.5      r5 " S1 S2\+5      r6S3 r7\7" S4\05      r8\7" S5\15      r9\7" S6\25      r:\7" S7\45      r;\7" S8\35      r<\7" S9\55      r=\7" S:\65      r>g)=    N)asarraydotvdot)normsolveinvqrsvdLinAlgError)get_blas_funcs)copy_if_needed)getfullargspec_no_self   )scalar_search_wolfe1scalar_search_armijo)	signature)get_close_matches)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!       I/var/www/html/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)   maxnormr1   &   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,   
issubdtyper4   inexactfloat64r/   s    r)   _as_inexactr8   *   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:   )r0   x0wraps      r)   _array_liker@   2   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_normrG   9   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_docrM   w   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+   )r8   r@   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   r_   )nitfunstatussuccessmessage)r1   TerminationConditionr8   rU   r,   	full_likerE   r   
asjacobiansetupcopysize
ValueErrorrangecheckminr   _nonlin_line_searchupdater.   sysstdoutwriteflushr   r@   	iteration) rW   r>   jacobianrS   verbosemaxiterrO   rP   rQ   rR   tol_normline_searchcallbackfull_outputraise_exception	conditionrX   r0   dxFxFx_normgammaeta_maxeta_tresholdetanrd   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   r_   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   r_   )rG   )r   storextrF   pr   rX   tmp_Fxtmp_phitmp_sr0   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   )rX   r0   r   r   search_typer   sminr   r   phi1phi0r   r   r   r   r   r   s   `` ` `      @@@@@r)   rq   rq     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)rg   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,   finfor7   epsrE   rQ   rR   rO   rP   r   rS   f0_normrw   )selfrO   rP   rQ   rR   rS   r   s          r)   __init__TerminationCondition.__init__K  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   r_   )	rw   r   r   rS   intrO   rP   rQ   rR   )r   fr0   r   f_normx_normdx_norms          r)   ro   TerminationCondition.checkc  s    !11))B-<<!LQ;99 233 Fjj( ;{{*dll:;::- :#KK/69< 	<r(   )r   rP   rO   rS   rw   r   rR   rQ   )	r"   r#   r$   r%   r&   r1   r   ro   r'   r!   r(   r)   rg   rg   >  s!     "$d40<r(   rg   c                   :    \ rS rSrS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   rr   matvecrmatvecrsolvematmattodenser<   r4   zUnknown keyword argument r   c                 D    Ub  [        SU 35      eU R                  5       $ )Nz`dtype` must be None, was )rm   r   )r   r4   rk   s      r)   	__array__$Jacobian.__init__.<locals>.__array__  s'    $$'A%%IJJ||~%r(   NN)itemsrm   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   rF   r]   s      r)   r   Jacobian.solve      !!r(   c                     g r+   r!   r   r0   rW   s      r)   rr   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+   )rX   rl   r<   r4   	__class__rj   r   rr   r   r0   rW   rX   s       r)   rj   Jacobian.setup  sM    	ffaff%
WW
>>8>>1KK 2r(   )r4   rX   r<   Nr   )r"   r#   r$   r%   r&   r   r   r   rr   rj   r'   r!   r(   r)   r   r   ~  s!    #J& %"r(   r   c                   >    \ rS rSrS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 )Nrj   r   )rx   r   r   rr   r   rj   r   r   )r   rx   s     r)   r   InverseJacobian.__init__  sR     nnoo8W%%!DJ8X&&#??DL 'r(   c                 .    U R                   R                  $ r+   )rx   r<   r   s    r)   r<   InverseJacobian.shape      }}"""r(   c                 .    U R                   R                  $ r+   )rx   r4   r   s    r)   r4   InverseJacobian.dtype  r   r(   )rx   r   r   rj   rr   N)
r"   r#   r$   r%   r&   r   propertyr<   r4   r'   r!   r(   r)   r   r     s4    (+ # # # #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.
r_   zarray must have rank <= 2r   r   zarray must be squarec                    > [        TU 5      $ r+   )r   rF   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   rF   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   r4   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!   rF   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<   r4   r   r   r   r   rr   rj   )r   r   r   r   rr   rj   r4   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+   r/   r   s      r)   rr   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)	r0   
isinstancer,   ndarrayr   scipysparseissparserm   r   rF   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   )	r0   r   r,   r   r   r   r  r  rm   r   rF   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   )r0   r   r,   r   r   r   r   r   r  r  rm   r  s       r)   r   asjacobian.<locals>.Jac.rsolve+  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   )r0   r   r,   r   r   r   r   r   r  r  rm   r  s      r)   r   asjacobian.<locals>.Jac.rmatvec4  sm    dffIa,,qvvxzz1--\\**1--668::>)$%:;;r(   r/   Nr   )
r"   r#   r$   r%   rr   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   ndimrm   
atleast_2dr   r<   r4   r  r   r=   r   callablestrdictr   BroydenSecondAndersonDiagBroydenLinearMixingExcitingMixingr   	TypeError)r   r  r   s   ` @r)   ri   ri     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                   &    \ rS rSrS rS rS rSrg)GenericBroydeniM  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   rj   last_flast_xr   r!  r   r.   )r   r>   f0rX   normf0s        r)   rj   GenericBroyden.setupN  si    t*4!!djj&8 "XF T"Xq!11F:
 
 '9!r(   c                     [         er+   r   r   r0   r   r   dfr   df_norms          r)   _updateGenericBroyden._update\  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$  r,  r   )r   r0   r   r*  r   s        r)   rr   GenericBroyden.update_  s<    __Q248T"X6r(   )r!  r#  r$  N)r"   r#   r$   r%   rj   r,  rr   r'   r!   r(   r)   r  r  M  s    !"r(   r  c                       \ rS rSrS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)LowRankMatrixig  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   r4   	collapsed)r   r!  r   r4   s       r)   r   LowRankMatrix.__init__r  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   ziprl   )rF   r!  r3  r   r7  r8  r9  wcdas              r)   _matvecLowRankMatrix._matvecz  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   r7  r9  Nr   r3   )
lenr   r,   identityr4   	enumeratezerosr   r:  rl   )rF   r!  r3  r   r7  r9  c0Air=  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)r4  r,   r   r1  r?  r!  r3  r   r   rF   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)
r4  r,   r   r   r   r1  r?  r!  r   r3  rP  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      $ )rB  )r4  r   r1  rM  r!  r3  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)
r4  r   r   r   r1  rM  r,   r!  r   r3  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+   )r4  r   r3  appendr   rC  rl   collapse)r   r<  r=  s      r)   rY  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 r3   )warningswarnr4  r!  r,   rD  r   r4   r:  r3  r   r   )r   r4   rk   Gmr<  r=  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.)rk   N)r,   rD   r   r4  r3  r   r!  r   s    r)   rZ  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   r4  rC  r3  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   rf  rg  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

Nr_   r   r   economic)modeF)full_matrices)r4  r3  rp   rC  r.   r,   rD   r   r   r	   r   r   r
   r   rn   rk   )r   max_rank	to_retainr   rK  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!  r4  r3  r   r4   r   r   r   r+   )r"   r#   r$   r%   r&   r   staticmethodr?  rM  r   r   r   r   rY  r   rZ  ri  rl  r{  r'   r!   r(   r)   r1  r1  g  sj        6FOEN	"		?r(   r1  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   iK  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+   )ra  r{  reduce_paramsr   s   r)   r   'BroydenFirst.__init__.<locals>.<lambda>  s    477#5#5}#Er(   simplec                  6   > TR                   R                  " T 6 $ r+   )ra  rl  r  s   r)   r   r    s    477#8#8-#Hr(   restartc                  6   > TR                   R                  " T 6 $ r+   )ra  ri  r  s   r)   r   r    s    477#9#9=#Ir(   zUnknown rank reduction method '')r  r   r!  ra  r,   rE   rr  r   r  _reducerm   )r   r!  reduction_methodrr  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  rj   r1  r!  r<   r4   ra  r   s       r)   rj   BroydenFirst.setup  s4    Ta.TZZ]DJJGr(   c                 ,    [        U R                  5      $ r+   )r   ra  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+   )	ra  r   r,   rB   rC   rj   r$  r#  rX   )r   r   r]   rs       r)   r   BroydenFirst.solve  s_    GGNN1{{1~!!##JJt{{DKK;77>>!$$r(   c                 8    U R                   R                  U5      $ r+   )ra  r   r   r   s     r)   r   BroydenFirst.matvec  s    ww}}Qr(   c                 8    U R                   R                  U5      $ r+   )ra  r   r   r   r]   s      r)   r   BroydenFirst.rsolve  s    wwq!!r(   c                 8    U R                   R                  U5      $ r+   )ra  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  ra  r   r   r   rY  
r   r0   r   r   r*  r   r+  rF   r<  r=  s
             r)   r,  BroydenFirst._update  sO    GGOOB##ROqr(   )ra  r  r!  rr  )Nr  Nr   )r"   r#   r$   r%   r&   r   rj   r   r   r   r   r   r,  r'   r!   r(   r)   r   r   K  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 Nr_   )r  ra  r   rY  r  s
             r)   r,  BroydenSecond._update  s@    ##
Nqr(   r!   N)r"   r#   r$   r%   r&   r,  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__B  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   r3   )r!  rC  r   r,   emptyr4   rn   r   r*  r   r>  r   )	r   r   r]   r   r   df_frz  r   r  s	            r)   r   Anderson.solveK  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   r3   r_   )r!  rC  r   r,   r  r4   rn   r   r*  r  r   )r   r   r   r   r  rz  brI  rJ  r   r  s              r)   r   Anderson.matvecb  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   r3   r_   r   )r  r   rY  r*  rC  popr,   rF  r4   rn   r  r   triur   r   r>  )r   r0   r   r   r*  r   r+  r   r>  rI  rJ  wds               r)   r,  Anderson._updatey  s#   66Q;rr$''lTVV#GGKKNGGKKN $''lTVV# LHHaV177+qA1[6!BBB$TWWQZ <<A# !  	
RWWQ]__!!##r(   )r  r>  r!  r*  r   r   r  )Nr      r   )
r"   r#   r$   r%   r&   r   r   r   r,  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   r3   )r  rj   r,   fullr<   r!  r4   r=  r   s       r)   rj   DiagBroyden.setup  s=    Ta.$**Q-)1tzz>Lr(   c                 "    U* U R                   -  $ r+   r=  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+   r=  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,   diagr=  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)   r,  DiagBroyden._update  s(    2r	>2%gqj00r(   )r!  r=  r+   r   r"   r#   r$   r%   r&   r   rj   r   r   r   r   r   r,  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)   r,  LinearMixing._update  r   r(   r  r+   r   )r"   r#   r$   r%   r&   r   r   r   r   r   r   r,  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__$  s!    %
 	r(   c                     [         R                  XX#5        [        R                  " U R                  S   4U R
                  U R                  S9U l        g r  )r  rj   r,   r  r<   r!  r4   r  r   s       r)   rj   ExcitingMixing.setup*  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.matvec1  r  r(   c                 >    U* U R                   R                  5       -  $ r+   r  r   r  s      r)   r   ExcitingMixing.rsolve4      r$)).."""r(   c                 >    U* U R                   R                  5       -  $ r+   r  r  s     r)   r   ExcitingMixing.rmatvec7  r  r(   c                 H    [         R                  " SU R                  -  5      $ )Nr  )r,   r  r  r   s    r)   r   ExcitingMixing.todense:  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   r0   r   r   r*  r   r+  incrs           r)   r,  ExcitingMixing._update=  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   iH  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)rz   r  r  r   rz   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.r]  )r^  category)preconditionerr   r  r   r  r  r  r  r  r  r  r  getmethod	method_kw
setdefaultgcrotmkr   
parametersr   
startswithrm   r   r_  r`  UserWarning)r   r   r  inner_maxiterinner_Mr  r   rz  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>   r.   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#  rX   r>   r%  r,   rC   rB   rm   )r   rF   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 )Nrr   )r>   r%  r&  r  r   rr   )r   r0   r   s      r)   rr   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"  rj   )r   rj   r>   r%  r   r  r  aslinearoperatorr.  r   r,   r   r4   r   r&  r  r   )r   r0   r   rX   s       r)   rj   KrylovJacobian.setup  s    t(,,%%66t<::!''*..48DJ  *t**G44##))!5 5 +r(   )r%  r  r  r#  r.  r  r   r>   )Nr     N
   r   )r"   r#   r$   r%   r&   r   r&  r   r   rr   rj   r'   r!   r(   r)   r   r   H  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:  rC  joinrm   r  r"   rr   globalsexecr&   rM   )r   r;  r   r  varargsvarkwdefaults
kwonlyargs
kwdefaults_r  rz  rF   kw_strkwkw_strwrappernsrX   s                     r)   _nonlin_wrapperrL  0  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   )?r  rs   r_  numpyr,   r   r   r   scipy.linalgr   r   r   r	   r
   r   scipy.sparse.linalgr   scipy.sparser   scipy._lib._utilr   r   r=  _linesearchr   r   r   difflibr   __all__	Exceptionr   r1   r8   r@   rG   r  striprK   rM   r   rq   rg   r   r   ri   r  r1  r   r  r  r  r  r  r   rL  r   r   r   r   r   r   r   r!   r(   r)   <module>rW     s    
   $ $ ? ?   ' + F C  %J	I 	   	(P 	a1
h/
 ?DKO?C48O"d 	  FJ!*Z9< 9<@E EP$# $#NY?@X 4I IX * 	+  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(   