
    _-Ph&                     z    d Z ddlmZ ddlZddlmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZmZ d	 Z	 	 ddZddZd ZdS )zCompatible Relaxation.    )deepcopyN)norm)
isspmatrixspdiagsisspmatrix_csr)amg_core   )gauss_seidelgauss_seidel_indexedc                    | j         d         }t          j        |f          }t          |dddf                   }	d|	|<   t	          |	          }
d}d}	 |dvrt          d          |dk    rt          | |	|d	           d|	|<   n|d
k    rt          | |	||d           |
}t	          |	          }
|}|
|z  }|dz  }|d|z  k     rn!t          ||z
            |z  dk     r||k    rn||	fS )a9  Perform CR sweeps on a target vector.

    Internal function called by CR. Performs habituated or concurrent
    relaxation sweeps on target vector. Stops when either (i) very fast
    convergence, CF < 0.1*thetacr, are observed, or at least a given number
    of sweeps have been performed and the relative change in CF < 0.1.

    Parameters
    ----------
    A : csr_matrix
    B : array like
        Target near null space mode
    Findex : array like
        List of F indices in current splitting
    Cindex : array like
        List of C indices in current splitting
    nu : int
        minimum number of relaxation sweeps to do
    thetacr
        Desired convergence factor

    Returns
    -------
    rho : float
        Convergence factor of last iteration
    e : array like
        Smoothed error vector

    r   Ng           T)
habituated
concurrentz4method not recognized: need habituated or concurrentr   )
iterationsr   )indicesr   g?)	shapenpzerosr   r   NotImplementedErrorr
   r   abs)ABFindexCindexnuthetacrmethodnzeenormrhokit	enorm_oldrhok_olds                  R/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/pyamg/classical/cr.py_CRsweepr'      sC   < 	

A
!A111a4AAfIGGED	
B555% '6 7 7 7\!!AqQ////AfII|## Aq&QGGGG	Qy 
a #- !!D(C//bBhh-0 7N    r      ffffff?auto   Fc                    | j         d         }|dk    rnt          |t                    r|                                 n$t          |t                    rt          |          }t          j        |          dk    st          j        |          dk    rt          d          |dk    s|dk    rt          d          t          |           st          d          | j        t          k    rt          d          |t          j        |df          }|j        dk    r$|                    t#          |          df          }|dddf         }	t          j        |fd	
          }
t          j        |dz   fd	
          }||d<   t          j        d|d	
          |dd<   |dd         }t          j        dd	
          }t          j        |f          }t+          | ||||||          \  }}t-          d|          D ]}|dk    rd|z
  }n/|d         }t#          |          dk    r|                                 t0          j        } || j        | j        |	|||
||           |d         }|d|dz            }||dz   d         }t+          | ||||||          \  }}|r$t9          d| d| d||d         z
  |z              ||k     r n|
S )a  Use Compatible Relaxation to compute a C/F splitting.

    Parameters
    ----------
    A : csr_matrix
        sparse matrix (n x n) usually matrix A of Ax=b
    method : {'habituated','concurrent'}
        Method used during relaxation:
            - concurrent: GS relaxation on F-points, leaving e_c = 0
            - habituated: full relaxation, setting e_c = 0
    B : array like
        Target algebraically smooth vector used in CR. If multiple
        vectors passed in, only first one is used. If B=None, the
        constant vector is used.
    nu : int
        Number of smoothing iterations to apply each CR sweep.
    thetacr : float
        Desired convergence factor of relaxations, 0 < thetacr < 1.
    thetacs : list, float, 'auto'
        Threshold value, 0 < thetacs < 1, to consider nodes from
        candidate set for coarse grid. If e[i] > thetacs for relaxed
        error vector, e, node i is considered for the coarse grid.
        Can be passed in as float to be used for every iteration,
        list of floats to be used on progressive iterations, or as
        string 'auto,' wherein each iteration thetacs = 1 - rho, for
        convergence factor rho from most recent smoothing.
    maxiter : int
        Maximum number of CR iterations (updating of C/F splitting)
        to do.
    verbose : bool
        If true, print iteration number, convergence factor and
        coarsening factor after each iteration.

    Returns
    -------
    splitting : array
        C/F list of 1's (coarse pt) and 0's (fine pt) (n x 1)

    References
    ----------
    [1] Brannick, James J., and Robert D. Falgout. "Compatible
    relaxation and coarsening in algebraic multigrid." SIAM Journal
    on Scientific Computing 32.3 (2010): 1393-1416.

    Examples
    --------
    >>> from pyamg.gallery import poisson
    >>> from pyamg.classical.cr import CR
    >>> A = poisson((20,20),format='csr')
    >>> splitting = CR(A)

    r   r+   r   zMust have 0 < thetacs < 1zMust have 0 < thetacr < 1zexpecting csr sparse matrix Acomplex A not implementedNintc)dtype)r   )r   zCR Iteration z CF = z, Coarsening factor = )r   
