
    Yh                        d dl Z d dlZd dlZd dlZd dlmZmZmZ d dlm	Z	m
Z
mZmZmZmZ d dlZd dlZd dlmZ d dlmZ d dlmZ ddlmZmZ d d	l mZ d d
lmZ g dZ G d de          Zd Z d Z!d Z"d Z# e$d%                                d%                                          Z&d Z'	 	 	 	 dAdZ( e'e(           	 	 dBd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)%                                e&d*<    G d+ d,e.          Z0 G d- d.e0          Z1 G d/ d0e.          Z2 G d1 d2e.          Z3 G d3 d4e.          Z4 G d5 d6e.          Z5 G d7 d8e+          Z6d9 Z7 e7d:e0          Z8 e7d;e1          Z9 e7d<e2          Z: e7d=e4          Z; e7d>e3          Z< e7d?e5          Z= e7d@e6          Z>dS )C    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                       e Zd ZdZdS )r   z\Exception raised when nonlinear solver fails to converge within the specified
    `maxiter`.N)__name__
__module____qualname____doc__     h/var/www/tools.fuzzalab.pt/emblema-extractor/venv/lib/python3.11/site-packages/scipy/optimize/_nonlin.pyr   r       s         Dr%   r   c                 N    t          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)   
issubdtyper1   inexactfloat64r,   s    r&   _as_inexactr5   *   s?    

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getattrr7   )r-   x0wraps      r&   _array_liker=   2   s=    

1bhrll##A2')9::D477Nr%   c                     t          j        |                                           st          j        t           j                  S t          |           S r(   )r)   isfiniteallarrayinfr   )vs    r&   
_safe_normrD   9   s;    ;q>>  x77Nr%   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                 @    | j         r| j         t          z  | _         d S d S r(   )r#   
_doc_parts)objs    r&   _set_docrJ   w   s(    
{ /kJ./ /r%   krylovFarmijoTc           
          |
t           n|
}
t          ||||	||
          }t                     fd}                                }t	          j        |t          j                  } ||          }t          |          }t          |          }|	                    |
                                ||           |||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 ]}|                    |||          }|r nt          |||z            }|                    ||           }t          |          dk    rt          d          |rt#          |||||          \  }}}}n!d}||z   } ||          }t          |          }|                    |
                                |           |r |||           ||dz  z  |dz  z  }||dz  z  |k     rt          ||          }n$t          |t'          |||dz  z                      }|}|rQt(          j                            | d |
|          dd|dd           t(          j                                         |rt1          t3          |                    d}|r,|j        |||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                 t    t           t          |                                                               S r(   )r5   r=   flatten)zFr;   s    r&   funcznonlin_solve.<locals>.func   s1    11[B//001199;;;r%   r   d   TrL   F)NrL   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)r.   TerminationConditionr5   rT   r)   	full_likerB   r   
asjacobiansetupcopysize
ValueErrorrangecheckminr   _nonlin_line_searchupdater+   sysstdoutwriteflushr   r=   	iteration) rV   r;   jacobianrR   verbosemaxiterrN   rO   rP   rQ   tol_normline_searchcallbackfull_outputraise_exception	conditionrW   r-   dxFxFx_normgammaeta_maxeta_tresholdetanra   rZ   sFx_norm_neweta_Ainfos    ``                              r&   nonlin_solver   |   s   Z #*wwH$5+0*.X? ? ?I 
RB< < < < < <


