
    _-Ph                         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d	lmZmZmZmZmZ dd
lmZ d!dZd"dZd#dZd$dZ	 	 d%dZ	 	 	 d%dZd Zd&dZd'dZd  ZdS )(ao  Strength of Connection functions.

Requirements for the strength matrix C are:
    1) Nonzero diagonal whenever A has a nonzero diagonal
    2) Non-negative entries (float or bool) in [0,1]
    3) Large entries denoting stronger connections
    4) C denotes nodal connections, i.e., if A is an nxn BSR matrix with
       row block size of m, then C is (n/m) x (n/m)

    )warnN)sparse   )amg_core)jacobi)approximate_spectral_radius)scale_rows_by_largest_entry
amalgamate
scale_rowsget_block_diagscale_columns)set_tol       @Tc                 p   t          j        |           rrt          | j        d         | j        d         z            }t          j        | j        j        d         f          }t          j        || j	        | j
        f||f          } t          j        |           s.t          dt           j                   t          j        |           } |j        d         }| j	        }t          j        t          j        | j        d                   | j
        dd         | j
        dd         z
            }||df         ||df         z
  dz  }	t!          d|          D ]}
|	|||
f         |||
f         z
  dz  z  }	t          j        |	          }	d|	|	dk     <   t          j        |	| j	                                        | j
                                        f| j                  }	|d	u rC|t
          j        k    r2t)          j        |	j        d         ||	j
        |	j	        |	j                   n2t)          j        |	j        d         ||	j
        |	j	        |	j                   |	                                 |	t          j        |	j        d         |	j        d         d
          z   }	d|	j        z  |	_        t3          |	          }	|	S )a  Distance based strength-of-connection.

    Parameters
    ----------
    A : csr_matrix or bsr_matrix
        Square, sparse matrix in CSR or BSR format
    V : array
        Coordinates of the vertices of the graph of A
    relative_drop : bool
        If false, then a connection must be within a distance of theta
        from a point to be strongly connected.
        If true, then the closest connection is always strong, and other points
        must be within theta times the smallest distance to be strong

    Returns
    -------
    C : csr_matrix
        C(i,j) = distance(point_i, point_j)
        Strength of connection matrix where strength values are
        distances, i.e. the smaller the value, the stronger the connection.
        Sparsity pattern of C is copied from A.

    Notes
    -----
    - theta is a drop tolerance that is applied row-wise
    - If a BSR matrix given, then the return matrix is still CSR.  The strength
      is given between super nodes based on the BSR block size.

    Examples
    --------
    >>> from pyamg.gallery import load_example
    >>> from pyamg.strength import distance_strength_of_connection
    >>> data = load_example('airfoil')
    >>> A = data['A'].tocsr()
    >>> S = distance_strength_of_connection(data['A'], data['vertices'])

    r   shapeImplicit conversion of A to csrr   N   gư>Tcsrformat      ?)r   isspmatrix_bsrintr   	blocksizenponesdata
csr_matrixindicesindptrisspmatrix_csrr   SparseEfficiencyWarningrepeatarangerangesqrtcopyinfr   apply_distance_filterapply_absolute_distance_filtereliminate_zeroseyer	   )AVthetarelative_dropsnudimcolsrowsCds              N/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/pyamg/strength.pydistance_strength_of_connectionr;      s   N Q Hak!n,--GQV\!_&''q!)QX6r2hGGG ## !.0NOOOa  
'!*C 9D9RYqwqz**AHQRRL18AbD>,IJJD 
47aaj	 1$A1c]] * *	aaj1T1W:%))


