
    xf                        d dl Z d dlZd dlmZmZmZmZmZm	Z	 d dlm
Z
mZmZ d dlZd dlZd dlmZ d dlZd dlmZ ddlmZmZ g dZ G d	 d
e      Zd Zd Zd Zd Z edjA                         djA                               Z!d Z"	 	 	 	 d8dZ# e"e#       	 	 d9dZ$ G d d      Z% G d d      Z& G d d      Z'd Z( G d de&      Z) G d d      Z*d jA                         e!d!<    G d" d#e)      Z+ G d$ d%e+      Z, G d& d'e)      Z- G d( d)e)      Z. G d* d+e)      Z/ G d, d-e)      Z0 G d. d/e&      Z1d0 Z2 e2d1e+      Z3 e2d2e,      Z4 e2d3e-      Z5 e2d4e/      Z6 e2d5e.      Z7 e2d6e0      Z8 e2d7e1      Z9y):    N)normsolveinvqrsvdLinAlgError)asarraydotvdot)get_blas_funcs)getfullargspec_no_self   )scalar_search_wolfe1scalar_search_armijo)
broyden1broyden2andersonlinearmixingdiagbroydenexcitingmixingnewton_krylovBroydenFirstKrylovJacobianInverseJacobianc                       e Zd Zy)NoConvergenceN)__name__
__module____qualname__     8/usr/lib/python3/dist-packages/scipy/optimize/_nonlin.pyr   r      s    r!   r   c                 H    t        j                  |       j                         S N)npabsolutemaxxs    r"   maxnormr*      s    ;;q>r!   c                     t        |       } t        j                  | j                  t        j                        st        | t        j
                        S | S )z:Return `x` as an array, of either floats or complex floatsdtype)r	   r%   