A	a	 	 B	aB2hhG(##HNN16688R&&&QhGG16!8nGd			333./// EGL
C7^^ . .Q++ 	E #s7{##nnRSn)))88q== . / / /
  	#$7aR8C%E %E!Aq"kk ABAaBr((K"%%% 	HQOOO Q&!336>L((gu%%CCgs5%Q,7788C  	JMMxx||MMMaMMMMNNNJ 	Ar 2 2333F " * !Q; , 3  %	&		 	 1b!!4''1b!!!r%   :0yE>{Gz?c                     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   r\   Tc                     | 	d         k    rd         S 
| z  z   } |          }t          |          dz  }|r| 	d<   |d<   |d<   |S )Nr   r\   )rD   )r   storextrC   pr~   rW   tmp_Fxtmp_phitmp_sr-   s        r&   phiz _nonlin_line_search.<locals>.phi  sl    a==1:2XDHHqMM1 	E!HGAJF1Ir%   c                 r    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$  sG    !ffvo!U*AbD&&&Q/255r%   rY   r   )xtolaminrL   )r   r[   )T)r   r   r   )rW   r-   r   r~   search_typer   sminr   r   phi1phi0r   r   r   r   r   r   s   `` ` `      @@@@@r&   rn   rn     se   CETFBxx{mG!WWtBxxF
 
 
 
 
 
 
 
 
 
 
6 6 6 6 6 6 6 g,S&'!*26TC C C4		 	 &sGAJ,02 2 24 	y 	AbDAE!H}}AYT!WW2hhGaWr%   c                   ,    e Zd ZdZdddddefdZd ZdS )rd   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                    |&t          j        t           j                  j        dz  }|t           j        }|t           j        }|t           j        }|| _        || _        || _        || _        || _	        || _
        d | _        d| _        d S )NgUUUUUU?r   )r)   finfor4   epsrB   rP   rQ   rN   rO   r   rR   f0_normrt   )selfrN   rO   rP   rQ   rR   r   s          r&   __init__zTerminationCondition.__init__K  s     =HRZ((,6E>VF=FE>VF

		r%   c                    | xj         dz  c_         |                     |          }|                     |          }|                     |          }| j        || _        |dk    rdS | j        d| j         | j        k    z  S t	          || j        k    o+|| j        z  | j        k    o|| j        k    o|| j        z  |k              S )Nr   r   r\   )	rt   r   r   rR   intrN   rO   rP   rQ   )r   fr-   r~   f_normx_normdx_norms          r&   rl   zTerminationCondition.checkc  s    !11))B--<!DLQ;;19 233 Fdj( ;t{*dl:;4:- :#DK/69< < 	<r%   )r    r!   r"   r#   r.   r   rl   r$   r%   r&   rd   rd   >  sQ          "$d4   0< < < < <r%   rd   c                   2    e Zd ZdZd Zd Zd	dZd Zd ZdS )
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}|                                 D ]4\  }}||vrt          d|           |t          | |||                    5t          | d          rdd}d S d S )N)	r   ro   matvecrmatvecrsolvematmattodenser9   r1   zUnknown keyword argument r   c                 R    |t          d|           |                                 S )Nz`dtype` must be None, was )rj   r   )r   r1   rh   s      r&   	__array__z$Jacobian.__init__.<locals>.__array__  s-    $$%I%%I%IJJJ||~~%r%   NN)itemsrj   setattrhasattr)r   kwnamesnamevaluer   s         r&   r   zJacobian.__init__  s    8 8 888:: 	. 	.KD%5   !CT!C!CDDD dBtH--- 4## 	&& & & & & &	& 	&r%   c                      t          |           S r(   )r   r   s    r&   aspreconditionerzJacobian.aspreconditioner  s    t$$$r%   r   c                     t           r(   NotImplementedErrorr   rC   rZ   s      r&   r   zJacobian.solve      !!r%   c                     d S r(   r$   r   r-   rV   s      r&   ro   zJacobian.update      r%   c                     || _         |j        |j        f| _        |j        | _        | j        j        t          j        u r|                     ||           d S d S r(   )rW   ri   r9   r1   	__class__rg   r   ro   r   r-   rV   rW   s       r&   rg   zJacobian.setup  sV    	faf%
W
>8>11KK1 21r%   Nr   )	r    r!   r"   r#   r   r   r   ro   rg   r$   r%   r&   r   r   ~  so        # #J& & & % % %" " " "      r%   r   c                   D    e Zd ZdZd Zed             Zed             ZdS )r   a  
    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                     || _         |j        | _        |j        | _        t	          |d          r|j        | _        t	          |d          r|j        | _        d S d S )Nrg   r   )ru   r   r   ro   r   rg   r   r   )r   ru   s     r&   r   zInverseJacobian.__init__  s_     no8W%% 	(!DJ8X&& 	+#?DLLL	+ 	+r%   c                     | j         j        S r(   )ru   r9   r   s    r&   r9   zInverseJacobian.shape      }""r%   c                     | j         j        S r(   )ru   r1   r   s    r&   r1   zInverseJacobian.dtype  r   r%   N)r    r!   r"   r#   r   propertyr9   r1   r$   r%   r&   r   r     sc         (+ + + # # X# # # X# # #r%   r   c                     t           j        j        j        t	           t
                    r S t          j                   rt           t
                    r
              S t	           t          j
                  r j        dk    rt          d          t          j        t          j                               j        d          j        d         k    rt          d          t           fd fdd fd	d fd		 j         j        
          S t           j                                       rZ j        d          j        d         k    rt          d          t           fd fdd fd	d fd	 j         j        
          S t%           d          rt%           d          r|t%           d          rlt          t'           d          t'           d           j        t'           d          t'           d          t'           d           j         j                  S t+                     r  G  fddt
                    } |            S t	           t,                    rG t/          t0          t2          t4          t6          t8          t:          t<                                          S t?          d          )zE
    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          |           S r(   )r   rC   Js    r&   <lambda>zasjacobian.<locals>.<lambda>  s    Q r%   c                 R    t                                          j        |           S r(   )r   conjTr   s    r&   r   zasjacobian.<locals>.<lambda>  s    #affhhj!*<*< r%   c                 $    t          |           S r(   )r   rC   rZ   r   s     r&   r   zasjacobian.<locals>.<lambda>  s    uQ{{ r%   c                 R    t                                          j        |           S r(   )r   r   r   r   s     r&   r   zasjacobian.<locals>.<lambda>   s    affhhj!0D0D r%   )r   r   r   r   r1   r9   zmatrix must be squarec                     | z  S r(   r$   r   s    r&   r   zasjacobian.<locals>.<lambda>  s    Q r%   c                 <                                     j        | z  S r(   r   r   r   s    r&   r   zasjacobian.<locals>.<lambda>  s    !&&((*q. r%   c                      |           S r(   r$   rC   rZ   r   spsolves     r&   r   zasjacobian.<locals>.<lambda>  s    wwq!}} r%   c                 J                                      j        |           S r(   r   r   s     r&   r   zasjacobian.<locals>.<lambda>  s    
