
    Gd4                     &   d Z ddlZddlmZ g dZ ed          dd            Z ed          dd            Zdd	Z ed
           ed          	 dd                        Z	 ed
           ed          	 dd                        Z
ddZdS )zLaplacian matrix of graphs.
    N)not_implemented_for)laplacian_matrixnormalized_laplacian_matrixtotal_spanning_tree_weightdirected_laplacian_matrix'directed_combinatorial_laplacian_matrixdirectedweightc           	         ddl }ddl}|t          |           }t          j        | ||d          }|j        \  }}|j                            |j                            |	                    d          d||d                    }||z
  S )a  Returns the Laplacian matrix of G.

    The graph Laplacian is the matrix L = D - A, where
    A is the adjacency matrix and D is the diagonal matrix of node degrees.

    Parameters
    ----------
    G : graph
       A NetworkX graph

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    Returns
    -------
    L : SciPy sparse array
      The Laplacian matrix of G.

    Notes
    -----
    For MultiGraph, the edges weights are summed.

    See Also
    --------
    to_numpy_array
    normalized_laplacian_matrix
    laplacian_spectrum

    Examples
    --------
    For graphs with multiple connected components, L is permutation-similar
    to a block diagonal matrix where each block is the respective Laplacian
    matrix for each component.

    >>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
    >>> print(nx.laplacian_matrix(G).toarray())
    [[ 1 -1  0  0  0]
     [-1  2 -1  0  0]
     [ 0 -1  1  0  0]
     [ 0  0  0  1 -1]
     [ 0  0  0 -1  1]]

    r   Ncsrnodelistr
   format   axisr   )
scipyscipy.sparselistnxto_scipy_sparse_arrayshapesparse	csr_arrayspdiagssum)	Gr   r
   spr   AnmDs	            ?lib/python3.11/site-packages/networkx/linalg/laplacianmatrix.pyr   r      s    d 77
 XfUSSSA7DAq
	BI--aeeemmQ1U-SSTTAq5L    c           	      ^   ddl }ddl}ddl}|t          |           }t	          j        | ||d          }|j        \  }}|                    d          }	|j        	                    |j        
                    |	d||d                    }
|
|z
  }|                    d	          5  d
|                    |	          z  }ddd           n# 1 swxY w Y   d||                    |          <   |j        	                    |j        
                    |d||d                    }|||z  z  S )a  Returns the normalized Laplacian matrix of G.

    The normalized graph Laplacian is the matrix

    .. math::

        N = D^{-1/2} L D^{-1/2}

    where `L` is the graph Laplacian and `D` is the diagonal matrix of
    node degrees [1]_.

    Parameters
    ----------
    G : graph
       A NetworkX graph

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    Returns
    -------
    N : SciPy sparse array
      The normalized Laplacian matrix of G.

    Notes
    -----
    For MultiGraph, the edges weights are summed.
    See :func:`to_numpy_array` for other options.

    If the Graph contains selfloops, D is defined as ``diag(sum(A, 1))``, where A is
    the adjacency matrix [2]_.

    See Also
    --------
    laplacian_matrix
    normalized_laplacian_spectrum

    References
    ----------
    .. [1] Fan Chung-Graham, Spectral Graph Theory,
       CBMS Regional Conference Series in Mathematics, Number 92, 1997.
    .. [2] Steve Butler, Interlacing For Weighted Graphs Using The Normalized
       Laplacian, Electronic Journal of Linear Algebra, Volume 16, pp. 90-98,
       March 2007.
    r   Nr   r   r   r   r   ignore)divide      ?)numpyr   r   r   r   r   r   r   r   r   r   errstatesqrtisinf)r   r   r
   npr   r   r    r!   r"   diagsr#   L
diags_sqrtDHs                 r$   r   r   M   sy   h 77
 XfUSSSA7DAqEEqEMME
	BI--eQ1U-KKLLA	AA	H	%	% * *2775>>)