AAa$hK1ainn..@ !	) 	) 	)A BF??*171:uah+,9af> > > 	/
E1801	16	C 	C 	C	FJqwqz171:e<<<<A 16\AF 	$A&&AH    皙?absc           
      F   t          j        |           rJ| j        d         | j        d         k    s| j        d         dk     rt          d          | j        d         }nd}|dk     s|dk    rt          d          |r-t          j        |           rt	          | j        d         |z            }|dk    rBt          j        t          j        t          j        | j	                  d          d          }n|dk    r0t          j
        t          j
        | j	        d          d          }na|dk    rLt          j        | j	                  | j	        z  }t          j        t          j        |d          d          }nt          d	          d
|t          j        |          dk     <   nVt          j        |           s.t          dt           j                   t          j        |           } | j	        }| j        d         }t          j        | j                  }t          j        | j                  }t          j        |          }	|dv r&t)          j        ||| j        | j        ||||	           n;|dk    r&t)          j        ||| j        | j        ||||	           nt          d          t          j        |	||f||g          }
t          j        |
j	                  |
_	        t/          |
          }
|
                                 |dk    r|st3          |
|          }
|
S )a
  Classical strength of connection measure.

    Return a strength of connection matrix using the classical AMG measure
    An off-diagonal entry A[i,j] is a strong connection iff::

             |A[i,j]| >= theta * max(|A[i,k]|), where k != i     (norm='abs')
             -A[i,j]  >= theta * max(-A[i,k]),  where k != i     (norm='min')

    Parameters
    ----------
    A : csr_matrix or bsr_matrix
        Square, sparse matrix in CSR or BSR format
    theta : float
        Threshold parameter in [0,1]
    block : bool, default True
        Compute strength of connection block-wise
    norm : 'string', default 'abs'
        Measure used in computing the strength::

            'abs' : |C[i,j]| >= theta * max(|C[i,k]|), where k != i
            'min' : -C[i,j]  >= theta * max(-C[i,k]),  where k != i

        where C = A for non-block-wise computations.  For block-wise::

            'abs'  : C[i, j] is the maximum absolute value in block A[i, j]
            'min'  : C[i, j] is the minimum (negative) value in block A[i, j]
            'fro'  : C[i, j] is the Frobenius norm of block A[i, j]

    Returns
    -------
    S : csr_matrix
        Matrix graph defining strong connections.  S[i,j] ~ 1.0 if vertex i
        is strongly influenced by vertex j, or block i is strongly influenced
        by block j if block=True.

    See Also
    --------
    symmetric_strength_of_connection : symmetric measure used in SA
    evolution_strength_of_connection : relaxation based strength measure

    Notes
    -----
    - A symmetric A does not necessarily yield a symmetric strength matrix S
    - Calls C++ function classical_strength_of_connection
    - The version as implemented is designed for M-matrices.  Trottenberg et
      al. use max A[i,k] over all negative entries, which is the same.  A
      positive edge weight never indicates a strong connection.
    - See [2000BrHeMc]_ and [2001bTrOoSc]_

    References
    ----------
    .. [2000BrHeMc] Briggs, W. L., Henson, V. E., McCormick, S. F., "A multigrid
        tutorial", Second edition. Society for Industrial and Applied
        Mathematics (SIAM), Philadelphia, PA, 2000. xii+193 pp.

    .. [2001bTrOoSc] Trottenberg, U., Oosterlee, C. W., Schuller, A., "Multigrid",
        Academic Press, Inc., San Diego, CA, 2001. xvi+631 pp.

    Examples
    --------
    >>> import numpy as np
    >>> from pyamg.gallery import stencil_grid
    >>> from pyamg.strength import classical_strength_of_connection
    >>> n=3
    >>> stencil = np.array([[-1.0,-1.0,-1.0],
    ...                        [-1.0, 8.0,-1.0],
    ...                        [-1.0,-1.0,-1.0]])
    >>> A = stencil_grid(stencil, (n,n), format='csr')
    >>> S = classical_strength_of_connection(A, 0.0)

    r   r   zMatrix must have square blockszexpected theta in [0,1]r>   axisminfrozInvalid choice of norm.        gؗҜ<r   )r>   rC   z*Unrecognized option for norm for strength.r   )r   r   r   
