
    _-Ph>;                     v    d Z ddlm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	 Zd
 Z	 	 ddZddZddZdS )zAggregation methods.    )warnN)sparse   )amg_core)lloyd_cluster) classical_strength_of_connectionc                    t          j        |           st          d          | j        d         | j        d         k    rt	          d          | j        j        }| j        d         }t          j        ||          }t          j        ||          }t          j
        } ||| j        | j        ||          }|d|         }|dk    r.t          j        |dfd          t          j        g |          fS ||f}|                                dk    r{|dk    }t          j        ||          |         }	||         }
t          j        t#          |
          d          }t          j        ||	|
ff|	                                          |fS t          j        |dz   |          }t          j        t#          |          d          }t          j        |||f|	          |fS )
a  Compute the sparsity pattern of the tentative prolongator.

    Parameters
    ----------
    C : csr_matrix
        strength of connection matrix

    Returns
    -------
    AggOp : csr_matrix
        aggregation operator which determines the sparsity pattern
        of the tentative prolongator
    Cpts : array
        array of Cpts, i.e., Cpts[i] = root node of aggregate i

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> from pyamg.gallery import poisson
    >>> from pyamg.aggregation.aggregate import standard_aggregation
    >>> A = poisson((4,), format='csr')   # 1D mesh with 4 vertices
    >>> A.toarray()
    array([[ 2., -1.,  0.,  0.],
           [-1.,  2., -1.,  0.],
           [ 0., -1.,  2., -1.],
           [ 0.,  0., -1.,  2.]])
    >>> standard_aggregation(A)[0].toarray() # two aggregates
    array([[1, 0],
           [1, 0],
           [0, 1],
           [0, 1]], dtype=int8)
    >>> A = csr_matrix([[1,0,0],[0,1,1],[0,1,1]])
    >>> A.toarray()                      # first vertex is isolated
    array([[1, 0, 0],
           [0, 1, 1],
           [0, 1, 1]])
    >>> standard_aggregation(A)[0].toarray() # one aggregate
    array([[0],
           [1],
           [1]], dtype=int8)

    See Also
    --------
    amg_core.standard_aggregation

    expected csr_matrixr      expected square matrixdtypeNint8shape)r   isspmatrix_csr	TypeErrorr   
ValueErrorindptrr   npemptyr   standard_aggregationindices
csr_matrixarrayminarangeoneslen
coo_matrixtocsr)C
index_typenum_rowsTjCptsfnnum_aggregatesr   maskrowcoldataTpTxs                 [/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/pyamg/aggregation/aggregate.pyr   r      s   ^  ## /-...wqzQWQZ1222JwqzH	(*	-	-	-B8HJ///D		&BR!(AIr4@@N D  (Af===HRz***+ 	+ ~&E 
vvxx2~~Rxi
333D9hws3xxv... $c
!35AAAGGII4OO 
8A:Z	0	0	0B	R	'	'	'Bb"b\777==    c                    t          j        |           st          d          | j        d         | j        d         k    rt	          d          | j        j        }| j        d         }t          j        ||          }t          j        ||          }t          j
        } ||| j        | j        ||          }|d|         }|dz
  }|dk    rt          j        |dfd          |fS ||f}t          j        |dz   |          }t          j        t          |          d          }	t          j        |	||f|          |fS )	a.  Compute the sparsity pattern of the tentative prolongator.

    Parameters
    ----------
    C : csr_matrix
        strength of connection matrix

    Returns
    -------
    AggOp : csr_matrix
        aggregation operator which determines the sparsity pattern
        of the tentative prolongator
    Cpts : array
        array of Cpts, i.e., Cpts[i] = root node of aggregate i

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> from pyamg.gallery import poisson
    >>> from pyamg.aggregation.aggregate import naive_aggregation
    >>> A = poisson((4,), format='csr')   # 1D mesh with 4 vertices
    >>> A.toarray()
    array([[ 2., -1.,  0.,  0.],
           [-1.,  2., -1.,  0.],
           [ 0., -1.,  2., -1.],
           [ 0.,  0., -1.,  2.]])
    >>> naive_aggregation(A)[0].toarray() # two aggregates
    array([[1, 0],
           [1, 0],
           [0, 1],
           [0, 1]], dtype=int8)
    >>> A = csr_matrix([[1,0,0],[0,1,1],[0,1,1]])
    >>> A.toarray()                      # first vertex is isolated
    array([[1, 0, 0],
           [0, 1, 1],
           [0, 1, 1]])
    >>> naive_aggregation(A)[0].toarray() # two aggregates
    array([[1, 0],
           [0, 1],
           [0, 1]], dtype=int8)

    See Also
    --------
    amg_core.naive_aggregation

    Notes
    -----
    Differs from standard aggregation.  Each dof is considered.  If it has been
    aggregated, skip over.  Otherwise, put dof and any unaggregated neighbors
    in an aggregate.  Results in possibly much higher complexities than
    standard aggregation.

    r
   r   r   r   r   Nr   r   )r   r   r   r   r   r   r   r   r   r   naive_aggregationr   r   r   r   r    )