issubdtyper-   inexactfloat_r(   s    r"   _as_inexactr1   "   s7    
A=="**-q		**Hr!   c                     t        j                  | t        j                  |            } t        |d| j                        } ||       S )z;Return ndarray `x` as same array subclass and shape as `x0`__array_wrap__)r%   reshapeshapegetattrr3   )r)   x0wraps      r"   _array_liker9   *   s8    


1bhhrl#A2')9)9:D7Nr!   c                     t        j                  |       j                         s#t        j                  t         j                        S t        |       S r$   )r%   isfiniteallarrayinfr   )vs    r"   
_safe_normr@   1   s2    ;;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                 N    | j                   r| j                   t        z  | _         y y r$   )__doc__
_doc_parts)objs    r"   _set_docrG   o   s    
{{kkJ. r!   c           
          |
t         n|
}
t        ||||	||
      }t               fd}j                         }t	        j
                  |t        j                        } ||      }t        |      }t        |      }|j                  |j                         ||       |||dz   }nd|j                  dz   z  }|du rd}n|du rd}|d	vrt        d
      d}d}d}d}t        |      D ]C  }|j                  |||      }|r nDt        |||z        }|j!                  ||       }t        |      dk(  rt        d      |rt#        |||||      \  }}}}nd}||z   } ||      }t        |      }|j%                  |j                         |       |r	 |||       ||dz  z  |dz  z  }||dz  z  |k  rt        ||      }nt        |t'        |||dz  z              }|}|st(        j*                  j-                  d| |
|      |fz         t(        j*                  j/                          F |rt1        t3        |            d}|r)|j4                  |||dk(  ddd|   d}t3        |      |fS t3        |      S )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         t        |                   j                         S r$   )r1   r9   flatten)zFr7   s    r"   funcznonlin_solve.<locals>.func   s#    1[B/0199;;r!   r   d   TarmijoF)NrT   wolfezInvalid line searchg?gH.?g?gMbP?)tolr   z[Jacobian inversion yielded zero vector. This indicates a bug in the Jacobian approximation.      ?   z%d:  |F(x)| = %g; step %g
z0A solution was found at the specified tolerance.z:The maximum number of iterations allowed has been reached.)r   rX   )nitfunstatussuccessmessage)r*   TerminationConditionr1   rO   r%   	full_liker>   r   
asjacobiansetupcopysize
ValueErrorrangecheckminr   _nonlin_line_searchupdater'   sysstdoutwriteflushr   r9   	iteration) rQ   r7   jacobianrM   verbosemaxiterrI   rJ   rK   rL   tol_normline_searchcallbackfull_outputraise_exception	conditionrR   r)   dxFxFx_normgammaeta_maxeta_tresholdetanr[   rV   sFx_norm_neweta_Ainfos    ``                              r"   nonlin_solver   t   s   Z #*wH$5+0*.X?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 JJ:8B<>$ $ %JJU/X Ar 233F ** !Q; , 3 %	&		 1b!4''1b!!r!   c                 l    dg|gt        |      dz  gt              t              z  d fd	fd}|dk(  rt        |d   d|      \  }}	}
n|dk(  rt        d   d    |	      \  }}	d
}|z  z   |d   k(  rd   }n        }t        |      }|||fS )Nr   rX   c                     | 	d   k(  rd   S 
| z  z   } |      }t        |      dz  }|r| 	d<   |d<   |d<   |S )Nr   rX   )r@   )r   storextr?   prx   rR   tmp_Fxtmp_phitmp_sr)   s        r"   phiz _nonlin_line_search.<locals>.phi  s_    a=1:2XHqM1E!HGAJF1Ir!   c                 ^    t        |       z   dz   z  } | |z   d       |       z
  |z  S )Nr   F)r   )abs)r   dsr   rdiffs_norms     r"   derphiz#_nonlin_line_search.<locals>.derphi  s9    !fvo!U*AbD&Q/255r!   rU   {Gz?)xtolaminrT   )r   rW   )T)r   r   r   )rR   r)   ry   rx   search_typer   sminr   r   phi1phi0rz   r   r   r   r   r   s   `` ` `      @@@@@r"   rh   rh   
  s    CETFBx{mG!WtBxF
 
6 g,S&'!*26TC4		 &sGAJ,024 	y 	AbDAE!H}AY!W2hGaWr!   c                   *    e Zd ZdZdddddefdZd Zy)r^   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                 D   |0t        j                  t         j                        j                  dz  }|t         j                  }|t         j                  }|t         j                  }|| _        || _        || _        || _        || _	        || _
        d | _        d| _        y )NgUUUUUU?r   )r%   finfor0   epsr>   rK   rL   rI   rJ   r   rM   f0_normrn   )selfrI   rJ   rK   rL   rM   r   s          r"   __init__zTerminationCondition.__init__D  s     =HHRYY'++5E>VVF=FFE>VVF

		r!   c                    | xj                   dz  c_         | j                  |      }| j                  |      }| j                  |      }| j                  || _        |dk(  ry| j                  d| j                   | j                  kD  z  S t	        || j
                  k  xr || j                  z  | j                  k  xr# || j                  k  xr || j                  z  |k        S )Nr   r   rX   )	rn   r   r   rM   intrI   rJ   rK   rL   )r   fr)   rx   f_normx_normdx_norms          r"   rf   zTerminationCondition.check\  s    !11))B-<<!DLQ;99 233 Fdjj( ;t{{*dll:;4::- :#DKK/69< 	<r!   )r   r   r   rD   r*   r   rf   r    r!   r"   r^   r^   7  s!     "$d40<r!   r^   c                   0    e Zd ZdZd Zd ZddZd Zd Zy)	Jacobiana  
    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                      g d}|j                         D ]*  \  }}||vrt        d|z        |t         |||          , t         d      r fd _        y y )N)	r   ri   matvecrmatvecrsolvematmattodenser5   r-   zUnknown keyword argument %sr   c                  $     j                         S r$   )r   r   s   r"   <lambda>z#Jacobian.__init__.<locals>.<lambda>  s    T\\^ r!   )itemsrd   setattrhasattr	__array__)r   kwnamesnamevalues   `    r"   r   zJacobian.__init__  sj    888: 	.KD%5  !>!EFF dBtH-		. 4#3DN $r!   c                     t        |       S r$   )r   r   s    r"   aspreconditionerzJacobian.aspreconditioner  s    t$$r!   c                     t         r$   NotImplementedErrorr   r?   rV   s      r"   r   zJacobian.solve      !!r!   c                      y r$   r    r   r)   rQ   s      r"   ri   zJacobian.update      r!   c                     || _         |j                  |j                  f| _        |j                  | _        | j                  j
                  t        j
                  u r| j                  ||       y y r$   )rR   rc   r5   r-   	__class__ra   r   ri   r   r)   rQ   rR   s       r"   ra   zJacobian.setup  sQ    	ffaff%
