
    h"+                         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\" S5      \R                  " SS9SS
 j5       5       r	g)zKatz centrality.    N)not_implemented_forkatz_centralitykatz_centrality_numpy
multigraphweight)
edge_attrsc                   ^^ [        U 5      S:X  a  0 $ U R                  5       nUc  U  V	s0 s H  oS_M     sn	mOUm [        R                  U [	        U5      5      n
[        U5       H  nTm[        R                  TS5      mT H6  n	X	    H+  nTU==   TU	   X	   U   R                  US5      -  -  ss'   M-     M8     T H  n	UTU	   -  X   -   TU	'   M     [        UU4S jT 5       5      nXU-  :  d  M  U(       a&   S[        R                  " TR!                  5       6 -  nOSnT H  n	TU	==   U-  ss'   M     Ts  $    [        R$                  " U5      es  sn	f ! [
        [        [        4 a<  nUn
[        U5      [        U 5      :w  a  [        R                  " S5      Ue SnAGNMSnAff = f! ["         a    Sn Nf = f)u  Compute the Katz centrality for the nodes of the graph G.

Katz centrality computes the centrality for a node based on the centrality
of its neighbors. It is a generalization of the eigenvector centrality. The
Katz centrality for node $i$ is

.. math::

    x_i = \alpha \sum_{j} A_{ij} x_j + \beta,

where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.

The parameter $\beta$ controls the initial centrality and

.. math::

    \alpha < \frac{1}{\lambda_{\max}}.

Katz centrality computes the relative influence of a node within a
network by measuring the number of the immediate neighbors (first
degree nodes) and also all other nodes in the network that connect
to the node under consideration through these immediate neighbors.

Extra weight can be provided to immediate neighbors through the
parameter $\beta$.  Connections made with distant neighbors
are, however, penalized by an attenuation factor $\alpha$ which
should be strictly less than the inverse largest eigenvalue of the
adjacency matrix in order for the Katz centrality to be computed
correctly. More information is provided in [1]_.

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

alpha : float, optional (default=0.1)
  Attenuation factor

beta : scalar or dictionary, optional (default=1.0)
  Weight attributed to the immediate neighborhood. If not a scalar, the
  dictionary must have a value for every node.

max_iter : integer, optional (default=1000)
  Maximum number of iterations in power method.

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

nstart : dictionary, optional
  Starting value of Katz iteration for each node.

normalized : bool, optional (default=True)
  If True normalize the resulting values.

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 Katz centrality as the value.

Raises
------
NetworkXError
   If the parameter `beta` is not a scalar but lacks a value for at least
   one node

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

Examples
--------
>>> import math
>>> G = nx.path_graph(4)
>>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix
>>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)
>>> for n, c in sorted(centrality.items()):
...     print(f"{n} {c:.2f}")
0 0.37
1 0.60
2 0.60
3 0.37

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

Notes
-----
Katz centrality was introduced by [2]_.

This algorithm it uses the power method to find the eigenvector
corresponding to the largest eigenvalue of the adjacency matrix of ``G``.
The parameter ``alpha`` should be strictly less than the inverse of largest
eigenvalue of the adjacency matrix for the algorithm to converge.
You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
eigenvalue of the adjacency matrix.
The iteration will stop after ``max_iter`` iterations or an error tolerance of
``number_of_nodes(G) * tol`` has been reached.

For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
Katz centrality approaches the results for eigenvector centrality.

For directed graphs this finds "left" eigenvectors which corresponds
to the in-edges in the graph. For out-edges Katz centrality,
first reverse the graph with ``G.reverse()``.

References
----------
.. [1] Mark E. J. Newman:
   Networks: An Introduction.
   Oxford University Press, USA, 2010, p. 720.
.. [2] Leo Katz:
   A New Status Index Derived from Sociometric Index.
   Psychometrika 18(1):39–43, 1953
   https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
r   N0beta dictionary must have a value for every node   c              3   L   >#    U  H  n[        TU   TU   -
  5      v   M     g 7f)N)abs).0nxxlasts     U/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/centrality/katz.py	<genexpr>"katz_centrality.<locals>.<genexpr>   s%     4!QC!uQx((!s   !$      ?)lennumber_of_nodesdictfromkeysfloat	TypeError
ValueErrorAttributeErrorsetnxNetworkXErrorrangegetsummathhypotvaluesZeroDivisionErrorPowerIterationFailedConvergence)Galphabetamax_itertolnstart
normalizedr   nnodesr   berr_nbrerrorsr   r   s                   @@r   r   r      s   T 1v{	 F~1aT1MM!U4[) 8_MM%#At#%(QT#Y]]61%===   A1Q4<!$&AaD  4!44C<djj!((*55A !	 H/ 0 
,
,X
66M  z>2 t9A""B 2 ) As.   EE  $F2F/31F**F/2G Gc                    SSK n[        U 5      S:X  a  0 $  UR                  5       n[        U5      [        U 5      :w  a  [        R
                  " S5      eUR                  [        UR                  5       5      [        S9n[        R                  " XUS9R                  5       R                   n	U	R"                  S   n
UR$                  R'                  UR)                  X5      X-  -
  U5      R+                  5       nU(       a6  UR-                  [/        U5      5      UR$                  R1                  U5      -  OSn[3        [5        XkU-  R7                  5       5      5      $ ! [         ac    [        U 5      n UR                  [        U5      S45      U-  n GN! [        [        [        4 a  n[        R
                  " S5      UeSnAff = ff = f)u%  Compute the Katz centrality for the graph G.

Katz centrality computes the centrality for a node based on the centrality
of its neighbors. It is a generalization of the eigenvector centrality. The
Katz centrality for node $i$ is

.. math::

    x_i = \alpha \sum_{j} A_{ij} x_j + \beta,

where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.

The parameter $\beta$ controls the initial centrality and

.. math::

    \alpha < \frac{1}{\lambda_{\max}}.

Katz centrality computes the relative influence of a node within a
network by measuring the number of the immediate neighbors (first
degree nodes) and also all other nodes in the network that connect
to the node under consideration through these immediate neighbors.

Extra weight can be provided to immediate neighbors through the
parameter $\beta$.  Connections made with distant neighbors
are, however, penalized by an attenuation factor $\alpha$ which
should be strictly less than the inverse largest eigenvalue of the
adjacency matrix in order for the Katz centrality to be computed
correctly. More information is provided in [1]_.

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

alpha : float
  Attenuation factor

beta : scalar or dictionary, optional (default=1.0)
  Weight attributed to the immediate neighborhood. If not a scalar the
  dictionary must have an value for every node.

normalized : bool
  If True normalize the resulting values.

weight : None or string, optional
  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 Katz centrality as the value.

Raises
------
NetworkXError
   If the parameter `beta` is not a scalar but lacks a value for at least
   one node

Examples
--------
>>> import math
>>> G = nx.path_graph(4)
>>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix
>>> centrality = nx.katz_centrality_numpy(G, 1 / phi)
>>> for n, c in sorted(centrality.items()):
...     print(f"{n} {c:.2f}")
0 0.37
1 0.60
2 0.60
3 0.37

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

Notes
-----
Katz centrality was introduced by [2]_.

This algorithm uses a direct linear solver to solve the above equation.
The parameter ``alpha`` should be strictly less than the inverse of largest
eigenvalue of the adjacency matrix for there to be a solution.
You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
eigenvalue of the adjacency matrix.

For strongly connected graphs, as $\alpha \to 1/\lambda_{\max}$, and $\beta > 0$,
Katz centrality approaches the results for eigenvector centrality.

For directed graphs this finds "left" eigenvectors which corresponds
to the in-edges in the graph. For out-edges Katz centrality,
first reverse the graph with ``G.reverse()``.

References
----------
.. [1] Mark E. J. Newman:
   Networks: An Introduction.
   Oxford University Press, USA, 2010, p. 173.
.. [2] Leo Katz:
   A New Status Index Derived from Sociometric Index.
   Psychometrika 18(1):39–43, 1953
   https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
r   Nr
   )dtyper   zbeta must be a number)nodelistr   )numpyr   keysr   r   r    arraylistr&   r   r   onesr   r   adjacency_matrixtodenseTshapelinalgsolveeyesqueezesignr#   normr   ziptolist)r)   r*   r+   r/   r   npr9   r1   r2   Ar   
centralityrH   s                r   r   r      sz   ` 
1v{	
E99;x=CF"""#UVVHHT$++-(H6 	A@HHJLLA	
A!;Q?GGIJ EO2773z?#biinnZ&@@TUDHD088:;<<  E7	EX*+d2A:~6 	E""#:;D	E	Es*   A)E G4FG+GGG)皙?r   i  gư>NTN)rN   r   TN)
__doc__r$   networkxr   networkx.utilsr   __all___dispatchabler   r        r   <module>rV      s       .5
6 \"X& 	u7 ' #u7p \"X&D= ' #D=rU   