ValueErrorr   r   r   maxr>   r   rB   	conjugatesumr#   r   r$   r    
empty_liker"   r!   r   $classical_strength_of_connection_abs$classical_strength_of_connection_minr	   r-   r
   )r/   r1   blocknormr   Nr   SpSjSxSs              r:    classical_strength_of_connectionrS   o   s   P Q KNak!n,,!+a.12D2D=>>>KN					UQYY2333  &q)) 
Y&'' 5==6"&a888qAAADDU]]6"&a000q999DDU]]<''!&0D6"&A...Q777DD6777 &)RVD\\E!""$Q'' 	%2F4RSSS!!$$AvGAJ	qx	 	 B	qy	!	!B	t		B~5uah	4R	= 	= 	= 	=	5uah	4R	= 	= 	= 	= EFFF2r2,q!f555A VAF^^AF#A&&A1}}U}q)$$Hr<   c           
      6   |dk     rt          d          t          j        |           rt          j        | j                  }t          j        | j                  }t          j        | j                  }t          j	        } || j
        d         || j        | j        | j        |||           t          j        |||f| j
                  }nt          j        |           r{| j
        \  }}| j        \  }	}
|	|
k    rt          d          |dk    rt          j        t          | j                  | j                  }t          j        || j                                        | j                                        ft%          ||	z            t%          ||
z            f          }nt          j        | j                  | j        z                      d|	|
z            }t          j        |                    d                    }t          j        || j        | j        ft%          ||	z            t%          ||
z            f          } t          | |          S t/          d	          t          j        |j                  |_        t3          |          }|S )
a;  Symmetric Strength Measure.

    Compute strength of connection matrix using the standard symmetric measure

    An off-diagonal connection A[i,j] is strong iff::

        abs(A[i,j]) >= theta * sqrt( abs(A[i,i]) * abs(A[j,j]) )

    Parameters
    ----------
    A : csr_matrix
        Matrix graph defined in sparse format.  Entry A[i,j] describes the
        strength of edge [i,j]
    theta : float
        Threshold parameter (positive).

    Returns
    -------
    S : csr_matrix
        Matrix graph defining strong connections.  S[i,j]=1 if vertex i
        is strongly influenced by vertex j.

    See Also
    --------
    symmetric_strength_of_connection : symmetric measure used in SA
    evolution_strength_of_connection : relaxation based strength measure

    Notes
    -----
        - For vector problems, standard strength measures may produce
          undesirable aggregates.  A "block approach" from Vanek et al. is used
          to replace vertex comparisons with block-type comparisons.  A
          connection between nodes i and j in the block case is strong if::

          ||AB[i,j]|| >= theta * sqrt( ||AB[i,i]||*||AB[j,j]|| ) where AB[k,l]

          is the matrix block (degrees of freedom) associated with nodes k and
          l and ||.|| is a matrix norm, such a Frobenius.

        - See [1996bVaMaBr]_ for more details.

    References
    ----------
    .. [1996bVaMaBr] 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

    Examples
    --------
    >>> import numpy as np
    >>> from pyamg.gallery import stencil_grid
    >>> from pyamg.strength import symmetric_strength_of_connection
    >>> n=3
    >>> stencil = np.array([[-1.0,-1.0,-1.0],
    ...                        [-1.0, 8.0,-1.0],
    ...                        [-1.0,-1.0,-1.0]])
    >>> A = stencil_grid(stencil, (n,n), format='csr')
    >>> S = symmetric_strength_of_connection(A, 0.0)

    r   expected a positive thetar   zmatrix must have square blocksdtyper   r   r@   !expected csr_matrix or bsr_matrix)rE   r   r#   r   rI   r"   r!   r   r    symmetric_strength_of_connectionr   r    r   r   r   lenrW   r)   r   rG   reshaper(   rH   	TypeErrorr>   r	   )r/   r1   rO   rP   rQ   fnrR   MrN   Rr8   r   s               r:   rY   rY      sI   ~ qyy4555Q != ]18$$]19%%]16""6
