o
    ¼ôjÄ  ã                   @   s2  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 g d	¢ZG d
d„ deƒZdd„ Zdd„ Zdd„ Zdd„ Z e!d "¡ d "¡ d�Z#dd„ Z$				dHdd„Z%e$e%ƒ 		 dId!d"„Z&G d#d$„ d$ƒZ'G d%d&„ d&ƒZ(G d'd(„ d(ƒZ)d)d*„ Z*G d+d,„ d,e(ƒZ+G d-d.„ d.ƒZ,d/ "¡ e#d0< G d1d2„ d2e+ƒZ-G d3d4„ d4e-ƒZ.G d5d6„ d6e+ƒZ/G d7d8„ d8e+ƒZ0G d9d:„ d:e+ƒZ1G d;d<„ d<e+ƒZ2G d=d>„ d>e(ƒZ3d?d@„ Z4e4dAe-ƒZ5e4dBe.ƒZ6e4dCe/ƒZ7e4dDe1ƒZ8e4dEe0ƒZ9e4dFe2ƒZ:e4dGe3ƒZ;dS )Jé    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)Úbroyden1Úbroyden2ÚandersonÚlinearmixingÚdiagbroydenÚexcitingmixingÚnewton_krylovÚBroydenFirstÚKrylovJacobianÚInverseJacobianÚNoConvergencec                   @   s   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__© r    r    úg/var/www/html/academy/tools/voices/clone/sv-venv/lib/python3.10/site-packages/scipy/optimize/_nonlin.pyr      s    r   c                 C   s   t  | ¡ ¡ S ©N)ÚnpÚabsoluteÚmax©Úxr    r    r!   Úmaxnorm$   ó   r(   c                 C   s*   t | ƒ} t | jtj¡st | tjd�S | S )z:Return `x` as an array, of either floats or complex floats©Údtype)r   r#   Ú
issubdtyper+   ÚinexactÚfloat64r&   r    r    r!   Ú_as_inexact(   s   r/   c                 C   s(   t  | t  |¡¡} t|d| jƒ}|| ƒS )z;Return ndarray `x` as same array subclass and shape as `x0`Ú__array_wrap__)r#   ÚreshapeÚshapeÚgetattrr0   )r'   Úx0Úwrapr    r    r!   Ú_array_like0   s   r6   c                 C   s"   t  | ¡ ¡ st  t j¡S t| ƒS r"   )r#   ÚisfiniteÚallÚarrayÚinfr   ©Úvr    r    r!   Ú
_safe_norm7   s   r=   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.

    )Zparams_basicZparams_extrac                 C   s   | j r| j t | _ d S d S r"   )r   Ú
_doc_parts)Úobjr    r    r!   Ú_set_docu   s   ÿr@   ÚkrylovFÚarmijoTc                     sT  |
du rt n|
}
t||||	||
d�}tˆƒ‰‡ ‡fdd„}ˆ ¡ }t |tj¡}||ƒ}t|ƒ}t|ƒ}| 	| 
¡ ||¡ |du rQ|durJ|d }nd|jd  }|du rXd}n|d	u r^d}|d
vrftdƒ‚d}d}d}d}t|ƒD ]Œ}| |||¡}|r nŒt||| ƒ}|j||d� }t|ƒdkr˜tdƒ‚|r§t|||||ƒ\}}}}nd}|| }||ƒ}t|ƒ}| | 
¡ |¡ |rÄ|||ƒ ||d  |d  }||d  |k rÜt||ƒ}nt|t|||d  ƒƒ}|}|rþtj d||
|ƒ|f ¡ tj ¡  qr|�r	tt|ˆƒƒ‚d}|�r%|j|||dkdddœ| dœ}t|ˆƒ|fS t|ˆƒ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                    s   t ˆ t| ˆƒƒƒ ¡ S r"   )r/   r6   Úflatten)Úz©ÚFr4   r    r!   Úfunc­   s   znonlin_solve.<locals>.funcr   éd   TrB   F)NrB   ÚwolfezInvalid line searchgÍÌÌÌÌÌì?g§èH.ÿï?gš™™™™™¹?gü©ñÒMbP?)Ú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   rQ   )ÚnitÚfunÚstatusÚsuccessÚmessage)r(   ÚTerminationConditionr/   rH   r#   Ú	full_liker:   r   Ú
asjacobianÚsetupÚcopyÚsizeÚ
ValueErrorÚrangeÚcheckÚminr   Ú_nonlin_line_searchÚupdater%   ÚsysÚstdoutÚwriteÚflushr   r6   Ú	iteration) rK   r4   ÚjacobianrG   ÚverboseÚmaxiterrC   rD   rE   rF   Útol_normÚline_searchÚcallbackÚfull_outputÚraise_exceptionÚ	conditionrL   r'   ÚdxÚFxÚFx_normÚgammaZeta_maxZeta_tresholdÚetaÚnrT   rO   ÚsZFx_norm_newZeta_AÚinfor    rJ   r!   Únonlin_solvez   s’   -þ