A0F0F r%   r9   r1   r   r   r   r   ro   rg   )r   r   r   r   ro   rg   r1   r9   c                   F    e Zd Zd Zd fd	Z fdZd fd	Z fdZdS )	asjacobian.<locals>.Jacc                     || _         d S r(   r,   r   s      r&   ro   zasjacobian.<locals>.Jac.update  s    r%   r   c                      | j                   }t          |t          j                  rt	          ||          S t
          j                            |          r ||          S t          d          NzUnknown matrix type)	r-   
isinstancer)   ndarrayr   scipysparseissparserj   r   rC   rZ   mr   r   s       r&   r   zasjacobian.<locals>.Jac.solve  sk    AdfIIa,, < A;;&\**1-- <"71a==($%:;;;r%   c                      | j                   }t          |t          j                  rt	          ||          S t
          j                            |          r||z  S t          d          r   )	r-   r   r)   r   r   r   r   r   rj   r   rC   r   r   s      r&   r   zasjacobian.<locals>.Jac.matvec"  sd    AdfIIa,, <q!99$\**1-- <q5L$%:;;;r%   c                 H    | j                   }t          |t          j                  r't	          |                                j        |          S t          j        	                    |          r# |                                j        |          S t          d          r   )r-   r   r)   r   r   r   r   r   r   r   rj   r   s       r&   r   zasjacobian.<locals>.Jac.rsolve+  s    AdfIIa,, < Q///\**1-- <"716688:q111$%:;;;r%   c                 :    | j                   }t          |t          j                  r't	          |                                j        |          S t          j        	                    |          r|                                j        |z  S t          d          r   )r-   r   r)   r   r   r   r   r   r   r   rj   r   s      r&   r   zasjacobian.<locals>.Jac.rmatvec4  s{    AdfIIa,, <qvvxxz1---\**1-- <6688:>)$%:;;;r%   Nr   )r    r!   r"   ro   r   r   r   r   )r   r   s   r&   Jacr     s          < < < < < < << < < < << < < < < < << < < < < < <r%   r   )r   r   r   r   r   r   rK   z#Cannot convert object to a JacobianNr   ) r   r   linalgr   r   r   inspectisclass