171:uah	162r2FFFr2rl!':::		q	!	! =w1{166=>>>A::73qy>>999D!4)9)918==??"K),QUSQZZ(@B B BAA
 L((161::2q1uEED74888++,,D!4AH"=),QUSQZZ(@B B BA3Au===;<<< VAF^^AF 	$A&&AHr<   rD   r   c           	      .	   |dk     rt          d          t          j        |           st          d          |dk     rt          d          t          |t                    st          d          t          j        |           r;d}| j        d         }| j        d         | j        d         k    rt          d          nd	}d}t          j        |           r)|                                 }| 	                                } n<| 	                                } |                                 }|
                                }|                                 }d
|z  }d||dk    <   t          j        |t          j        | j        d                   t          j        | j        d                   ff| j                  }|| z  }d
t!          |          z  }	~t          j        | j        | j                  }
t          j        | j        d         | j        d         d          }t'          |dz             D ]}|
|	||| |
z  z
  z  z  z   }
t'          |j        d                   D ]:}|
dd|f                                         }|                                }| |z  }t          j        t          j        |                                |                    }t'          |j        |         |j        |dz                      D ]}|j        |         }||                                         }d||<   t          j        t          j        |                                | |z                      |z  d
z
  }|dk    rt7          |          |j        |<   n
d|j        |<   |||<   <t;          ||          }|                                 ||
                                z   }|                                 |r|                     ||f          }|j        j        d         }t          j!        |f          }t          j"        ||j        |j        ft	          |j        d         |z            t	          |j        d         |z            f          }tG          |          }|S )a  Energy Strength Measure.

    Compute a strength of connection matrix using an energy-based measure.

    Parameters
    ----------
    A : sparse-matrix
        matrix from which to generate strength of connection information
    theta : float
        Threshold parameter in [0,1]
    k : int
        Number of relaxation steps used to generate strength information

    Returns
    -------
    S : csr_matrix
        Matrix graph defining strong connections.  The sparsity pattern
        of S matches that of A.  For BSR matrices, S is a reduced strength
        of connection matrix that describes connections between supernodes.

    Notes
    -----
    This method relaxes with weighted-Jacobi in order to approximate the
    matrix inverse.  A normalized change of energy is then used to define
    point-wise strength of connection values.  Specifically, let v be the
    approximation to the i-th column of the inverse, then

    (S_ij)^2 = <v_j, v_j>_A / <v, v>_A,

    where v_j = v, such that entry j in v has been zeroed out.  As is common,
    larger values imply a stronger connection.

    Current implementation is a very slow pure-python implementation for
    experimental purposes, only.

    See [2006BrBrMaMaMc]_ for more details.

    References
    ----------
    .. [2006BrBrMaMaMc] Brannick, Brezina, MacLachlan, Manteuffel, McCormick.
       "An Energy-Based AMG Coarsening Strategy",
       Numerical Linear Algebra with Applications,
       vol. 13, pp. 133-148, 2006.

    Examples
    --------
    >>> import numpy as np
    >>> from pyamg.gallery import stencil_grid
    >>> from pyamg.strength import energy_based_strength_of_connection
    >>> n=3
    >>> stencil =  np.array([[-1.0,-1.0,-1.0],
    ...                      [-1.0, 8.0,-1.0],
    ...                      [-1.0,-1.0,-1.0]])
    >>> A = stencil_grid(stencil, (n,n), format='csr')
    >>> S = energy_based_strength_of_connection(A, 0.0)

    r   rU   zexpected sparse matrixz!expected positive number of stepszexpected integerTr   z&expected square blocks in BSR matrix AFr   rD   r   rV   cscr   Ng{Gz)r1   r   )$rE   r   