ÿ

ÿ
€þüü

ry   ç:Œ0âŽyE>ç{®Gáz„?c                    sè   dg‰|g‰t |ƒd g‰t ˆƒt ˆ ƒ ‰d‡ ‡‡‡‡‡fdd„	‰‡‡‡fdd„}|dkr<tˆ|ˆd d	|d
�\}}	}
n|dkrOtˆˆd ˆd  |d�\}}	|d u rUd}ˆ|ˆ   ‰|ˆd krfˆd }nˆˆƒ}t |ƒ}|ˆ||fS )Nr   rQ   Tc                    sT   | ˆd kr
ˆd S ˆ| ˆ   }ˆ|ƒ}t |ƒd }|r(| ˆd< |ˆd< |ˆd< |S )Nr   rQ   )r=   )rw   ÚstoreÚxtr<   Úp)rq   rL   Útmp_FxÚtmp_phiÚtmp_sr'   r    r!   Úphi  s   z _nonlin_line_search.<locals>.phic                    s0   t | ƒˆ d ˆ }ˆ | | dd�ˆ | ƒ | S )Nr   F)r|   )Úabs)rw   Úds)r‚   ÚrdiffÚs_normr    r!   Úderphi#  s   z#_nonlin_line_search.<locals>.derphirN   r{   )ÚxtolÚaminrB   )r‰   rP   )T)r   r   r   )rL   r'   rr   rq   Zsearch_typer…   Úsminr‡   rw   Úphi1Úphi0rs   r    )	rq   rL   r‚   r…   r†   r   r€   r�   r'   r!   ra     s,   ÿ
ÿ
ra   c                   @   s.   e Zd ZdZdddddefdd„Zdd„ ZdS )rW   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                 C   sx   |d u rt  t j¡jd }|d u rt j}|d u rt j}|d u r"t j}|| _|| _|| _|| _|| _	|| _
d | _d| _d S )NgUUUUUUÕ?r   )r#   Úfinfor.   Úepsr:   rE   rF   rC   rD   r   rG   Úf0_normrg   )ÚselfrC   rD   rE   rF   rG   r   r    r    r!   Ú__init__J  s    
zTerminationCondition.__init__c                 C   s˜   |  j d7  _ |  |¡}|  |¡}|  |¡}| jd u r|| _|dkr$dS | jd ur1d| j | jk S t|| jkoJ|| j | jkoJ|| jkoJ|| j |kƒS )Nr   r   rQ   )	rg   r   r�   rG   ÚintrC   rD   rE   rF   )r�   Úfr'   rq   Úf_normÚx_normÚdx_normr    r    r!   r_   b  s    




ÿ
ýzTerminationCondition.check)r   r   r   r   r(   r‘   r_   r    r    r    r!   rW   =  s    
ÿrW   c                   @   s:   e Zd ZdZdd„ Zdd„ Zddd„Zd	d
„ Zd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                 K   sd   g d¢}|  ¡ D ]\}}||vrtd|› �ƒ‚|d ur#t| ||| ƒ qt| dƒr0ddd„}d S d S )N)	r   rb   ÚmatvecÚrmatvecÚrsolveÚmatmatÚtodenser2   r+   zUnknown keyword argument rœ   c                 S   s   |d urt d|› �ƒ‚|  ¡ S )Nz`dtype` must be None, was )r]   rœ   )r�   r+   r[   r    r    r!   Ú	__array__®  s   z$Jacobian.__init__.<locals>.__array__©NN)Úitemsr]   ÚsetattrÚhasattr)r�   ÚkwÚnamesÚnameÚvaluer�   r    r    r!   r‘   £  s   €
ÿzJacobian.__init__c                 C   s   t | ƒS r"   )r   ©r�   r    r    r!   Úaspreconditioner³  s   zJacobian.aspreconditionerr   c                 C   ó   t ‚r"   ©ÚNotImplementedError©r�   r<   rO   r    r    r!   r   ¶  ó   zJacobian.solvec                 C   ó   d S r"   r    ©r�   r'   rK   r    r    r!   rb   ¹  r¬   zJacobian.updatec                 C   s>   || _ |j|jf| _|j| _| jjtju r|  ||¡ d S d S r"   )rL   r\   r2   r+   Ú	__class__rZ   r—   rb   ©r�   r'   rK   rL   r    r    r!   rZ   ¼  s   þzJacobian.setupN©r   )	r   r   r   r   r‘   r§   r   rb   rZ   r    r    r    r!   r—   }  s    %
r—   c                   @   s0   e Zd ZdZdd„ Zedd„ ƒZed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                 C   sB   || _ |j| _|j| _t|dƒr|j| _t|dƒr|j| _d S d S )NrZ   rš   )rh   r   r˜   rb   r¡   rZ   rš   r™   )r�   rh   r    r    r!   r‘   Ú  s   