r#   r$   r%   r&   r'   r(   r)   r   r.   r/   s
             r0   r3   r3   b   sJ   l  ## /-...wqzQWQZ1222JwqzH	(*	-	-	-B8HJ///D		#BR!(AIr4@@N D	aB (Af===tCC~&E	8A:Z	0	0	0B	R	'	'	'Bb"b\777==r1         ?r   Fc           	         t          j        |           sft          j        |           sR	 |                                 } t	          dt           j                   n"# t          $ r}t          d          |d}~ww xY w| j        j	        }| }d}d}	t          d|          D ]}
t          j        |           rt          ||d|          }nt          ||d|          }|j        d         }t          j        ||          }t          j        ||          }t          j        } |||j        |j        |j        ||          }|	|d|         }	n|	|d|                  }	|d	z
  }|dk    r(t          j        |d	fd
          }t	          d           n||f}t          j        |d	z   |          }t          j        |           s=t          j        t-          |          d
          }t          j        |||f|          }n|d         | j        d         z  |d	         | j        d	         z  f}t          j        t-          |          t          j        | j        d                   gz  d
          }t          j        |||f| j        |          }|
dk    r|}nCt          j        |           rt          j        ||z            }nt          j        ||z            }|dk    r nM|
|d	z
  k     rBt          j        |          r!|j                                        |z  |z  }|j        |z  |z  }|r|                    | j	        d          }||	fS )a  Compute the sparsity pattern of the tentative prolongator.

    Parameters
    ----------
    A : csr_matrix or bsr_matrix
        level matrix
    matchings : int, default 2
        number of times to perform pairwise aggregation; each
        matching increases coarsening factor by about two.
    theta : float, default 0.25
        Strength tolerance used in computing classical SOC.
    norm : string, default 'min'
        Norm type used in computing classical SOC.
    compute_P : bool; default False
        Compute pairwise interpolation directly; if False, return
        integer aggregation matrix for smoothed_aggregation_solver.
        If True, return float interpolation P, converting to BSR
        form with identity of size bsize x bsize on each aggregate
        if A is BSR.

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> from pyamg.gallery import poisson
    >>> from pyamg.aggregation.aggregate import pairwise_aggregation
    >>> A = poisson((4,), format='csr')   # 1D mesh with 4 vertices
    >>> A.toarray()
    array([[ 2., -1.,  0.,  0.],
           [-1.,  2., -1.,  0.],
           [ 0., -1.,  2., -1.],
           [ 0.,  0., -1.,  2.]])
    >>> pairwise_aggregation(A, matchings=1)[0].toarray() # two aggregates
    array([[1, 0],
           [1, 0],
           [0, 1],
           [0, 1]], dtype=int8)
    >>> pairwise_aggregation(A, matchings=2)[0].toarray() # one aggregate
    array([[1],
           [1],
           [1],
           [1]], dtype=int8)

    See Also
    --------
    amg_core.pairwise_aggregation

    References
    ----------
    [0] Notay, Y. (2010). An aggregation-based algebraic multigrid
    method. Electronic transactions on numerical analysis, 37(6),
    123-146.
    zImplicit conversion of A to csrz(Invalid matrix type, must be CSR or BSR.Nr   T)AthetablocknormFr   r   r   z$No pairwise aggregates found, T = 0.r   )	blocksizer   )copy)r   isspmatrix_bsrr   r"   r   SparseEfficiencyWarning	Exceptionr   r   r   ranger   r   r   r   r   pairwise_aggregationr   r-   r   r   r   r    r:   r   identity