isspmatrix
isinstancer   r   r   r#   r)   tocsctocsrdiagonal
csc_matrixr   r&   r   r   rW   r.   r'   toarrayravelr(   innerconjr"   r!   r>   r   rS   r-   sort_indicestobsrr   r    r	   )r/   r1   kbsr_flagnumPDEsAtildeDDinvDinvAomegarR   Id_iivAvdenomjcolvjvalnblocksuones                          r:   #energy_based_strength_of_connectionr   c  s\   t qyy4555Q 312221uu<===a -+,,,Q +a.;q>Q[^++EFFF ,  Q  GGIIGGII 	


A7DDaLdRYqwqz%:%:%'Yqwqz%:%:%< =DEGM M MD1HE-e444E 	!'111A	AGAJ
5	9	9	9BAEll . .a!e,-- 6<?##  aaadGOOGGIIU2..//v}Q'q1u)=>> 	 	A.#C3BAcF'"(16688QU3344u<sBC U{{!$SA!$AAcFF	  .fEBBBF
 bhhjj F
  K'(:;;.&q)wz"""D&.&-#H*-fl1o.G*H*H*-fl1o.G*H*H*JK K K
 )00FMr<         @l2Fc           	      Z    t          dt          d           t          | ||||||          S )z:Use evolution_strength_of_connection instead (deprecated).zVode_strength_of_connection method is deprecated. Use evolution_strength_of_connection.r   )
stacklevel)r   DeprecationWarning evolution_strength_of_connection)r/   Bepsilonro   	proj_type
block_flagsymmetrize_measures          r:   ode_strength_of_connectionr     sO     	 
12DQRT T T T+Aq'1i,68JL L Lr<   c                 F   |dk     rt          d          |dk    rt          d          |dvrt          d          t          j        |           s#t          j        |           st	          d          |)t          j        | j        d         d	f| j        
          }nt          j	        |          }t          j        |           sd}| j
        d         }	|                                 }
|rt          | |	d          }t          j        |t          j        |j        d                   t          j        |j        d         d	z             f| j                  }|| z                                  }nCt          j        |
          }|
dk    }d|
|         z  ||<   d||
dk    <   t#          | |d          }|                                 } n[d}d	}	|                                 }
t          j        |
          }|