ÿzInverseJacobian.__init__c                 C   ó   | j jS r"   )rh   r2   r¦   r    r    r!   r2   ã  ó   zInverseJacobian.shapec                 C   r²   r"   )rh   r+   r¦   r    r    r!   r+   ç  r³   zInverseJacobian.dtypeN)r   r   r   r   r‘   Úpropertyr2   r+   r    r    r    r!   r   Å  s    	
r   c              
      sÌ  t jjj‰tˆ tƒrˆ S t ˆ ¡rtˆ tƒrˆ ƒ S tˆ t	j
ƒr\ˆ jdkr(tdƒ‚t	 t	 ˆ ¡¡‰ ˆ jd ˆ jd kr>tdƒ‚t‡ fdd„‡ fdd„d‡ fd	d„	d‡ fd
d„	ˆ jˆ jd�S t j ˆ ¡r�ˆ jd ˆ jd krptdƒ‚t‡ fdd„‡ fdd„d‡ ‡fdd„	d‡ ‡fdd„	ˆ jˆ jd�S tˆ dƒr½tˆ dƒr½tˆ dƒr½ttˆ dƒtˆ dƒˆ jtˆ dƒtˆ dƒtˆ dƒˆ jˆ jd�S tˆ ƒrÏG ‡ ‡fdd„dtƒ}|ƒ S tˆ tƒrâttttttttd�ˆ  ƒ S tdƒ‚) zE
    Convert given object to one suitable for use as a Jacobian.
    rQ   zarray must have rank <= 2r   r   zarray must be squarec                    ó
   t ˆ | ƒS r"   )r   r;   ©ÚJr    r!   Ú<lambda>ü  ó   
 zasjacobian.<locals>.<lambda>c                    ó   t ˆ  ¡ j| ƒS r"   )r   ÚconjÚTr;   r¶   r    r!   r¸   ý  ó    c                    rµ   r"   )r   ©r<   rO   r¶   r    r!   r¸   þ  r¹   c                    rº   r"   )r   r»   r¼   r¾   r¶   r    r!   r¸   ÿ  r½   )r˜   r™   r   rš   r+   r2   zmatrix must be squarec                    s   ˆ |  S r"   r    r;   r¶   r    r!   r¸     s    c                    s   ˆ   ¡ j|  S r"   ©r»   r¼   r;   r¶   r    r!   r¸     s    c                    s
   ˆˆ | ƒS r"   r    r¾   ©r·   Úspsolver    r!   r¸     r¹   c                    s   ˆˆ   ¡ j| ƒS r"   r¿   r¾   rÀ   r    r!   r¸     r½   r2   r+   r   r˜   r™   rš   rb   rZ   )r˜   r™   r   rš   rb   rZ   r+   r2   c                       sL   e Zd Zdd„ Zd‡ ‡fdd„	Z‡ fdd„Zd‡ ‡fdd	„	Z‡ fd
d„ZdS )zasjacobian.<locals>.Jacc                 S   s
   || _ d S r"   r&   r®   r    r    r!   rb     ó   
zasjacobian.<locals>.Jac.updater   c                    s>   ˆ | j ƒ}t|tjƒrt||ƒS tj |¡rˆ||ƒS tdƒ‚©NzUnknown matrix type)	r'   Ú
isinstancer#   Úndarrayr   ÚscipyÚsparseÚissparser]   ©r�   r<   rO   ÚmrÀ   r    r!   r     s   


zasjacobian.<locals>.Jac.solvec                    s<   ˆ | j ƒ}t|tjƒrt||ƒS tj |¡r|| S tdƒ‚rÃ   )	r'   rÄ   r#   rÅ   r   rÆ   rÇ   rÈ   r]   ©r�   r<   rÊ   r¶   r    r!   r˜   !  s   

