3
Odl              
   @   s   d Z ddddddg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 ddlmZ dddddZdZdZdd Zdd Zd/ddZeddd d!e d0d#dZed$d%e d1d&dZed'd(e d2d)dZed*d+e d3d,dZe d4d-dZe d5d.dZdS )6z,Iterative methods for solving linear systemsbicgbicgstabcgcgsgmresqmr    N   )
_iterative)LinearOperator)make_system)_aligned_zeros)non_reentrantsdcz)fr   FDzH
Parameters
----------
A : {sparse matrix, dense matrix, LinearOperator}aw  b : {array, matrix}
    Right hand side of the linear system. Has shape (N,) or (N,1).

Returns
-------
x : {array, matrix}
    The converged solution.
info : integer
    Provides convergence information:
        0  : successful exit
        >0 : convergence to tolerance not achieved, number of iterations
        <0 : illegal input or breakdown

Other Parameters
----------------
x0  : {array, matrix}
    Starting guess for the solution.
tol, atol : float, optional
    Tolerances for convergence, ``norm(residual) <= max(tol*norm(b), atol)``.
    The default for ``atol`` is ``'legacy'``, which emulates
    a different legacy behavior.

    .. warning::

       The default value for `atol` will be changed in a future release.
       For future compatibility, specify `atol` explicitly.
maxiter : integer
    Maximum number of iterations.  Iteration will stop after maxiter
    steps even if the specified tolerance has not been achieved.
M : {sparse matrix, dense matrix, LinearOperator}
    Preconditioner for A.  The preconditioner should approximate the
    inverse of A.  Effective preconditioning dramatically improves the
    rate of convergence, which implies that fewer iterations are needed
    to reach a given error tolerance.
callback : function
    User-supplied function to call after each iteration.  It is called
    as callback(xk), where xk is the current solution vector.

c             C   s(   t jj| }||kr|dfS |dfS dS )z;
    Successful termination condition for the solvers.
    r   r   N)nplinalgnorm)Zresidualatolresid r   X/var/www/html/virt/lib64/python3.6/site-packages/scipy/sparse/linalg/isolve/iterative.py	_stoptestC   s    r   c             C   sz   |dkr$t jdj|dtdd d}t| } |dkr`| }|| krFdS |dkrR| S | t| S ntt|| t| S dS )	a  
    Parse arguments for absolute tolerance in termination condition.

    Parameters
    ----------
    tol, atol : object
        The arguments passed into the solver routine by user.
    bnrm2 : float
        2-norm of the rhs vector.
    get_residual : callable
        Callable ``get_residual()`` that returns the initial value of
        the residual.
    routine_name : str
        Name of the routine.
    Na	  scipy.sparse.linalg.{name} called without specifying `atol`. The default value will be changed in a future release. For compatibility, specify a value for `atol` explicitly, e.g., ``{name}(..., atol=0)``, or to retain the old behavior ``{name}(..., atol='legacy')``)name   )category
stacklevellegacyexitr   )warningswarnformatDeprecationWarningfloatmax)tolr   bnrm2get_residualZroutine_namer   r   r   r   	_get_atolN   s    
r,    0c                s    fdd}|S )Nc                s&   dj td jdd tf| _| S )N
z    z
    )joincommon_doc1replacecommon_doc2__doc__)fn)Ainfofooterheaderr   r   combinex   s    zset_docstring.<locals>.combiner   )r8   r6   r7   Zatol_defaultr9   r   )r6   r7   r8   r   set_docstringw   s    r:   z7Use BIConjugate Gradient iteration to solve ``Ax = b``.zThe real or complex N-by-N matrix of the linear system.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` and ``A^T x`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.a+  
               
               Examples
               --------
               >>> from scipy.sparse import csc_matrix
               >>> from scipy.sparse.linalg import bicg
               >>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
               >>> b = np.array([2, 4, -1], dtype=float)
               >>> x, exitCode = bicg(A, b)
               >>> print(exitCode)            # 0 indicates successful convergence
               0
               >>> np.allclose(A.dot(x), b)
               True
               
               )r7   h㈵>c          
      s  t | || \} } }t }	|d kr0|	d }| j| j }
|j|j }}tjj }tt|d } fdd}t	||t
jj |d}|dkr|dfS |}d}d}td	|	 jd
}d}d}d}|}x|}| |||||||	\	}}}}}}}}|d k	r||kr| t|d |d |	 }t|d |d |	 }|dkrl|d k	rf| P n|dkr||  |9  < ||  |||  7  < n|dkr||  |9  < ||  ||
||  7  < n|dkr||| ||< nz|dkr||| ||< n^|dkrH||  |9  < ||  | 7  < n*|d	krr|r`d}d}t|| |\}}d}qW |dkr||kr||k r|}||fS )N
   Z