issubclassr)   r   ndimrj   
atleast_2dr   r9   r1   r   r   r:   r   callablestrdictr   BroydenSecondAndersonDiagBroydenLinearMixingExcitingMixingr   	TypeError)r   r   r   s   ` @r&   rf   rf     s    l!)G!X T?			 R?
1h 7 7 R?qss
	Arz	"	" P?6A::8999M"*Q--((71:##34442222 < < < <:::::DDDDDgQW	6 6 6 	6
 
		q	!	! D?71:##4555 8 8 8 8<<<<<<FFFFFFgQW	6 6 6 	6
 
G		 <?G!4!4 <?G9L9L <?wq(33 '9 5 5g&q(33&q(33%a11gg' ' ' 	' 
! 3?&	< &	< &	< &	< &	< &	< &	< &	<( &	< &	< &	<N suu	As		 	?.t\*% +!-#1)+ + + ,-. 0 0 	0 =>>>r%   c                        e Zd Zd Zd Zd ZdS )GenericBroydenc                    t                               | |||           || _        || _        t	          | d          rK| j        Ft          |          }|r*dt          t          |          d          z  |z  | _        d S d| _        d S d S d S )Nalpha      ?r   r[   )r   rg   last_flast_xr   r  r   r+   )r   r;   f0rW   normf0s        r&   rg   zGenericBroyden.setupN  s    tRT***4!! 	!dj&8 "XXF ! T"XXq!1!11F:


 


	! 	!&8&8r%   c                     t           r(   r   r   r-   r   r~   dfr   df_norms          r&   _updatezGenericBroyden._update\  r   r%   c           
          || j         z
  }|| j        z
  }|                     ||||t          |          t          |                     || _         || _        d S r(   )r  r  r  r   )r   r-   r   r  r~   s        r&   ro   zGenericBroyden.update_  sR    __Q2r488T"XX666r%   N)r    r!   r"   rg   r  ro   r$   r%   r&   r	  r	  M  sA        ! ! !" " "    r%   r	  c                       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dZd Zd Zd ZddZdS )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                 Z    || _         g | _        g | _        || _        || _        d | _        d S r(   )r  csr   r   r1   	collapsed)r   r  r   r1   s       r&   r   zLowRankMatrix.__init__r  s0    

r%   c                     t          g d|d d         | gz             \  }}}|| z  }t          ||          D ]$\  }}	 ||	|           }
 ||||j        |
          }%|S )N)axpyscaldotcr   )r   zipri   )rC   r  r  r   r  r  r  wcdas              r&   _matveczLowRankMatrix._matvecz  s    )*B*B*B*,RaR&A3,8 8dDAIBKK 	& 	&DAqQ

AQ161%%AAr%   c           	         t          |          dk    r| |z  S t          ddg|dd         | gz             \  }}|d         }|t          j        t          |          |j                  z  }t          |          D ]6\  }}	t          |          D ]!\  }
}|||
fxx          ||	|          z  cc<   "7t          j        t          |          |j                  }t          |          D ]\  }
}	 ||	|           ||
<   ||z  }t          ||          }| |z  }t          ||          D ]\  }} ||||j	        |           }|S )Evaluate w = M^-1 vr   r  r  Nr   r0   )
lenr   r)   identityr1   	enumeratezerosr   r   ri   )rC   r  r  r   r  r  c0Air#  jr"  qr!  qcs                  r&   _solvezLowRankMatrix._solve  sq    r77a<<U7N $VV$4b!fslCC
dUBKBrx8888bMM 	% 	%DAq!" % %1!A#$$q!**$% HSWWBH---bMM 	 	DAq41::AaDD	U
!QKKeGQZZ 	( 	(EArQ16B3''AAr%   c                     | j         t          j        | j         |          S t                              || j        | j        | j                  S )zEvaluate w = M v)r  r)   r   r  r%  r  r  r   r   rC   s     r&   r   zLowRankMatrix.matvec  s>    >%6$.!,,,$$Q
DGTWEEEr%   c                     | j         1t          j        | j         j                                        |          S t
                              |t          j        | j                  | j        | j	                  S )zEvaluate w = M^H v)
r  r)   r   r   r   r  r%  r  r   r  r4  s     r&   r   zLowRankMatrix.rmatvec  sW    >%6$.*//111555$$Q
(;(;TWdgNNNr%   r   c                     | j         t          | j         |          S t                              || j        | j        | j                  S )r'  )r  r   r  r2  r  r  r   r   s      r&   r   zLowRankMatrix.solve  s<    >%+++##Atz47DGDDDr%   c                     | j         ,t          | j         j                                        |          S t                              |t          j        | j                  | j        | j	                  S )zEvaluate w = M^-H v)
r  r   r   r   r  r2  r)   r  r   r  r   s      r&   r   zLowRankMatrix.rsolve  sU    >%)..00!444##Arwtz':':DGTWMMMr%   c                 X   | j         ;| xj         |d d d f         |d d d f                                         z  z  c_         d S | j                            |           | j                            |           t          | j                  |j        k    r|                                  d S d S r(   )r  r   r  appendr   r(  ri   collapse)r   r"  r#  s      r&   r9  zLowRankMatrix.append  s    >%NNa$i!DF)..*:*:::NNFqqtw<<!&  MMOOOOO ! r%   Nc                 ~   |t          j        d| dd           |t          j        d| dd           | j        | j        S | j        t	          j        | j        | j                  z  }t          | j	        | j
                  D ]3\  }}||d d d f         |d d d f                                         z  z  }4|S )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 r0   )warningswarnr  r  r)   r)  r   r1   r   r  r   r   )r   r1   rh   Gmr"  r#  s         r&   r   zLowRankMatrix.__array__  s   M O9>O O O%&( ( ( ( M N9=N N N%&( ( ( ( >%>!ZDF$*====)) 	- 	-DAq!AAAdF)Ad111fINN,,,,BB	r%   c                 p    t          j        | t                    | _        d| _        d| _        d| _        dS )z0Collapse the low-rank matrix to a full-rank one.)rh   N)r)   rA   r   r  r  r   r  r   s    r&   r:  zLowRankMatrix.collapse  s1    $^<<<


r%   c                     | j         dS |dk    sJ t          | j                  |k    r| j        dd= | j        dd= dS dS )zH
        Reduce the rank of the matrix by dropping all vectors.
        Nr   r  r(  r  r   r   ranks     r&   restart_reducezLowRankMatrix.restart_reduce  sW     >%Faxxxxtw<<$



 r%   c                     | j         dS |dk    sJ t          | j                  |k    r*| j        d= | j        d= t          | j                  |k    (dS dS )zK
        Reduce the rank of the matrix by dropping oldest vectors.
        Nr   rC  rD  s     r&   simple_reducezLowRankMatrix.simple_reduce  sd     >%Faxxxx$'llT!!

 $'llT!!!!!!r%   c                    | j         dS |}||}n|dz
  }| j        r(t          |t          | j        d                             }t	          dt          ||dz
                      }t          | j                  }||k     rdS t          j        | j                  j        }t          j        | j                  j        }t          |d          \  }}t          ||j                                                  }t          |d          \  }	}
}t          |t          |                    }t          ||j                                                  }t          |          D ]N}|dd|f                                         | j        |<   |dd|f                                         | j        |<   O| j        |d= | j        |d= dS )	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

        Nr\   r   r   economic)modeF)full_matrices)r  r  rm   r(  r+   r)   rA   r   r   r	   r   r   r
   r   rk   rh   )r   max_rank	to_retainr   r0  r   CDRUSWHks                r&   
svd_reducezLowRankMatrix.svd_reduce  s   : >%F AAAA7 	(As471:''A3q!A#;;LLq55FHTWHTW!*%%%11388::q...1b3r77OO2499;;q 	' 	'A111Q3DGAJ111Q3DGAJJGABBKGABBKKKr%   r   r   r(   )r    r!   r"   r#   r   staticmethodr%  r2  r   r   r   r   r9  r   r:  rF  rH  rV  r$   r%   r&   r  r  g  s             \   \6F F FO O OE E E EN N N 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                   H    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dS )r   al  
    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])

    Nrestartc                 ~    t                                           | _        d  _        |t          j        }| _        t          |t                    rdn|dd          |d         }|dz
  fz   |dk    r fd _	        d S |dk    r fd _	        d S |dk    r fd	 _	        d S t          d
| d          )Nr$   r   r   r
   c                  "     j         j          S r(   )r@  rV  reduce_paramsr   s   r&   r   z'BroydenFirst.__init__.<locals>.<lambda>  s    #547#5}#E r%   simplec                  "     j         j          S r(   )r@  rH  r]  s   r&   r   z'BroydenFirst.__init__.<locals>.<lambda>  s    #847#8-#H r%   rZ  c                  "     j         j          S r(   )r@  rF  r]  s   r&   r   z'BroydenFirst.__init__.<locals>.<lambda>  s    #947#9=#I r%   zUnknown rank reduction method '')r	  r   r  r@  r)   rB   rM  r   r   _reducerj   )r   r  reduction_methodrM  r^  s   `   @r&   r   zBroydenFirst.__init__  s    %%%