zasjacobian.<locals>.Jac.matvecc                    sJ   ˆ | 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È   r]   rÉ   rÀ   r    r!   rš   *  s   
zasjacobian.<locals>.Jac.rsolvec                    sH   ˆ | 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È   r]   rË   r¶   r    r!   r™   3  s   
zasjacobian.<locals>.Jac.rmatvecNr±   )r   r   r   rb   r   r˜   rš   r™   r    rÀ   r    r!   ÚJac  s    			rÌ   )r   r   r   r   r   r   rA   z#Cannot convert object to a JacobianNr±   ) rÆ   rÇ   ÚlinalgrÁ   rÄ   r—   ÚinspectÚisclassÚ
issubclassr#   rÅ   Úndimr]   Ú
atleast_2dr   r2   r+   rÈ   r¡   r3   r   ÚcallableÚstrÚdictr   ÚBroydenSecondÚAndersonÚDiagBroydenÚLinearMixingÚExcitingMixingr   Ú	TypeError)r·   rÌ   r    rÀ   r!   rY   ì  sf   



ü
ü
ù'
úúrY   c                   @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )ÚGenericBroydenc                 C   sj   t  | |||¡ || _|| _t| dƒr1| jd u r3t|ƒ}|r,dtt|ƒdƒ | | _d S d| _d S d S d S )NÚalphaç      à?r   rP   )r—   rZ   Úlast_fÚlast_xr¡   rÝ   r   r%   )r�   r4   Úf0rL   Znormf0r    r    r!   rZ   M  s   
ùzGenericBroyden.setupc                 C   r¨   r"   r©   ©r�   r'   r“   rq   Údfr–   Údf_normr    r    r!   Ú_update[  r¬   zGenericBroyden._updatec              	   C   s@   || j  }|| j }|  ||||t|ƒt|ƒ¡ || _ || _d S r"   )rß   rà   rå   r   )r�   r'   r“   rã   rq   r    r    r!   rb   ^  s
   


zGenericBroyden.updateN)r   r   r   rZ   rå   rb   r    r    r    r!   rÜ   L  s    rÜ   c                   @   sˆ   e Zd ZdZdd„ Zedd„ ƒZedd„ ƒZdd	„ Zd
d„ Z	ddd„Z
ddd„Zdd„ Zddd„Zdd„ Zdd„ Zdd„ Zd 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                 C   s(   || _ g | _g | _|| _|| _d | _d S r"   )rÝ   Úcsr„   rv   r+   Ú	collapsed)r�   rÝ   rv   r+   r    r    r!   r‘   q  s   
zLowRankMatrix.__init__c                 C   s\   t g d¢|d d… | g ƒ\}}}||  }t||ƒD ]\}}	||	| ƒ}
||||j|
ƒ}q|S )N)ÚaxpyÚscalÚdotcr   )r   Úzipr\   )r<   rÝ   rç   r„   ré   rê   rë   ÚwÚcÚdÚar    r    r!   Ú_matvecy  s   
ÿ
zLowRankMatrix._matvecc                 C   s
  t |ƒdkr