WW
>>8>>1KK1 2r!   Nr   )	r   r   r   rD   r   r   r   ri   ra   r    r!   r"   r   r   w  s!    #J
4%"r!   r   c                   2    e Zd Zd Zed        Zed        Zy)r   c                     || _         |j                  | _        |j                  | _        t	        |d      r|j
                  | _        t	        |d      r|j                  | _        y y )Nra   r   )ro   r   r   ri   r   ra   r   r   )r   ro   s     r"   r   zInverseJacobian.__init__  sN     nnoo8W%!DJ8X&#??DL 'r!   c                 .    | j                   j                  S r$   )ro   r5   r   s    r"   r5   zInverseJacobian.shape      }}"""r!   c                 .    | j                   j                  S r$   )ro   r-   r   s    r"   r-   zInverseJacobian.dtype  r   r!   N)r   r   r   r   propertyr5   r-   r    r!   r"   r   r     s/    + # # # #r!   r   c                 (    t         j                  j                  j                  t	         t
              r S t        j                         rt         t
              r         S t	         t        j                        r j                  dkD  rt        d      t        j                  t        j                                 j                  d    j                  d   k7  rt        d      t         fd fd fd fd	 j                    j                  
      S t         j                  j#                         r] j                  d    j                  d   k7  rt        d      t         fd fd fd fd j                    j                  
      S t%         d      r{t%         d      rot%         d      rct        t'         d      t'         d       j(                  t'         d      t'         d      t'         d       j                    j                        S t+               r G  fddt
              } |       S t	         t,              r6 t/        t0        t2        t4        t6        t8        t:        t<                         S t?        d      )zE
    Convert given object to one suitable for use as a Jacobian.
    rX   zarray must have rank <= 2r   r   zarray must be squarec                     t        |       S r$   )r
   r?   Js    r"   r   zasjacobian.<locals>.<lambda>  s    Q r!   c                 L    t        j                         j                  |       S r$   )r
   conjTr   s    r"   r   zasjacobian.<locals>.<lambda>  s    #affhjj!*< r!   c                     t        |       S r$   )r   r   s    r"   r   zasjacobian.<locals>.<lambda>  s    a r!   c                 L    t        j                         j                  |       S r$   )r   r   r   r   s    r"   r   zasjacobian.<locals>.<lambda>  s    qvvxzz1)= r!   )r   r   r   r   r-   r5   zmatrix must be squarec                     | z  S r$   r    r   s    r"   r   zasjacobian.<locals>.<lambda>  s    1 r!   c                 >    j                         j                  | z  S r$   r   r   r   s    r"   r   zasjacobian.<locals>.<lambda>  s    !&&(**q. r!   c                      |       S r$   r    r?   r   spsolves    r"   r   zasjacobian.<locals>.<lambda>  s    1 r!   c                 F     j                         j                  |       S r$   r   r   s    r"   r   zasjacobian.<locals>.<lambda>  s    Q)? r!   r5   r-   r   r   r   r   ri   ra   )r   r   r   r   ri   ra   r-   r5   c                   D    e Zd Zd Zd fd	Z fdZd fd	Z fdZy)asjacobian.<locals>.Jacc                     || _         y r$   r(   r   s      r"   ri   zasjacobian.<locals>.Jac.update  s	    r!   c                      | j                         }t        |t        j                        rt	        ||      S t
        j                  j                  |      r	 ||      S t        d      NzUnknown matrix type)	r)   
isinstancer%   ndarrayr   scipysparse
isspmatrixrd   r   r?   rV   mr   r   s       r"   r   zasjacobian.<locals>.Jac.solve  sT    dffIa, A;&\\,,Q/"1a=($%:;;r!   c                      | j                         }t        |t        j                        rt	        ||      S t
        j                  j                  |      r||z  S t        d      r   )	r)   r   r%   r   r
   r   r   r   rd   r   r?   r   r   s      r"   r   zasjacobian.<locals>.Jac.matvec  sQ    dffIa,q!9$\\,,Q/Q3J$%:;;r!   c                 :    | j                         }t        |t        j                        r$t	        |j                         j                  |      S t        j                  j                  |      r! |j                         j                  |      S t        d      r   )r)   r   r%   r   r   r   r   r   r   r   rd   r   s       r"   r   zasjacobian.<locals>.Jac.rsolve  sj    dffIa, Q//\\,,Q/"1668::q11$%:;;r!   c                 2    | j                         }t        |t        j                        r$t	        |j                         j                  |      S t        j                  j                  |      r|j                         j                  |z  S t        d      r   )r)   r   r%   r   r
   r   r   r   r   r   rd   r   s      r"   r   zasjacobian.<locals>.Jac.rmatvec  sg    dffIa,qvvxzz1--\\,,Q/668::>)$%:;;r!   Nr   )r   r   r   ri   r   r   r   r   )r   r   s   r"   Jacr     s    <<<<r!   r   )r   r   r   r   r   r   krylovz#Cannot convert object to a Jacobian) r   r   linalgr   r   r   inspectisclass
issubclassr%   r   ndimrd   
atleast_2dr	   r5   r-   r   r   r6   r   callablestrdictr   BroydenSecondAndersonDiagBroydenLinearMixingExcitingMixingr   	TypeError)r   r   r   s   ` @r"   r`   r`     s    ll!!))G!X		
1h 7s
	Arzz	"66A:899MM"**Q-(771:#3442 <3=ggQWW	6 	6
 
	 	 	#771:#455} 85?ggQWW	6 	6
 
G	G!4G9Lwq(3 '9 5gg&q(3&q(3%a1gggg' 	' 
!&	<( &	<N u	As	.t\*% +!-#1)+ ,-. 0 	0 =>>r!   c                       e Zd Zd Zd Zd Zy)GenericBroydenc                     t         j                  | |||       || _        || _        t	        | d      rC| j
                  6t        |      }|r!dt        t        |      d      z  |z  | _        y d| _        y y y )Nalpha      ?r   rW   )r   ra   last_flast_xr   r  r   r'   )r   r7   f0rR   normf0s        r"   ra   zGenericBroyden.setup/  sn    tRT*4!djj&8 "XF T"Xq!11F:
 
 '9!r!   c                     t         r$   r   r   r)   r   rx   dfr   df_norms          r"   _updatezGenericBroyden._update=  r   r!   c           
          || j                   z
  }|| j                  z
  }| j                  ||||t        |      t        |             || _         || _        y r$   )r  r  r  r   )r   r)   r   r  rx   s        r"   ri   zGenericBroyden.update@  sH    __Q2r48T"X6r!   N)r   r   r   ra   r  ri   r    r!   r"   r  r  .  s    !"r!   r  c                   x    e Zd ZdZd Zed        Zed        Zd Zd Z	ddZ
ddZd	 Zd
 Zd Zd Zd ZddZy)LowRankMatrixz
    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                 X    || _         g | _        g | _        || _        || _        d | _        y r$   )r  csr   r   r-   	collapsed)r   r  r   r-   s       r"   r   zLowRankMatrix.__init__S  s,    

r!   c                     t        g d|d d | gz         \  }}}|| z  }t        ||      D ]#  \  }}	 ||	|       }
 ||||j                  |
      }% |S )N)axpyscaldotcr   )r   ziprc   )r?   r  r  r   r  r  r  wcdas              r"   _matveczLowRankMatrix._matvec[  sm    )*B*,Ra&A3,8dDAIBK 	&DAqQ
AQ1661%A	& r!   c           	      J   t        |      dk(  r| |z  S t        ddg|dd | gz         \  }}|d   }|t        j                  t        |      |j                        z  }t        |      D ].  \  }}	t        |      D ]  \  }
}|||
fxx    ||	|      z  cc<    0 t        j                  t        |      |j                        }t        |      D ]  \  }
}	 ||	|       ||
<    ||z  }t        ||      }| |z  }t        ||      D ]  \  }} ||||j                  |       } |S )Evaluate w = M^-1 vr   r  r  Nr   r,   )
lenr   r%   identityr-   	enumeratezerosr   r  rc   )r?   r  r  r   r  r  c0Air  jr  qr  qcs                  r"   _solvezLowRankMatrix._solvee  s:    r7a<U7N $VV$4b!fslC
dUBKKBrxx88bM 	%DAq!" %1!A#$q!*$%	% HHSWBHH-bM 	DAq1:AaD		U
!QKeGQZ 	(EArQ166B3'A	( r!   c                     | j                    t        j                  | j                   |      S t        j	                  || j
                  | j                  | j                        S )zEvaluate w = M v)r  r%   r
   r  r  r  r  r   r   r?   s     r"   r   zLowRankMatrix.matvec  sD    >>%66$..!,,$$Q

DGGTWWEEr!   c                    | j                   8t        j                  | j                   j                  j	                         |      S t
        j                  |t        j                  | j                        | j                  | j                        S )zEvaluate w = M^H v)
r  r%   r
   r   r   r  r  r  r   r  r,  s     r"   r   zLowRankMatrix.rmatvec  s\    >>%66$..**//1155$$Q

(;TWWdggNNr!   c                     | j                   t        | j                   |      S t        j                  || j                  | j
                  | j                        S )r  )r  r   r  r*  r  r  r   r   s      r"   r   zLowRankMatrix.solve  s@    >>%++##Atzz477DGGDDr!   c                    | j                   .t        | j                   j                  j                         |      S t        j                  |t        j                  | j                        | j                  | j                        S )zEvaluate w = M^-H v)
r  r   r   r   r  r*  r%   r  r   r  r   s      r"   r   zLowRankMatrix.rsolve  sX    >>%))..0!44##Arwwtzz':DGGTWWMMr!   c                 X   | j                   5| xj                   |d d d f   |d d d f   j                         z  z  c_         y | j                  j                  |       | j                  j                  |       t        | j                        |j                  kD  r| j                          y y r$   )r  r   r  appendr   r   rc   collapse)r   r  r  s      r"   r1  zLowRankMatrix.append  s{    >>%NNa$i!DF)..*:::Nqqtww<!&& MMO !r!   c                 >   | j                   | j                   S | j                  t        j                  | j                  | j
                        z  }t        | j                  | j                        D ])  \  }}||d d d f   |d d d f   j                         z  z  }+ |S )Nr,   )
r  r  r%   r!  r   r-   r  r  r   r   )r   Gmr  r  s       r"   r   zLowRankMatrix.__array__  s    >>%>>!ZZDFF$**==) 	-DAq!AdF)Ad1fINN,,,B	-	r!   c                 b    t        j                  |       | _        d| _        d| _        d| _        y)z0Collapse the low-rank matrix to a full-rank one.N)r%   r=   r  r  r   r  r   s    r"   r2  zLowRankMatrix.collapse  s&    $
r!   c                     | j                   y|dkD  sJ t        | j                        |kD  r| j                  dd= | j                  dd= yy)zH
        Reduce the rank of the matrix by dropping all vectors.
        Nr   r  r   r  r   r   ranks     r"   restart_reducezLowRankMatrix.restart_reduce  sG     >>%axxtww<$

 r!   c                     | j                   y|dkD  sJ t        | j                        |kD  r4| j                  d= | j                  d= t        | j                        |kD  r3yy)zK
        Reduce the rank of the matrix by dropping oldest vectors.
        Nr   r7  r8  s     r"   simple_reducezLowRankMatrix.simple_reduce  sT     >>%axx$''lT!

 $''lT!r!   Nc                    | j                   y|}||}n|dz
  }| j                  r"t        |t        | j                  d               }t	        dt        ||dz
              }t        | j                        }||k  ryt        j                  | j                        j                  }t        j                  | j                        j                  }t        |d      \  }}t        ||j                  j                               }t        |d      \  }	}
}t        |t        |            }t        ||j                  j                               }t        |      D ]J  }|dd|f   j                         | j                  |<   |dd|f   j                         | j                  |<   L | j                  |d= | j                  |d= y)	a  
        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

        NrX   r   r   economic)modeF)full_matrices)r  r  rg   r   r'   r%   r=   r   r   r   r
   r   r   r   re   rb   )r   max_rank	to_retainr   r(  r   CDRUSWHks                r"   
svd_reducezLowRankMatrix.svd_reduce  sh   : >>% AAA77As4771:'A3q!A#;Lq5HHTWWHHTWW!*%113388:q.1b3r7O24499;q 	'A1Q3DGGAJ1Q3DGGAJ	' GGABKGGABKr!   r   r$   )r   r   r   rD   r   staticmethodr  r*  r   r   r   r   r1  r   r2  r:  r<  rJ  r    r!   r"   r  r  H  sj        6FOEN			?r!   r  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                   F    e Zd ZdZddZd Zd ZddZd ZddZ	d	 Z
d
 Zy)r   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://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.broyden1(fun, [0, 0])
    >>> sol
    array([0.84116396, 0.15883641])

    Nc                 L    t         j                          | _        d  _        |t        j
                  }| _        t        |t              rdn
|dd  |d   }|dz
  fz   |dk(  r fd _	        y |dk(  r fd _	        y |dk(  r fd	 _	        y t        d
|z        )Nr    r   r   r   c                  6     j                   j                    S r$   )r4  rJ  reduce_paramsr   s   r"   r   z'BroydenFirst.__init__.<locals>.<lambda>k  s    #5477#5#5}#E r!   simplec                  6     j                   j                    S r$   )r4  r<  rP  s   r"   r   z'BroydenFirst.__init__.<locals>.<lambda>m  s    #8477#8#8-#H r!   restartc                  6     j                   j                    S r$   )r4  r:  rP  s   r"   r   z'BroydenFirst.__init__.<locals>.<lambda>o  s    #9477#9#9=#I r!   z"Unknown rank reduction method '%s')r  r   r  r4  r%   r>   rA  r   r   _reducerd   )r   r  reduction_methodrA  rQ  s   `   @r"   r   zBroydenFirst.__init__Z  s    %
vvH &,M,QR0M/2!A-7u$EDL)HDL*IDLA-. / /r!   c                     t         j                  | |||       t        | j                   | j                  d   | j
                        | _        y )Nr   )r  ra   r  r  r5   r-   r4  r   s       r"   ra   zBroydenFirst.setupt  s8    T1a.TZZ]DJJGr!   c                 ,    t        | j                        S r$   )r   r4  r   s    r"   r   zBroydenFirst.todensex  s    477|r!   c                    | j                   j                  |      }t        j                  |      j	                         sL| j                  | j                  | j                  | j                         | j                   j                  |      S |S r$   )	r4  r   r%   r;   r<   ra   r  r  rR   )r   r   rV   rs       r"   r   zBroydenFirst.solve{  s\    GGNN1{{1~!!#JJt{{DKK;77>>!$$r!   c                 8    | j                   j                  |      S r$   )r4  r   r   r   s     r"   r   zBroydenFirst.matvec  s    ww}}Qr!   c                 8    | j                   j                  |      S r$   )r4  r   r   r   rV   s      r"   r   zBroydenFirst.rsolve  s    wwq!!r!   c                 8    | j                   j                  |      S r$   )r4  r   r]  s     r"   r   zBroydenFirst.rmatvec  s    ww~~a  r!   c                     | j                          | j                  j                  |      }|| j                  j                  |      z
  }|t	        ||      z  }	| j                  j                  ||	       y r$   )rV  r4  r   r   r   r1  
r   r)   r   rx   r  r   r  r?   r  r  s
             r"   r  zBroydenFirst._update  sU    GGOOB##ROq!r!   )NrT  Nr   )r   r   r   rD   r   ra   r   r   r   r   r   r  r    r!   r"   r   r   $  s1    3j/4H "!r!   r   c                       e Zd ZdZd Zy)r   aK  
    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                     | j                          |}|| j                  j                  |      z
  }||dz  z  }	| j                  j                  ||	       y NrX   )rV  r4  r   r1  rb  s
             r"   r  zBroydenSecond._update  sF    ##
Nq!r!   N)r   r   r   rD   r  r    r!   r"   r   r     s    0dr!   r   c                   ,    e Zd ZdZddZddZd Zd Zy)	r   a  
    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                     t         j                  |        || _        || _        g | _        g | _        d | _        || _        y r$   )r  r   r  Mrx   r  r{   w0)r   r  ri  rh  s       r"   r   zAnderson.__init__  s:    %

r!   c                    | j                    |z  }t        | j                        }|dk(  r|S t        j                  ||j
                        }t        |      D ]  }t        | j                  |   |      ||<     	 t        | j                  |      }t        |      D ]7  }|||   | j                  |   | j                   | j                  |   z  z   z  z  }9 |S # t        $ r# | j                  d d = | j                  d d = |cY S w xY wNr   r,   )r  r   rx   r%   emptyr-   re   r   r  r   r  r   )	r   r   rV   rx   r   df_frI  r{   r   s	            r"   r   zAnderson.solve&  s    jj[]L6Ixx)q 	*A4771:q)DG	*	$&&$'E q 	@A%(DGGAJDGGAJ)>>??B	@	  	

I		s   ;C )DDc           
      B   | | j                   z  }t        | j                        }|dk(  r|S t        j                  ||j
                        }t        |      D ]  }t        | j                  |   |      ||<     t        j                  ||f|j
                        }t        |      D ]  }t        |      D ]  }t        | j                  |   | j                  |         |||f<   ||k(  s4| j                  dk7  sD|||fxx   t        | j                  |   | j                  |         | j                  dz  z  | j                   z  z  cc<     t        ||      }	t        |      D ]7  }
||	|
   | j                  |
   | j                  |
   | j                   z  z   z  z  }9 |S )Nr   r,   rX   )r  r   rx   r%   rl  r-   re   r   r  ri  r   )r   r   rx   r   rm  rI  br&  r'  r{   r   s              r"   r   zAnderson.matvec=  sy   R

]L6Ixx)q 	*A4771:q)DG	* HHaV177+q 	QA1X Qdggaj$''!*5!A#6dgglacFd4771:twwqz:477A:EdjjPPFQ	Q
 aq 	@A%(DGGAJDJJ)>>??B	@	r!   c                 8   | j                   dk(  ry | j                  j                  |       | j                  j                  |       t	        | j                        | j                   kD  rY| j                  j                  d       | j                  j                  d       t	        | j                        | j                   kD  rYt	        | j                        }t        j                  ||f|j                        }t        |      D ][  }	t        |	|      D ]J  }
|	|
k(  r| j                  dz  }nd}d|z   t        | j                  |	   | j                  |
         z  ||	|
f<   L ] |t        j                  |d      j                  j                         z  }|| _        y )Nr   r,   rX   r   )rh  rx   r1  r  r   popr%   r#  r-   re   ri  r   triur   r   r  )r   r)   r   rx   r  r   r  r   r  r&  r'  wds               r"   r  zAnderson._updateT  s7   66Q;rr$''lTVV#GGKKNGGKKN $''lTVV# LHHaV177+q 	=A1a[ =6!BBB$TWWQZ <<!A#=	= 	
RWWQ]__!!##r!   )Nr      r   )r   r   r   rD   r   r   r   r  r    r!   r"   r   r     s    +L..r!   r   c                   F    e Zd ZdZddZd ZddZd ZddZd Z	d	 Z
d
 Zy)r   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                 <    t         j                  |        || _        y r$   r  r   r  r   r  s     r"   r   zDiagBroyden.__init__      %
r!   c                     t         j                  | |||       t        j                  | j                  d   fd| j
                  z  | j                        | _        y )Nr   r   r,   )r  ra   r%   fullr5   r  r-   r  r   s       r"   ra   zDiagBroyden.setup  sA    T1a.$**Q-)1tzz>Lr!   c                 "    | | j                   z  S r$   r  r_  s      r"   r   zDiagBroyden.solve      rDFF{r!   c                 "    | | j                   z  S r$   r}  r]  s     r"   r   zDiagBroyden.matvec  r~  r!   c                 >    | | j                   j                         z  S r$   r  r   r_  s      r"   r   zDiagBroyden.rsolve      rDFFKKM!!r!   c                 >    | | j                   j                         z  S r$   r  r]  s     r"   r   zDiagBroyden.rmatvec  r  r!   c                 B    t        j                  | j                         S r$   )r%   diagr  r   s    r"   r   zDiagBroyden.todense  s    wwwr!   c                 `    | xj                   || j                   |z  z   |z  |dz  z  z  c_         y re  r}  r
  s          r"   r  zDiagBroyden._update  s*    2r	>2%gqj00r!   r$   r   r   r   r   rD   r   ra   r   r   r   r   r   r  r    r!   r"   r   r   r  s1    &PM"" 1r!   r   c                   @    e Zd ZdZd
dZddZd ZddZd Zd Z	d	 Z
y)r   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                 <    t         j                  |        || _        y r$   rw  rx  s     r"   r   zLinearMixing.__init__  ry  r!   c                 "    | | j                   z  S r$   r  r_  s      r"   r   zLinearMixing.solve      r$**}r!   c                 "    | | j                   z  S r$   r  r]  s     r"   r   zLinearMixing.matvec  r  r!   c                 H    | t        j                  | j                        z  S r$   r%   r   r  r_  s      r"   r   zLinearMixing.rsolve      r"''$**%%%r!   c                 H    | t        j                  | j                        z  S r$   r  r]  s     r"   r   zLinearMixing.rmatvec  r  r!   c                     t        j                  t        j                  | j                  d   d| j                  z              S )Nr   )r%   r  r{  r5   r  r   s    r"   r   zLinearMixing.todense  s,    wwrwwtzz!}bm<==r!   c                      y r$   r    r
  s          r"   r  zLinearMixing._update  r   r!   r$   r   )r   r   r   rD   r   r   r   r   r   r   r  r    r!   r"   r   r     s*    ,&&>r!   r   c                   F    e Zd ZdZddZd ZddZd ZddZd Z	d	 Z
d
 Zy)r   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                 X    t         j                  |        || _        || _        d | _        y r$   )r  r   r  alphamaxbeta)r   r  r  s      r"   r   zExcitingMixing.__init__  s%    %
 	r!   c                     t         j                  | |||       t        j                  | j                  d   f| j
                  | j                        | _        y rk  )r  ra   r%   r{  r5   r  r-   r  r   s       r"   ra   zExcitingMixing.setup  s=    T1a.GGTZZ],djj

K	r!   c                 "    | | j                   z  S r$   r  r_  s      r"   r   zExcitingMixing.solve	      r$))|r!   c                 "    | | j                   z  S r$   r  r]  s     r"   r   zExcitingMixing.matvec  r  r!   c                 >    | | j                   j                         z  S r$   r  r   r_  s      r"   r   zExcitingMixing.rsolve      r$)).."""r!   c                 >    | | j                   j                         z  S r$   r  r]  s     r"   r   zExcitingMixing.rmatvec  r  r!   c                 F    t        j                  d| j                  z        S )Nr  )r%   r  r  r   s    r"   r   zExcitingMixing.todense  s    wwr$))|$$r!   c                    || j                   z  dkD  }| j                  |xx   | j                  z  cc<   | j                  | j                  | <   t        j                  | j                  d| j
                  | j                         y )Nr   )out)r  r  r  r%   clipr  )r   r)   r   rx   r  r   r  incrs           r"   r  zExcitingMixing._update  s\    }q 		$4::%::		4%
		1dmm;r!   )NrW   r   r  r    r!   r"   r   r     s0    4L##%<r!   r   c                   <    e Zd ZdZ	 	 d	dZd Zd Zd
