
    _-Ph,                     j    d Z ddlZddlmZ ddlZddlZddlmZm	Z	 ddl
mZ ddlmZ d Z	 	 	 ddZdS )z(GMRES Gram-Schmidt-based implementation.    N)warn)get_blas_funcsget_lapack_funcs   )norm)make_systemc                     t          |          D ]2}| |         }t          j        ||||dz                      |||dz   <   3dS )a  Apply the first k Givens rotations in Q to v.

    Parameters
    ----------
    Q : list
        list of consecutive 2x2 Givens rotations
    v : array
        vector to apply the rotations to
    k : int
        number of rotations to apply.

    Returns
    -------
    v is changed in place

    Notes
    -----
    This routine is specialized for GMRES.  It assumes that the first Givens
    rotation is for dofs 0 and 1, the second Givens rotation is for
    dofs 1 and 2, and so on.

    r   N)rangenpdot)QvkjQlocs        W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/pyamg/krylov/_gmres_mgs.pyapply_givensr      sW    . 1XX * *t6$!AaC%))!AaC%* *    h㈵>Fc           
      p   |
1|t          d          |
}d}t          j        |t          d           t	          | |||          \  } }}}}| j        d         }t          j        dd	           t          d
g|g          \  }t          j	        t          j
        d|j                            rt          g d|g          \  }}}}nt          g d|g          \  }}}}|r!|r|}nd}||k    rt          d           |}|}n.d}|t          |d          }n||k    rt          d           |}|}|dk    rAt          j        | t          j        dg|j                  z            } |||z            dfS || |z  z
  }||z  }t!          |          }||g|dd<   t!          |          }|dk    rd}nt!          ||z            }|||z  k     r ||          dfS d}t#          |          D ]9}g }t          j
        |dz   |dz   f|j                  }t          j
        |dz   |f|j                  }g }  |d|z  |          |dddf<   |                     |dddf                    t          j
        |f|j                  }!||!d<   t#          |          D ]6}"||"dz   ddf         }#t          j        || | d         z  z            |#dd<   |                     |#           t!          |#          }$t#          |"dz             D ]1}%| |%         }& ||&|#          }'|'||"|%f<    ||&|#||'           |#dd<   2t!          |#          }(|(||"|"dz   f<   |	du r[|$|$d|(z  z   k    rOt#          |"dz             D ]<}%| |%         }& ||&|#          }'||"|%f         |'z   ||"|%f<    ||&|#||'           |#dd<   =||"|"dz   f         dk    r |d||"|"dz   f         z  |#          |#dd<   |"dk    rt'          |||"ddf         |"           |"|dz
  k    r||"|"dz   f         dk    r |||"|"f         ||"|"dz   f                   \  })}*}t          j        |)|*gt          j        |*           |)gg|j                  }+|                    |+           t          j        |+|!|"|"dz                      |!|"|"dz   <    ||+dddf         ||"|"|"dz   f                   ||"|"f<   d||"|"dz   f<   |dz  }|"|dz
  k     rt          j        |!|"dz                      }|||z  k     r n||                    |           |t.          j                            |d|"dz   d|"dz   f         j        |!d|"dz                      },t          j        |d|"dz   ddf         j                            |,                    dd                              }- |||-z              8t.          j                            |d|"dz   d|"dz   f         j        |!d|"dz                      },t          j        |d|"dz   ddf         j                            |,                    dd                              }-||-z   }|| |z  z
  }||z  }t!          |          }| ||           ||                    |           |dk    }.|.                                rJt          j        t          j        |-|.         ||.         z                      }/|/dk     r ||          dfc S |||z  k     r ||          dfc S ; ||          |fS )a  Generalized Minimum Residual Method (GMRES) based on MGS.

    GMRES iteratively refines the initial solution guess to the system
    Ax = b.  Modified Gram-Schmidt version.  Left preconditioning, leading
    to preconditioned residuals.

    Parameters
    ----------
    A : array, matrix, sparse matrix, LinearOperator
        n x n, linear system to solve
    b : array, matrix
        right hand side, shape is (n,) or (n,1)
    x0 : array, matrix
        initial guess, default is a vector of zeros
    tol : float
        Tolerance for stopping criteria, let r=r_k
        ||M r|| < tol ||M b||
        if ||b||=0, then set ||M b||=1 for these tests.
    restart : None, int
        - if int, restart is max number of inner iterations
          and maxiter is the max number of outer iterations
        - if None, do not restart GMRES, and max number of inner iterations
          is maxiter
    maxiter : None, int
        - if restart is None, maxiter is the max number of inner iterations
          and GMRES does not restart
        - if restart is int, maxiter is the max number of outer iterations,
          and restart is the max number of inner iterations
        - defaults to min(n,40) if restart=None
    M : array, matrix, sparse matrix, LinearOperator
        n x n, inverted preconditioner, i.e. solve M A x = M b.
    callback : function
        User-supplied function is called after each iteration as
        callback(xk), where xk is the current solution vector
    residuals : list
        preconditioned residual history in the 2-norm,
        including the initial preconditioned residual
    reorth : boolean
        If True, then a check is made whether to re-orthogonalize the Krylov
        space each GMRES iteration
    restrt : None, int
        Deprecated.  See restart.

    Returns
    -------
    (xk, info)
    xk : an updated guess after k iterations to the solution of Ax = b
    info : halting status

            ==  =======================================
            0   successful exit
            >0  convergence to tolerance not achieved,
                return iteration count instead.
            <0  numerical breakdown, or illegal input
            ==  =======================================

    Notes
    -----
    The LinearOperator class is in scipy.sparse.linalg.
    Use this class if you prefer to define A or M as a mat-vec routine
    as opposed to explicitly constructing the matrix.

    For robustness, modified Gram-Schmidt is used to orthogonalize the
    Krylov Space Givens Rotations are used to provide the residual norm
    each iteration

    The residual is the *preconditioned* residual.

    Examples
    --------
    >>> from pyamg.krylov import gmres
    >>> from pyamg.util.linalg import norm
    >>> import numpy as np
    >>> from pyamg.gallery import poisson
    >>> A = poisson((10,10))
    >>> b = np.ones((A.shape[0],))
    >>> (x,flag) = gmres(A,b, maxiter=2, tol=1e-8, orthog='mgs')
    >>> print(f'{norm(b - A*x):.6}')
    6.54282

    References
    ----------
    .. [1] Yousef Saad, "Iterative Methods for Sparse Linear Systems,
       Second Edition", SIAM, pp. 151-172, pp. 272-275, 2003
       http://www-users.cs.umn.edu/~saad/books.html

    .. [2] C. T. Kelley, http://www4.ncsu.edu/~ctk/matlab_roots.html

    Nz*Only use restart, not restrt (deprecated).zaThe keyword argument "restrt" is deprecated and will be removed in 2024.   Use "restart" instead.   )