vH &,, 	3MM,QRR0M/2!A-7u$$EEEEEDLLL))HHHHHDLLL**IIIIIDLLLR?ORRRSSSr%   c                     t                               | |||           t          | j         | j        d         | j                  | _        d S )Nr   )r	  rg   r  r  r9   r1   r@  r   s       r&   rg   zBroydenFirst.setup  s?    T1a...TZ]DJGGr%   c                 *    t          | j                  S r(   )r   r@  r   s    r&   r   zBroydenFirst.todense  s    47||r%   r   c                    | j                             |          }t          j        |                                          s@|                     | j        | j        | j                   | j                             |          S |S r(   )	r@  r   r)   r?   r@   rg   r  r  rW   )r   r   rZ   rs       r&   r   zBroydenFirst.solve  sf    GNN1{1~~!!## 	%JJt{DK;;;7>>!$$$r%   c                 6    | j                             |          S r(   )r@  r   r   r   s     r&   r   zBroydenFirst.matvec  s    w}}Qr%   c                 6    | j                             |          S r(   )r@  r   r   r   rZ   s      r&   r   zBroydenFirst.rsolve  s    wq!!!r%   c                 6    | j                             |          S r(   )r@  r   rj  s     r&   r   zBroydenFirst.rmatvec  s    w~~a   r%   c                     |                                   | j                            |          }|| j                            |          z
  }|t	          ||          z  }	| j                            ||	           d S r(   )rc  r@  r   r   r   r9  
r   r-   r   r~   r  r   r  rC   r"  r#  s
             r&   r  zBroydenFirst._update  sg    GOOB###ROq!r%   )NrZ  Nr   )r    r!   r"   r#   r   rg   r   r   r   r   r   r  r$   r%   r&   r   r   K  s        2 2hT T T T2H H H          " " " "! ! !    r%   r   c                       e Zd ZdZd ZdS )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                            |          z
  }||dz  z  }	| j                            ||	           d S Nr\   )rc  r@  r   r9  ro  s
             r&   r  zBroydenSecond._update  sU    ###