dZd Zd Z	y)r   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                 J   || _         || _        t        t        j                  j
                  j                  t        j                  j
                  j                  t        j                  j
                  j                  t        j                  j
                  j                  t        j                  j
                  j                  t        j                  j
                  j                        j                  ||      | _        t        || j                         | _        | j                  t        j                  j
                  j                  u r<|| j                  d<   d| j                  d<   | j                  j                  dd       nR| j                  t        j                  j
                  j                   t        j                  j
                  j                  t        j                  j
                  j                  fv r| j                  j                  dd       n| j                  t        j                  j
                  j                  u r|| j                  d<   d| j                  d<   | j                  j                  d	g        | j                  j                  d
d       | j                  j                  dd       | j                  j                  dd       |j#                         D ]6  \  }}|j%                  d      st'        d|z        || j                  |dd  <   8 y )N)bicgstabgmreslgmrescgsminrestfqmr)rq   rh  rT  r   rq   atolr   outer_kouter_vprepend_outer_vTstore_outer_AvFinner_zUnknown parameter %s   )preconditionerr   r   r   r   r   r  r  r  r  r  r  getmethod	method_kw
setdefaultgcrotmkr   
startswithrd   )	r   r   r  inner_maxiterinner_Mr  r   keyr   s	            r"   r   zKrylovJacobian.__init__  s9   %
 \\((11,,%%++<<&&--##''<<&&--,,%%++ c&&! 	 mt7J7JK;;%,,--333(5DNN9%()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(/DNN9%()DNN9%NN%%i4NN%%&7> NN%%&6>NN%%fa0((* 	,JC>>(+ !7#!=>>&+DNN3qr7#	,r!   c                     t        | j                        j                         }t        | j                        j                         }| j                  t        d|      z  t        d|      z  | _        y )Nr   )r   r7   r'   r  r   omega)r   mxmfs      r"   _update_diff_stepz KrylovJacobian._update_diff_step  sO    \\ZZ#a*,s1bz9
r!   c                 f   t        |      }|dk(  rd|z  S | j                  |z  }| j                  | j                  ||z  z         | j                  z
  |z  }t        j                  t        j                  |            s3t        j                  t        j                  |            rt        d      |S )Nr   z$Function returned non-finite results)	r   r  rR   r7   r  r%   r<   r;   rd   )r   r?   nvscr[  s        r"   r   zKrylovJacobian.matvec  s    !W7Q3JZZ"_YYtwwA~&0B6vvbkk!n%"&&Q*@CDDr!   c                     d| j                   v r- | j                  | j                  |fi | j                   \  }}|S  | j                  | j                  |fd|i| j                   \  }}|S )NrV   )r  r  op)r   rhsrV   solr   s        r"   r   zKrylovJacobian.solve  sg    DNN"#DGGSCDNNCIC 
 $DGGSLcLT^^LIC
r!   c                     || _         || _        | j                          | j                  4t	        | j                  d      r| j                  j                  ||       y y y )Nri   )r7   r  r  r  r   ri   )r   r)   r   s      r"   ri   zKrylovJacobian.update  sZ      *t**H5##**1a0 6 +r!   c                    t         j                  | |||       || _        || _        t        j
                  j                  j                  |       | _        | j                  1t        j                  |j                        j                  dz  | _	        | j                          | j                  5t!        | j                  d      r| j                  j                  |||       y y y )Nr  ra   )r   ra   r7   r  r   r   r   aslinearoperatorr  r   r%   r   r-   r   r  r  r   )r   r)   r   rR   s       r"   ra   zKrylovJacobian.setup  s    tQ4(,,%%66t<::!''*..48DJ  *t**G4##))!Q5 5 +r!   )Nr     N
   r   )