bicgrevcomc                  s   t jj  S )N)r   r   r   r   )bmatvecxr   r   <lambda>   s    zbicg.<locals>.<lambda>r   r"   r   r      )dtypeT      r      FrF   rF   )r   lenr>   rmatvec
_type_convrB   chargetattrr	   r,   r   r   r   r   slicer   )Ar=   x0r)   maxiterMcallbackr   postprocessnrH   psolverpsolveltrrevcomr+   r   ndx1ndx2workijobinfoftflagiter_olditersclr1sclr2slice1slice2r   )r=   r>   r?   r   r      sj    *







 zBUse BIConjugate Gradient STABilized iteration to solve ``Ax = b``.zThe real or complex N-by-N matrix of the linear system.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.c          
      sD  t | || \} } }t }	|d kr0|	d }| j|j}
tjj }tt|d } fdd}t||t	j
j |d}|dkr|dfS |}d}d}td	|	 jd
}d}d}d}|}xP|}| |||||||	\	}}}}}}}}|d k	r||kr| t|d |d |	 }t|d |d |	 }|dkrZ|d k	rV| P n|dkr||  |9  < ||  |||  7  < nz|dkr|
|| ||< n^|dkr||  |9  < ||  | 7  < n*|dkr|rd}d}t|| |\}}d}qW |dkr8||kr8||k r8|}||fS )Nr<   Zbicgstabrevcomc                  s   t jj  S )N)r   r   r   r   )r=   r>   r?   r   r   r@      s    zbicgstab.<locals>.<lambda>r   r"   r   r      )rB   TrC   rD   r   FrF   rF   rF   )r   rG   r>   rI   rB   rJ   rK   r	   r,   r   r   r   r   rL   r   )rM   r=   rN   r)   rO   rP   rQ   r   rR   rS   rT   rV   rW   r+   r   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   r   )r=   r>   r?   r   r      s`    *





 z5Use Conjugate Gradient iteration to solve ``Ax = b``.zThe real or complex N-by-N matrix of the linear system.
``A`` must represent a hermitian, positive definite matrix.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.c          
      sz  t | || \} } }t }	|d kr0|	d }| j|j}