dk    }d|
|         z  ||<   d||
dk    <   t#          | |d          }|                                  |                                  | j        d	         }|j        d	         }t)          |          }|dk    rt          j        |
gdg||d          }nt          j        ||d| j                  }t/          t          j        |                    }|d|z  z
  }t          j        ||d| j                  }|d|z  |z  z
  }|j                                        }|                                 }|	d	k    rt          j        |j                  }t          j        t          j        |          |	          }t          j        ||          }d|j        t          j        |j         |	          |k    <   ~~|                                 |dk    rtC          d| d           tE          |          D ]}||z  }|d|z  |z  z
  j                                        }tE          |          D ]}||z  }~d|j        dd<   |#                    |          }|                                 |                                 n6|dk    rP|	d	k    rId|j        dd<   |#                    |          }|                                 |                                 ntE          |d	z
            D ]}||z  }|$                                }|                                 |                                 |                                 tK          j&        |j        |j         |j        |j        |j         |j        |j        |j         |j        |
  
         ~~|}|                                 |                                 ~~~|d	k    rt          j'        |          }d||dk    <   |                                }t          j'        |          |z  }|j                                        }d|j        dd<   t#          ||          }tQ          |t          j'        |                    }t          j#        t          j)        |j                  t          j)        |                    t          j#        t          j*        |j                  t          j*        |                    z   }|dk     }t          j+        |tX          
          }|j        |z  |_        t          j-        |j                  dk     } t[          d|j        z
            |_        d|j        | <   d|j        |<   |                                 d|j        |j        t          j.        t          j/        t`                    j1                  k     <   ~~ ~nt/          t          j2        t          j        |d	z                                 }!t          j3        ||!f| j        
          }"d}#tE          |          D ]v}$tE          |$|          D ]c}%dt          j4        t          j'        |dd|$f                             t          j'        ||dd|%f         z            z  z  |"dd|#f<   |#d	z   }#dwtk          |j                  }&tK          j6        |j        |j        |j         |j        d         t          j'        |          t          j'        ||7                                z  j                  t          j'        |"          |!||&
  
         |                                 t          j+        t          j)        |j                  t`          
          |_        |t
          j8        k    r;tK          j9        |||j        |j         |j                   |                                 |rd||j        z   z  }t          j        ||d          }|xj        |                                z  c_        ||z   }|s|:                    |	|	f          }|j         j        d         }'|j
        d         |j
        d	         z  }(t          j3        |'f          })tK          j;        |'|(t          j'        t          j	        |j                            |)           t          j<        |)|j         |j        ft/          |j        d         |	z            t/          |j        d	         |	z            f          }d|j        z  |_        t{          |          }|S )a  Evolution Strength Measure.

    Construct strength of connection matrix using an Evolution-based measure

    Parameters
    ----------
    A : csr_matrix, bsr_matrix
        Sparse NxN matrix
    B : string, array
        If B=None, then the near nullspace vector used is all ones.  If B is
        an (NxK) array, then B is taken to be the near nullspace vectors.
    epsilon : scalar
        Drop tolerance
    k : integer
        ODE num time steps, step size is assumed to be 1/rho(DinvA)
    proj_type : {'l2','D_A'}
        Define norm for constrained min prob, i.e. define projection
    block_flag : boolean
        If True, use a block D inverse as preconditioner for A during
        weighted-Jacobi

    Returns
    -------
    Atilde : csr_matrix
        Sparse matrix of strength values

    See [2008OlScTu]_ for more details.

    References
    ----------
    .. [2008OlScTu] Olson, L. N., Schroder, J., Tuminaro, R. S.,
       "A New Perspective on Strength Measures in Algebraic Multigrid",
       submitted, June, 2008.

    Examples
    --------
    >>> import numpy as np
    >>> from pyamg.gallery import stencil_grid
    >>> from pyamg.strength import evolution_strength_of_connection
    >>> n=3
    >>> stencil =  np.array([[-1.0,-1.0,-1.0],
    ...                        [-1.0, 8.0,-1.0],
    ...                        [-1.0,-1.0,-1.0]])
    >>> A = stencil_grid(stencil, (n,n), format='csr')
    >>> S = evolution_strength_of_connection(A,  np.ones((A.shape[0],1)))

    r   zexpected epsilon > 1.0r   z number of time steps must be > 0)r   D_Azproj_type must be "l2" or "D_A"rX   Nr   rV   FT)r   inv_flagr   rD   )r)   r   r   r   )r   rW   r   zmThe most efficient time stepping for the Evolution Strength Method is done in powers of two.
You have chosen z time steps.g-C6?r         ?rb   )>rE   r   r#   r   r\   r   r   r   rW   asarrayr   rg   r   
bsr_matrixr&   rf   
zeros_liker   r-   rm   r   spdiagsr.   r   log2Tr)   diffr"   modr%   r   r!   r   r'   multiplyre   r   incomplete_mat_mult_csrrj   r   realimagarrayboolr>   r(   finfofloatepsrH   zerosrG   r   evolution_strength_helperrl   r*   r+   rn   
min_blocksr    r	   )*r/   r   r   ro   r   r   r   Bmatcsrflagrq   rs   rt   Dinv_AmaskdimenNullDim	rho_DinvAr   nsquarenincrw   rr   
row_lengthmy_pderx   
JacobiStep	AtildeCSCBmat_forscalingDAtildeDAtildeDivBr   angle
weak_ratioBDBColsBDBcounterry   r}   toln_blocksr   CSRdatas*                                             r:   r   r     s
   h }}1222Avv;<<<%%:;;;!!$$ =v/DQ/G/G =;<<<
 	yw