| | S tddg|dd… | g ƒ\}}|d }|tjt |ƒ|jd� }t|ƒD ]\}}	t|ƒD ]\}
}|||
f  ||	|ƒ7  < q6q.tjt |ƒ|jd�}t|ƒD ]\}
}	||	| ƒ||
< qW|| }t||ƒ}| | }t||ƒD ]\}}||||j	| ƒ}qu|S )úEvaluate w = M^-1 vr   ré   rë   Nr   r*   )
Úlenr   r#   Úidentityr+   Ú	enumerateÚzerosr   rì   r\   )r<   rÝ   rç   r„   ré   rë   Úc0ÚAÚirï   Újrî   Úqrí   Úqcr    r    r!   Ú_solveƒ  s$    ÿ
zLowRankMatrix._solvec                 C   s.   | j durt | j |¡S t || j| j| j¡S )zEvaluate w = M vN)rè   r#   r   ræ   rñ   rÝ   rç   r„   ©r�   r<   r    r    r!   r˜   Ÿ  s   
zLowRankMatrix.matvecc                 C   s:   | j durt | j j ¡ |¡S t |t | j¡| j| j	¡S )zEvaluate w = M^H vN)
rè   r#   r   r¼   r»   ræ   rñ   rÝ   r„   rç   rþ   r    r    r!   r™   ¥  s   
zLowRankMatrix.rmatvecr   c                 C   s,   | j durt| j |ƒS t || j| j| j¡S )rò   N)rè   r   ræ   rý   rÝ   rç   r„   r«   r    r    r!   r   «  s   
zLowRankMatrix.solvec                 C   s8   | j durt| j j ¡ |ƒS t |t | j¡| j| j	¡S )zEvaluate w = M^-H vN)
rè   r   r¼   r»   ræ   rý   r#   rÝ   r„   rç   r«   r    r    r!   rš   ±  s   
zLowRankMatrix.rsolvec                 C   st   | j d ur|  j |d d …d f |d d d …f  ¡  7  _ d S | j |¡ | j |¡ t| jƒ|jkr8|  ¡  d S d S r"   )rè   r»   rç   Úappendr„   ró   r\   Úcollapse)r�   rî   rï   r    r    r!   rÿ   ·  s   
.ÿzLowRankMatrix.appendNc                 C   s¨   |d urt jd|› d�dd� |d urt jd|› d�dd� | jd ur&| jS | jtj| j| jd� }t| j	| j
ƒD ]\}}||d d …d f |d d d …f  ¡  7 }q9|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 r*   )ÚwarningsÚwarnrè   rÝ   r#   rô   rv   r+   rì   rç   r„   r»   )r�   r+   r[   ÚGmrî   rï   r    r    r!   r�   Â  s$   ÿþÿþ
*zLowRankMatrix.__array__c                 C   s&   t j| td�| _d| _d| _d| _dS )z0Collapse the low-rank matrix to a full-rank one.)r[   N)r#   r9   r   rè   rç   r„   rÝ   r¦   r    r    r!   r   Ó  s   
zLowRankMatrix.collapsec                 C   sH   | j dur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�   Úrankr    r    r!   Úrestart_reduceÚ  s   
þzLowRankMatrix.restart_reducec                 C   sN   | j durdS |dksJ ‚t| jƒ|kr%| jd= | jd= t| jƒ|ksdS dS )zK
        Reduce the rank of the matrix by dropping oldest vectors.
        Nr   r  r  r    r    r!   Úsimple_reduceå  s   
