3
Od<                 @   sp   d dl Z d dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlmZ dgZddf f dfddZdddZdS )    N)LinAlgError)get_blas_funcsqrsolvesvd	qr_insertlstsq)make_systemgcrotmkFc	       "      C   s  |dkrdd }|dkr dd }t ddddg|f\}	}
}}|g}g }d}tj}|t| }tjt||f|jd	}tjd|jd	}tjd|jd	}tj|jj}d}x~t	|D ]p}|r|t|k r|| \}}nb|r|t|kr||}d}nD| r(||t| kr(|||t|   \}}n||d }d}|dkrP|| |}n|j
 }||}xBt|D ]6\}}|
||}||||f< |	|||jd | }qjW tj|d |jd	}x>t|D ]2\}}|
||}|||< |	|||jd | }qW ||||d
 < tjddd d
|d  }W dQ R X tj|rD|||}|d || ksZd}|j| |j| tj|d |d f|jdd}||d|d
 d|d
 f< d
||d
 |d
 f< tj|d |f|jdd} || d|d
 ddf< t|| ||dddd\}}t|d }||k s"|rP qW tj|||f sBt t|d|d
 d|d
 f |dd|d
 f j \}}!}!}!|ddd|d
 f }|||||||fS )a  
    FGMRES Arnoldi process, with optional projection or augmentation

    Parameters
    ----------
    matvec : callable
        Operation A*x
    v0 : ndarray
        Initial vector, normalized to nrm2(v0) == 1
    m : int
        Number of GMRES rounds
    atol : float
        Absolute tolerance for early exit
    lpsolve : callable
        Left preconditioner L
    rpsolve : callable
        Right preconditioner R
    CU : list of (ndarray, ndarray)
        Columns of matrices C and U in GCROT
    outer_v : list of ndarrays
        Augmentation vectors in LGMRES
    prepend_outer_v : bool, optional
        Whether augmentation vectors come before or after 
        Krylov iterates

    Raises
    ------
    LinAlgError
        If nans encountered

    Returns
    -------
    Q, R : ndarray
        QR decomposition of the upper Hessenberg H=QR
    B : ndarray
        Projections corresponding to matrix C
    vs : list of ndarray
        Columns of matrix V
    zs : list of ndarray
        Columns of matrix Z
    y : ndarray
        Solution to ||H y - e_1||_2 = min!
    res : float
        The final (preconditioned) residual norm

    Nc             S   s   | S )N )xr   r   W/var/www/html/virt/lib64/python3.6/site-packages/scipy/sparse/linalg/isolve/_gcrotmk.py<lambda>@   s    z_fgmres.<locals>.<lambda>c             S   s   | S )Nr   )r   r   r   r   r   B   s    axpydotscalnrm2)dtype   r   F   ignore)ZoverdivideTF)r   ordercol)whichZoverwrite_qruZcheck_finite)r   r   )r   r   r   r   r   )r   r   )r   npnanlenZzerosr   ZonesZfinfoepsrangecopy	enumerateshapeZerrstateisfiniteappendr   absr   r   Zconj)"matvecZv0matolZlpsolverpsolvecsZouter_vZprepend_outer_vr   r   r   r   vszsyresBQRr    Z	breakdownjzwZw_normicalphaZhcurvZQ2ZR2_r   r   r   _fgmres   s|    1