tjj }tt|d } fdd}t||t	j
j |d}|dkr|dfS |}d}d}td	|	 jd
}d}d}d}|}x|}| |||||||	\	}}}}}}}}|d k	r||kr| t|d |d |	 }t|d |d |	 }|dkrZ|d k	rV| P n|dkr||  |9  < ||  |||  7  < n|dkr|
|| ||< n|dkr||  |9  < ||  | 7  < n`|d	krB|rd}d}t|| |\}}|dkrB|dkrB  ||< t|| |\}}d}qW |dkrn||krn||k rn|}||fS )Nr<   Zcgrevcomc                  s   t jj  S )N)r   r   r   r   )r=   r>   r?   r   r   r@   -  s    zcg.<locals>.<lambda>r   r"   r   r   r   )rB   TrC   rD   FrF   rF   rF   )r   rG   r>   rI   rB   rJ   rK   r	   r,   r   r   r   r   rL   r   )rM   r=   rN   r)   rO   rP   rQ   r   rR   rS   rT   rV   rW   r+   r   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   r   )r=   r>   r?   r   r     sf    *





 z=Use Conjugate Gradient Squared iteration to solve ``Ax = b``.zThe real-valued N-by-N matrix of the linear system.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.c          
      s  t | || \} } }t }	|d kr0|	d }| j|j}
tjj }tt|d } fdd}t||t	j
j |d}|dkr|dfS |}d}d}td	|	 jd
}d}d}d}|}x|}| |||||||	\	}}}}}}}}|d k	r||kr| t|d |d |	 }t|d |d |	 }|dkrZ|d k	rV| P n|dkr||  |9  < ||  |||  7  < n|dkr|
|| ||< n|dkr||  |9  < ||  | 7  < n`|dkrB|rd}d}t|| |\}}|dkrB|dkrB  ||< t|| |\}}d}qW |dkrtt  |\}}|rtd}|dkr||kr||k r|}||fS )Nr<   Z	cgsrevcomc                  s   t jj  S )N)r   r   r   r   )r=   r>   r?   r   r   r@   t  s    zcgs.<locals>.<lambda>r   r"   r   r   rd   )rB   TrC   rD   r   FrF   rF   rF   i)r   rG   r>   rI   rB   rJ   rK   r	   r,   r   r   r   r   rL   r   )rM   r=   rN   r)   rO   rP   rQ   r   rR   rS   rT   rV   rW   r+   r   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   okr   )r=   r>   r?   r   r   b  sn    *






 c       (         s  |dkr|}n|dk	rt d|dk	r>|
