
    _-Ph6,                     ^    d Z ddlZddlmZmZmZ ddlmZ ddl	m
Z
 d Zdd	Zd
 Z	 	 ddZdS )zSolve an arbitrary system.    N)isspmatrix_csrisspmatrix_bsr
csr_matrix   )smoothed_aggregation_solver)ishermitianc                 D   t          |           sQt          |           sB	 t          |           } t          d           n"# t          $ r}t          d          |d}~ww xY w| j        d         | j        d         k    rt          d          |                                 } | S )a^  
    Convert A to CSR, if A is not a CSR or BSR matrix already.

    Parameters
    ----------
    A : array, matrix, sparse matrix
        (n x n) matrix to convert to CSR

    Returns
    -------
    A : csr_matrix, bsr_matrix
        If A is csr_matrix or bsr_matrix, then do nothing and return A.
        Else, convert A to CSR if possible and return.

    Examples
    --------
    >>> from pyamg.gallery import poisson
    >>> from pyamg.blackbox import make_csr
    >>> A = poisson((40,40),format='csc')
    >>> Acsr = make_csr(A)
    Implicit conversion of A to CSR in pyamg.blackbox.make_csr

    z:Implicit conversion of A to CSR in pyamg.blackbox.make_csrzSArgument A must have type csr_matrix or bsr_matrix, or be convertible to csr_matrixNr   r   zArgument A must be a square)r   r   r   print	Exception	TypeErrorshapeasfptype)Aes     N/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/pyamg/blackbox.pymake_csrr      s    2 1 R!2!2 R	R1ANOOOO 	R 	R 	R J K KPQR	R 	wqzQWQZ5666	

AHs   ? 
A	AATc                    t          |           } i }t          | d          rd|d<   |rt          d           nd|d<   |rt          d           |d         dk    r!dd	d
dddf|d<   ddddf|d<   ddddf|d<   n ddd
dddf|d<   ddddf|d<   ddddf|d<   |t          |           r| j        d         dk    rn| j        d         }t          j        t          j        t          | j	        d         |z            df| j
                  t          j        |                    |d<   nt          j        | j	        d         df| j
                  |d<   nt          |t
          j                  rt          |j	                  dk    r|                    dd          }|j	        d         | j	        d         k    s|j	        d         dk    rt!          d          t          j        || j
                  |d<   nt!          d          |d         dk    rd|d<   n|d                                         |d<   ddd d!d"f|d#<   d$|d%<   d&|d'<   d(|d)<   d*|d+<   d,|d-<   |S ).a  Generate a dictionary of SA parameters for an arbitrary matrix A.

    Parameters
    ----------
    A : array, matrix, csr_matrix, bsr_matrix
        (n x n) matrix to invert, CSR or BSR format preferred for efficiency
    B : None, array
        Near null-space modes used to construct the smoothed aggregation solver
        If None, the constant vector is used
        If (n x m) array, then B is passed to smoothed_aggregation_solver
    verb : bool
        If True, print verbose output during runtime

    Returns
    -------
    config : dict
        A dictionary of solver configuration parameters that one uses to
        generate a smoothed aggregation solver

    Notes
    -----
    The config dictionary contains the following parameter entries: symmetry,
    smooth, presmoother, postsmoother, B, strength, max_levels, max_coarse,
    coarse_solver, aggregate, keep.  See smoothed_aggregtion_solver for each
    parameter's description.

    Examples
    --------
    >>> from pyamg.gallery import poisson
    >>> from pyamg import solver_configuration
    >>> A = poisson((40,40),format='csr')
    >>> solver_config = solver_configuration(A,verb=False)

    T)
fast_check	hermitiansymmetryz  Detected a Hermitian matrixnonsymmetricz!  Detected a non-Hermitian matrixenergycg      local)krylovmaxiterdegree	weightingsmoothblock_gauss_seidel	symmetricr   )sweep
iterationspresmootherpostsmoothergmresgauss_seidel_nrNr   dtypeBz9Invalid dimensions of B, B.shape[0] must equal A.shape[0]z	Invalid BBH	evolutionl2g      @)k	proj_typeepsilonstrength   
max_levelsi  
max_coarsepinvcoarse_solverstandard	aggregateFkeep)r   r   r
   r   	blocksizenpkrononesintr   r+   eye
isinstancendarraylenreshaper   arraycopy)r   r,   verbconfigbsizes        r   solver_configurationrL   4   s   H 	AF 1&&& 7(z 	31222+z 	75666 j[(($!12'J 'J Kx!5+6a!H!H!J}"6,7q"I"I"K~ %Q12'J 'J Kx!2+6a!H!H!J}"3,7q"I"I"K~ 	y! 	BQ!!3!3KNE'"'3qwqzE/A+B+BA*F01#9 #9 #9:<&--I IF3KK '171:q/AAAF3KK	Arz	"	" 	%qw<<1		"a  AGAJ!'!*$$!'!*//WXXXhq000s$$$j[((tc{''))t &QT36(8 (8 9F:F<F<$F?$F;F6NM    c                 .   t          |           } 	 t          | |d         |d         |d         |d         |d         |d         |d         |d         |d	         |d
         |d         |d                   S # t          $ r}t          d          |d}~ww xY w)a  Generate an SA solver given matrix A and a configuration.

    Parameters
    ----------
    A : array, matrix, csr_matrix, bsr_matrix
        Matrix to invert, CSR or BSR format preferred for efficiency
    config : dict
        A dictionary of solver configuration parameters that is used to
        generate a smoothed aggregation solver

    Returns
    -------
    ml : smoothed_aggregation_solver
        smoothed aggregation hierarchy

    Notes
    -----
    config must contain the following parameter entries for
    smoothed_aggregation_solver: symmetry, smooth, presmoother, postsmoother,
    B, strength, max_levels, max_coarse, coarse_solver, aggregate, keep

    Examples
    --------
    >>> from pyamg.gallery import poisson
    >>> from pyamg import solver_configuration,solver
    >>> A = poisson((40,40),format='csr')
    >>> config = solver_configuration(A,verb=False)
    >>> ml = solver(A,config)

    r,   r.   r!   r4   r6   r7   r9   r   r;   r&   r'   r<   )r,   r.   r!   r4   r6   r7   r9   r   r;   r&   r'   r<   z-Failed generating smoothed_aggregation_solverN)r   r   r   r   )r   rJ   r   s      r   solverrO      s    @ 	AP'*0++1$</5h/?17