stacklevelr   alwayszpyamg.krylov._gmres_mgs)modulelartg)r   )dtype)axpydotudotcscal)r   r   r   r    z&Setting restart to maximum allowed, n.(   z&Setting maxiter to maximum allowed, n.g      ?g        TgMbP?r   g-q=)
ValueErrorwarningsr   DeprecationWarningr   shapefilterwarningsr   r   iscomplexobjzerosr   r   minravelarrayr   r
   appendr   	conjugater   abssplinalgsolveTreshapeanymax)0Abx0tolrestartmaxiterMcallback	residualsreorthrestrtmsgxpostprocessnr   r   r   r   r    	max_outer	max_innerentryrnormrnormbnormMbniter_outerr   HVvsginnerr   	normv_oldr   vkalphanormvcsQblockyupdateindiceschanges0                                                   r   	gmres_mgsr_   )   s   x IJJJ>c-!<<<< *!QA66Aq!Q	
A H-FGGGG y1#..GU	rxAG44455 @;;;aSAA 	!tT44
 999A3?? 	!tT4   	IIIQ;;9:::G			?!RjjGGq[[9:::G	 	AvvRXse17;;;;<<AeG$$a(( 	
AE	A 	
AAGGEw	!!! GGE||a!e sV|A""
 E 	"" x' x'  Hik9Q;/qw???Hik1%QW555 $s5y!$$!QQQ$
		!AqqqD' HaT)))!9%% B	) B	)E %'111*A8ARV,--AaaaDIIaLLLQI 57^^ . .UR#%(tB1uf--!!!GGE %AeU1Wn $Y)eem2K%K%KuQw 2 2AAB DQKKE"#E1H+"5AeQhK4Aq5&11AaaaDD a C''tC%q. 11155!!! qyyQ%(U333
 !||UE!G^$)) %auoqa7H I IIQ1X1va0@!/D&EQWUUUFHHV$$$ (*vfaeAg6F'G'GAeE!Gm$ '+d6!QQQ$<5%a-;O9P&Q&QAeUlO(+AeU1Wn%QJE y{""qqz**3<''E($$U+++'	!E!G)QuQwY*>(?(A1QuQwY<PPAXaq!!!n&6&:&:199R;K;K&L&LMMFHQZ(((
 IOOAaai57235q57|DD!HU1WHaaaK.*..qyyQ/?/?@@AAJAI EQ HQKKK U### q&;;== 	,VBF6'?QwZ#?@@AAF~~#A++++ 3<KNNA&&&&  
 KNNE""r   )	Nr   NNNNNFN)__doc__r$   r   numpyr   scipyr0   scipy.linalgr   r   util.linalgr   utilr   r   r_    r   r   <module>rg      s    . .                9 9 9 9 9 9 9 9            * * *8 "&$(JNi# i# i# i# i# i#r   