Aag666z!}}  ## 0+a.JJLL 	4!!wFFFD$dBIdjm,D,D&(i
10A&B&B&D+,74 4 4D Qh%%''FF=##D8DqwDJDaL4d333FGGIIJJLL}QCx1T7]T
Q!VAt$///NN GAJEjmG ,F33I EnaS1#ueEBBBje17CCC "'!**ooGq'z>D 
E5ag	>	>	>B3?f,,FX^^F
 6688D {{WT[))
	%(('226:..=@	"&w//69:
 axx RBCR R R 	S 	S 	S .. 	% 	%Bf_FFC)Ov558>>@@
++ 	) 	)Bj(FF 	!!!&&   	AQ;; DIaaaL__T**F""$$$!!!
 !$$ 	% 	%Bf_FF LLNN	   ()/i6F)2):IN)-dlDI).		0 	0 	0 v   fd* !|| (4..031,-//##hw''/9 {!!AAAFK00vrx'@'@AA
 BGFK00"'$--@@K,,bgdmm<<=d+++ kD( VFK((4/
 #+,, #&J E 	   BFFK"'"(5//*=">">>?*ee bfRYw{334455hw'qw777w 	& 	&A1g&& & &"%\"(41:"6"677"(3aaaQRdCS:T:TT#VAAAwJ!A+& fl## 	*6;+1=+1>+1<?+-8D>>+-8S16688^4F+G+G+-8C==+2GS	B 	B 	B 	    (276;//u===FK "&&ugv}'-~v{	D 	D 	D     +)* 
E5	/	/	/BGGv   GGb[F  K'(:;;>'*$Q'&*:1*==	(H;''HiHRZ%<%<==w	H 	H 	H "GV^V]#K*-fl1o.G*H*H*-fl1o.G*H*H*JK K K #FK )00FMr<   c                 *   | j         d         }t          j                            ||z            dz
  }t          j        |||fd          }t          j        |df          }t          d|          D ] }t          | |dd|f         |||           !|S )a  Generate test vectors by relaxing on Ax=0 for some random vectors x.

    Parameters
    ----------
    A : csr_matrix
        Sparse NxN matrix
    alpha : scalar
        Weight for Jacobi
    R : integer
        Number of random vectors
    k : integer
        Number of relaxation passes

    Returns
    -------
    x : array
        Dense array N x k array of relaxation vectors

    r   r   F)orderr   N)