1C39,3G39,3G6<_6M17
1C282E4:=4I5;N5K-3F^= = =	=  P P PGHHaOPs   A#A5 5
B?BBh㈵>  Fc	           	         t          |           } |#t          | d|          }	t          | |	          }n;|j        d         j        j        d         | j        d         k    rt          d          |j        d         j        j        dk    rd}
nd}
|Ct          j	        t          j
                            | j        d                   | j                  }|r0t          j        d	          t          d
|            d fd}nd}|                    |||
||||          }|r|| |z  z
  }|| |z  z
  }|                                }t          j        t          j        t          j        ||z            |                    }t          j        t          j        t          j        ||z            |                    }t          d|dd|d           t          j        |          dk    r||z  }t          d|d           |r|                    |j                  |fS |                    |j                  S )a  Solve Ax=b.

    Solve the arbitrary system Ax=b with the best out-of-the box choice for a
    solver.  The matrix A can be non-Hermitian, indefinite, Hermitian
    positive-definite, complex, etc...  Generic and robust settings for
    smoothed_aggregation_solver(..) are used to invert A.


    Parameters
    ----------
    A : array, matrix, csr_matrix, bsr_matrix
        Matrix to invert, CSR or BSR format preferred for efficiency
    b : array
        Right hand side.
    x0 : array
        Initial guess (default random vector)
    tol : float
        Stopping criteria: relative residual r[k]/r[0] tolerance
    maxiter : int
        Stopping criteria: maximum number of allowable iterations
    return_solver : bool
        True: return the solver generated
    existing_solver : smoothed_aggregation_solver
        If instance of a multilevel solver, then existing_solver is used
        to invert A, thus saving time on setup cost.
    verb : bool
        If True, print verbose output during runtime
    residuals : list
        List to contain residual norms at each iteration.
        The preconditioned norm is used, namely
        ||r||_M = (M r, r)^(1/2) = (r, r)^(1/2)

    Returns
    -------
    x : array
        Solution to Ax = b
    ml : MultilevelSolver
        Optional return of the multilevel structure used for the solve

    Notes
    -----
    If calling solve(...) multiple times for the same matrix, A, solver reuse
    is easy and efficient.  Set "return_solver=True", and the return value will
    be a tuple, (x,ml), where ml is the solver used to invert A, and x is the
    solution to Ax=b.  Then, the next time solve(...) is called, set
    "existing_solver=ml".

    Examples
    --------
    >>> import numpy as np
    >>> from pyamg import solve
    >>> from pyamg.gallery import poisson
    >>> from pyamg.util.linalg import norm
    >>> A = poisson((40,40),format='csr')
    >>> b = np.array(np.arange(A.shape[0]), dtype=float)
    >>> x = solve(A,b,verb=False)
    >>> print(f'{norm(b - A*x)/norm(b):1.2e}')
    6.28e-06

    N)r,   rI   r   z_Argument existing_solver must have level 0 matrix                             of same size as Ar   r   r(   r*   )r   z    maxiter = c                 R    |d         dz   |d<   t          d|d                     d S )Nr   r   z    iteration )r
   )_x	iterations     r   callbackzsolve.<locals>.callback-  s5    $Q<!+IaL19Q<1122222rM   c                      |           S )N )xrV   rU   s    r   	callback2zsolve.<locals>.callback21  s    8Ay)))rM   )x0acceltolr   rV   	residualsz#  Residuals ||r_k||_M, ||r_0||_M = z1.2ez, gV瞯<z+  Residual reduction ||r_k||_M/||r_0||_M = )r   rL   rO   levelsr   r   r   r   r>   rG   randomrandr+   zerosr
   solveaspreconditionersqrtinner	conjugateabsrF   )r   br[   r]   r   return_solverexisting_solverrI   r^   rJ   r\   rZ   rY   r0rkMnr0nrkratiorV   rU   s                      @@r   rc   rc      s   ~ 	A  &a4d;;; F++ !!$&,Q/171:== 0 1 1 1 a "+{:: 
zXbinnQWQZ11AAA  HTNN	(w(()))	3 	3 	3	* 	* 	* 	* 	* 	* 	* 	 	aBeg'0I 	 	G 	GA  	NRZQY,,..gbhr|AF33R8899gbhr|AF33R8899JCJJJJJJKKK6#;;#IELLLLMMM 5		!'""O4499QWrM   )NT)NrP   rQ   FNTN)__doc__numpyr>   scipy.sparser   r   r   aggregationr   util.linalgr   r   rL   rO   rc   rX   rM   r   <module>rw      s            C C C C C C C C C C 4 4 4 4 4 4 $ $ $ $ $ $& & &Rc c c cL3P 3P 3Pl ?D59w w w w w wrM   