r   r   r   rD   r   r  r   r   ri   ra   r    r!   r"   r   r   #  s2    cJ CE')-,^:
16r!   r   c           	      L   t        |j                        }|\  }}}}}}}	t        t        |t	        |       d |            }
dj                  |
D cg c]  \  }}| d| c}}      }|rd|z   }dj                  |
D cg c]  \  }}| d|  c}}      }|r|dz   }|rt        d|z        d}|t        | ||j                  |      z  }i }|j                  t                      t        ||       ||    }|j                  |_        t        |       |S c c}}w c c}}w )a  
    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 %sa  
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  r   joinrd   r   r   ri   globalsexecrD   rG   )r   r  	signatureargsvarargsvarkwdefaults
kwonlyargs
kwdefaults_kwargsrI  r?   kw_strkwkw_strwrappernsrR   s                     r"   _nonlin_wrapperr    s,     -I@I=D'5(J
A#dCM>?+X67FYY8A1#Qqe89Fyy8AQCq*89Hd?2Y>??G $6s||"*, ,G	BIIgi"d8D;;DLTNK; 9 9s   D
D 
r   r   r   r   r   r   r   )r   NFNNNNNNrT   NFT)rT   g:0yE>r   ):rj   numpyr%   scipy.linalgr   r   r   r   r   r   r	   r
   r   scipy.sparse.linalgr   scipy.sparser   r   scipy._lib._utilr   r  _linesearchr   r   __all__	Exceptionr   r*   r1   r9   r@   r   striprE   rG   r   rh   r^   r   r   r`   r  r  r   r   r   r   r   r   r   r  r   r   r   r   r   r   r   r    r!   r"   <module>r     s     ? ? $ $   '  F C9	I 	   	(P 	a1
h/
 ?DKO?C48P"f 	  FJ!*Z9< 9<@A AH# #&Y?@X 4A AH * 	+  0o> od9L 9@U~ UxA1. A1H+> +\8<^ 8<~C6X C6T)X :|4:}5:x0~|<m[9 !1>B@r!   