* * * * * * * * * * * * * * *'(Jrxx
##$			RY..z1a5.QQ	R	RBR=s   (CCCc                     ddl }t          j        | |                                          }t	          |j                            |ddddf                             S )as  
    Returns the total weight of all spanning trees of `G`.

    Kirchoff's Tree Matrix Theorem states that the determinant of any cofactor of the
    Laplacian matrix of a graph is the number of spanning trees in the graph. For a
    weighted Laplacian matrix, it is the sum across all spanning trees of the
    multiplicative weight of each tree. That is, the weight of each tree is the
    product of its edge weights.

    Parameters
    ----------
    G : NetworkX Graph
        The graph to use Kirchhoff's theorem on.

    weight : string or None
        The key for the edge attribute holding the edge weight. If `None`, then
        each edge is assumed to have a weight of 1 and this function returns the
        total number of spanning trees in `G`.

    Returns
    -------
    float
        The sum of the total multiplicative weights for all spanning trees in `G`
    r   N)r
   r   )r*   r   r   toarrayabslinalgdet)r   r
   r.   G_laplacians       r$   r   r      s^    2 %a777??AAKry}}[QRR011222r%   
undirected
multigraphffffff?c           	         ddl }ddl}ddl}ddl}t	          | ||||          }|j        \  }	}
|j        j                            |j	        d          \  }}|
                                j        }||                                z  }|                    |          }|j                            |j                            |d|	|	                    |z  |j                            |j                            d|z  d|	|	                    z  }|                    t#          |                     }|||j	        z   dz  z
  S )a>  Returns the directed Laplacian matrix of G.

    The graph directed Laplacian is the matrix

    .. math::

        L = I - (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} ) / 2

    where `I` is the identity matrix, `P` is the transition matrix of the
    graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and
    zeros elsewhere [1]_.

    Depending on the value of walk_type, `P` can be the transition matrix
    induced by a random walk, a lazy random walk, or a random walk with
    teleportation (PageRank).

    Parameters
    ----------
    G : DiGraph
       A NetworkX graph

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    walk_type : string or None, optional (default=None)
       If None, `P` is selected depending on the properties of the
       graph. Otherwise is one of 'random', 'lazy', or 'pagerank'

    alpha : real
       (1 - alpha) is the teleportation probability used with pagerank

    Returns
    -------
    L : NumPy matrix
      Normalized Laplacian of G.

    Notes
    -----
    Only implemented for DiGraphs

    See Also
    --------
    laplacian_matrix

    References
    ----------
    .. [1] Fan Chung (2005).
       Laplacians and the Cheeger inequality for directed graphs.
       Annals of Combinatorics, 9(1), 2005
    r   Nr   r
   	walk_typealphar   kr)          @)r*   r   r   scipy.sparse.linalg_transition_matrixr   r   r6   eigsTflattenrealr   r,   r   r   identitylen)r   r   r
   r>   r?   r.   r   r   Pr!   r"   evalsevecsvpsqrtpQIs                     r$   r   r      sQ   x  		HVy	 	 	A 7DAq9#(((22LE5A	AEEGGAGGAJJE 		BI--eQ1==>>
	 )