>r<   h㈵>     oldestc       A      C   s*  t | |||\} }}}}tj|j s.td|dkrDtd|f |dkr`tjdtdd |}| j}|j}|	dkrxg }	|dkr|}d\}}}||| }t	d	d
ddg||f\}}}}||}|
rdd |	D |	dd< |	rP|	j
dd d tj| jd t|	f|jdd}g }d}xN|	rf|	jd\}}|dkr@||}||dd|f< |d7 }|j| qW t|dddd\}}}~t|j}g } xtt|D ]}|||  }x8t|D ],}!||||!  ||jd ||!|f  }qW t|||f dt|d   k r
P |d|||f  |}| j| qW tt|| ddd! |	dd< |	rt	d	d
g|f\}}xF|	D ]>\}}|||}"||||jd |"}||||jd |" }qpW x6t|D ](}#|dk	r|| ||}$t||| }%|$|%kr|#dks|	r||| }||}$|$|%kr*d"}#P |t|t|	 d }&dd |	D }y@t|||$ |&|t||| |$ |d\}}}'}(})}*}+|*|$9 }*W n tk
r   P Y nX |)d |*d  },x<t|)dd |*dd D ]\}-}"||-|,|,jd |"},qW |'j|*}.x6t|	|.D ](\}/}0|/\}}|||,|,jd |0 },qW |j|j|*}1|(d |1d  }2x<t|(dd |1dd D ]\}3}4||3|2|2jd |4}2qtW y"d||2 }5tj|5st W n ttfk
r   wY nX ||5|2}2||5|,},||2|}6||2||jd |6 }||,||jd |6}|dkrPx t|	|krJ|	rJ|	d= q,W n|dkrt|	|kr|	rt|dd#ddf j|'jj}7t|7\}8}9}:g };x(t|8ddd|d f jD ]\}}<|	d \}}||<d  }||<d  }xXt|	dd |<dd D ]:\}=}>|=\}?}@||?||jd |>}||@||jd |>}qW xH|;D ]@\}?}@||?|}5||?||jd |5 }||@||jd |5 }qPW ||}5|d|5 |}|d|5 |}|;j||f qW |;|	dd< |	j|2|,f qW |	jd|j  f |
rdd |	D |	dd< |||#d fS )$a  
    Solve a matrix equation using flexible GCROT(m,k) algorithm.

    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).
    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 `tol`.

        .. warning::

           The default value for `atol` will be changed in a future release.
           For future compatibility, specify `atol` explicitly.
    maxiter : int, optional
        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}, optional
        Preconditioner for A.  The preconditioner should approximate the
        inverse of A. gcrotmk is a 'flexible' algorithm and the preconditioner
        can vary from iteration to iteration. Effective preconditioning
        dramatically improves the rate of convergence, which implies that
        fewer iterations are needed to reach a given error tolerance.
    callback : function, optional
        User-supplied function to call after each iteration.  It is called
        as callback(xk), where xk is the current solution vector.
    m : int, optional
        Number of inner FGMRES iterations per each outer iteration.
        Default: 20
    k : int, optional
        Number of vectors to carry between inner FGMRES iterations.
        According to [2]_, good values are around m.
        Default: m
    CU : list of tuples, optional
        List of tuples ``(c, u)`` which contain the columns of the matrices
        C and U in the GCROT(m,k) algorithm. For details, see [2]_.
        The list given and vectors contained in it are modified in-place.
        If not given, start from empty matrices. The ``c`` elements in the
        tuples can be ``None``, in which case the vectors are recomputed
        via ``c = A u`` on start and orthogonalized as described in [3]_.
    discard_C : bool, optional
        Discard the C-vectors at the end. Useful if recycling Krylov subspaces
        for different linear systems.
    truncate : {'oldest', 'smallest'}, optional
        Truncation scheme to use. Drop: oldest vectors, or vectors with
        smallest singular values using the scheme discussed in [1,2].
        See [2]_ for detailed comparison.
        Default: 'oldest'

    Returns
    -------
    x : array or matrix
        The solution found.
    info : int
        Provides convergence information:

        * 0  : successful exit
        * >0 : convergence to tolerance not achieved, number of iterations

    References
    ----------
    .. [1] E. de Sturler, ''Truncation strategies for optimal Krylov subspace
           methods'', SIAM J. Numer. Anal. 36, 864 (1999).
    .. [2] J.E. Hicken and D.W. Zingg, ''A simplified and flexible variant
           of GCROT for solving nonsymmetric linear systems'',
           SIAM J. Sci. Comput. 32, 172 (2010).
    .. [3] M.L. Parks, E. de Sturler, G. Mackey, D.D. Johnson, S. Maiti,
           ''Recycling Krylov subspaces for sequences of linear systems'',
           SIAM J. Sci. Comput. 28, 1651 (2006).

    z$RHS must contain only finite numbersr@   smallestz Invalid value for 'truncate': %rNzscipy.sparse.linalg.gcrotmk called without specifying `atol`. The default value will change in the future. To preserve current behavior, set ``atol=tol``.r   )category
stacklevelr   r   r   r   c             S   s   g | ]\}}d |fqS )Nr   ).0r8   ur   r   r   
<listcomp>)  s    zgcrotmk.<locals>.<listcomp>c             S   s   | d d k	S )Nr   r   )cur   r   r   r   .  s    zgcrotmk.<locals>.<lambda>)keyr   r   )r   r   r   TZeconomic)Zoverwrite_amodeZpivotingg-q=g      ?c             S   s   g | ]\}}|qS r   r   )rD   r8   rE   r   r   r   rF   y  s    )r+   r*   r,   c             S   s   g | ]\}}d |fqS )Nr   )rD   czuzr   r   r   rF     s    )r@   rA   )NNN)r   r   r   r   r   )!r	   r   r%   all
ValueErrorwarningswarnDeprecationWarningr(   r   sortemptyr$   r   r   popr&   r   listTr!   r'   zipmaxr<   r   r   FloatingPointErrorZeroDivisionErrorr   r   r#   r"   )AAbZx0ZtolmaxiterMcallbackr)   kZCUZ	discard_Ctruncater*   r   postprocessr(   Zpsolver   r   r   rr   Zb_normCusr4   r8   rE   r2   r3   Pr,   Znew_usr7   ZycZj_outerbetaZbeta_tolmlr1   r-   r.   r/   ZpresZuxr5   ZbyrG   ZbycZhyZcxr:   Zhycr9   gammaDWsigmaVZnew_CUr6   cupZwpcpZupr   r   r   r
      s    R

 

," 



$
$






 ,$
)Nr=   r>   NNr?   NNFr@   N)rN   Znumpyr   Znumpy.linalgr   Zscipy.linalgr   r   r   r   r   r   Z scipy.sparse.linalg.isolve.utilsr	   __all__r<   r
   r   r   r   r   <module>   s     (  