Nq!r%   N)r    r!   r"   r#   r  r$   r%   r&   r  r    s.        0 0d    r%   r  c                   .    e Zd ZdZd
dZddZd Zd	 ZdS )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])

    Nr      c                     t                               |            || _        || _        g | _        g | _        d | _        || _        d S r(   )r	  r   r  Mr~   r  r   w0)r   r  rw  rv  s       r&   r   zAnderson.__init__B  sD    %%%

r%   r   c                    | j          |z  }t          | j                  }|dk    r|S t          j        ||j                  }t          |          D ] }t          | j        |         |          ||<   !	 t          | j
        |          }n&# t          $ r | j        d d = | j        d d = |cY S w xY wt          |          D ]1}|||         | j        |         | j         | j        |         z  z   z  z  }2|S Nr   r0   )r  r(  r~   r)   emptyr1   rk   r   r  r   r$  r   )	r   r   rZ   r~   r   df_frU  r   r   s	            r&   r   zAnderson.solveK  s   j[]LL66Ix)))q 	* 	*A471:q))DGG	$&$''EE 	 	 	

III		 q 	@ 	@A%(DGAJDGAJ)>>??BB	s   4B
 
 B-,B-c           
         | | 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    rT| j	        dk    rI|||fxx         t          | j        |         | j        |                   | j	        dz  z  | j         z  z  cc<   t          ||          }	t          |          D ]1}
||	|
         | j        |
         | j        |
         | j         z  z   z  z  }2|S )Nr   r0   r\   )r  r(  r~   r)   rz  r1   rk   r   r  rw  r   )r   r   r~   r   r{  rU  br.  r/  r   r   s              r&   r   zAnderson.matvecb  s   R
]LL66Ix)))q 	* 	*A471:q))DGGHaV17+++q 	Q 	QA1XX Q Qdgaj$'!*55!A#66dgllacFFFd471:twqz::47A:EdjPPFFFQ aq 	@ 	@A%(DGAJDJ)>>??BB	r%   c                    | j         dk    rd S | j                            |           | j                            |           t	          | j                  | j         k    rQ| j                            d           | j                            d           t	          | j                  | j         k    Qt	          | j                  }t          j        ||f|j                  }t          |          D ]Y}	t          |	|          D ]F}
|	|
k    r| j
        dz  }nd}d|z   t          | j        |	         | j        |
                   z  ||	|
f<   GZ|t          j        |d          j                                        z  }|| _        d S )Nr   r0   r\   r   )rv  r~   r9  r  r(  popr)   r+  r1   rk   rw  r   triur   r   r$  )r   r-   r   r~   r  r   r  r   r$  r.  r/  wds               r&   r  zAnderson._updatey  sZ   6Q;;Frr$'llTV##GKKNNNGKKNNN $'llTV## LLHaV17+++q 	= 	=A1a[[ = =66!BBBB$TWQZ < <<!A#= 	
RWQ]]_!!###r%   )Nr   rt  r   )r    r!   r"   r#   r   r   r   r  r$   r%   r&   r  r    se        + +L      .  .    r%   r  c                   H    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dS )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                 H    t                               |            || _        d S r(   r	  r   r  r   r  s     r&   r   zDiagBroyden.__init__  !    %%%


r%   c                     t                               | |||           t          j        | j        d         fd| j        z  | j                  | _        d S )Nr   r   r0   )r	  rg   r)   fullr9   r  r1   r#  r   s       r&   rg   zDiagBroyden.setup  sI    T1a...$*Q-)1tz>LLLr%   r   c                     | | j         z  S r(   r#  rl  s      r&   r   zDiagBroyden.solve      rDF{r%   c                     | | j         z  S r(   r  rj  s     r&   r   zDiagBroyden.matvec  r  r%   c                 <    | | j                                         z  S r(   r#  r   rl  s      r&   r   zDiagBroyden.rsolve      rDFKKMM!!r%   c                 <    | | j                                         z  S r(   r  rj  s     r&   r   zDiagBroyden.rmatvec  r  r%   c                 6    t          j        | j                   S r(   )r)   diagr#  r   s    r&   r   zDiagBroyden.todense  s    wwr%   c                 N    | xj         || j         |z  z   |z  |dz  z  z  c_         d S rr  r  r  s          r&   r  zDiagBroyden._update  s.    2r	>2%gqj00r%   r(   r   r    r!   r"   r#   r   rg   r   r   r   r   r   r  r$   r%   r&   r  r    s        & &P   M M M     " " " "" " "     1 1 1 1 1r%   r  c                   B    e Zd ZdZddZddZd ZddZd Zd	 Z	d
 Z