þzLowRankMatrix.simple_reducec                 C   s6  | j durdS |}|dur|}n|d }| jr!t|t| jd ƒƒ}tdt||d ƒƒ}t| jƒ}||k r6dS t | j¡j}t | j¡j}t	|dd�\}}t
||j ¡ ƒ}t|dd�\}	}
}t
|t|ƒƒ}t
||j ¡ ƒ}t|ƒD ]}|dd…|f  ¡ | j|< |dd…|f  ¡ | j|< qp| 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

        NrQ   r   r   Úeconomic)ÚmodeF)Úfull_matrices)rè   rç   r`   ró   r%   r#   r9   r¼   r„   r   r   r»   r	   r   r^   r[   )r�   Úmax_rankZ	to_retainr~   rû   rÊ   ÚCÚDÚRÚUÚSZWHÚkr    r    r!   Ú
svd_reduceð  s0   

zLowRankMatrix.svd_reducer±   rž   r"   )r   r   r   r   r‘   Ústaticmethodrñ   rý   r˜   r™   r   rš   rÿ   r�   r   r	  r
  r  r    r    r    r!   ræ   f  s"    

	



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).
    Zbroyden_paramsc                   @   sV   e Zd ZdZddd„Zdd„ Zdd	„ Zddd„Zdd„ Zddd„Z	dd„ Z
d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                    sÀ   t  ˆ¡ |ˆ_d ˆ_|d u rtj}|ˆ_t|tƒrd‰ n
|dd … ‰ |d }|d fˆ  ‰ |dkr<‡ ‡fdd„ˆ_	d S |dkrJ‡ ‡fdd„ˆ_	d S |d	krX‡ ‡fd
d„ˆ_	d S t
d|› d�ƒ‚)Nr    r   r   r	   c                      ó   ˆj jˆ Ž S r"   )r  r  r    ©Zreduce_paramsr�   r    r!   r¸   �  ó    z'BroydenFirst.__init__.<locals>.<lambda>Úsimplec                      r  r"   )r  r
  r    r  r    r!   r¸   ’  r  r  c                      r  r"   )r  r	  r    r  r    r!   r¸   ”  r  zUnknown rank reduction method 'ú')rÜ   r‘   rÝ   r  r#   r:   r  rÄ   rÔ   Ú_reducer]   )r�   rÝ   Zreduction_methodr  r    r  r!   r‘     s$   

zBroydenFirst.__init__c                 C   s.   t  | |||¡ t| j | jd | jƒ| _d S )Nr   )rÜ   rZ   ræ   rÝ   r2   r+   r  r°   r    r    r!   rZ   ˜  s   zBroydenFirst.setupc                 C   s
   t | jƒS r"   )r   r  r¦   r    r    r!   rœ   œ  rÂ   zBroydenFirst.todenser   c                 C   s>   | j  |¡}t |¡ ¡ s|  | j| j| j¡ | j  |¡S |S r"   )	r  r˜   r#   r7   r8   rZ   rà   rß   rL   )r�   r“   rO   Úrr    r    r!   r   Ÿ  s
   zBroydenFirst.solvec                 C   ó   | j  |¡S r"   )r  r   ©r�   r“   r    r    r!   r˜   §  ó   zBroydenFirst.matvecc                 C   r  r"   )r  r™   ©r�   r“   rO   r    r    r!   rš   ª  r!  zBroydenFirst.rsolvec                 C   r  r"   )r  rš   r   r    r    r!   r™   ­  r!  zBroydenFirst.rmatvecc           
      C   sD   |   ¡  | j |¡}|| j |¡ }|t||ƒ }	| j ||	¡ d S r"   )r  r  r™   r˜   r   rÿ   ©
r�   r'   r“   rq   rã   r–   rä   r<   rî   rï   r    r    r!   rå   °  s
   zBroydenFirst._update)Nr  Nr±   )r   r   r   r   r‘   rZ   rœ   r   r˜   rš   r™   rå   r    r    r    r!   r   J  s    
4

r   c                   @   s   e Zd ZdZd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           
      C   s:   |   ¡  |}|| j |¡ }||d  }	| j ||	¡ d S ©NrQ   )r  r  r˜   rÿ   r#  r    r    r!   rå   í  s
   zBroydenSecond._updateN)r   r   r   r   rå   r    r    r    r!   rÖ   º  s    2rÖ   c                   @   s4   e Zd ZdZddd„Zddd	„Zd
d„ Zd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                 C   s2   t  | ¡ || _|| _g | _g | _d | _|| _d S r"   )rÜ   r‘   rÝ   ÚMrq   rã   rt   Úw0)r�   rÝ   r'  r&  r    r    r!   r‘   A  s   

zAnderson.__init__r   c           	      C   sÌ   | j  | }t| jƒ}|dkr|S tj||jd�}t|ƒD ]}t| j| |ƒ||< qzt	| j
|ƒ}W n tyI   | jd d …= | jd d …= | Y S w t|ƒD ]}||| | j| | j | j|    7 }qN|S ©Nr   r*   )rÝ   ró   rq   r#   Úemptyr+   r^   r   rã   r   rð   r
   )	r�   r“   rO   rq   rv   Údf_fr  rt   rÊ   r    r    r!   r   J  s"   
ü(zAnderson.solvec              	   C   s,  | | j  }t| jƒ}|dkr|S tj||jd�}t|ƒD ]}t| j| |ƒ||< qtj||f|jd�}t|ƒD ]<}t|ƒD ]5}t| j| | j| ƒ|||f< ||krs| j	dkrs|||f  t| j| | j| ƒ| j	d  | j  8  < q>q8t
||ƒ}	t|ƒD ]}
||	|
 | j|
 | j|
 | j    7 }q~|S )Nr   r*   rQ   )rÝ   ró   rq   r#   r)  r+   r^   r   rã   r'  r   )r�   r“   rq   rv   r*  r  Úbrù   rú   rt   rÊ   r    r    r!   r˜   a  s&   
6€ý
(zAnderson.matvecc                 C   sø   | j dkrd S | j |¡ | j |¡ t| jƒ| j kr/| j d¡ | j d¡ t| jƒ| j kst| jƒ}tj||f|jd�}t	|ƒD ])}	t	|	|ƒD ]!}
|	|
krU| j
d }nd}d| t| j|	 | j|
 ƒ ||	|
f< qIqB|t |d¡j ¡ 7 }|| _d S )Nr   r*   rQ   r   )r&  rq   rÿ   rã   ró   Úpopr#   rö   r+   r^   r'  r   Útriur¼   r»   rð   )r�   r'   r“   rq   rã   r–   rä   rv   rð   rù   rú   Úwdr    r    r!   rå   x  s&   
þ
(û
zAnderson._update)Nr{   r%  r±   )r   r   r   r   r‘   r   r˜   rå   r    r    r    r!   r×   ú  s    
F
	r×   c                   @   sV   e Zd ZdZddd„Zdd„ Zddd	„Zd
d„ Zddd„Zdd„ Z	dd„ Z
d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                 C   ó   t  | ¡ || _d S r"   ©rÜ   r‘   rÝ   ©r�   rÝ   r    r    r!   r‘   ¿  ó   

zDiagBroyden.__init__c                 C   s6   t  | |||¡ tj| jd fd| j | jd�| _d S )Nr   r   r*   )rÜ   rZ   r#   Úfullr2   rÝ   r+   rï   r°   r    r    r!   rZ   Ã  s   &zDiagBroyden.setupr   c                 C   ó   | | j  S r"   ©rï   r"  r    r    r!   r   Ç  r!  zDiagBroyden.solvec                 C   ó   | | j  S r"   r5  r   r    r    r!   r˜   Ê  r!  zDiagBroyden.matvecc                 C   ó   | | j  ¡  S r"   ©rï   r»   r"  r    r    r!   rš   Í  ó   zDiagBroyden.rsolvec                 C   ó   | | j  ¡  S r"   r8  r   r    r    r!   r™   Ð  r9  zDiagBroyden.rmatvecc                 C   s   t  | j ¡S r"   )r#   Údiagrï   r¦   r    r    r!   rœ   Ó  r)   zDiagBroyden.todensec                 C   s(   |  j || j |  | |d  8  _ d S r$  r5  râ   r    r    r!   rå   Ö  s   (zDiagBroyden._updater"   r±   ©r   r   r   r   r‘   rZ   r   r˜   rš   r™   rœ   rå   r    r    r    r!   rØ   –  s    
(

rØ   c                   @   sN   e Zd ZdZddd„Zddd„Zdd	„ Zdd
d„Zdd„ Zdd„ Z	d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                 C   r/  r"   r0  r1  r    r    r!   r‘   ñ  r2  zLinearMixing.__init__r   c                 C   r6  r"   ©rÝ   r"  r    r    r!   r   õ  r!  zLinearMixing.solvec                 C   r4  r"   r=  r   r    r    r!   r˜   ø  r!  zLinearMixing.matvecc                 C   s   | t  | j¡ S r"   ©r#   r»   rÝ   r"  r    r    r!   rš   û  ó   zLinearMixing.rsolvec                 C   s   | t  | j¡ S r"   r>  r   r    r    r!   r™   þ  r?  zLinearMixing.rmatvecc                 C   s   t  t  | jd d| j ¡¡S )Nr   éÿÿÿÿ)r#   r;  r3  r2   rÝ   r¦   r    r    r!   rœ     s   zLinearMixing.todensec                 C   r­   r"   r    râ   r    r    r!   rå     r¬   zLinearMixing._updater"   r±   )r   r   r   r   r‘   r   r˜   rš   r™   rœ   rå   r    r    r    r!   rÙ   Ú  s    


rÙ   c                   @   sV   e Zd ZdZddd„Zdd„ Zdd	d
„Zdd„ Zddd„Zdd„ Z	dd„ Z
d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
    NrP   c                 C   s    t  | ¡ || _|| _d | _d S r"   )rÜ   r‘   rÝ   ÚalphamaxÚbeta)r�   rÝ   rA  r    r    r!   r‘   #  s   

zExcitingMixing.__init__c                 C   s2   t  | |||¡ tj| jd f| j| jd�| _d S r(  )rÜ   rZ   r#   r3  r2   rÝ   r+   rB  r°   r    r    r!   rZ   )  s   "zExcitingMixing.setupr   c                 C   r6  r"   ©rB  r"  r    r    r!   r   -  r!  zExcitingMixing.solvec                 C   r4  r"   rC  r   r    r    r!   r˜   0  r!  zExcitingMixing.matvecc                 C   r:  r"   ©rB  r»   r"  r    r    r!   rš   3  r9  zExcitingMixing.rsolvec                 C   r7  r"   rD  r   r    r    r!   r™   6  r9  zExcitingMixing.rmatvecc                 C   s   t  d| j ¡S )Nr@  )r#   r;  rB  r¦   r    r    r!   rœ   9  r9  zExcitingMixing.todensec                 C   sL   || j  dk}| j|  | j7  < | j| j| < tj| jd| j| jd� d S )Nr   )Úout)rß   rB  rÝ   r#   ÚcliprA  )r�   r'   r“   rq   rã   r–   rä   Úincrr    r    r!   rå   <  s   zExcitingMixing._update)NrP   r±   r<  r    r    r    r!   rÚ     s    


rÚ   c                   @   sH   e Zd ZdZ		ddd„Zdd	„ Zd
d„ Zddd„Zdd„ Zd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           	      K   s`  || _ || _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d� ||¡| _t|| j d�| _| jtjjju rI|| jd< d| jd< | j dd¡ nG| jtjjjtjjjtjjj	fv rb| 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 ]\}}| d¡s¤td|› �ƒ‚|| j|dd … < q”d S )N)ÚbicgstabÚgmresrH  ÚcgsÚminresÚtfqmr)rj   r&  r  r   rj   Úatolr   Úouter_kÚouter_vÚprepend_outer_vTÚstore_outer_AvFZinner_zUnknown parameter é   )Úpreconditionerr…   rÕ   rÆ   rÇ   rÍ   rK  rL  rH  rM  rN  rO  ÚgetÚmethodÚ	method_kwÚ
setdefaultÚgcrotmkrŸ   Ú
startswithr]   )	r�   r…   rX  Zinner_maxiterZinner_MrQ  r¢   Úkeyr¥   r    r    r!   r‘   ­  sD   úù	

