
    _-Ph&O                        d Z ddlmZ ddlZddlmZmZmZm	Z	 ddl
mZ ddlm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mZmZmZmZmZmZ ddlm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z' dddddddddifdddifddddfddddfdZ(	 ddZ)dS )z"Support for aggregation-based AMG.    )warnN)
csr_matrixisspmatrix_csrisspmatrix_bsrSparseEfficiencyWarning   )MultilevelSolver)change_smoothers)relaxation_as_linear_operator)scale_Tget_Cpt_paramseliminate_diag_dom_nodesget_blocksize levelize_strength_or_aggregation%levelize_smooth_or_improve_candidates) classical_strength_of_connection symmetric_strength_of_connection evolution_strength_of_connection#energy_based_strength_of_connectiondistance_strength_of_connectionalgebraic_distanceaffinity_distance   )standard_aggregationnaive_aggregationlloyd_aggregationpairwise_aggregation)fit_candidates)energy_prolongation_smoother	hermitian	symmetricstandardenergyblock_gauss_seidelsweep   )r%   
iterations
   Fc           
      F   t          |           sWt          |           sH	 t          |           } t          dt                     n"# t
          $ r}t          d          |d}~ww xY w|                                 } |dvrt          d          || _	        | j
        d         | j
        d         k    rt          d          |xt          j        t          j        t          | j
        d         t          |           z            df| j        	          t          j        t          |                               }nt          j        || j        	          }t'          |j
                  dk    r|                    d
d          }|j
        d         | j
        d         k    rt          d          |j
        d         t          |           k     rt          d          | j	        dk    r||                                }nt          j        || j        	          }t'          |j
                  dk    r|                    d
d          }|j
        d         |j
        d         k    rt          d          |j
        d         | j
        d         k    rt          d          t-          ||
|          \  }
}}t-          ||
|          \  }
}}t/          |	|
          }	t/          ||
          }g }|                    t3          j                               | |d
         _        ||d
         _        | j	        dk    r||d
         _        t'          |          |
k     rt          |d
         j        j
        d         t          |d
         j                  z            |k    rlt=          |||||	||           t'          |          |
