We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Incorrect link to the paper in katz_centrality documentation
### Current Behavior

Link [2] in katz_centrality documentation directs to the incorrect paper: 'Universal Behavior of Load Distribution in Scale-Free Networks'

### Expected Behavior
Link [2] in katz_centrality documentation directs to the correct paper: 'A New Status Index Derived from Sociometric Index'

### Steps to Reproduce
Open the page https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.centrality.katz_centrality.html

### Additional context
I guess the correct link is https://link.springer.com/content/pdf/10.1007/BF02289026.pdf


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `networkx/algorithms/centrality/katz.py`
Content:
```
1 """Katz centrality."""
2 from math import sqrt
3 
4 import networkx as nx
5 from networkx.utils import not_implemented_for
6 
7 __all__ = ["katz_centrality", "katz_centrality_numpy"]
8 
9 
10 @not_implemented_for("multigraph")
11 def katz_centrality(
12     G,
13     alpha=0.1,
14     beta=1.0,
15     max_iter=1000,
16     tol=1.0e-6,
17     nstart=None,
18     normalized=True,
19     weight=None,
20 ):
21     r"""Compute the Katz centrality for the nodes of the graph G.
22 
23     Katz centrality computes the centrality for a node based on the centrality
24     of its neighbors. It is a generalization of the eigenvector centrality. The
25     Katz centrality for node $i$ is
26 
27     .. math::
28 
29         x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
30 
31     where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
32 
33     The parameter $\beta$ controls the initial centrality and
34 
35     .. math::
36 
37         \alpha < \frac{1}{\lambda_{\max}}.
38 
39     Katz centrality computes the relative influence of a node within a
40     network by measuring the number of the immediate neighbors (first
41     degree nodes) and also all other nodes in the network that connect
42     to the node under consideration through these immediate neighbors.
43 
44     Extra weight can be provided to immediate neighbors through the
45     parameter $\beta$.  Connections made with distant neighbors
46     are, however, penalized by an attenuation factor $\alpha$ which
47     should be strictly less than the inverse largest eigenvalue of the
48     adjacency matrix in order for the Katz centrality to be computed
49     correctly. More information is provided in [1]_.
50 
51     Parameters
52     ----------
53     G : graph
54       A NetworkX graph.
55 
56     alpha : float
57       Attenuation factor
58 
59     beta : scalar or dictionary, optional (default=1.0)
60       Weight attributed to the immediate neighborhood. If not a scalar, the
61       dictionary must have an value for every node.
62 
63     max_iter : integer, optional (default=1000)
64       Maximum number of iterations in power method.
65 
66     tol : float, optional (default=1.0e-6)
67       Error tolerance used to check convergence in power method iteration.
68 
69     nstart : dictionary, optional
70       Starting value of Katz iteration for each node.
71 
72     normalized : bool, optional (default=True)
73       If True normalize the resulting values.
74 
75     weight : None or string, optional (default=None)
76       If None, all edge weights are considered equal.
77       Otherwise holds the name of the edge attribute used as weight.
78       In this measure the weight is interpreted as the connection strength.
79 
80     Returns
81     -------
82     nodes : dictionary
83        Dictionary of nodes with Katz centrality as the value.
84 
85     Raises
86     ------
87     NetworkXError
88        If the parameter `beta` is not a scalar but lacks a value for at least
89        one node
90 
91     PowerIterationFailedConvergence
92         If the algorithm fails to converge to the specified tolerance
93         within the specified number of iterations of the power iteration
94         method.
95 
96     Examples
97     --------
98     >>> import math
99     >>> G = nx.path_graph(4)
100     >>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix
101     >>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)
102     >>> for n, c in sorted(centrality.items()):
103     ...     print(f"{n} {c:.2f}")
104     0 0.37
105     1 0.60
106     2 0.60
107     3 0.37
108 
109     See Also
110     --------
111     katz_centrality_numpy
112     eigenvector_centrality
113     eigenvector_centrality_numpy
114     pagerank
115     hits
116 
117     Notes
118     -----
119     Katz centrality was introduced by [2]_.
120 
121     This algorithm it uses the power method to find the eigenvector
122     corresponding to the largest eigenvalue of the adjacency matrix of ``G``.
123     The parameter ``alpha`` should be strictly less than the inverse of largest
124     eigenvalue of the adjacency matrix for the algorithm to converge.
125     You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
126     eigenvalue of the adjacency matrix.
127     The iteration will stop after ``max_iter`` iterations or an error tolerance of
128     ``number_of_nodes(G) * tol`` has been reached.
129 
130     When $\alpha = 1/\lambda_{\max}$ and $\beta=0$, Katz centrality is the same
131     as eigenvector centrality.
132 
133     For directed graphs this finds "left" eigenvectors which corresponds
134     to the in-edges in the graph. For out-edges Katz centrality
135     first reverse the graph with ``G.reverse()``.
136 
137     References
138     ----------
139     .. [1] Mark E. J. Newman:
140        Networks: An Introduction.
141        Oxford University Press, USA, 2010, p. 720.
142     .. [2] Leo Katz:
143        A New Status Index Derived from Sociometric Index.
144        Psychometrika 18(1):39–43, 1953
145        http://phya.snu.ac.kr/~dkim/PRL87278701.pdf
146     """
147     if len(G) == 0:
148         return {}
149 
150     nnodes = G.number_of_nodes()
151 
152     if nstart is None:
153         # choose starting vector with entries of 0
154         x = {n: 0 for n in G}
155     else:
156         x = nstart
157 
158     try:
159         b = dict.fromkeys(G, float(beta))
160     except (TypeError, ValueError, AttributeError) as e:
161         b = beta
162         if set(beta) != set(G):
163             raise nx.NetworkXError(
164                 "beta dictionary " "must have a value for every node"
165             ) from e
166 
167     # make up to max_iter iterations
168     for i in range(max_iter):
169         xlast = x
170         x = dict.fromkeys(xlast, 0)
171         # do the multiplication y^T = Alpha * x^T A - Beta
172         for n in x:
173             for nbr in G[n]:
174                 x[nbr] += xlast[n] * G[n][nbr].get(weight, 1)
175         for n in x:
176             x[n] = alpha * x[n] + b[n]
177 
178         # check convergence
179         err = sum([abs(x[n] - xlast[n]) for n in x])
180         if err < nnodes * tol:
181             if normalized:
182                 # normalize vector
183                 try:
184                     s = 1.0 / sqrt(sum(v ** 2 for v in x.values()))
185                 # this should never be zero?
186                 except ZeroDivisionError:
187                     s = 1.0
188             else:
189                 s = 1
190             for n in x:
191                 x[n] *= s
192             return x
193     raise nx.PowerIterationFailedConvergence(max_iter)
194 
195 
196 @not_implemented_for("multigraph")
197 def katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):
198     r"""Compute the Katz centrality for the graph G.
199 
200     Katz centrality computes the centrality for a node based on the centrality
201     of its neighbors. It is a generalization of the eigenvector centrality. The
202     Katz centrality for node $i$ is
203 
204     .. math::
205 
206         x_i = \alpha \sum_{j} A_{ij} x_j + \beta,
207 
208     where $A$ is the adjacency matrix of graph G with eigenvalues $\lambda$.
209 
210     The parameter $\beta$ controls the initial centrality and
211 
212     .. math::
213 
214         \alpha < \frac{1}{\lambda_{\max}}.
215 
216     Katz centrality computes the relative influence of a node within a
217     network by measuring the number of the immediate neighbors (first
218     degree nodes) and also all other nodes in the network that connect
219     to the node under consideration through these immediate neighbors.
220 
221     Extra weight can be provided to immediate neighbors through the
222     parameter $\beta$.  Connections made with distant neighbors
223     are, however, penalized by an attenuation factor $\alpha$ which
224     should be strictly less than the inverse largest eigenvalue of the
225     adjacency matrix in order for the Katz centrality to be computed
226     correctly. More information is provided in [1]_.
227 
228     Parameters
229     ----------
230     G : graph
231       A NetworkX graph
232 
233     alpha : float
234       Attenuation factor
235 
236     beta : scalar or dictionary, optional (default=1.0)
237       Weight attributed to the immediate neighborhood. If not a scalar the
238       dictionary must have an value for every node.
239 
240     normalized : bool
241       If True normalize the resulting values.
242 
243     weight : None or string, optional
244       If None, all edge weights are considered equal.
245       Otherwise holds the name of the edge attribute used as weight.
246       In this measure the weight is interpreted as the connection strength.
247 
248     Returns
249     -------
250     nodes : dictionary
251        Dictionary of nodes with Katz centrality as the value.
252 
253     Raises
254     ------
255     NetworkXError
256        If the parameter `beta` is not a scalar but lacks a value for at least
257        one node
258 
259     Examples
260     --------
261     >>> import math
262     >>> G = nx.path_graph(4)
263     >>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix
264     >>> centrality = nx.katz_centrality_numpy(G, 1 / phi)
265     >>> for n, c in sorted(centrality.items()):
266     ...     print(f"{n} {c:.2f}")
267     0 0.37
268     1 0.60
269     2 0.60
270     3 0.37
271 
272     See Also
273     --------
274     katz_centrality
275     eigenvector_centrality_numpy
276     eigenvector_centrality
277     pagerank
278     hits
279 
280     Notes
281     -----
282     Katz centrality was introduced by [2]_.
283 
284     This algorithm uses a direct linear solver to solve the above equation.
285     The parameter ``alpha`` should be strictly less than the inverse of largest
286     eigenvalue of the adjacency matrix for there to be a solution.
287     You can use ``max(nx.adjacency_spectrum(G))`` to get $\lambda_{\max}$ the largest
288     eigenvalue of the adjacency matrix.
289 
290     When $\alpha = 1/\lambda_{\max}$ and $\beta=0$, Katz centrality is the same
291     as eigenvector centrality.
292 
293     For directed graphs this finds "left" eigenvectors which corresponds
294     to the in-edges in the graph. For out-edges Katz centrality
295     first reverse the graph with ``G.reverse()``.
296 
297     References
298     ----------
299     .. [1] Mark E. J. Newman:
300        Networks: An Introduction.
301        Oxford University Press, USA, 2010, p. 720.
302     .. [2] Leo Katz:
303        A New Status Index Derived from Sociometric Index.
304        Psychometrika 18(1):39–43, 1953
305        http://phya.snu.ac.kr/~dkim/PRL87278701.pdf
306     """
307     import numpy as np
308 
309     if len(G) == 0:
310         return {}
311     try:
312         nodelist = beta.keys()
313         if set(nodelist) != set(G):
314             raise nx.NetworkXError(
315                 "beta dictionary " "must have a value for every node"
316             )
317         b = np.array(list(beta.values()), dtype=float)
318     except AttributeError:
319         nodelist = list(G)
320         try:
321             b = np.ones((len(nodelist), 1)) * float(beta)
322         except (TypeError, ValueError, AttributeError) as e:
323             raise nx.NetworkXError("beta must be a number") from e
324 
325     A = nx.adj_matrix(G, nodelist=nodelist, weight=weight).todense().T
326     n = A.shape[0]
327     centrality = np.linalg.solve(np.eye(n, n) - (alpha * A), b)
328     if normalized:
329         norm = np.sign(sum(centrality)) * np.linalg.norm(centrality)
330     else:
331         norm = 1.0
332     centrality = dict(zip(nodelist, map(float, centrality / norm)))
333     return centrality
334
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/networkx/algorithms/centrality/katz.py b/networkx/algorithms/centrality/katz.py
--- a/networkx/algorithms/centrality/katz.py
+++ b/networkx/algorithms/centrality/katz.py
@@ -142,7 +142,7 @@
     .. [2] Leo Katz:
        A New Status Index Derived from Sociometric Index.
        Psychometrika 18(1):39–43, 1953
-       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf
+       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
     """
     if len(G) == 0:
         return {}
@@ -302,7 +302,7 @@
     .. [2] Leo Katz:
        A New Status Index Derived from Sociometric Index.
        Psychometrika 18(1):39–43, 1953
-       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf
+       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf
     """
     import numpy as np

{"golden_diff": "diff --git a/networkx/algorithms/centrality/katz.py b/networkx/algorithms/centrality/katz.py\n--- a/networkx/algorithms/centrality/katz.py\n+++ b/networkx/algorithms/centrality/katz.py\n@@ -142,7 +142,7 @@\n     .. [2] Leo Katz:\n        A New Status Index Derived from Sociometric Index.\n        Psychometrika 18(1):39\u201343, 1953\n-       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf\n+       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf\n     \"\"\"\n     if len(G) == 0:\n         return {}\n@@ -302,7 +302,7 @@\n     .. [2] Leo Katz:\n        A New Status Index Derived from Sociometric Index.\n        Psychometrika 18(1):39\u201343, 1953\n-       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf\n+       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf\n     \"\"\"\n     import numpy as np\n", "issue": "Incorrect link to the paper in katz_centrality documentation\n### Current Behavior\r\n\r\nLink [2] in katz_centrality documentation directs to the incorrect paper: 'Universal Behavior of Load Distribution in Scale-Free Networks'\r\n\r\n### Expected Behavior\r\nLink [2] in katz_centrality documentation directs to the correct paper: 'A New Status Index Derived from Sociometric Index'\r\n\r\n### Steps to Reproduce\r\nOpen the page https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.centrality.katz_centrality.html\r\n\r\n### Additional context\r\nI guess the correct link is https://link.springer.com/content/pdf/10.1007/BF02289026.pdf\r\n\n", "before_files": [{"content": "\"\"\"Katz centrality.\"\"\"\nfrom math import sqrt\n\nimport networkx as nx\nfrom networkx.utils import not_implemented_for\n\n__all__ = [\"katz_centrality\", \"katz_centrality_numpy\"]\n\n\n@not_implemented_for(\"multigraph\")\ndef katz_centrality(\n    G,\n    alpha=0.1,\n    beta=1.0,\n    max_iter=1000,\n    tol=1.0e-6,\n    nstart=None,\n    normalized=True,\n    weight=None,\n):\n    r\"\"\"Compute the Katz centrality for the nodes of the graph G.\n\n    Katz centrality computes the centrality for a node based on the centrality\n    of its neighbors. It is a generalization of the eigenvector centrality. The\n    Katz centrality for node $i$ is\n\n    .. math::\n\n        x_i = \\alpha \\sum_{j} A_{ij} x_j + \\beta,\n\n    where $A$ is the adjacency matrix of graph G with eigenvalues $\\lambda$.\n\n    The parameter $\\beta$ controls the initial centrality and\n\n    .. math::\n\n        \\alpha < \\frac{1}{\\lambda_{\\max}}.\n\n    Katz centrality computes the relative influence of a node within a\n    network by measuring the number of the immediate neighbors (first\n    degree nodes) and also all other nodes in the network that connect\n    to the node under consideration through these immediate neighbors.\n\n    Extra weight can be provided to immediate neighbors through the\n    parameter $\\beta$.  Connections made with distant neighbors\n    are, however, penalized by an attenuation factor $\\alpha$ which\n    should be strictly less than the inverse largest eigenvalue of the\n    adjacency matrix in order for the Katz centrality to be computed\n    correctly. More information is provided in [1]_.\n\n    Parameters\n    ----------\n    G : graph\n      A NetworkX graph.\n\n    alpha : float\n      Attenuation factor\n\n    beta : scalar or dictionary, optional (default=1.0)\n      Weight attributed to the immediate neighborhood. If not a scalar, the\n      dictionary must have an value for every node.\n\n    max_iter : integer, optional (default=1000)\n      Maximum number of iterations in power method.\n\n    tol : float, optional (default=1.0e-6)\n      Error tolerance used to check convergence in power method iteration.\n\n    nstart : dictionary, optional\n      Starting value of Katz iteration for each node.\n\n    normalized : bool, optional (default=True)\n      If True normalize the resulting values.\n\n    weight : None or string, optional (default=None)\n      If None, all edge weights are considered equal.\n      Otherwise holds the name of the edge attribute used as weight.\n      In this measure the weight is interpreted as the connection strength.\n\n    Returns\n    -------\n    nodes : dictionary\n       Dictionary of nodes with Katz centrality as the value.\n\n    Raises\n    ------\n    NetworkXError\n       If the parameter `beta` is not a scalar but lacks a value for at least\n       one node\n\n    PowerIterationFailedConvergence\n        If the algorithm fails to converge to the specified tolerance\n        within the specified number of iterations of the power iteration\n        method.\n\n    Examples\n    --------\n    >>> import math\n    >>> G = nx.path_graph(4)\n    >>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix\n    >>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)\n    >>> for n, c in sorted(centrality.items()):\n    ...     print(f\"{n} {c:.2f}\")\n    0 0.37\n    1 0.60\n    2 0.60\n    3 0.37\n\n    See Also\n    --------\n    katz_centrality_numpy\n    eigenvector_centrality\n    eigenvector_centrality_numpy\n    pagerank\n    hits\n\n    Notes\n    -----\n    Katz centrality was introduced by [2]_.\n\n    This algorithm it uses the power method to find the eigenvector\n    corresponding to the largest eigenvalue of the adjacency matrix of ``G``.\n    The parameter ``alpha`` should be strictly less than the inverse of largest\n    eigenvalue of the adjacency matrix for the algorithm to converge.\n    You can use ``max(nx.adjacency_spectrum(G))`` to get $\\lambda_{\\max}$ the largest\n    eigenvalue of the adjacency matrix.\n    The iteration will stop after ``max_iter`` iterations or an error tolerance of\n    ``number_of_nodes(G) * tol`` has been reached.\n\n    When $\\alpha = 1/\\lambda_{\\max}$ and $\\beta=0$, Katz centrality is the same\n    as eigenvector centrality.\n\n    For directed graphs this finds \"left\" eigenvectors which corresponds\n    to the in-edges in the graph. For out-edges Katz centrality\n    first reverse the graph with ``G.reverse()``.\n\n    References\n    ----------\n    .. [1] Mark E. J. Newman:\n       Networks: An Introduction.\n       Oxford University Press, USA, 2010, p. 720.\n    .. [2] Leo Katz:\n       A New Status Index Derived from Sociometric Index.\n       Psychometrika 18(1):39\u201343, 1953\n       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf\n    \"\"\"\n    if len(G) == 0:\n        return {}\n\n    nnodes = G.number_of_nodes()\n\n    if nstart is None:\n        # choose starting vector with entries of 0\n        x = {n: 0 for n in G}\n    else:\n        x = nstart\n\n    try:\n        b = dict.fromkeys(G, float(beta))\n    except (TypeError, ValueError, AttributeError) as e:\n        b = beta\n        if set(beta) != set(G):\n            raise nx.NetworkXError(\n                \"beta dictionary \" \"must have a value for every node\"\n            ) from e\n\n    # make up to max_iter iterations\n    for i in range(max_iter):\n        xlast = x\n        x = dict.fromkeys(xlast, 0)\n        # do the multiplication y^T = Alpha * x^T A - Beta\n        for n in x:\n            for nbr in G[n]:\n                x[nbr] += xlast[n] * G[n][nbr].get(weight, 1)\n        for n in x:\n            x[n] = alpha * x[n] + b[n]\n\n        # check convergence\n        err = sum([abs(x[n] - xlast[n]) for n in x])\n        if err < nnodes * tol:\n            if normalized:\n                # normalize vector\n                try:\n                    s = 1.0 / sqrt(sum(v ** 2 for v in x.values()))\n                # this should never be zero?\n                except ZeroDivisionError:\n                    s = 1.0\n            else:\n                s = 1\n            for n in x:\n                x[n] *= s\n            return x\n    raise nx.PowerIterationFailedConvergence(max_iter)\n\n\n@not_implemented_for(\"multigraph\")\ndef katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):\n    r\"\"\"Compute the Katz centrality for the graph G.\n\n    Katz centrality computes the centrality for a node based on the centrality\n    of its neighbors. It is a generalization of the eigenvector centrality. The\n    Katz centrality for node $i$ is\n\n    .. math::\n\n        x_i = \\alpha \\sum_{j} A_{ij} x_j + \\beta,\n\n    where $A$ is the adjacency matrix of graph G with eigenvalues $\\lambda$.\n\n    The parameter $\\beta$ controls the initial centrality and\n\n    .. math::\n\n        \\alpha < \\frac{1}{\\lambda_{\\max}}.\n\n    Katz centrality computes the relative influence of a node within a\n    network by measuring the number of the immediate neighbors (first\n    degree nodes) and also all other nodes in the network that connect\n    to the node under consideration through these immediate neighbors.\n\n    Extra weight can be provided to immediate neighbors through the\n    parameter $\\beta$.  Connections made with distant neighbors\n    are, however, penalized by an attenuation factor $\\alpha$ which\n    should be strictly less than the inverse largest eigenvalue of the\n    adjacency matrix in order for the Katz centrality to be computed\n    correctly. More information is provided in [1]_.\n\n    Parameters\n    ----------\n    G : graph\n      A NetworkX graph\n\n    alpha : float\n      Attenuation factor\n\n    beta : scalar or dictionary, optional (default=1.0)\n      Weight attributed to the immediate neighborhood. If not a scalar the\n      dictionary must have an value for every node.\n\n    normalized : bool\n      If True normalize the resulting values.\n\n    weight : None or string, optional\n      If None, all edge weights are considered equal.\n      Otherwise holds the name of the edge attribute used as weight.\n      In this measure the weight is interpreted as the connection strength.\n\n    Returns\n    -------\n    nodes : dictionary\n       Dictionary of nodes with Katz centrality as the value.\n\n    Raises\n    ------\n    NetworkXError\n       If the parameter `beta` is not a scalar but lacks a value for at least\n       one node\n\n    Examples\n    --------\n    >>> import math\n    >>> G = nx.path_graph(4)\n    >>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix\n    >>> centrality = nx.katz_centrality_numpy(G, 1 / phi)\n    >>> for n, c in sorted(centrality.items()):\n    ...     print(f\"{n} {c:.2f}\")\n    0 0.37\n    1 0.60\n    2 0.60\n    3 0.37\n\n    See Also\n    --------\n    katz_centrality\n    eigenvector_centrality_numpy\n    eigenvector_centrality\n    pagerank\n    hits\n\n    Notes\n    -----\n    Katz centrality was introduced by [2]_.\n\n    This algorithm uses a direct linear solver to solve the above equation.\n    The parameter ``alpha`` should be strictly less than the inverse of largest\n    eigenvalue of the adjacency matrix for there to be a solution.\n    You can use ``max(nx.adjacency_spectrum(G))`` to get $\\lambda_{\\max}$ the largest\n    eigenvalue of the adjacency matrix.\n\n    When $\\alpha = 1/\\lambda_{\\max}$ and $\\beta=0$, Katz centrality is the same\n    as eigenvector centrality.\n\n    For directed graphs this finds \"left\" eigenvectors which corresponds\n    to the in-edges in the graph. For out-edges Katz centrality\n    first reverse the graph with ``G.reverse()``.\n\n    References\n    ----------\n    .. [1] Mark E. J. Newman:\n       Networks: An Introduction.\n       Oxford University Press, USA, 2010, p. 720.\n    .. [2] Leo Katz:\n       A New Status Index Derived from Sociometric Index.\n       Psychometrika 18(1):39\u201343, 1953\n       http://phya.snu.ac.kr/~dkim/PRL87278701.pdf\n    \"\"\"\n    import numpy as np\n\n    if len(G) == 0:\n        return {}\n    try:\n        nodelist = beta.keys()\n        if set(nodelist) != set(G):\n            raise nx.NetworkXError(\n                \"beta dictionary \" \"must have a value for every node\"\n            )\n        b = np.array(list(beta.values()), dtype=float)\n    except AttributeError:\n        nodelist = list(G)\n        try:\n            b = np.ones((len(nodelist), 1)) * float(beta)\n        except (TypeError, ValueError, AttributeError) as e:\n            raise nx.NetworkXError(\"beta must be a number\") from e\n\n    A = nx.adj_matrix(G, nodelist=nodelist, weight=weight).todense().T\n    n = A.shape[0]\n    centrality = np.linalg.solve(np.eye(n, n) - (alpha * A), b)\n    if normalized:\n        norm = np.sign(sum(centrality)) * np.linalg.norm(centrality)\n    else:\n        norm = 1.0\n    centrality = dict(zip(nodelist, map(float, centrality / norm)))\n    return centrality\n", "path": "networkx/algorithms/centrality/katz.py"}], "after_files": [{"content": "\"\"\"Katz centrality.\"\"\"\nfrom math import sqrt\n\nimport networkx as nx\nfrom networkx.utils import not_implemented_for\n\n__all__ = [\"katz_centrality\", \"katz_centrality_numpy\"]\n\n\n@not_implemented_for(\"multigraph\")\ndef katz_centrality(\n    G,\n    alpha=0.1,\n    beta=1.0,\n    max_iter=1000,\n    tol=1.0e-6,\n    nstart=None,\n    normalized=True,\n    weight=None,\n):\n    r\"\"\"Compute the Katz centrality for the nodes of the graph G.\n\n    Katz centrality computes the centrality for a node based on the centrality\n    of its neighbors. It is a generalization of the eigenvector centrality. The\n    Katz centrality for node $i$ is\n\n    .. math::\n\n        x_i = \\alpha \\sum_{j} A_{ij} x_j + \\beta,\n\n    where $A$ is the adjacency matrix of graph G with eigenvalues $\\lambda$.\n\n    The parameter $\\beta$ controls the initial centrality and\n\n    .. math::\n\n        \\alpha < \\frac{1}{\\lambda_{\\max}}.\n\n    Katz centrality computes the relative influence of a node within a\n    network by measuring the number of the immediate neighbors (first\n    degree nodes) and also all other nodes in the network that connect\n    to the node under consideration through these immediate neighbors.\n\n    Extra weight can be provided to immediate neighbors through the\n    parameter $\\beta$.  Connections made with distant neighbors\n    are, however, penalized by an attenuation factor $\\alpha$ which\n    should be strictly less than the inverse largest eigenvalue of the\n    adjacency matrix in order for the Katz centrality to be computed\n    correctly. More information is provided in [1]_.\n\n    Parameters\n    ----------\n    G : graph\n      A NetworkX graph.\n\n    alpha : float\n      Attenuation factor\n\n    beta : scalar or dictionary, optional (default=1.0)\n      Weight attributed to the immediate neighborhood. If not a scalar, the\n      dictionary must have an value for every node.\n\n    max_iter : integer, optional (default=1000)\n      Maximum number of iterations in power method.\n\n    tol : float, optional (default=1.0e-6)\n      Error tolerance used to check convergence in power method iteration.\n\n    nstart : dictionary, optional\n      Starting value of Katz iteration for each node.\n\n    normalized : bool, optional (default=True)\n      If True normalize the resulting values.\n\n    weight : None or string, optional (default=None)\n      If None, all edge weights are considered equal.\n      Otherwise holds the name of the edge attribute used as weight.\n      In this measure the weight is interpreted as the connection strength.\n\n    Returns\n    -------\n    nodes : dictionary\n       Dictionary of nodes with Katz centrality as the value.\n\n    Raises\n    ------\n    NetworkXError\n       If the parameter `beta` is not a scalar but lacks a value for at least\n       one node\n\n    PowerIterationFailedConvergence\n        If the algorithm fails to converge to the specified tolerance\n        within the specified number of iterations of the power iteration\n        method.\n\n    Examples\n    --------\n    >>> import math\n    >>> G = nx.path_graph(4)\n    >>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix\n    >>> centrality = nx.katz_centrality(G, 1 / phi - 0.01)\n    >>> for n, c in sorted(centrality.items()):\n    ...     print(f\"{n} {c:.2f}\")\n    0 0.37\n    1 0.60\n    2 0.60\n    3 0.37\n\n    See Also\n    --------\n    katz_centrality_numpy\n    eigenvector_centrality\n    eigenvector_centrality_numpy\n    pagerank\n    hits\n\n    Notes\n    -----\n    Katz centrality was introduced by [2]_.\n\n    This algorithm it uses the power method to find the eigenvector\n    corresponding to the largest eigenvalue of the adjacency matrix of ``G``.\n    The parameter ``alpha`` should be strictly less than the inverse of largest\n    eigenvalue of the adjacency matrix for the algorithm to converge.\n    You can use ``max(nx.adjacency_spectrum(G))`` to get $\\lambda_{\\max}$ the largest\n    eigenvalue of the adjacency matrix.\n    The iteration will stop after ``max_iter`` iterations or an error tolerance of\n    ``number_of_nodes(G) * tol`` has been reached.\n\n    When $\\alpha = 1/\\lambda_{\\max}$ and $\\beta=0$, Katz centrality is the same\n    as eigenvector centrality.\n\n    For directed graphs this finds \"left\" eigenvectors which corresponds\n    to the in-edges in the graph. For out-edges Katz centrality\n    first reverse the graph with ``G.reverse()``.\n\n    References\n    ----------\n    .. [1] Mark E. J. Newman:\n       Networks: An Introduction.\n       Oxford University Press, USA, 2010, p. 720.\n    .. [2] Leo Katz:\n       A New Status Index Derived from Sociometric Index.\n       Psychometrika 18(1):39\u201343, 1953\n       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf\n    \"\"\"\n    if len(G) == 0:\n        return {}\n\n    nnodes = G.number_of_nodes()\n\n    if nstart is None:\n        # choose starting vector with entries of 0\n        x = {n: 0 for n in G}\n    else:\n        x = nstart\n\n    try:\n        b = dict.fromkeys(G, float(beta))\n    except (TypeError, ValueError, AttributeError) as e:\n        b = beta\n        if set(beta) != set(G):\n            raise nx.NetworkXError(\n                \"beta dictionary \" \"must have a value for every node\"\n            ) from e\n\n    # make up to max_iter iterations\n    for i in range(max_iter):\n        xlast = x\n        x = dict.fromkeys(xlast, 0)\n        # do the multiplication y^T = Alpha * x^T A - Beta\n        for n in x:\n            for nbr in G[n]:\n                x[nbr] += xlast[n] * G[n][nbr].get(weight, 1)\n        for n in x:\n            x[n] = alpha * x[n] + b[n]\n\n        # check convergence\n        err = sum([abs(x[n] - xlast[n]) for n in x])\n        if err < nnodes * tol:\n            if normalized:\n                # normalize vector\n                try:\n                    s = 1.0 / sqrt(sum(v ** 2 for v in x.values()))\n                # this should never be zero?\n                except ZeroDivisionError:\n                    s = 1.0\n            else:\n                s = 1\n            for n in x:\n                x[n] *= s\n            return x\n    raise nx.PowerIterationFailedConvergence(max_iter)\n\n\n@not_implemented_for(\"multigraph\")\ndef katz_centrality_numpy(G, alpha=0.1, beta=1.0, normalized=True, weight=None):\n    r\"\"\"Compute the Katz centrality for the graph G.\n\n    Katz centrality computes the centrality for a node based on the centrality\n    of its neighbors. It is a generalization of the eigenvector centrality. The\n    Katz centrality for node $i$ is\n\n    .. math::\n\n        x_i = \\alpha \\sum_{j} A_{ij} x_j + \\beta,\n\n    where $A$ is the adjacency matrix of graph G with eigenvalues $\\lambda$.\n\n    The parameter $\\beta$ controls the initial centrality and\n\n    .. math::\n\n        \\alpha < \\frac{1}{\\lambda_{\\max}}.\n\n    Katz centrality computes the relative influence of a node within a\n    network by measuring the number of the immediate neighbors (first\n    degree nodes) and also all other nodes in the network that connect\n    to the node under consideration through these immediate neighbors.\n\n    Extra weight can be provided to immediate neighbors through the\n    parameter $\\beta$.  Connections made with distant neighbors\n    are, however, penalized by an attenuation factor $\\alpha$ which\n    should be strictly less than the inverse largest eigenvalue of the\n    adjacency matrix in order for the Katz centrality to be computed\n    correctly. More information is provided in [1]_.\n\n    Parameters\n    ----------\n    G : graph\n      A NetworkX graph\n\n    alpha : float\n      Attenuation factor\n\n    beta : scalar or dictionary, optional (default=1.0)\n      Weight attributed to the immediate neighborhood. If not a scalar the\n      dictionary must have an value for every node.\n\n    normalized : bool\n      If True normalize the resulting values.\n\n    weight : None or string, optional\n      If None, all edge weights are considered equal.\n      Otherwise holds the name of the edge attribute used as weight.\n      In this measure the weight is interpreted as the connection strength.\n\n    Returns\n    -------\n    nodes : dictionary\n       Dictionary of nodes with Katz centrality as the value.\n\n    Raises\n    ------\n    NetworkXError\n       If the parameter `beta` is not a scalar but lacks a value for at least\n       one node\n\n    Examples\n    --------\n    >>> import math\n    >>> G = nx.path_graph(4)\n    >>> phi = (1 + math.sqrt(5)) / 2.0  # largest eigenvalue of adj matrix\n    >>> centrality = nx.katz_centrality_numpy(G, 1 / phi)\n    >>> for n, c in sorted(centrality.items()):\n    ...     print(f\"{n} {c:.2f}\")\n    0 0.37\n    1 0.60\n    2 0.60\n    3 0.37\n\n    See Also\n    --------\n    katz_centrality\n    eigenvector_centrality_numpy\n    eigenvector_centrality\n    pagerank\n    hits\n\n    Notes\n    -----\n    Katz centrality was introduced by [2]_.\n\n    This algorithm uses a direct linear solver to solve the above equation.\n    The parameter ``alpha`` should be strictly less than the inverse of largest\n    eigenvalue of the adjacency matrix for there to be a solution.\n    You can use ``max(nx.adjacency_spectrum(G))`` to get $\\lambda_{\\max}$ the largest\n    eigenvalue of the adjacency matrix.\n\n    When $\\alpha = 1/\\lambda_{\\max}$ and $\\beta=0$, Katz centrality is the same\n    as eigenvector centrality.\n\n    For directed graphs this finds \"left\" eigenvectors which corresponds\n    to the in-edges in the graph. For out-edges Katz centrality\n    first reverse the graph with ``G.reverse()``.\n\n    References\n    ----------\n    .. [1] Mark E. J. Newman:\n       Networks: An Introduction.\n       Oxford University Press, USA, 2010, p. 720.\n    .. [2] Leo Katz:\n       A New Status Index Derived from Sociometric Index.\n       Psychometrika 18(1):39\u201343, 1953\n       https://link.springer.com/content/pdf/10.1007/BF02289026.pdf\n    \"\"\"\n    import numpy as np\n\n    if len(G) == 0:\n        return {}\n    try:\n        nodelist = beta.keys()\n        if set(nodelist) != set(G):\n            raise nx.NetworkXError(\n                \"beta dictionary \" \"must have a value for every node\"\n            )\n        b = np.array(list(beta.values()), dtype=float)\n    except AttributeError:\n        nodelist = list(G)\n        try:\n            b = np.ones((len(nodelist), 1)) * float(beta)\n        except (TypeError, ValueError, AttributeError) as e:\n            raise nx.NetworkXError(\"beta must be a number\") from e\n\n    A = nx.adj_matrix(G, nodelist=nodelist, weight=weight).todense().T\n    n = A.shape[0]\n    centrality = np.linalg.solve(np.eye(n, n) - (alpha * A), b)\n    if normalized:\n        norm = np.sign(sum(centrality)) * np.linalg.norm(centrality)\n    else:\n        norm = 1.0\n    centrality = dict(zip(nodelist, map(float, centrality / norm)))\n    return centrality\n", "path": "networkx/algorithms/centrality/katz.py"}]}