
    h75                         S r SSKrSSKrSSKJr  SS/r\" S5      \R                  " SS9SS	 j5       5       r\R                  " SS9SS
 j5       r	g)z/Functions for computing eigenvector centrality.    N)not_implemented_foreigenvector_centralityeigenvector_centrality_numpy
multigraphweight)
edge_attrsc                   ^^ [        U 5      S:X  a  [        R                  " S5      eUc  U  Vs0 s H  oUS_M     nn[        S UR	                  5        5       5      (       a  [        R
                  " S5      e[        UR	                  5       5      nUR                  5        VVs0 s H
  u  puXuU-  _M     snnmU R                  5       n[        U5       H  n	TmTR                  5       mT HA  n
X
    H6  nU(       a  X
   U   R                  US5      OSnTU==   TU
   U-  -  ss'   M8     MC     [        R                  " TR	                  5       6 =(       d    SnTR                  5        VVs0 s H
  u  puXuU-  _M     snnm[        UU4S jT 5       5      X-  :  d  M  Ts  $    [        R                  " U5      es  snf s  snnf s  snnf )u  Compute the eigenvector centrality for the graph G.

Eigenvector centrality computes the centrality for a node by adding
the centrality of its predecessors. The centrality for node $i$ is the
$i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
of maximum modulus that is positive. Such an eigenvector $x$ is
defined up to a multiplicative constant by the equation

.. math::

     \lambda x^T = x^T A,

where $A$ is the adjacency matrix of the graph G. By definition of
row-column product, the equation above is equivalent to

.. math::

    \lambda x_i = \sum_{j\to i}x_j.

That is, adding the eigenvector centralities of the predecessors of
$i$ one obtains the eigenvector centrality of $i$ multiplied by
$\lambda$. In the case of undirected graphs, $x$ also solves the familiar
right-eigenvector equation $Ax = \lambda x$.

By virtue of the Perron–Frobenius theorem [1]_, if G is strongly
connected there is a unique eigenvector $x$, and all its entries
are strictly positive.

If G is not strongly connected there might be several left
eigenvectors associated with $\lambda$, and some of their elements
might be zero.

Parameters
----------
G : graph
  A networkx graph.

max_iter : integer, optional (default=100)
  Maximum number of power iterations.

tol : float, optional (default=1.0e-6)
  Error tolerance (in Euclidean norm) used to check convergence in
  power iteration.

nstart : dictionary, optional (default=None)
  Starting value of power iteration for each node. Must have a nonzero
  projection on the desired eigenvector for the power method to converge.
  If None, this implementation uses an all-ones vector, which is a safe
  choice.

weight : None or string, optional (default=None)
  If None, all edge weights are considered equal. Otherwise holds the
  name of the edge attribute used as weight. In this measure the
  weight is interpreted as the connection strength.

Returns
-------
nodes : dictionary
   Dictionary of nodes with eigenvector centrality as the value. The
   associated vector has unit Euclidean norm and the values are
   nonegative.

Examples
--------
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> sorted((v, f"{c:0.2f}") for v, c in centrality.items())
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]

Raises
------
NetworkXPointlessConcept
    If the graph G is the null graph.

NetworkXError
    If each value in `nstart` is zero.

PowerIterationFailedConvergence
    If the algorithm fails to converge to the specified tolerance
    within the specified number of iterations of the power iteration
    method.

See Also
--------
eigenvector_centrality_numpy
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`

Notes
-----
Eigenvector centrality was introduced by Landau [2]_ for chess
tournaments. It was later rediscovered by Wei [3]_ and then
popularized by Kendall [4]_ in the context of sport ranking. Berge
introduced a general definition for graphs based on social connections
[5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
it popular in link analysis.

This function computes the left dominant eigenvector, which corresponds
to adding the centrality of predecessors: this is the usual approach.
To add the centrality of successors first reverse the graph with
``G.reverse()``.

The implementation uses power iteration [7]_ to compute a dominant
eigenvector starting from the provided vector `nstart`. Convergence is
guaranteed as long as `nstart` has a nonzero projection on a dominant
eigenvector, which certainly happens using the default value.

The method stops when the change in the computed vector between two
iterations is smaller than an error tolerance of ``G.number_of_nodes()
* tol`` or after ``max_iter`` iterations, but in the second case it
raises an exception.

This implementation uses $(A + I)$ rather than the adjacency matrix
$A$ because the change preserves eigenvectors, but it shifts the
spectrum, thus guaranteeing convergence even for networks with
negative eigenvalues of maximum modulus.

References
----------
.. [1] Abraham Berman and Robert J. Plemmons.
   "Nonnegative Matrices in the Mathematical Sciences."
   Classics in Applied Mathematics. SIAM, 1994.

.. [2] Edmund Landau.
   "Zur relativen Wertbemessung der Turnierresultate."
   Deutsches Wochenschach, 11:366–369, 1895.

.. [3] Teh-Hsing Wei.
   "The Algebraic Foundations of Ranking Theory."
   PhD thesis, University of Cambridge, 1952.

.. [4] Maurice G. Kendall.
   "Further contributions to the theory of paired comparisons."
   Biometrics, 11(1):43–62, 1955.
   https://www.jstor.org/stable/3001479

.. [5] Claude Berge
   "Théorie des graphes et ses applications."
   Dunod, Paris, France, 1958.

.. [6] Phillip Bonacich.
   "Technique for analyzing overlapping memberships."
   Sociological Methodology, 4:176–185, 1972.
   https://www.jstor.org/stable/270732

.. [7] Power iteration:: https://en.wikipedia.org/wiki/Power_iteration

r   ,cannot compute centrality for the null graph   c              3   *   #    U  H	  oS :H  v   M     g7f)r   N ).0vs     \/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/centrality/eigenvector.py	<genexpr>)eigenvector_centrality.<locals>.<genexpr>   s     
+?a6?s   z*initial vector cannot have all zero valuesc              3   L   >#    U  H  n[        TU   TU   -
  5      v   M     g 7f)N)abs)r   nxxlasts     r   r   r      s%     /Qs1Q4%(?##Qs   !$)lennxNetworkXPointlessConceptallvaluesNetworkXErrorsumitemsnumber_of_nodesrangecopygetmathhypotPowerIterationFailedConvergence)Gmax_itertolnstartr   r   
nstart_sumknnodes_r   nbrwnormr   r   s                 @@r   r   r      s   n 1v{)):
 	
 ~ !"1Q$"

+6==?
+++KLL V]]_%J'-||~6~tq
N	~6A F8_JJLAt06ADIMM&!,A#%(Q,&   zz188:&+!%&WWY/YTQQD[Y//Q//&,>H! " 
,
,X
665 # 	7  0s   F<$G-Gc                    SSK nSSKn[        U 5      S:X  a  [        R                  " S5      eU R                  5       (       a  [        R                  " U 5      O[        R                  " U 5      nU(       d  [        R                  " S5      e[        R                  " U [        U 5      U[        S9nUR                  R                  R                  UR                  SSX#S9u  pU	R!                  5       R"                  n
UR%                  U
R'                  5       5      UR                  R)                  U
5      -  n[+        [-        X
U-  R/                  5       5      5      $ )	u  Compute the eigenvector centrality for the graph `G`.

Eigenvector centrality computes the centrality for a node by adding
the centrality of its predecessors. The centrality for node $i$ is the
$i$-th element of a left eigenvector associated with the eigenvalue $\lambda$
of maximum modulus that is positive. Such an eigenvector $x$ is
defined up to a multiplicative constant by the equation

.. math::

     \lambda x^T = x^T A,

where $A$ is the adjacency matrix of the graph `G`. By definition of
row-column product, the equation above is equivalent to

.. math::

    \lambda x_i = \sum_{j\to i}x_j.

That is, adding the eigenvector centralities of the predecessors of
$i$ one obtains the eigenvector centrality of $i$ multiplied by
$\lambda$. In the case of undirected graphs, $x$ also solves the familiar
right-eigenvector equation $Ax = \lambda x$.

By virtue of the Perron--Frobenius theorem [1]_, if `G` is (strongly)
connected, there is a unique eigenvector $x$, and all its entries
are strictly positive.

However, if `G` is not (strongly) connected, there might be several left
eigenvectors associated with $\lambda$, and some of their elements
might be zero.
Depending on the method used to choose eigenvectors, round-off error can affect
which of the infinitely many eigenvectors is reported.
This can lead to inconsistent results for the same graph,
which the underlying implementation is not robust to.
For this reason, only (strongly) connected graphs are accepted.

Parameters
----------
G : graph
    A connected NetworkX graph.

weight : None or string, optional (default=None)
    If ``None``, all edge weights are considered equal. Otherwise holds the
    name of the edge attribute used as weight. In this measure the
    weight is interpreted as the connection strength.

max_iter : integer, optional (default=50)
    Maximum number of Arnoldi update iterations allowed.

tol : float, optional (default=0)
    Relative accuracy for eigenvalues (stopping criterion).
    The default value of 0 implies machine precision.

Returns
-------
nodes : dict of nodes
    Dictionary of nodes with eigenvector centrality as the value. The
    associated vector has unit Euclidean norm and the values are
    nonnegative.

Examples
--------
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality_numpy(G)
>>> print([f"{node} {centrality[node]:0.2f}" for node in centrality])
['0 0.37', '1 0.60', '2 0.60', '3 0.37']

Raises
------
NetworkXPointlessConcept
    If the graph `G` is the null graph.

ArpackNoConvergence
    When the requested convergence is not obtained. The currently
    converged eigenvalues and eigenvectors can be found as
    eigenvalues and eigenvectors attributes of the exception object.

AmbiguousSolution
    If `G` is not connected.

See Also
--------
:func:`scipy.sparse.linalg.eigs`
eigenvector_centrality
:func:`~networkx.algorithms.link_analysis.pagerank_alg.pagerank`
:func:`~networkx.algorithms.link_analysis.hits_alg.hits`

Notes
-----
Eigenvector centrality was introduced by Landau [2]_ for chess
tournaments. It was later rediscovered by Wei [3]_ and then
popularized by Kendall [4]_ in the context of sport ranking. Berge
introduced a general definition for graphs based on social connections
[5]_. Bonacich [6]_ reintroduced again eigenvector centrality and made
it popular in link analysis.

This function computes the left dominant eigenvector, which corresponds
to adding the centrality of predecessors: this is the usual approach.
To add the centrality of successors first reverse the graph with
``G.reverse()``.

This implementation uses the
:func:`SciPy sparse eigenvalue solver<scipy.sparse.linalg.eigs>` (ARPACK)
to find the largest eigenvalue/eigenvector pair using Arnoldi iterations
[7]_.

References
----------
.. [1] Abraham Berman and Robert J. Plemmons.
   "Nonnegative Matrices in the Mathematical Sciences".
   Classics in Applied Mathematics. SIAM, 1994.

.. [2] Edmund Landau.
   "Zur relativen Wertbemessung der Turnierresultate".
   Deutsches Wochenschach, 11:366--369, 1895.

.. [3] Teh-Hsing Wei.
   "The Algebraic Foundations of Ranking Theory".
   PhD thesis, University of Cambridge, 1952.

.. [4] Maurice G. Kendall.
   "Further contributions to the theory of paired comparisons".
   Biometrics, 11(1):43--62, 1955.
   https://www.jstor.org/stable/3001479

.. [5] Claude Berge.
   "Théorie des graphes et ses applications".
   Dunod, Paris, France, 1958.

.. [6] Phillip Bonacich.
   "Technique for analyzing overlapping memberships".
   Sociological Methodology, 4:176--185, 1972.
   https://www.jstor.org/stable/270732

.. [7] Arnoldi, W. E. (1951).
   "The principle of minimized iterations in the solution of the matrix eigenvalue problem".
   Quarterly of Applied Mathematics. 9 (1): 17--29.
   https://doi.org/10.1090/qam/42792
r   Nr
   zW`eigenvector_centrality_numpy` does not give consistent results for disconnected graphs)nodelistr   dtyper   LR)r,   whichmaxiterr)   )numpyscipyr   r   r   is_directedis_strongly_connectedis_connectedAmbiguousSolutionto_scipy_sparse_arraylistfloatsparselinalgeigsTflattenrealsignr   r1   dictziptolist)r'   r   r(   r)   npsp	connectedMr.   eigenvectorlargestr1   s               r   r   r      s   \ 
1v{)):
 	
 01}}((+BOOTUDVI""e
 	
 	  T!WV5QAYY%%**	qh + NA !!#((G777;;=!BIINN7$;;DA$..0122    )d   gư>NN)N2   r   )
__doc__r$   networkxr   networkx.utilsr   __all___dispatchabler   r   r   rQ   r   <module>rY      sl    5   .#%C
D \"X&u7 ' #u7p X&_3 '_3rQ   