bi//eQ1EE
F
F	G  	CFFAAC3r%   c                    ddl }ddl}ddl}t          | ||||          }|j        \  }}	|j        j                            |j        d          \  }
}|	                                j
        }||                                z  }|j                            |j                            |d||                                                    }|||z  |j        |z  z   dz  z
  S )a  Return the directed combinatorial Laplacian matrix of G.

    The graph directed combinatorial Laplacian is the matrix

    .. math::

        L = \Phi - (\Phi P + P^T \Phi) / 2

    where `P` is the transition matrix of the graph and `\Phi` a matrix
    with the Perron vector of `P` in the diagonal and zeros elsewhere [1]_.

    Depending on the value of walk_type, `P` can be the transition matrix
    induced by a random walk, a lazy random walk, or a random walk with
    teleportation (PageRank).

    Parameters
    ----------
    G : DiGraph
       A NetworkX graph

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    walk_type : string or None, optional (default=None)
       If None, `P` is selected depending on the properties of the
       graph. Otherwise is one of 'random', 'lazy', or 'pagerank'

    alpha : real
       (1 - alpha) is the teleportation probability used with pagerank

    Returns
    -------
    L : NumPy matrix
      Combinatorial Laplacian of G.

    Notes
    -----
    Only implemented for DiGraphs

    See Also
    --------
    laplacian_matrix

    References
    ----------
    .. [1] Fan Chung (2005).
       Laplacians and the Cheeger inequality for directed graphs.
       Annals of Combinatorics, 9(1), 2005
    r   Nr=   r   r@   rB   )r   r   rC   rD   r   r   r6   rE   rF   rG   rH   r   r   r   r4   )r   r   r
   r>   r?   r   r   rK   r!   r"   rL   rM   rN   rO   Phis                  r$   r   r     s    v 	HVy	 	 	A 7DAq9#(((22LE5A	AEEGGA )

bi//1a;;
<
<
D
D
F
FC#'AC#I%,,,r%   c                 f   ddl }ddl}ddl}|0t          j        |           rt          j        |           rd}nd}nd}t          j        | ||t                    }|j        \  }	}
|dv r|j	        
                    |j	                            d|                    d	
          z  d|	|	                    }|dk    r||z  }n|j	        
                    |j	                            |	                    }|||z  z   dz  }n|dk    rd|cxk     rd	k     sn t          j        d          |                                }d	|	z  ||                    d	
          dk    ddf<   ||                    d	
          |j        ddf         j        z  }||z  d	|z
  |	z  z   }nt          j        d          |S )a  Returns the transition matrix of G.

    This is a row stochastic giving the transition probabilities while
    performing a random walk on the graph. Depending on the value of walk_type,
    P can be the transition matrix induced by a random walk, a lazy random walk,
    or a random walk with teleportation (PageRank).

    Parameters
    ----------
    G : DiGraph
       A NetworkX graph

    nodelist : list, optional
       The rows and columns are ordered according to the nodes in nodelist.
       If nodelist is None, then the ordering is produced by G.nodes().

    weight : string or None, optional (default='weight')
       The edge data key used to compute each value in the matrix.
       If None, then each edge has weight 1.

    walk_type : string or None, optional (default=None)
       If None, `P` is selected depending on the properties of the
       graph. Otherwise is one of 'random', 'lazy', or 'pagerank'

    alpha : real
       (1 - alpha) is the teleportation probability used with pagerank

    Returns
    -------
    P : numpy.ndarray
      transition matrix of G.

    Raises
    ------
    NetworkXError
        If walk_type not specified or alpha not in valid range
    r   Nrandomlazypagerank)r   r
   dtype)rV   rW   r)   r   r   rB   zalpha must be between 0 and 1z+walk_type must be random, lazy, or pagerank)r*   r   r   r   is_strongly_connectedis_aperiodicr   floatr   r   r   r   r   rI   NetworkXErrorr4   newaxisrF   )r   r   r
   r>   r?   r.   r   r   r    r!   r"   DIrK   rR   s                 r$   rD   rD   a  s   L #A&& 	#q!! #$		"		"I
 XfERRRA7DAq&&&Y  !2!23A3F1a!P!PQQ  QAA 	##BI$6$6q$9$9::AR!Vs"AA	j	 	 EA"#BCCCIIKK#$q5!%%Q%--1
aaa
 1bj!!!m,..AIUa'LMMMHr%   )Nr
   )N)Nr
   Nr;   )__doc__networkxr   networkx.utilsr   __all__r   r   r   r   r   rD    r%   r$   <module>re      si        . . . . . .   Z  : : : ! :z Z  D D D ! DN3 3 3 3H \""\""=AT T T #" #"Tn \""\""=AJ- J- J- #" #"J-ZL L L L L Lr%   