þ


ýzKrylovJacobian.__init__c                 C   s<   t | jƒ ¡ }t | jƒ ¡ }| jtd|ƒ td|ƒ | _d S )Nr   )rƒ   r4   r%   rá   r…   Úomega)r�   ÚmxÚmfr    r    r!   Ú_update_diff_stepÜ  s    z KrylovJacobian._update_diff_stepc                 C   sl   t |ƒ}|dkrd| S | j| }|  | j||  ¡| j | }t t |¡¡s4t t |¡¡r4tdƒ‚|S )Nr   z$Function returned non-finite results)	r   r^  rL   r4   rá   r#   r8   r7   r]   )r�   r<   ÚnvÚscr  r    r    r!   r˜   á  s   
 zKrylovJacobian.matvecr   c                 C   sN   d| j v r| j| j|fi | j ¤Ž\}}|S | j| j|fd|i| j ¤Ž\}}|S )NÚrtol)rY  rX  Úop)r�   ÚrhsrO   Úsolrx   r    r    r!   r   ë  s
   
 ÿzKrylovJacobian.solvec                 C   sD   || _ || _|  ¡  | jd urt| jdƒr | j ||¡ d S d S d S )Nrb   )r4   rá   ra  rV  r¡   rb   )r�   r'   r“   r    r    r!   rb   ò  s   