dS )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                 H    t                               |            || _        d S r(   r  r  s     r&   r   zLinearMixing.__init__  r  r%   r   c                     | | j         z  S r(   r  rl  s      r&   r   zLinearMixing.solve      r$*}r%   c                     | | j         z  S r(   r  rj  s     r&   r   zLinearMixing.matvec  r  r%   c                 <    | t          j        | j                  z  S r(   r)   r   r  rl  s      r&   r   zLinearMixing.rsolve      r"'$*%%%%r%   c                 <    | t          j        | j                  z  S r(   r  rj  s     r&   r   zLinearMixing.rmatvec  r  r%   c                 v    t          j        t          j        | j        d         d| j        z                      S )Nr   )r)   r  r  r9   r  r   s    r&   r   zLinearMixing.todense  s*    wrwtz!}bm<<===r%   c                     d S r(   r$   r  s          r&   r  zLinearMixing._update  r   r%   r(   r   )r    r!   r"   r#   r   r   r   r   r   r   r  r$   r%   r&   r  r    s         ,        & & & && & &> > >    r%   r  c                   H    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dS )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
    Nr[   c                 d    t                               |            || _        || _        d | _        d S r(   )r	  r   r  alphamaxbeta)r   r  r  s      r&   r   zExcitingMixing.__init__$  s/    %%%
 			r%   c                     t                               | |||           t          j        | j        d         f| j        | j                  | _        d S ry  )r	  rg   r)   r  r9   r  r1   r  r   s       r&   rg   zExcitingMixing.setup*  sE    T1a...GTZ],dj