isinstancelistreversefloatr   maxmin
ValueErrorr   	TypeErrorr0   complexr   onesndimreshapelenr   arangeemptyr'   rangepopr   	cr_helperindptrr   print)r   r   r   r   r   thetacsmaxiterverboser   target	splittingr   r   r   gammarhor    r#   tcsfnnum_Fs                        r&   CRrP   N   s=   l 	

A&gt$$ 	$OO'' 	$7mmGF7OOq  bfWoo&:&:89991'Q,,4555! 97888w'!"=>>> 	yGQFOOv{{IIs1vvqk""qqq!tWF !V,,,Ih!vV,,,GGAJ)Aq///GABBKQRR[FXd&)))FHaTNNE aFFBGGGFC Aw $ $ fC%CC"+C7||a 
189	 	 	 
E!G%%'$ !QGFKKKQ  	? >" > >C > >,-gajL!+;> > ? ? ? ==E  r(   h㈵>
   c                    t          |           st          d          | j        t          k    rt	          d          | j        d         }d}t          j        |df                                          }| 	                    |           
                                }|                                                                }||z  }d|z  t          j        ||          z  }	t          ||          }
|
|k    r||k     rt          d|          D ]]}|dz
  ||         z  }|dz
  ||         ||         ||         z  z
  z  }||          ||         z  ||         z  d||         z  ||         z  z   ||	z  z
  }| dk     rt          d           | c S d|z  | t          j        ||z  d	|z  |z  z
            z
  z  }|||         z
  }|j        |         }|j        |dz            }t          j        ||j        ||                  |j        ||                   }|	d|z  |z  |||         z   ||         |z  z   z  z   }	||j        ||         xx         ||j        ||         z  z  cc<   |||<   _t          ||          }
|dz  }|
|k    r||k     t          j        |          }t)          |                                dg||          }|| z  |z  }|                                }|	                    |                              d
          }t          j        d|z  t          j        |          z            }d|z  |z  S )a  Binormalize matrix A.  Attempt to create unit l_1 norm rows.

    Parameters
    ----------
    A : csr_matrix
        sparse matrix (n x n)
    tol : float
        tolerance
    x : array
        guess at the diagonal
    maxiter : int
        maximum number of iterations to try

    Returns
    -------
    C : csr_matrix
        diagonally scaled A, C=DAD

    Notes
    -----
        - Goal: Scale A so that l_1 norm of the rows are equal to 1:
        - B = DAD
        - want row sum of B = 1
        - easily done with tol=0 if B=DA, but this is not symmetric
        - algorithm is O(N log (1.0/tol))

    Examples
    --------
    >>> from pyamg.gallery import poisson
    >>> from pyamg.classical.cr import binormalize
    >>> A = poisson((10,),format='csr')
    >>> C = binormalize(A)

    References
    ----------
    .. [1] Livne, Golub, "Scaling by Binormalization"
       Tech Report SCCM-03-12, SCCM, Stanford, 2003
       http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.3.1679

    zexpecting sparse matrix Ar.   r   r         ?r	   g+=z&warning: A nearly un-binormalizable...   )axis)r   r9   r0   r:   r   r   r   r;   ravelmultiplytocscdiagonaldotrowsum_stdevrA   rE   sqrtrD   r   datar   tocsrsum)r   tolrG   r   r#   xr   dbetabetabarstdevic2c1c0xnewdxiiiiidot_BcolDCscales                          r&   binormalizers      sA   R a== 53444w'!"=>>>	
A	
B
AA 	


1A	

A q5D1uq$'GD!!E #++"w,,q! 	 	A A#qtBA#Q!A$qt)+,BA$qtAaD1T!W9QqT>1AgI=BsU{{>??? bDB3B2b!9!99:D!B !B(1Q3-Cva	"S& 12AF2c6NCCHQ
HtAw,>1b,H IIG2c6"###r!&C.'88###AaDDQ%%
a9 #++"w,,> 	

A		A31%%A	A	A			A::a==!$$DGSUbfTll*++EeGQ;r(   c                     | j         }d|z  t          j        | |          z  }t          j        d|z  t          j        t          j        t          j        | |          |z
  d                    z            }||z  S )ai  Compute row sum standard deviation.

    Compute for approximation x, the std dev of the row sums
    s(x) = ( 1/n \sum_k  (x_k beta_k - betabar)^2 )^(1/2)
    with betabar = 1/n dot(beta,x)

    Parameters
    ----------
    x : array
    beta : array

    Returns
    -------
    s(x)/betabar : float

    Notes
    -----
    equation (7) in Livne/Golub

    rT   r	   )sizer   r[   r]   r`   powerrX   )rb   rd   r   re   rf   s        r&   r\   r\   ?  sm    * 	
AQw"&D//)GGS1WrxAt0D0Dw0NPQ'R'R S SSTTE7?r(   )r   Nr)   r*   r+   r,   F)rQ   rR   )__doc__copyr   numpyr   scipy.linalgr   scipy.sparser   r   r   pyamgr   relaxation.relaxationr
   r   r'   rP   rs   r\    r(   r&   <module>r      s                      < < < < < < < < < <       F F F F F F F F? ? ?D 69,1I I I IXb b b bJ    r(   