bsr_matrixTastype)r6   	matchingsr7   r9   	compute_Per$   AcrC   r'   ir#   r%   r&   new_cptsr(   r)   T_tempr   r.   r/   s                        r0   r@   r@      s   n !!$$ O(=a(@(@ O	O		A2F4RSSSS 	O 	O 	OFGGQN	O J	
BAD 1i   7, 7,  ## 	\02U$UYZZZAA02U%VZ[[[A 71:Xhj1118HJ777*Hah	162xPP<O^O,DD.12D!V Q&!}FCCCF78888~.E8A:Z888B(++ ]WSWWF333*BB<uEEEq!+a.0%(1;q>2IJXc"ggr{1;q>'B'B&CC6RRR*BB<1;V[\\\ 66AA$Q'' 2%a&j11%a&j11 QE 	!$V,, ,X^^%%*V3X]V+  *HHQW5H))d7Ns   .A 
A8#A33A8Q?unit
   c           	         |dk    s|dk    rt          d          t          j        |           s#t          j        |           st	          d          |dk    r2t          j        | j                                      t                    }n|dk    rt          | j                  }nf|dk    rdt          | j                  z  }nH|d	k    r| j        }n:|d
k    r"| j        | j                                        z
  }nt          d|           | j        t          k    rt          j        |          }|                                dk    sJ |                     || j        | j        f| j                  }t'          t          t)          ||j        d         z  d          |j        d                             }t+          |||          \  }}}	|dk                                    d         }
||
         }t          j        t1          |
          d          }t          j        ||
|ff|j        d         |f                                          }||	fS )ab  Aggregate nodes using Lloyd Clustering.

    Parameters
    ----------
    C : csr_matrix
        strength of connection matrix
    ratio : scalar
        Fraction of the nodes which will be seeds.
    distance : ['unit','abs','inv',None]
        Distance assigned to each edge of the graph G used in Lloyd clustering

        For each nonzero value C[i,j]:

        =======  ===========================
        'unit'   G[i,j] = 1
        'abs'    G[i,j] = abs(C[i,j])
        'inv'    G[i,j] = 1.0/abs(C[i,j])
        'same'   G[i,j] = C[i,j]
        'sub'    G[i,j] = C[i,j] - min(C)
        =======  ===========================

    maxiter : int
        Maximum number of iterations to perform

    Returns
    -------
    AggOp : csr_matrix
        aggregation operator which determines the sparsity pattern
        of the tentative prolongator
    seeds : array
        array of Cpts, i.e., Cpts[i] = root node of aggregate i

    See Also
    --------
    amg_core.standard_aggregation

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> from pyamg.gallery import poisson
    >>> from pyamg.aggregation.aggregate import lloyd_aggregation
    >>> A = poisson((4,), format='csr')   # 1D mesh with 4 vertices
    >>> A.toarray()
    array([[ 2., -1.,  0.,  0.],
           [-1.,  2., -1.,  0.],
           [ 0., -1.,  2., -1.],
           [ 0.,  0., -1.,  2.]])
    >>> lloyd_aggregation(A)[0].toarray() # one aggregate
    array([[1],
           [1],
           [1],
           [1]], dtype=int8)
    >>> # more seeding for two aggregates
    >>> Agg = lloyd_aggregation(A,ratio=0.5)[0].toarray()

    r   r   zratio must be > 0.0 and <= 1.0!expected csr_matrix or csc_matrixrM   absinvg      ?samer   zUnrecognized value distance=r   )maxiterr   r   )r   r   r   isspmatrix_cscr   r   	ones_liker-   rD   floatrQ   r   r   complexreal	__class__r   r   r   intmaxr   nonzeror   r    r!   r"   )r#   ratiodistancerT   r-   G	num_seeds_clustersseedsr+   r,   AggOps                r0   lloyd_aggregationrf   9  s,   r zzUQYY9:::!!$$ =(=a(@(@ =;<<<6|AF##**511	U		16{{	U		3qv;;	V		v	U		v