KKK			r%   r   c                     | | j         z  S r(   r  rl  s      r&   r   zExcitingMixing.solve.      r$)|r%   c                     | | j         z  S r(   r  rj  s     r&   r   zExcitingMixing.matvec1  r  r%   c                 <    | | j                                         z  S r(   r  r   rl  s      r&   r   zExcitingMixing.rsolve4      r$)..""""r%   c                 <    | | j                                         z  S r(   r  rj  s     r&   r   zExcitingMixing.rmatvec7  r  r%   c                 :    t          j        d| j        z            S )Nr  )r)   r  r  r   s    r&   r   zExcitingMixing.todense:  s    wr$)|$$$r%   c                     || j         z  dk    }| j        |xx         | j        z  cc<   | j        | j        | <   t          j        | j        d| j        | j                   d S )Nr   )out)r  r  r  r)   clipr  )r   r-   r   r~   r  r   r  incrs           r&   r  zExcitingMixing._update=  sa    }q 	$4:%:	4%
	1dm;;;;;;r%   )Nr[   r   r  r$   r%   r&   r  r  	  s         4   L L L     # # # ## # #% % %< < < < <r%   r  c                   >    e Zd ZdZ	 	 ddZd Zd Zdd
Zd Zd Z	dS )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])

    Nlgmres   
   c                    || _         || _        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                                      ||          | _        t          || j                   | _        | j        t          j        j        j        u r1|| j        d<   d| j        d<   | j                            dd           n| j        t          j        j        j        t          j        j        j        t          j        j        j	        fv r| j                            dd           n| j        t          j        j        j        u r|| j        d<   d| j        d<   | j                            d	g            | j                            d
d           | j                            dd           | j                            dd           d t#          | j                  j        D             }|                                D ]\  }}	|                    d          st+          d|           |dd          |vrRt-          |dd          |d          }
|
rd|
d          d}nd}t/          j        d| d| d|z   dt2                     |	| j        |dd          <   d S )N)bicgstabgmresr  cgsminrestfqmr)rw   rv  rZ  r   rw   atolr   outer_kouter_vprepend_outer_vTstore_outer_AvFc                     g | ]}|d v|	S ))r   argskwargsr$   ).0rU  s     r&   
<listcomp>z+KrylovJacobian.__init__.<locals>.<listcomp>  s.     
 
 
222 222r%   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   
startswithrj   r   r>  r?  UserWarning)r   r   r  inner_maxiterinner_Mr  r   valid_inner_paramskeyr   inner_param_suggestionssuggestion_msgs               r&   r   zKrylovJacobian.__init__  s"   %
 \(1,%+<&-#'<&-,%+   c&&!! 	 mt7JKKK;%,-333(5DN9%()DN9%N%%fa0000[U\08"\09"\046 6 6 N%%fa0000[EL/666(/DN9%()DN9%N%%i444N%%&7>>> N%%&6>>>N%%fa000
 
 --8
 
 

 ((** 	, 	,JC>>(++ = !;c!;!;<<<122w000*;CG<N>?+A +A +A' + ('H)@)C'H 'H 'HNN &(N Qs Q Qv Q Q Q %%  !(	 	 	 	 &+DN3qrr7##7	, 	,r%   c                     t          | j                                                  }t          | j                                                  }| j        t          d|          z  t          d|          z  | _        d S )Nr   )r   r;   r+   r  r   omega)r   mxmfs      r&   _update_diff_stepz KrylovJacobian._update_diff_step  s[    \\\\Z#a**,s1bzz9


r%   c                 Z   t          |          }|dk    rd|z  S | j        |z  }|                     | j        ||z  z             | j        z
  |z  }t          j        t          j        |                    s5t          j        t          j        |                    rt          d          |S )Nr   z$Function returned non-finite results)	r   r  rW   r;   r  r)   r@   r?   rj   )r   rC   nvscrh  s        r&   r   zKrylovJacobian.matvec   s    !WW77Q3JZ"_YYtwA~&&0B6vbk!nn%% 	E"&Q*@*@ 	ECDDDr%   r   c                     d| j         v r | j        | j        |fi | j         \  }}n | j        | j        |fd|i| j         \  }}|S )Nrtol)r  r  op)r   rhsrZ   solr   s        r&   r   zKrylovJacobian.solve
  sa    T^###DGSCCDNCCIC#DGSMMsMdnMMIC
r%   c                     || _         || _        |                                  | j        2t	          | j        d          r| j                            ||           d S d S d S )Nro   )r;   r  r  r  r   ro   )r   r-   r   s      r&   ro   zKrylovJacobian.update  ss        *t*H55 1#**1a00000 +*1 1r%   c                    t                               | |||           || _        || _        t          j        j                            |           | _        | j	        &t          j        |j                  j        dz  | _	        |                                  | j        3t!          | j        d          r | j                            |||           d S d S d S )Nr  rg   )r   rg   r;   r  r   r   r   aslinearoperatorr  r   r)   r   r1   r   r  r  r   )r   r-   r   rW   s       r&   rg   zKrylovJacobian.setup  s    tQ4(((,%66t<<:!'**.48DJ    *t*G44 6#))!Q55555 +*6 6r%   )Nr  r  Nr  r   )
r    r!   r"   r#   r   r  r   r   ro   rg   r$   r%   r&   r   r   H  s        c cJ CE')K, K, K, K,Z: : :
     1 1 16 6 6 6 6r%   r   c                 N   t          |j                  }|\  }}}}}}}	t          t          |t	          |           d         |                    }
d                    d |
D                       }|rd|z   }d                    d |
D                       }|r|dz   }|rt          d|           d}|t          | ||j        |          z  }i }|	                    t                                 t          ||           ||          }|j        |_        t          |           |S )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, c                 "    g | ]\  }}| d |S =r$   r  rU  rC   s      r&   r  z#_nonlin_wrapper.<locals>.<listcomp><  s&    888A1q888r%   c                 "    g | ]\  }}| d | S r  r$   r  s      r&   r  z#_nonlin_wrapper.<locals>.<listcomp>?  s&    888AQ****888r%   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   r(  joinrj   r  r    ro   globalsexecr#   rJ   )r   r  r   r  varargsvarkwdefaults
kwonlyargs
kwdefaults_r  kw_strkwkw_strwrappernsrW   s                   r&   _nonlin_wrapperr  0  sL     --I@I=D'5(J
A#dCMM>??+X6677FYY8888899F yy8888899H #d? ><<<===G $6s|"*, , , ,G	BIIgii"d8D;DLTNNNKr%   r   r   r   r   r   r   r   )rK   NFNNNNNNrL   NFT)rL   r   r   )?r   rp   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   r.   r5   r=   rD   r  striprH   rJ   r   rn   rd   r   r   rf   r	  r  r   r  r  r  r  r  r   r  r   r   r   r   r   r   r   r$   r%   r&   <module>r     s
    



      $ $ $ $ $ $ $ $ $ $ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?         ' ' ' ' ' ' + + + + + + F F F F F F C C C C C C C C       % % % % % %J J J	 	 	 	 	I 	 	 	            T 	(P 	a1 1 1
h/ / /
 ?DKO?C48O" O" O" O"d 	    FJ!* * * *Z9< 9< 9< 9< 9< 9< 9< 9<@E E E E E E E EP$# $# $# $# $# $# $# $#NY? Y? Y?@    X   4I I I I I I I IX * 	+  0m m m m m> m m m`9 9 9 9 9L 9 9 9@U U U U U~ U U UxA1 A1 A1 A1 A1. A1 A1 A1H+ + + + +> + + +\8< 8< 8< 8< 8<^ 8< 8< 8<~a6 a6 a6 a6 a6X a6 a6 a6P) ) )X ?:|44?:}55?:x00~|<<om[99 !1>BB@@r%   