dkr>tjdtdd |
dkrJd}
|
dkr`t d	j|
|dkrld
}
t| || \} } }t }|dkr|d }|dkrd}t||}| j|j}t	j
j }tt|d }tjj }tjj| } fdd}t||	||d}	|	dkr*|dfS |dkr@| dfS d}|t||	|  }tj}tj}d}d}td| | j
d}t|d d| d  j
d}d}d}d}|}|}d} d}!d}"x.|}#| ||||||||||\	}}}}}}$}%}|
dkr||#kr| t|d |d | }&t|d |d | }'|d kr~|
d!krf|!rx|||  n|
dkrx| P nJ|dkr||'  |%9  < ||'  |$ 7  < n|dkr|||' ||&< |  r|dkrd}!d} n|dkrJ||'  |%9  < ||'  |$||&  7  < |!r|
d"kr<|||  d}!|"d }"n~|dkr|rbd#}d}t||& |	\}}|s||krtdd| }ntdd| }|dkr|t||	|  }n|| }|}d}|
dkr|"|kr|}P qW |dkr
||	k r
|}||fS )$ag  
    Use Generalized Minimal RESidual iteration to solve ``Ax = b``.

    Parameters
    ----------
    A : {sparse matrix, dense matrix, LinearOperator}
        The real or complex N-by-N matrix of the linear system.
        Alternatively, ``A`` can be a linear operator which can
        produce ``Ax`` using, e.g.,
        ``scipy.sparse.linalg.LinearOperator``.
    b : {array, matrix}
        Right hand side of the linear system. Has shape (N,) or (N,1).

    Returns
    -------
    x : {array, matrix}
        The converged solution.
    info : int
        Provides convergence information:
          * 0  : successful exit
          * >0 : convergence to tolerance not achieved, number of iterations
          * <0 : illegal input or breakdown

    Other parameters
    ----------------
    x0 : {array, matrix}
        Starting guess for the solution (a vector of zeros by default).
    tol, atol : float, optional
        Tolerances for convergence, ``norm(residual) <= max(tol*norm(b), atol)``.
        The default for ``atol`` is ``'legacy'``, which emulates
        a different legacy behavior.

        .. warning::

           The default value for `atol` will be changed in a future release.
           For future compatibility, specify `atol` explicitly.
    restart : int, optional
        Number of iterations between restarts. Larger values increase
        iteration cost, but may be necessary for convergence.
        Default is 20.
    maxiter : int, optional
        Maximum number of iterations (restart cycles).  Iteration will stop
        after maxiter steps even if the specified tolerance has not been
        achieved.
    M : {sparse matrix, dense matrix, LinearOperator}
        Inverse of the preconditioner of A.  M should approximate the
        inverse of A and be easy to solve for (see Notes).  Effective
        preconditioning dramatically improves the rate of convergence,
        which implies that fewer iterations are needed to reach a given
        error tolerance.  By default, no preconditioner is used.
    callback : function
        User-supplied function to call after each iteration.  It is called
        as `callback(args)`, where `args` are selected by `callback_type`.
    callback_type : {'x', 'pr_norm', 'legacy'}, optional
        Callback function argument requested:
          - ``x``: current iterate (ndarray), called on every restart
          - ``pr_norm``: relative (preconditioned) residual norm (float),
            called on every inner iteration
          - ``legacy`` (default): same as ``pr_norm``, but also changes the
            meaning of 'maxiter' to count inner iterations instead of restart
            cycles.
    restrt : int, optional
        DEPRECATED - use `restart` instead.

    See Also
    --------
    LinearOperator

    Notes
    -----
    A preconditioner, P, is chosen such that P is close to A but easy to solve
    for. The preconditioner parameter required by this routine is
    ``M = P^-1``. The inverse should preferably not be calculated
    explicitly.  Rather, use the following template to produce M::

      # Construct a linear operator that computes P^-1 * x.
      import scipy.sparse.linalg as spla
      M_x = lambda x: spla.spsolve(P, x)
      M = spla.LinearOperator((n, n), M_x)

    Examples
    --------
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import gmres
    >>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
    >>> b = np.array([2, 4, -1], dtype=float)
    >>> x, exitCode = gmres(A, b)
    >>> print(exitCode)            # 0 indicates successful convergence
    0
    >>> np.allclose(A.dot(x), b)
    True
    NzOCannot specify both restart and restrt keywords. Preferably use 'restart' only.a4  scipy.sparse.linalg.gmres called without specifying `callback_type`. The default value will be changed in a future release. For compatibility, specify a value for `callback_type` explicitly, e.g., ``{name}(..., callback_type='pr_norm')``, or to retain the old behavior ``{name}(..., callback_type='legacy')``rD   )r   r    r!   r?   pr_normzUnknown callback_type: {!r}noner<      Zgmresrevcomc                  s   t jj  S )N)r   r   r   r   )r=   r>   r?   r   r   r@   :  s    zgmres.<locals>.<lambda>r   r"   r   g      ?r   rA   )rB   rC   TFr   g      ?gؗҜ<g      ?)r?   rf   r!   rF   rF   )rf   r!   )rf   r!   rF   )
ValueErrorr#   r$   r&   r%   r   rG   minr>   rI   rB   rJ   rK   r	   r   r   r   r,   nanr   rL   r   r(   )(rM   r=   rN   r)   ZrestartrO   rP   rQ   Zrestrtr   Zcallback_typerR   rS   rT   rV   rW   r*   ZMb_nrm2r+   Zptol_max_factorZptolr   ZpresidrX   rY   rZ   Zwork2r[   r\   r]   r^   Zold_ijobZ
first_passZresid_readyZiter_numr_   r`   ra   rb   rc   r   )r=   r>   r?   r   r     s    a



0











c	       !   
      sp   t  d|\ }	}