k     rDt          |d
         j        j
        d         t          |d
         j                  z            |k    lt3          |fi |}t?          |||           |S )a;#  Create a multilevel solver using root-node based Smoothed Aggregation (SA).

    See the notes below, for the major differences with the classical-style
    smoothed aggregation solver in aggregation.smoothed_aggregation_solver.

    Parameters
    ----------
    A : csr_matrix, bsr_matrix
        Sparse NxN matrix in CSR or BSR format

    B : None, array_like
        Right near-nullspace candidates stored in the columns of an NxK array.
        K must be >= the blocksize of A (see reference [2011OlScTu]_). The default value
        B=None is equivalent to choosing the constant over each block-variable,
        B=np.kron(np.ones((A.shape[0]/get_blocksize(A), 1)), np.eye(get_blocksize(A)))

    BH : None, array_like
        Left near-nullspace candidates stored in the columns of an NxK array.
        BH is only used if symmetry='nonsymmetric'.  K must be >= the
        blocksize of A (see reference [2011OlScTu]_). The default value B=None is
        equivalent to choosing the constant over each block-variable,
        B=np.kron(np.ones((A.shape[0]/get_blocksize(A), 1)), np.eye(get_blocksize(A)))

    symmetry : string
        'symmetric' refers to both real and complex symmetric
        'hermitian' refers to both complex Hermitian and real Hermitian
        'nonsymmetric' i.e. nonsymmetric in a hermitian sense
        Note that for the strictly real case, symmetric and hermitian are
        the same
        Note that this flag does not denote definiteness of the operator.

    strength : list
        Method used to determine the strength of connection between unknowns of
        the linear system.  Method-specific parameters may be passed in using a
        tuple, e.g. strength=('symmetric',{'theta' : 0.25 }). If strength=None,
        all nonzero entries of the matrix are considered strong.

    aggregate : list
        Method used to aggregate nodes.

    smooth : list
        Method used to smooth the tentative prolongator.  Method-specific
        parameters may be passed in using a tuple, e.g.  smooth=
        ('energy',{'krylov' : 'gmres'}).  Only 'energy' and None are valid
        prolongation smoothing options.

    presmoother : tuple, string, list
        Defines the presmoother for the multilevel cycling.  The default block
        Gauss-Seidel option defaults to point-wise Gauss-Seidel, if the matrix
        is CSR or is a BSR matrix with blocksize of 1.  See notes below for
        varying this parameter on a per level basis.

    postsmoother : tuple, string, list
        Same as presmoother, except defines the postsmoother.

    improve_candidates : tuple, string, list
        The ith entry defines the method used to improve the candidates B on
        level i.  If the list is shorter than max_levels, then the last entry
        will define the method for all levels lower.  If tuple or string, then
        this single relaxation descriptor defines improve_candidates on all
        levels.
        The list elements are relaxation descriptors of the form used for
        presmoother and postsmoother.  A value of None implies no action on B.

    max_levels : integer
        Maximum number of levels to be used in the multilevel solver.

    max_coarse : integer
        Maximum number of variables permitted on the coarse grid.

    diagonal_dominance : bool, tuple
        If True (or the first tuple entry is True), then avoid coarsening
        diagonally dominant rows.  The second tuple entry requires a
        dictionary, where the key value 'theta' is used to tune the diagonal
        dominance threshold.

    keep : bool
        Flag to indicate keeping extra operators in the hierarchy for
        diagnostics.  For example, if True, then strength of connection (C),
        tentative prolongation (T), aggregation (AggOp), and arrays
        storing the C-points (Cpts) and F-points (Fpts) are kept at
        each level.

    Other Parameters
    ----------------
    cycle_type : ['V','W','F']
        Structrure of multigrid cycle
    coarse_solver : ['splu', 'lu', 'cholesky, 'pinv', 'gauss_seidel', ... ]
        Solver used at the coarsest level of the MG hierarchy.
        Optionally, may be a tuple (fn, args), where fn is a string such as
        ['splu', 'lu', ...] or a callable function, and args is a dictionary of
        arguments to be passed to fn.

    Returns
    -------
    ml : MultilevelSolver
        Multigrid hierarchy of matrices and prolongation operators

    See Also
    --------
    MultilevelSolver, aggregation.smoothed_aggregation_solver,
    classical.ruge_stuben_solver

    Notes
    -----
         - Root-node style SA differs from classical SA primarily by preserving
           and identity block in the interpolation operator, P.  Each aggregate
           has a 'root-node' or 'center-node' associated with it, and this
           root-node is injected from the coarse grid to the fine grid.  The
           injection corresponds to the identity block.

         - Only smooth={'energy', None} is supported for prolongation
           smoothing.  See reference [2011OlScTu]_ below for more details on why the
           'energy' prolongation smoother is the natural counterpart to
           root-node style SA.

         - The additional parameters are passed through as arguments to
           MultilevelSolver.  Refer to pyamg.MultilevelSolver for additional
           documentation.

         - At each level, four steps are executed in order to define the coarser
           level operator.

           1. Matrix A is given and used to derive a strength matrix, C.

           2. Based on the strength matrix, indices are grouped or aggregated.

           3. The aggregates define coarse nodes and a tentative prolongation
              operator T is defined by injection

           4. The tentative prolongation operator is smoothed by a relaxation
              scheme to improve the quality and extent of interpolation from the
              aggregates to fine nodes.

         - The parameters smooth, strength, aggregate, presmoother, postsmoother
           can be varied on a per level basis.  For different methods on
           different levels, use a list as input so that the i-th entry defines
           the method at the i-th level.  If there are more levels in the
           hierarchy than list entries, the last entry will define the method
           for all levels lower.

           Examples are:
           smooth=[('jacobi', {'omega':1.0}), None, 'jacobi']
           presmoother=[('block_gauss_seidel', {'sweep':symmetric}), 'sor']
           aggregate=['standard', 'naive', 'lloyd', 'pairwise']
           strength=[('symmetric', {'theta':0.25}), ('symmetric', {'theta':0.08})]

         - Predefined strength of connection and aggregation schemes can be
           specified.  These options are best used together, but aggregation can
           be predefined while strength of connection is not.

           For predefined strength of connection, use a list consisting of
           tuples of the form ('predefined', {'C' : C0}), where C0 is a
           csr_matrix and each degree-of-freedom in C0 represents a supernode.
           For instance to predefine a three-level hierarchy, use
           [('predefined', {'C' : C0}), ('predefined', {'C' : C1}) ].

           Similarly for predefined aggregation, use a list of tuples.  For
           instance to predefine a three-level hierarchy, use [('predefined',
           {'AggOp' : Agg0}), ('predefined', {'AggOp' : Agg1}) ], where the
           dimensions of A, Agg0 and Agg1 are compatible, i.e.  Agg0.shape[1] ==
           A.shape[0] and Agg1.shape[1] == Agg0.shape[0].  Each AggOp is a
           csr_matrix.

           Because this is a root-nodes solver, if a member of the predefined
           aggregation list is predefined, it must be of the form
           ('predefined', {'AggOp' : Agg, 'Cnodes' : Cnodes}).

    Examples
    --------
    >>> from pyamg import rootnode_solver
    >>> from pyamg.gallery import poisson
    >>> from scipy.sparse.linalg import cg
    >>> import numpy as np
    >>> A = poisson((100, 100), format='csr')           # matrix
    >>> b = np.ones((A.shape[0]))                   # RHS
    >>> ml = rootnode_solver(A)                     # AMG solver
    >>> M = ml.aspreconditioner(cycle='V')             # preconditioner
    >>> x, info = cg(A, b, tol=1e-8, maxiter=30, M=M)   # solve with CG

    References
    ----------
    .. [1996VaMa] Vanek, P. and Mandel, J. and Brezina, M.,
       "Algebraic Multigrid by Smoothed Aggregation for
       Second and Fourth Order Elliptic Problems",
       Computing, vol. 56, no. 3, pp. 179--196, 1996.
       http://citeseer.ist.psu.edu/vanek96algebraic.html
    .. [2011OlScTu] Olson, L. and Schroder, J. and Tuminaro, R.,
       "A general interpolation strategy for algebraic
       multigrid using energy minimization", SIAM Journal
       on Scientific Computing (SISC), vol. 33, pp.
       966--991, 2011.

    zImplicit conversion of A to CSRzQArgument A must have type csr_matrix, bsr_matrix, or be convertible to csr_matrixN)r!   r    nonsymmetriczOExpected "symmetric", "nonsymmetric" or "hermitian" for the symmetry parameter.r   r   zexpected square matrixdtypez`The near null-space modes B have incorrect                               dimensions for matrix Az(B.shape[1] must be >= the blocksize of Ar*   zlThe number of left and right near                                   null-space modes B and BH, must be equalzeThe near null-space modes BH have                                   incorrect dimensions for matrix A) r   r   r   r   r   	Exception	TypeErrorasfptype
ValueErrorsymmetryshapenpkrononesintr   r,   eyeasarraylenreshapecopyr   r   appendr	   LevelABBH_extend_hierarchyr
   )r?   r@   rA   r2   strength	aggregatesmoothpresmootherpostsmootherimprove_candidates
max_levels
max_coarsediagonal_dominancekeepkwargselevelsmls                     Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/pyamg/aggregation/rootnode.pyrootnode_solverrR      s=   \ 1 R!2!2 R	R1A2(* * * * 	R 	R 	R J K KPQR	R 	


AAAA F G G 	GAJwqzQWQZ1222yGBGSM!,<,<!<==qAQQQF=++,,. . Jq(((qw<<1		"a  A71:## 7 8 8 871:a((((GHHH 	z^##:BBBag...B28}}!!ZZA&&x{agaj((  "L M M Mx{agaj((  "E F F F 	):zJJ %J
H 	)J
KK &J
I 	..@*MM 26:FFF F
MM"(**+++F2JL F2JLz^##r

f++

"
"r
"1%mF2JL&A&AABBZOO&(Iv,.@$	H 	H 	H f++

"
"r
"1%mF2JL&A&AABBZOO 
&	+	+F	+	+BRl333Is   $A 
A$AA$Tc           	      .   d }| d         j         }| d         j        }	|j        dk    r>|j                                                            |j                  }
| d         j        } ||t          |           dz
                     \  }}|dk    rt          |fi |}n|dk    rt          |fi |}n|dk    rt          |fi |}n|dv r!d	|v rt          |fi |}nt          ||	fi |}n|d
k    rt          |fi |}n|dk    r|d                                         }n^|dk    rt          |fi |}nJ|dk    rt!          |fi |}n6||                                }nt#          dt%          |                      ||          \  }}|rt'          ||fi |} ||t          |           dz
                     \  }}|dk    rt)          |fi |\  }}n|dk    rt+          |fi |\  }}nv|dk    rt-          |fi |\  }}n_|dk    rt/          |fi |\  }}nH|dk    r#|d                                         }|d         }nt#          dt%          |                      ||t          |           dz
                     \  }}|yt1          j        |j        d         df|j                  }t9          ||f||          |	z  }	|	| d         _        |j        dk    r#t9          ||f|
|          |z  }|| d         _        t;          ||	dddt=          |          f                   \  }}~|j        dk    r-t;          ||dddt=          |          f                   \  }}~dt?          ||||          f}tA          ||d         d         |d         d                   }|j        dk    r)tA          ||d         d         |d         d                   }|d         d         j        | d         j        z  }	|j        dk    r!|d         d         j        | d         j        z  } ||t          |           dz
                     \  }}|dk    rtC          ||||	| d         j        fd|i|}n$||}nt#          dt%          |                     |j        }|d k    r|j                                        }n|dk    r|j        }n|dk    r ||t          |           dz
                     \  }}|dk    r8tC          |
|||| d         j        fd|i|}|j                                        }n;||j                                        }nt#          dt%          |                     |r|| d         _"        || d         _#        || d         _        |d         d!         | d         _$        |d         d         | d         _%        |d         d         | d         _&        |d         d"         | d         _'        || d         _(        || d         _)        |d         d#         | d         _*        | +                    tY          j-                               ||z  |z  }||_        || d         _         |	| d         _        |j        dk    r|| d         _        dS dS )$zExtend the multigrid hierarchy.

    Service routine to implement the strength of connection, aggregation,
    tentative prolongation construction, and prolongation smoothing.  Called by
    smoothed_aggregation_solver.

    c                 T    t          | t                    r| d         | d         fS | i fS )Nr   r   )
isinstancetuple)vs    rQ   
unpack_argz%_extend_hierarchy.<locals>.unpack_arg>  s/    a 	Q41:"u    r-   r*   r   r!   	classicaldistance)ode	evolutionr@   energy_based
predefinedCr   affinityNz,Unrecognized strength of connection method: r"   naivelloydpairwiseAggOpCnodesz!Unrecognized aggregation method: r   r+   TP_II_Fr#   
Cpt_paramsz+Unrecognized prolongation smoother method: r    FptsI_CCpts).r?   r@   r2   T	conjugateasformatformatrA   r:   r   r   r   r   r   tocsrr   r   r1   strr   r   r   r   r   r4   zerosr3   r,   r   r   r   r   r   r   r`   re   rj   rg   rh   rk   PRrl   r=   r	   r>   )rO   rC   rD   rE   rH   rK   rL   rX   r?   r@   AHrA   fnrM   r`   flagre   rf   brm   dummyTHdummyHri   rt   r2   ru   s                              rQ   rB   rB   5  sp     
 	r
Ar
Az^##S]]__%%ah//BZ] HS[[]344JB	[,Q99&99	{		,Q99&99	z		+A8888	#	#	#&==0==f==AA0A@@@@AA	~		/<<V<<	|		3K	#	#	#q++F++	z		a**6**	GGIIQBQQRRR :011LD& 5$Q44V44
 Ic&kk!m455JB	Z,Q99&99vv	w)!66v66vv	w)!66v66vv	z		,Q99&99vv	|		w%%''!FSWWFFGGG .s6{{1}=>>JB	~Hagaj!_AG444)2v,1==Ar
:''.F|RCCbHBF2JM
 eQqqq!M!,<,<*<'<%=>>HAuz^###E2aaa=3C3C1C.C+DEE
F q&%;;<J:a='Au)=>>Az^##RAu-z!}U/CDD 	1evbz|+Az^##]5!#F2JM1 F3v;;q=122JB	X~~(Aq!VBZ\ J J4>JBHJ J	Ps2wwPPQQQ
 zH;CMMOO	[	 	 C	^	#	#Zs6{{1} 566
F>>,RQF2JM N N8BNFLN NAAAZAAT3r77TTUUU .r
 r
r
$Q-/r
#Au-r
#Au-r
#Au-r
F2JLF2JL mF+F2JO
MM"(**+++	A	AAJF2JLF2JLz^##r
 $#rY   )FT)*__doc__warningsr   numpyr4   scipy.sparser   r   r   r   
multilevelr	   relaxation.smoothingr
   relaxation.utilsr   
util.utilsr   r   r   r   r   r   rC   r   r   r   r   r   r   r   rD   r   r   r   r   	tentativer   rE   r   rR   rB    rY   rQ   <module>r      s@   ( (                      * ) ) ) ) ) 3 3 3 3 3 3 < < < < < <* * * * * * * * * * * * * * * ** * * * * * * * * * * * * * * * * *, , , , , , , , , , , , % % % % % % 0 0 0 0 0 0 $(;(!5");!7!9"6#*K"8":(<2=78): ):(;  "b',5X X X Xx 6:W W W W W WrY   