þzKrylovJacobian.updatec                 C   s„   t  | |||¡ || _|| _tjj | ¡| _| j	d u r%t
 |j¡jd | _	|  ¡  | jd ur>t| jdƒr@| j |||¡ d S d S d S )NrÞ   rZ   )r—   rZ   r4   rá   rÆ   rÇ   rÍ   Úaslinearoperatorre  r…   r#   r�   r+   rŽ   ra  rV  r¡   )r�   r'   r“   rL   r    r    r!   rZ   ü  s   

þzKrylovJacobian.setup)NrH  rI  NrJ  r±   )
r   r   r   r   r‘   ra  r˜   r   rb   rZ   r    r    r    r!   r   G  s    e
ÿ/


r   c                 C   sÚ   t |jƒ}|\}}}}}}}	tt|t|ƒ d… |ƒƒ}
d dd„ |
D ƒ¡}|r,d| }d dd„ |
D ƒ¡}|r<|d }|rEtd|› �ƒ‚d}|t| ||j|d� }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                 S   s   g | ]\}}|› d |›�‘qS ©ú=r    ©Ú.0r  r<   r    r    r!   Ú
<listcomp>  ó    z#_nonlin_wrapper.<locals>.<listcomp>c                 S   s   g | ]\}}|› d |› �‘qS ri  r    rk  r    r    r!   rm     rn  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¢   ÚjacZkwkw)Ú_getfullargspecr‘   Úlistrì   ró   Újoinr]   rÕ   r   rb   ÚglobalsÚexecr   r@   )r¤   ro  Ú	signatureÚargsÚvarargsÚvarkwÚdefaultsÚ
kwonlyargsÚ
kwdefaultsÚ_ÚkwargsZkw_strZkwkw_strÚwrapperÚnsrL   r    r    r!   Ú_nonlin_wrapper  s,   
	
ÿ
r€  r   r   r   r   r   r   r   )rA   NFNNNNNNrB   NFT)rB   rz   r{   )<rÎ   rc   r  Únumpyr#   r   r   r   Úscipy.linalgr   r   r   r   r	   r
   Úscipy.sparse.linalgrÆ   Úscipy.sparser   Úscipy._lib._utilr   r   rp  Ú_linesearchr   r   Ú__all__Ú	Exceptionr   r(   r/   r6   r=   rÕ   Ústripr>   r@   ry   ra   rW   r—   r   rY   rÜ   ræ   r   rÖ   r×   rØ   rÙ   rÚ   r   r€  r   r   r   r   r   r   r   r    r    r    r!   Ú<module>   s|    

(Ð4
ý 
ÿ-@H'` Mëp@ D.? K
,




