K i~RdZddlZddlmZmZmZgdZGddZGddZ d Z d Z d Z d Z ed edejd ddZed edejd ddZedejd ddZejd ddZy)zB Algebraic connectivity and Fiedler vectors of undirected graphs. N)not_implemented_fornp_random_statereverse_cuthill_mckee_ordering)algebraic_connectivityfiedler_vectorspectral_orderingspectral_bisectionc"eZdZdZdZdZdZy) _PCGSolveraPreconditioned conjugate gradient method. To solve Ax = b: M = A.diagonal() # or some other preconditioner solver = _PCGSolver(lambda x: A * x, lambda x: M * x) x = solver.solve(b) The inputs A and M are functions which compute matrix multiplication on the argument. A - multiply by the matrix A in Ax=b M - multiply by M, the preconditioner surrogate for A Warning: There is no limit on number of iterations. c ||_||_yN)_A_M)selfAMs k/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/networkx/linalg/algebraicconnectivity.py__init__z_PCGSolver.__init__$scddl}|j|}|j|jd}t |jdD]"}|j |dd|f||dd|f<$|SNrForder)numpyasarrayndarrayshaperange_solverBtolnpXjs rsolvez_PCGSolver.solve(sk JJqM JJqwwcJ *qwwqz" 0Akk!AqD'3/AadG 0rc|ddl}ddl}|j}|j}||jj j |z}|j|j}|j}||} |jj j|| } | j} || } | |jj j| | z } |jj j| || }|jj j| || }|jj j ||kr|S||} |jj j|| }|| z |} }|jj j| | |}  )Nr)a) rscipyrrlinalgblasdasumzerosrcopyddotdaxpy)rbr$r%sprrxrzrzpApalphabetas rr!z_PCGSolver._solve2sa GG GG ryy~~##A&& HHQWW  FFH aD YY^^ A & FFH1B,,Q33E $$QU$3A $$Ruf$5Ayy~~##A&,!A99>>&&q!,Dby$"D $$QT$2ArN)__name__ __module__ __qualname____doc__rr(r!rrr r s 3rr ceZdZdZdZddZy) _LUSolverzLU factorization. To solve Ax = b: solver = _LUSolver(A) x = solver.solve(b) optional argument `tol` on solve method is ignored but included to match _PCGsolver API. cnddl}|jjj|ddddd|_y)Nr MMD_AT_PLUS_AT)Equil SymmetricMode) permc_specdiag_pivot_threshoptions)r+sparser,splu_LU)rrr4s rrz_LUSolver.__init__Xs799##(( &!"T: ) rNcddl}|j|}|j|jd}t |jdD]+}|j j |dd|f|dd|f<-|Sr)rrrrr rNr(r"s rr(z_LUSolver.solvebsk JJqM JJqwwcJ *qwwqz" .AhhnnQq!tW-AadG .rr )r=r>r?r@rr(rArrrCrCMs rrCcjrStj}|j|j fdj dD|j sfdj dD}nfdj D}tj}|j|j d|D|S)z5Compute edge weights and eliminate zero-weight edges.c3\K|]#\}}}||k7s |||jdf%yw?N)get.0uveweights r z$_preprocess_graph..rs0 TGAq!QRSVaAEE&#& ' Ts,,T)data)rZc 3nK|],\}}}||k7s ||t|jdf.ywrRabsrTrUs rr[z$_preprocess_graph..ws< 071aQRVWQWQ3quuVS)* + s5#5c3K|]7\}}||k7r-||tfd||jDf9yw)c3TK|]}t|jd!ywrRr^)rVrYrZs rr[z._preprocess_graph...|s!I1s155-.Is%(N)sumvalues)rVrWrXGrZs rr[z$_preprocess_graph..{sE 1Av3I!Q8HII J s=Ac3:K|]\}}}|dk7s |||fyw)rNrA)rVrWrXrYs rr[z$_preprocess_graph..s"GGAq!Qq!QiGs ) is_directednx MultiGraphadd_nodes_fromadd_weighted_edges_fromedges is_multigraphGraph)rdrZHrks`` r_preprocess_graphrols}} MMO  !! TqwwDw7I T "   ??  ;<777;M      AQGuGG Hrcddl}|j|}t|}t|}t t |t |}|j|t}t|D] \}}||||<||dz dz z}|S)zEEstimate the Fiedler vector using the reverse Cuthill-McKee ordering.rNdtyper@) rsubgraphrlendictzipr rfloat enumerate) rdnodelistr%rnindexr5irWs r _rcm_estimater~s 8A *1 -E H A XuQx( )E 1E "A% 1%( !a%3A Hrc ddlddl}|jd|rjj |j j |j jdz ddzzdjjdz z|rfd}nfd }|d k(r6j jttfd fd }n|d k(rl|j jtd}|jdd|jddz j} j || | f<t#|}nt%j&d|t)j+dj-j/} ||j1|jd} jj3|d}|z| ddddf<|j4| z} |jj7| d\} }||z}|jj8j;| |dddfz| d|dddfzz | z }||krnd|j=||| ddddf<|jj?| j4|z| j4zj4}|| | jA|fS)aCompute the Fiedler vector of L using the TraceMIN-Fiedler algorithm. The Fiedler vector of a connected undirected graph is the eigenvector corresponding to the second smallest eigenvalue of the Laplacian matrix of the graph. This function starts with the Laplacian L, not the Graph. Parameters ---------- L : Laplacian of a possibly weighted or normalized, but undirected graph X : Initial guess for a solution. Usually a matrix of random numbers. This function allows more than one column in X to identify more than one eigenvector if desired. normalized : bool Whether the normalized Laplacian matrix is used. tol : float Tolerance of relative residual in eigenvalue computation. Warning: There is no limit on number of iterations. method : string Should be 'tracemin_pcg' or 'tracemin_lu'. Otherwise exception is raised. Returns ------- sigma, X : Two NumPy arrays of floats. The lowest eigenvalues and corresponding eigenvectors of L. The size of input X determines the size of these outputs. As this is for Fiedler vectors, the zero eigenvalue (and constant eigenvector) are avoided. rNrcsrformatrScj|}t|jdD] }|dd|fxx|dd|fzzzcc<"yz(Make X orthogonal to the nullspace of L.rN)rr r)r&r'rYr%s rprojectz"_tracemin_fiedler..projectsO 1 A1771:& -!Q$AadGaK1,, -rcj|}t|jdD]+}|dd|fxx|dd|fjz zcc<-yr)rr rrb)r&r'r{r%s rrz"_tracemin_fiedler..projectsQ 1 A1771:& -!Q$1QT7;;=1,, -r tracemin_pcgc|zSr rA)r5Ls rz#_tracemin_fiedler..s a!erc|zSr rA)r5Ds rrz#_tracemin_fiedler..s q1ur tracemin_luT)rrr0zUnknown linear system solver: )axisrr) overwrite_a)!rr+rsqrtdiagonalrL csr_arrayspdiagsr,normastyperxr csc_arrayindptrargmaxinfrCrg NetworkXErrorr_rbflattenmaxrqrTeighr-r.r(invr)rr& normalizedr$methodr4rsolverrr}LnormWrnsigmaYresrrYr{r%s` @@@@r_tracemin_fiedlerrsD  A GGAJJL ! II   1 1!a%Aq 1 O P EAI S299>>!Q' '' - -  JJL   &O_= = II  T  : XXab\AHHSbM ) 1 1 3&&!Q$1!?xHII FJJAJ  & & ( , , .E AJ 177# &A  IILLOA a%!Q$ CC!G99>>!>6q Eiinn""1qAw;qAadG1C#CDuL 9 ,,q#&!Q$ YY]]1337 #acc ) , , % ( "**Q- rcddldk(rddvrfd}|Sdk(sdk(rfd }|Stjd d ) z>Returns a function that solves the Fiedler eigenvalue problem.rNtraceminr)rrcdk(rdntd|jddz } j|j||jdfj}t ||||\}}|d|dddffS)Nrrr)size)minrrnormalrr) rr5rr$seedqr&rrr%s r find_fiedlerz'_get_fiedler_func..find_fiedler s|~-3q!''!*q.3IA 4;;Q O;<=??A(Az3GHE18Qq!tW$ $rlanczoslobpcgc ddl}|jj|t}|jd}|rb|jj|jj d j |jz dg||d}||z|z} dk(s|dkr;|jjj|dd |d \}} |d | ddd ffS j j|j} |jj|jj d|jz d||} j|} |r| jz} |jjj|| | j| j||d \}} |d| dddffS)NrrqrScscrr rSMT)whichr$return_eigenvectorsrF)rrr$maxiterlargest)r+rLrrxrrrrr,eigshr atleast_2drronesr)rr5rr$rr4r{rrr&rrrr%s rrz'_get_fiedler_func..find_fiedlers  ##AU#3A AII''II%%bggajjl33aS!Qu& EAI"a"f99++11q#42qQx1a4((JJr}}Q/112II'' (9(9# :LaQRTU(VWGGAJ%A99++22qAq!1!3!3aQV3qQx1a4((rzunknown method .)rrgr)rrr%s` @r_get_fiedler_funcrsf  00 %X M 9 ( 2 )H  !<==rdirectedrZ) edge_attrsctt|dkrtjdt||}tj|sytj |}|j ddk(r|sdt|dzSdSt|}|dk7rdn t||}||||||\} } t| S) a Returns the algebraic connectivity of an undirected graph. The algebraic connectivity of a connected undirected graph is the second smallest eigenvalue of its Laplacian matrix. Parameters ---------- G : NetworkX graph An undirected graph. weight : object, optional (default: None) The data key used to determine the weight of each edge. If None, then each edge has unit weight. normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used. tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation. method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG). The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used. =============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ======================================== seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- algebraic_connectivity : float Algebraic connectivity. Raises ------ NetworkXNotImplemented If G is directed. NetworkXError If G has less than two nodes. Notes ----- Edge weights are interpreted by their absolute values. For MultiGraph's, weights of parallel edges are summed. Zero-weighted edges are ignored. See Also -------- laplacian_matrix Examples -------- For undirected graphs algebraic connectivity can tell us if a graph is connected or not `G` is connected iff ``algebraic_connectivity(G) > 0``: >>> G = nx.complete_graph(5) >>> nx.algebraic_connectivity(G) > 0 True >>> G.add_node(10) # G is no longer connected >>> nx.algebraic_connectivity(G) > 0 False rgraph has less than two nodes.rFrrs)rrrN) rurgrro is_connectedlaplacian_matrixrrxrr~) rdrZrr$rrrrr5rfiedlers rrr8s` 1vz?@@!V$A ??1  AAwwqzQ+5sU1T7^#>3>$V,L(" a(;A!!Q C>NE7 <rcddl}t|dkrtjdt ||}tj |stjdt|dk(r|j ddgSt|}tj|}|dk7rdn t||} ||| |||\} } | S) a Returns the Fiedler vector of a connected undirected graph. The Fiedler vector of a connected undirected graph is the eigenvector corresponding to the second smallest eigenvalue of the Laplacian matrix of the graph. Parameters ---------- G : NetworkX graph An undirected graph. weight : object, optional (default: None) The data key used to determine the weight of each edge. If None, then each edge has unit weight. normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used. tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation. method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG). The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used. =============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ======================================== seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- fiedler_vector : NumPy array of floats. Fiedler vector. Raises ------ NetworkXNotImplemented If G is directed. NetworkXError If G has less than two nodes or is not connected. Notes ----- Edge weights are interpreted by their absolute values. For MultiGraph's, weights of parallel edges are summed. Zero-weighted edges are ignored. See Also -------- laplacian_matrix Examples -------- Given a connected graph the signs of the values in the Fiedler vector can be used to partition the graph into two components. >>> G = nx.barbell_graph(5, 0) >>> nx.fiedler_vector(G, normalized=True, seed=1) array([-0.32864129, -0.32864129, -0.32864129, -0.32864129, -0.26072899, 0.26072899, 0.32864129, 0.32864129, 0.32864129, 0.32864129]) The connected components are the two 5-node cliques of the barbell graph. rNrrzgraph is not connected.rSgr) rrurgrrorarrayrrr~) rdrZrr$rrr%rrr5rrs rrrs` 1vz?@@!V$A ??1 899 1v{xxd $$$V,L AA(" a(;A!!Q C>NE7 Nrct|dk(rtjdt||}t |}g}tj |D]}t|} | dkDrptj ||} |dk7rdn t||} || | |||\} } t| t| |}|jdt|D|j||S)aCompute the spectral_ordering of a graph. The spectral ordering of a graph is an ordering of its nodes where nodes in the same weakly connected components appear contiguous and ordered by their corresponding elements in the Fiedler vector of the component. Parameters ---------- G : NetworkX graph A graph. weight : object, optional (default: None) The data key used to determine the weight of each edge. If None, then each edge has unit weight. normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used. tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation. method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG). The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used. =============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ======================================== seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness`. Returns ------- spectral_ordering : NumPy array of floats. Spectral ordering of nodes. Raises ------ NetworkXError If G is empty. Notes ----- Edge weights are interpreted by their absolute values. For MultiGraph's, weights of parallel edges are summed. Zero-weighted edges are ignored. See Also -------- laplacian_matrix rzgraph is empty.rrNc3(K|] \}}}| ywr rA)rVr5crWs rr[z$spectral_ordering..Gs`. Returns ------- bisection : tuple of sets Sets with the bisection of nodes Examples -------- >>> G = nx.barbell_graph(3, 0) >>> nx.spectral_bisection(G) ({0, 1, 2}, {3, 4, 5}) References ---------- .. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370 Oxford University Press 2011. rN)rrgrrlistsettolist) rdrZrr$rrr%rXnodespos_valss rr r Nsov !VZfdCA HHT!W EAvH uhY&&( )3uX/E/E/G+H HHr)rZFg:0yE>rN)r@networkxrgnetworkx.utilsrrr__all__r rCror~rr _dispatchablerrrr rArrrs*  6363r> 4  i X4nZ X&PTZ'!ZzZ X&PT\'!\~X&PTO'OdX&PT@I'@Ir