$BBBCCCw'wt}}88::????	T19ah/qw??ACEAGAJ.22AGAJ??@@I&q)WEEEAxq=
!
!
#
#A
&C
3-C73s886***Dtc3Z0%&WQZ$;= = ==BUWW 
%<r1   c           
         |t          | j        d         dz            }|dk     s|| j        d         k    rt          d          t          j        |           s#t          j        |           st          d          | j                                        dk    rt          d          | j	        t          k    rt          j        | j                  }n| j        }|                     || j        | j        f| j                  }|j        d         }t          j                            |          d|         }|                    t          j                  }t          j        |j	                  j        }|t          j        ||j	        	          z  }d||<   d
t          j        |t          j        	          z  }|||<   t/          j        ||j        |j        |j        ||||           |}	t          j        t5          |                    }
t          j        t5          |
          t          j        	          }t          j        ||
|	ff|j        d         |f                                          }||fS )a  Aggregate nodes using Balanced Lloyd Clustering.

    Parameters
    ----------
    C : csr_matrix
        strength of connection matrix with positive weights
    num_clusters : int
        Number of seeds or clusters expected (default: C.shape[0] / 10)

    Returns
    -------
    AggOp : csr_matrix
        aggregation operator which determines the sparsity pattern
        of the tentative prolongator
    seeds : array
        array of Cpts, i.e., Cpts[i] = root node of aggregate i

    See Also
    --------
    amg_core.standard_aggregation

    Examples
    --------
    >>> import pyamg
    >>> from pyamg.aggregation.aggregate import balanced_lloyd_aggregation
    >>> data = pyamg.gallery.load_example('unit_square')
    >>> G = data['A']
    >>> xy = data['vertices'][:,:2]
    >>> G.data[:] = np.ones(len(G.data))

    >>> np.random.seed(787888)
    >>> AggOp, seeds = balanced_lloyd_aggregation(G)

    Nr   rN   r   z$num_clusters must be between 1 and nrP   zpositive edge weights requiredr   r   r   )r[   r   r   r   r   rU   r   r-   r   r   rX   r   rY   rZ   r   r   randompermutationrD   int32finfor\   r   r   lloyd_cluster_exactr   r    r!   r"   )r#   num_clustersr-   r`   	num_nodesrd   mvdcmr,   r+   re   s               r0   balanced_lloyd_aggregationrr     s2   F 171:?++a<!'!*44?@@@!!$$ =(=a(@(@ =;<<<vzz||q9:::w'wqvv	T19ah/qw??A
II!!),,]l];ELL""E	!'			B
RWYag....AAeH	bgirx000	0BBuI !"19af!-!"B/ / /
 C
)CGG

C73s8828,,,Dtc3Z0%&WQZ$>@ @ @@E 
%<r1   )r   r4   r   F)rL   rM   rN   )N)__doc__warningsr   numpyr   scipyr    r   graphr   strengthr   r   r3   r@   rf   rr    r1   r0   <module>r{      s                            ! ! ! ! ! ! 7 7 7 7 7 7S> S> S>lP> P> P>f 04/4A A A AH\ \ \ \~J J J J J Jr1   