iterationsrv   )r   r   randomrandr[   r   r'   r   )r/   r_   ro   alphanxbrs           r:   relaxation_vectorsr   S  s    * 	

A
	q1u#A

1q!fC(((A 	!QA1a[[ 9 9q!AAAqD'1%88888 Hr<   r         c                     t          j                   st          j                    |dk     rt          d          |dk    st	          |t
                    st          d          |dk    st	          |t
                    st          d          |dk     rt          d           fd}t           |||||          S )a  Affinity Distance Strength Measure.

    Parameters
    ----------
    A : csr_matrix
        Sparse NxN matrix
    alpha : scalar
        Weight for Jacobi
    R : integer
        Number of random vectors
    k : integer
        Number of relaxation passes
    epsilon : scalar
        Drop tolerance

    Returns
    -------
    C : csr_matrix
        Sparse matrix of strength values

    References
    ----------
    .. [LiBr] Oren E. Livne and Achi Brandt, "Lean Algebraic Multigrid
        (LAMG): Fast Graph Laplacian Linear Solver"

    Notes
    -----
    No unit testing yet.

    Does not handle BSR matrices yet.

    See [LiBr]_ for more details.

    r   expected alpha>0expected integer R>0expected integer k>0r   expected epsilon>1.0c                                                     \  }}dt          j        | |         | |         z  d          dz  t          j        | |         dz  d          t          j        | |         dz  d          z  z  z
  S )Nr   r@   r   )nonzeror   rH   )r   r7   r6   r/   s      r:   distancez#affinity_distance.<locals>.distance  s    yy{{t26!D'AdG+!444a7VAdGQJQ'''"&4!!*D*D*DDF F 	Fr<   r   r#   r    rE   rd   r   distance_measure_common)r/   r   r_   ro   r   r   s   `     r:   affinity_distancer   v  s    F  ## !a  qyy+,,,AvvZ3''v/000AvvZ3''v/000{{/000F F F F F
 #1hq!WEEEr<   c                     t          j                   st          j                    |dk     rt          d          dk    st	          t
                    st          d          |dk    st	          |t
                    st          d          |dk     rt          d          dk     rt          d           fd}t           ||||          S )	a  Algebraic Distance Strength Measure.

    Parameters
    ----------
    A : csr_matrix
        Sparse NxN matrix
    alpha : scalar
        Weight for Jacobi
    R : integer
        Number of random vectors
    k : integer
        Number of relaxation passes
    epsilon : scalar
        Drop tolerance
    p : scalar or inf
        p-norm of the measure

    Returns
    -------
    C : csr_matrix
        Sparse matrix of strength values

    References
    ----------
    .. [SaSaSc] Ilya Safro, Peter Sanders, and Christian Schulz,
        "Advanced Coarsening Schemes for Graph Partitioning"

    Notes
    -----
    No unit testing yet.

    Does not handle BSR matrices yet.

    See [SaSaSc]_ for more details.

    r   r   r   r   r   r   z"expected p>1 or equal to numpy.infc                 J                                    \  }}t          j        k    rEt          j        t          j        | |         | |         z
            z  d          z  }|dz  z  S t          j        | |         | |         z
                                d          S )Nr   r@   r   )r   r   r*   rH   r>   rF   )r   r7   r6   avgr/   r_   ps       r:   r   z$algebraic_distance.<locals>.distance  s    yy{{t;;&$!D' 122A5A>>>BC37##vag$'((,,!,444r<   r   )r/   r   r_   ro   r   r   r   s   ` `  ` r:   algebraic_distancer     s    J  ## !a  qyy+,,,AvvZ3''v/000AvvZ3''v/000{{/0001uu=>>>5 5 5 5 5 5 5 #1hq!WEEEr<   c                 B   t          | |||          } ||          }|                                 \  }}	t          j        ||	k              d         }
d||
<   t	          j        |||	ff| j                  }|                                 t          j	        |j        d         ||j
        |j        |j                   |                                 d|j        z  |_        |t	          j        |j        d         |j        d         d          z   }t          |          }|S )zRCreate strength of connection matrixfrom a function applied to relaxation vectors.r   r   r   r   r   r   )r   r   r   wherer   r    r   r-   r   r+   r"   r!   r   r.   r	   )r/   funcr   r_   ro   r   r   r9   r7   r6   weakr8   s               r:   r   r     s    	1aE**A 	QA 99;;LT48DDL!!!$DAdG1tTl+17;;;A "171:w#$9af6 6 6 16\AF 	
FJqwqz171:e<<<<A 	$A&&AHr<   )r   T)r=   Tr>   )r   )rD   r   )Nr   r   r   FT)r   r   r   r   )r   r   r   r   r   )__doc__warningsr   numpyr   scipyr    r   relaxation.relaxationr   util.linalgr   
util.utilsr	   r
   r   r   r   util.paramsr   r;   rS   rY   r   r   r   r   r   r   r    r<   r:   <module>r      s  	 	                       ) ) ) ) ) ) 4 4 4 4 4 48 8 8 8 8 8 8 8 8 8 8 8 8 8            T T T TnC C C CLk k k k\P P P Pf GKDHL L L L @A@E8<Q Q Q Qh
     F7F 7F 7F 7Ft?F ?F ?F ?FD    r<   