|dkr|dkrtdrfdd}fdd}fdd}fd	d
}t j||d}t j||d}n(dd }t j||d}t j||d}t}|dkr|d }tjj }tt	|d } fdd}t
||tjj|d}|dkr |
dfS |}d}d }td| j}d}d}d}|}x|}||||||||	\	}}}}}}}}|dk	r||kr| t|d |d | }t|d |d | } |d!kr|dk	r| P nN|dkr$||   |9  < ||   | j||  7  < n|dkr^||   |9  < ||   | j||  7  < n|dkr||j||  ||< n|dkr|j||  ||< n|dkr|j||  ||< n~|dkr|j||  ||< n`|dkr||   |9  < ||   | j 7  < n*|dkr6|r$d"}d}t|| |\}}d}qPW |dkrd||krd||k rd|}|
|fS )#a	  Use Quasi-Minimal Residual iteration to solve ``Ax = b``.

    Parameters
    ----------
    A : {sparse matrix, dense matrix, LinearOperator}
        The real-valued N-by-N matrix of the linear system.
        Alternatively, ``A`` can be a linear operator which can
        produce ``Ax`` and ``A^T x`` using, e.g.,
        ``scipy.sparse.linalg.LinearOperator``.
    b : {array, matrix}
        Right hand side of the linear system. Has shape (N,) or (N,1).

    Returns
    -------
    x : {array, matrix}
        The converged solution.
    info : integer
        Provides convergence information:
            0  : successful exit
            >0 : convergence to tolerance not achieved, number of iterations
            <0 : illegal input or breakdown

    Other Parameters
    ----------------
    x0  : {array, matrix}
        Starting guess for the solution.
    tol, atol : float, optional
        Tolerances for convergence, ``norm(residual) <= max(tol*norm(b), atol)``.
        The default for ``atol`` is ``'legacy'``, which emulates
        a different legacy behavior.

        .. warning::

           The default value for `atol` will be changed in a future release.
           For future compatibility, specify `atol` explicitly.
    maxiter : integer
        Maximum number of iterations.  Iteration will stop after maxiter
        steps even if the specified tolerance has not been achieved.
    M1 : {sparse matrix, dense matrix, LinearOperator}
        Left preconditioner for A.
    M2 : {sparse matrix, dense matrix, LinearOperator}
        Right preconditioner for A. Used together with the left
        preconditioner M1.  The matrix M1*A*M2 should have better
        conditioned than A alone.
    callback : function
        User-supplied function to call after each iteration.  It is called
        as callback(xk), where xk is the current solution vector.

    See Also
    --------
    LinearOperator

    Examples
    --------
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import qmr
    >>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
    >>> b = np.array([2, 4, -1], dtype=float)
    >>> x, exitCode = qmr(A, b)
    >>> print(exitCode)            # 0 indicates successful convergence
    0
    >>> np.allclose(A.dot(x), b)
    True
    NrT   c                s    j | dS )Nleft)rT   )r=   )A_r   r   left_psolve  s    zqmr.<locals>.left_psolvec                s    j | dS )Nright)rT   )r=   )rm   r   r   right_psolve  s    zqmr.<locals>.right_psolvec                s    j | dS )Nrl   )rU   )r=   )rm   r   r   left_rpsolve  s    zqmr.<locals>.left_rpsolvec                s    j | dS )Nro   )rU   )r=   )rm   r   r   right_rpsolve  s    zqmr.<locals>.right_rpsolve)r>   rH   c             S   s   | S )Nr   )r=   r   r   r   id  s    zqmr.<locals>.idr<   Z	qmrrevcomc                  s   t jj j S )N)r   r   r   r>   r   )rM   r=   r?   r   r   r@     s    zqmr.<locals>.<lambda>r   r"   r   r      TrC   rD   r   rE   rA   rd      FrF   rF   rF   )r   hasattrr
   shaperG   rI   rB   rJ   rK   r	   r,   r   r   r   r   rL   r>   rH   r   )!rM   r=   rN   r)   rO   ZM1ZM2rQ   r   rP   rR   rn   rp   rq   rr   rs   rS   rV   rW   r+   r   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   r   )rM   rm   r=   r?   r   r     s    C

*


"
 






 )r-   r.   )Nr;   NNNN)Nr;   NNNN)Nr;   NNNN)Nr;   NNNN)	Nr;   NNNNNNN)Nr;   NNNNN)r4   __all__r#   Znumpyr   r-   r	   Zscipy.sparse.linalg.interfacer
   utilsr   Zscipy._lib._utilr   Zscipy._lib._threadsafetyr   rI   r1   r3   r   r,   r:   r   r   r   r   r   r   r   r   r   r   <module>   sL   ))
	A<AG  h 