We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Wrong degree_assortativity_coefficient for directed graphs
### Current Behavior
``degree_assortativity_coefficient`` will fail for most directed graphs except if the set of in- or out-degrees is the same as the set of total-degrees.
This issue was introduced in 2.6 by #4928 ([L78](https://github.com/networkx/networkx/pull/4928/files#diff-76675aa4f0d3a79d394219c8e15ec346b3f5af9f4a733d5ef9e7026421d43bd9R78)).

### Expected Behavior
The mapping should include all relevant in- and out-degrees for directed graphs.

### Steps to Reproduce
```python
G = nx.DiGraph()
G.add_edges_from([(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 2)])

nx.degree_assortativity_coefficient(G)  # returns NaN
nx.degree_pearson_correlation_coefficient(G)  # returns the correct value 0.14852
```

### Environment
Python version: 3.9
NetworkX version: 2.6+


--- 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/assortativity/correlation.py`
Content:
```
1 """Node assortativity coefficients and correlation measures.
2 """
3 from networkx.algorithms.assortativity.mixing import (
4     degree_mixing_matrix,
5     attribute_mixing_matrix,
6     numeric_mixing_matrix,
7 )
8 from networkx.algorithms.assortativity.pairs import node_degree_xy
9 
10 __all__ = [
11     "degree_pearson_correlation_coefficient",
12     "degree_assortativity_coefficient",
13     "attribute_assortativity_coefficient",
14     "numeric_assortativity_coefficient",
15 ]
16 
17 
18 def degree_assortativity_coefficient(G, x="out", y="in", weight=None, nodes=None):
19     """Compute degree assortativity of graph.
20 
21     Assortativity measures the similarity of connections
22     in the graph with respect to the node degree.
23 
24     Parameters
25     ----------
26     G : NetworkX graph
27 
28     x: string ('in','out')
29        The degree type for source node (directed graphs only).
30 
31     y: string ('in','out')
32        The degree type for target node (directed graphs only).
33 
34     weight: string or None, optional (default=None)
35        The edge attribute that holds the numerical value used
36        as a weight.  If None, then each edge has weight 1.
37        The degree is the sum of the edge weights adjacent to the node.
38 
39     nodes: list or iterable (optional)
40         Compute degree assortativity only for nodes in container.
41         The default is all nodes.
42 
43     Returns
44     -------
45     r : float
46        Assortativity of graph by degree.
47 
48     Examples
49     --------
50     >>> G = nx.path_graph(4)
51     >>> r = nx.degree_assortativity_coefficient(G)
52     >>> print(f"{r:3.1f}")
53     -0.5
54 
55     See Also
56     --------
57     attribute_assortativity_coefficient
58     numeric_assortativity_coefficient
59     degree_mixing_dict
60     degree_mixing_matrix
61 
62     Notes
63     -----
64     This computes Eq. (21) in Ref. [1]_ , where e is the joint
65     probability distribution (mixing matrix) of the degrees.  If G is
66     directed than the matrix e is the joint probability of the
67     user-specified degree type for the source and target.
68 
69     References
70     ----------
71     .. [1] M. E. J. Newman, Mixing patterns in networks,
72        Physical Review E, 67 026126, 2003
73     .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
74        Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
75     """
76     if nodes is None:
77         nodes = G.nodes
78     degrees = set([d for n, d in G.degree(nodes, weight=weight)])
79     mapping = {d: i for i, d, in enumerate(degrees)}
80     M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
81     return numeric_ac(M, mapping=mapping)
82 
83 
84 def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None):
85     """Compute degree assortativity of graph.
86 
87     Assortativity measures the similarity of connections
88     in the graph with respect to the node degree.
89 
90     This is the same as degree_assortativity_coefficient but uses the
91     potentially faster scipy.stats.pearsonr function.
92 
93     Parameters
94     ----------
95     G : NetworkX graph
96 
97     x: string ('in','out')
98        The degree type for source node (directed graphs only).
99 
100     y: string ('in','out')
101        The degree type for target node (directed graphs only).
102 
103     weight: string or None, optional (default=None)
104        The edge attribute that holds the numerical value used
105        as a weight.  If None, then each edge has weight 1.
106        The degree is the sum of the edge weights adjacent to the node.
107 
108     nodes: list or iterable (optional)
109         Compute pearson correlation of degrees only for specified nodes.
110         The default is all nodes.
111 
112     Returns
113     -------
114     r : float
115        Assortativity of graph by degree.
116 
117     Examples
118     --------
119     >>> G = nx.path_graph(4)
120     >>> r = nx.degree_pearson_correlation_coefficient(G)
121     >>> print(f"{r:3.1f}")
122     -0.5
123 
124     Notes
125     -----
126     This calls scipy.stats.pearsonr.
127 
128     References
129     ----------
130     .. [1] M. E. J. Newman, Mixing patterns in networks
131            Physical Review E, 67 026126, 2003
132     .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.
133        Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).
134     """
135     import scipy as sp
136     import scipy.stats  # call as sp.stats
137 
138     xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)
139     x, y = zip(*xy)
140     return sp.stats.pearsonr(x, y)[0]
141 
142 
143 def attribute_assortativity_coefficient(G, attribute, nodes=None):
144     """Compute assortativity for node attributes.
145 
146     Assortativity measures the similarity of connections
147     in the graph with respect to the given attribute.
148 
149     Parameters
150     ----------
151     G : NetworkX graph
152 
153     attribute : string
154         Node attribute key
155 
156     nodes: list or iterable (optional)
157         Compute attribute assortativity for nodes in container.
158         The default is all nodes.
159 
160     Returns
161     -------
162     r: float
163        Assortativity of graph for given attribute
164 
165     Examples
166     --------
167     >>> G = nx.Graph()
168     >>> G.add_nodes_from([0, 1], color="red")
169     >>> G.add_nodes_from([2, 3], color="blue")
170     >>> G.add_edges_from([(0, 1), (2, 3)])
171     >>> print(nx.attribute_assortativity_coefficient(G, "color"))
172     1.0
173 
174     Notes
175     -----
176     This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),
177     where M is the joint probability distribution (mixing matrix)
178     of the specified attribute.
179 
180     References
181     ----------
182     .. [1] M. E. J. Newman, Mixing patterns in networks,
183        Physical Review E, 67 026126, 2003
184     """
185     M = attribute_mixing_matrix(G, attribute, nodes)
186     return attribute_ac(M)
187 
188 
189 def numeric_assortativity_coefficient(G, attribute, nodes=None):
190     """Compute assortativity for numerical node attributes.
191 
192     Assortativity measures the similarity of connections
193     in the graph with respect to the given numeric attribute.
194 
195     Parameters
196     ----------
197     G : NetworkX graph
198 
199     attribute : string
200         Node attribute key.
201 
202     nodes: list or iterable (optional)
203         Compute numeric assortativity only for attributes of nodes in
204         container. The default is all nodes.
205 
206     Returns
207     -------
208     r: float
209        Assortativity of graph for given attribute
210 
211     Examples
212     --------
213     >>> G = nx.Graph()
214     >>> G.add_nodes_from([0, 1], size=2)
215     >>> G.add_nodes_from([2, 3], size=3)
216     >>> G.add_edges_from([(0, 1), (2, 3)])
217     >>> print(nx.numeric_assortativity_coefficient(G, "size"))
218     1.0
219 
220     Notes
221     -----
222     This computes Eq. (21) in Ref. [1]_ , for the mixing matrix
223     of the specified attribute.
224 
225     References
226     ----------
227     .. [1] M. E. J. Newman, Mixing patterns in networks
228            Physical Review E, 67 026126, 2003
229     """
230     if nodes is None:
231         nodes = G.nodes
232     vals = set(G.nodes[n][attribute] for n in nodes)
233     mapping = {d: i for i, d, in enumerate(vals)}
234     M = attribute_mixing_matrix(G, attribute, nodes, mapping)
235     return numeric_ac(M, mapping)
236 
237 
238 def attribute_ac(M):
239     """Compute assortativity for attribute matrix M.
240 
241     Parameters
242     ----------
243     M : numpy.ndarray
244         2D ndarray representing the attribute mixing matrix.
245 
246     Notes
247     -----
248     This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),
249     where e is the joint probability distribution (mixing matrix)
250     of the specified attribute.
251 
252     References
253     ----------
254     .. [1] M. E. J. Newman, Mixing patterns in networks,
255        Physical Review E, 67 026126, 2003
256     """
257     if M.sum() != 1.0:
258         M = M / M.sum()
259     s = (M @ M).sum()
260     t = M.trace()
261     r = (t - s) / (1 - s)
262     return r
263 
264 
265 def numeric_ac(M, mapping):
266     # M is a numpy matrix or array
267     # numeric assortativity coefficient, pearsonr
268     import numpy as np
269 
270     if M.sum() != 1.0:
271         M = M / float(M.sum())
272     nx, ny = M.shape  # nx=ny
273     x = np.array(list(mapping.keys()))
274     y = x  # x and y have the same support
275     idx = list(mapping.values())
276     a = M.sum(axis=0)
277     b = M.sum(axis=1)
278     vara = (a[idx] * x ** 2).sum() - ((a[idx] * x).sum()) ** 2
279     varb = (b[idx] * y ** 2).sum() - ((b[idx] * y).sum()) ** 2
280     xy = np.outer(x, y)
281     ab = np.outer(a[idx], b[idx])
282     return (xy * (M - ab)).sum() / np.sqrt(vara * varb)
283
```
--- 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/assortativity/correlation.py b/networkx/algorithms/assortativity/correlation.py
--- a/networkx/algorithms/assortativity/correlation.py
+++ b/networkx/algorithms/assortativity/correlation.py
@@ -75,9 +75,27 @@
     """
     if nodes is None:
         nodes = G.nodes
-    degrees = set([d for n, d in G.degree(nodes, weight=weight)])
+
+    degrees = None
+
+    if G.is_directed():
+        indeg = (
+            set([d for _, d in G.in_degree(nodes, weight=weight)])
+            if "in" in (x, y)
+            else set()
+        )
+        outdeg = (
+            set([d for _, d in G.out_degree(nodes, weight=weight)])
+            if "out" in (x, y)
+            else set()
+        )
+        degrees = set.union(indeg, outdeg)
+    else:
+        degrees = set([d for _, d in G.degree(nodes, weight=weight)])
+
     mapping = {d: i for i, d, in enumerate(degrees)}
     M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)
+
     return numeric_ac(M, mapping=mapping)

{"golden_diff": "diff --git a/networkx/algorithms/assortativity/correlation.py b/networkx/algorithms/assortativity/correlation.py\n--- a/networkx/algorithms/assortativity/correlation.py\n+++ b/networkx/algorithms/assortativity/correlation.py\n@@ -75,9 +75,27 @@\n     \"\"\"\n     if nodes is None:\n         nodes = G.nodes\n-    degrees = set([d for n, d in G.degree(nodes, weight=weight)])\n+\n+    degrees = None\n+\n+    if G.is_directed():\n+        indeg = (\n+            set([d for _, d in G.in_degree(nodes, weight=weight)])\n+            if \"in\" in (x, y)\n+            else set()\n+        )\n+        outdeg = (\n+            set([d for _, d in G.out_degree(nodes, weight=weight)])\n+            if \"out\" in (x, y)\n+            else set()\n+        )\n+        degrees = set.union(indeg, outdeg)\n+    else:\n+        degrees = set([d for _, d in G.degree(nodes, weight=weight)])\n+\n     mapping = {d: i for i, d, in enumerate(degrees)}\n     M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)\n+\n     return numeric_ac(M, mapping=mapping)\n", "issue": "Wrong degree_assortativity_coefficient for directed graphs\n### Current Behavior\r\n``degree_assortativity_coefficient`` will fail for most directed graphs except if the set of in- or out-degrees is the same as the set of total-degrees.\r\nThis issue was introduced in 2.6 by #4928 ([L78](https://github.com/networkx/networkx/pull/4928/files#diff-76675aa4f0d3a79d394219c8e15ec346b3f5af9f4a733d5ef9e7026421d43bd9R78)).\r\n\r\n### Expected Behavior\r\nThe mapping should include all relevant in- and out-degrees for directed graphs.\r\n\r\n### Steps to Reproduce\r\n```python\r\nG = nx.DiGraph()\r\nG.add_edges_from([(0, 3), (1, 0), (1, 2), (2, 4), (4, 1), (4, 3), (4, 2)])\r\n\r\nnx.degree_assortativity_coefficient(G)  # returns NaN\r\nnx.degree_pearson_correlation_coefficient(G)  # returns the correct value 0.14852\r\n```\r\n\r\n### Environment\r\nPython version: 3.9\r\nNetworkX version: 2.6+\r\n\n", "before_files": [{"content": "\"\"\"Node assortativity coefficients and correlation measures.\n\"\"\"\nfrom networkx.algorithms.assortativity.mixing import (\n    degree_mixing_matrix,\n    attribute_mixing_matrix,\n    numeric_mixing_matrix,\n)\nfrom networkx.algorithms.assortativity.pairs import node_degree_xy\n\n__all__ = [\n    \"degree_pearson_correlation_coefficient\",\n    \"degree_assortativity_coefficient\",\n    \"attribute_assortativity_coefficient\",\n    \"numeric_assortativity_coefficient\",\n]\n\n\ndef degree_assortativity_coefficient(G, x=\"out\", y=\"in\", weight=None, nodes=None):\n    \"\"\"Compute degree assortativity of graph.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the node degree.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    x: string ('in','out')\n       The degree type for source node (directed graphs only).\n\n    y: string ('in','out')\n       The degree type for target node (directed graphs only).\n\n    weight: string or None, optional (default=None)\n       The edge attribute that holds the numerical value used\n       as a weight.  If None, then each edge has weight 1.\n       The degree is the sum of the edge weights adjacent to the node.\n\n    nodes: list or iterable (optional)\n        Compute degree assortativity only for nodes in container.\n        The default is all nodes.\n\n    Returns\n    -------\n    r : float\n       Assortativity of graph by degree.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> r = nx.degree_assortativity_coefficient(G)\n    >>> print(f\"{r:3.1f}\")\n    -0.5\n\n    See Also\n    --------\n    attribute_assortativity_coefficient\n    numeric_assortativity_coefficient\n    degree_mixing_dict\n    degree_mixing_matrix\n\n    Notes\n    -----\n    This computes Eq. (21) in Ref. [1]_ , where e is the joint\n    probability distribution (mixing matrix) of the degrees.  If G is\n    directed than the matrix e is the joint probability of the\n    user-specified degree type for the source and target.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks,\n       Physical Review E, 67 026126, 2003\n    .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.\n       Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).\n    \"\"\"\n    if nodes is None:\n        nodes = G.nodes\n    degrees = set([d for n, d in G.degree(nodes, weight=weight)])\n    mapping = {d: i for i, d, in enumerate(degrees)}\n    M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)\n    return numeric_ac(M, mapping=mapping)\n\n\ndef degree_pearson_correlation_coefficient(G, x=\"out\", y=\"in\", weight=None, nodes=None):\n    \"\"\"Compute degree assortativity of graph.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the node degree.\n\n    This is the same as degree_assortativity_coefficient but uses the\n    potentially faster scipy.stats.pearsonr function.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    x: string ('in','out')\n       The degree type for source node (directed graphs only).\n\n    y: string ('in','out')\n       The degree type for target node (directed graphs only).\n\n    weight: string or None, optional (default=None)\n       The edge attribute that holds the numerical value used\n       as a weight.  If None, then each edge has weight 1.\n       The degree is the sum of the edge weights adjacent to the node.\n\n    nodes: list or iterable (optional)\n        Compute pearson correlation of degrees only for specified nodes.\n        The default is all nodes.\n\n    Returns\n    -------\n    r : float\n       Assortativity of graph by degree.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> r = nx.degree_pearson_correlation_coefficient(G)\n    >>> print(f\"{r:3.1f}\")\n    -0.5\n\n    Notes\n    -----\n    This calls scipy.stats.pearsonr.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks\n           Physical Review E, 67 026126, 2003\n    .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.\n       Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).\n    \"\"\"\n    import scipy as sp\n    import scipy.stats  # call as sp.stats\n\n    xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)\n    x, y = zip(*xy)\n    return sp.stats.pearsonr(x, y)[0]\n\n\ndef attribute_assortativity_coefficient(G, attribute, nodes=None):\n    \"\"\"Compute assortativity for node attributes.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the given attribute.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    attribute : string\n        Node attribute key\n\n    nodes: list or iterable (optional)\n        Compute attribute assortativity for nodes in container.\n        The default is all nodes.\n\n    Returns\n    -------\n    r: float\n       Assortativity of graph for given attribute\n\n    Examples\n    --------\n    >>> G = nx.Graph()\n    >>> G.add_nodes_from([0, 1], color=\"red\")\n    >>> G.add_nodes_from([2, 3], color=\"blue\")\n    >>> G.add_edges_from([(0, 1), (2, 3)])\n    >>> print(nx.attribute_assortativity_coefficient(G, \"color\"))\n    1.0\n\n    Notes\n    -----\n    This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),\n    where M is the joint probability distribution (mixing matrix)\n    of the specified attribute.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks,\n       Physical Review E, 67 026126, 2003\n    \"\"\"\n    M = attribute_mixing_matrix(G, attribute, nodes)\n    return attribute_ac(M)\n\n\ndef numeric_assortativity_coefficient(G, attribute, nodes=None):\n    \"\"\"Compute assortativity for numerical node attributes.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the given numeric attribute.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    attribute : string\n        Node attribute key.\n\n    nodes: list or iterable (optional)\n        Compute numeric assortativity only for attributes of nodes in\n        container. The default is all nodes.\n\n    Returns\n    -------\n    r: float\n       Assortativity of graph for given attribute\n\n    Examples\n    --------\n    >>> G = nx.Graph()\n    >>> G.add_nodes_from([0, 1], size=2)\n    >>> G.add_nodes_from([2, 3], size=3)\n    >>> G.add_edges_from([(0, 1), (2, 3)])\n    >>> print(nx.numeric_assortativity_coefficient(G, \"size\"))\n    1.0\n\n    Notes\n    -----\n    This computes Eq. (21) in Ref. [1]_ , for the mixing matrix\n    of the specified attribute.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks\n           Physical Review E, 67 026126, 2003\n    \"\"\"\n    if nodes is None:\n        nodes = G.nodes\n    vals = set(G.nodes[n][attribute] for n in nodes)\n    mapping = {d: i for i, d, in enumerate(vals)}\n    M = attribute_mixing_matrix(G, attribute, nodes, mapping)\n    return numeric_ac(M, mapping)\n\n\ndef attribute_ac(M):\n    \"\"\"Compute assortativity for attribute matrix M.\n\n    Parameters\n    ----------\n    M : numpy.ndarray\n        2D ndarray representing the attribute mixing matrix.\n\n    Notes\n    -----\n    This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),\n    where e is the joint probability distribution (mixing matrix)\n    of the specified attribute.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks,\n       Physical Review E, 67 026126, 2003\n    \"\"\"\n    if M.sum() != 1.0:\n        M = M / M.sum()\n    s = (M @ M).sum()\n    t = M.trace()\n    r = (t - s) / (1 - s)\n    return r\n\n\ndef numeric_ac(M, mapping):\n    # M is a numpy matrix or array\n    # numeric assortativity coefficient, pearsonr\n    import numpy as np\n\n    if M.sum() != 1.0:\n        M = M / float(M.sum())\n    nx, ny = M.shape  # nx=ny\n    x = np.array(list(mapping.keys()))\n    y = x  # x and y have the same support\n    idx = list(mapping.values())\n    a = M.sum(axis=0)\n    b = M.sum(axis=1)\n    vara = (a[idx] * x ** 2).sum() - ((a[idx] * x).sum()) ** 2\n    varb = (b[idx] * y ** 2).sum() - ((b[idx] * y).sum()) ** 2\n    xy = np.outer(x, y)\n    ab = np.outer(a[idx], b[idx])\n    return (xy * (M - ab)).sum() / np.sqrt(vara * varb)\n", "path": "networkx/algorithms/assortativity/correlation.py"}], "after_files": [{"content": "\"\"\"Node assortativity coefficients and correlation measures.\n\"\"\"\nfrom networkx.algorithms.assortativity.mixing import (\n    degree_mixing_matrix,\n    attribute_mixing_matrix,\n    numeric_mixing_matrix,\n)\nfrom networkx.algorithms.assortativity.pairs import node_degree_xy\n\n__all__ = [\n    \"degree_pearson_correlation_coefficient\",\n    \"degree_assortativity_coefficient\",\n    \"attribute_assortativity_coefficient\",\n    \"numeric_assortativity_coefficient\",\n]\n\n\ndef degree_assortativity_coefficient(G, x=\"out\", y=\"in\", weight=None, nodes=None):\n    \"\"\"Compute degree assortativity of graph.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the node degree.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    x: string ('in','out')\n       The degree type for source node (directed graphs only).\n\n    y: string ('in','out')\n       The degree type for target node (directed graphs only).\n\n    weight: string or None, optional (default=None)\n       The edge attribute that holds the numerical value used\n       as a weight.  If None, then each edge has weight 1.\n       The degree is the sum of the edge weights adjacent to the node.\n\n    nodes: list or iterable (optional)\n        Compute degree assortativity only for nodes in container.\n        The default is all nodes.\n\n    Returns\n    -------\n    r : float\n       Assortativity of graph by degree.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> r = nx.degree_assortativity_coefficient(G)\n    >>> print(f\"{r:3.1f}\")\n    -0.5\n\n    See Also\n    --------\n    attribute_assortativity_coefficient\n    numeric_assortativity_coefficient\n    degree_mixing_dict\n    degree_mixing_matrix\n\n    Notes\n    -----\n    This computes Eq. (21) in Ref. [1]_ , where e is the joint\n    probability distribution (mixing matrix) of the degrees.  If G is\n    directed than the matrix e is the joint probability of the\n    user-specified degree type for the source and target.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks,\n       Physical Review E, 67 026126, 2003\n    .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.\n       Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).\n    \"\"\"\n    if nodes is None:\n        nodes = G.nodes\n\n    degrees = None\n\n    if G.is_directed():\n        indeg = (\n            set([d for _, d in G.in_degree(nodes, weight=weight)])\n            if \"in\" in (x, y)\n            else set()\n        )\n        outdeg = (\n            set([d for _, d in G.out_degree(nodes, weight=weight)])\n            if \"out\" in (x, y)\n            else set()\n        )\n        degrees = set.union(indeg, outdeg)\n    else:\n        degrees = set([d for _, d in G.degree(nodes, weight=weight)])\n\n    mapping = {d: i for i, d, in enumerate(degrees)}\n    M = degree_mixing_matrix(G, x=x, y=y, nodes=nodes, weight=weight, mapping=mapping)\n\n    return numeric_ac(M, mapping=mapping)\n\n\ndef degree_pearson_correlation_coefficient(G, x=\"out\", y=\"in\", weight=None, nodes=None):\n    \"\"\"Compute degree assortativity of graph.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the node degree.\n\n    This is the same as degree_assortativity_coefficient but uses the\n    potentially faster scipy.stats.pearsonr function.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    x: string ('in','out')\n       The degree type for source node (directed graphs only).\n\n    y: string ('in','out')\n       The degree type for target node (directed graphs only).\n\n    weight: string or None, optional (default=None)\n       The edge attribute that holds the numerical value used\n       as a weight.  If None, then each edge has weight 1.\n       The degree is the sum of the edge weights adjacent to the node.\n\n    nodes: list or iterable (optional)\n        Compute pearson correlation of degrees only for specified nodes.\n        The default is all nodes.\n\n    Returns\n    -------\n    r : float\n       Assortativity of graph by degree.\n\n    Examples\n    --------\n    >>> G = nx.path_graph(4)\n    >>> r = nx.degree_pearson_correlation_coefficient(G)\n    >>> print(f\"{r:3.1f}\")\n    -0.5\n\n    Notes\n    -----\n    This calls scipy.stats.pearsonr.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks\n           Physical Review E, 67 026126, 2003\n    .. [2] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M.\n       Edge direction and the structure of networks, PNAS 107, 10815-20 (2010).\n    \"\"\"\n    import scipy as sp\n    import scipy.stats  # call as sp.stats\n\n    xy = node_degree_xy(G, x=x, y=y, nodes=nodes, weight=weight)\n    x, y = zip(*xy)\n    return sp.stats.pearsonr(x, y)[0]\n\n\ndef attribute_assortativity_coefficient(G, attribute, nodes=None):\n    \"\"\"Compute assortativity for node attributes.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the given attribute.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    attribute : string\n        Node attribute key\n\n    nodes: list or iterable (optional)\n        Compute attribute assortativity for nodes in container.\n        The default is all nodes.\n\n    Returns\n    -------\n    r: float\n       Assortativity of graph for given attribute\n\n    Examples\n    --------\n    >>> G = nx.Graph()\n    >>> G.add_nodes_from([0, 1], color=\"red\")\n    >>> G.add_nodes_from([2, 3], color=\"blue\")\n    >>> G.add_edges_from([(0, 1), (2, 3)])\n    >>> print(nx.attribute_assortativity_coefficient(G, \"color\"))\n    1.0\n\n    Notes\n    -----\n    This computes Eq. (2) in Ref. [1]_ , (trace(M)-sum(M^2))/(1-sum(M^2)),\n    where M is the joint probability distribution (mixing matrix)\n    of the specified attribute.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks,\n       Physical Review E, 67 026126, 2003\n    \"\"\"\n    M = attribute_mixing_matrix(G, attribute, nodes)\n    return attribute_ac(M)\n\n\ndef numeric_assortativity_coefficient(G, attribute, nodes=None):\n    \"\"\"Compute assortativity for numerical node attributes.\n\n    Assortativity measures the similarity of connections\n    in the graph with respect to the given numeric attribute.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    attribute : string\n        Node attribute key.\n\n    nodes: list or iterable (optional)\n        Compute numeric assortativity only for attributes of nodes in\n        container. The default is all nodes.\n\n    Returns\n    -------\n    r: float\n       Assortativity of graph for given attribute\n\n    Examples\n    --------\n    >>> G = nx.Graph()\n    >>> G.add_nodes_from([0, 1], size=2)\n    >>> G.add_nodes_from([2, 3], size=3)\n    >>> G.add_edges_from([(0, 1), (2, 3)])\n    >>> print(nx.numeric_assortativity_coefficient(G, \"size\"))\n    1.0\n\n    Notes\n    -----\n    This computes Eq. (21) in Ref. [1]_ , for the mixing matrix\n    of the specified attribute.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks\n           Physical Review E, 67 026126, 2003\n    \"\"\"\n    if nodes is None:\n        nodes = G.nodes\n    vals = set(G.nodes[n][attribute] for n in nodes)\n    mapping = {d: i for i, d, in enumerate(vals)}\n    M = attribute_mixing_matrix(G, attribute, nodes, mapping)\n    return numeric_ac(M, mapping)\n\n\ndef attribute_ac(M):\n    \"\"\"Compute assortativity for attribute matrix M.\n\n    Parameters\n    ----------\n    M : numpy.ndarray\n        2D ndarray representing the attribute mixing matrix.\n\n    Notes\n    -----\n    This computes Eq. (2) in Ref. [1]_ , (trace(e)-sum(e^2))/(1-sum(e^2)),\n    where e is the joint probability distribution (mixing matrix)\n    of the specified attribute.\n\n    References\n    ----------\n    .. [1] M. E. J. Newman, Mixing patterns in networks,\n       Physical Review E, 67 026126, 2003\n    \"\"\"\n    if M.sum() != 1.0:\n        M = M / M.sum()\n    s = (M @ M).sum()\n    t = M.trace()\n    r = (t - s) / (1 - s)\n    return r\n\n\ndef numeric_ac(M, mapping):\n    # M is a numpy matrix or array\n    # numeric assortativity coefficient, pearsonr\n    import numpy as np\n\n    if M.sum() != 1.0:\n        M = M / float(M.sum())\n    nx, ny = M.shape  # nx=ny\n    x = np.array(list(mapping.keys()))\n    y = x  # x and y have the same support\n    idx = list(mapping.values())\n    a = M.sum(axis=0)\n    b = M.sum(axis=1)\n    vara = (a[idx] * x ** 2).sum() - ((a[idx] * x).sum()) ** 2\n    varb = (b[idx] * y ** 2).sum() - ((b[idx] * y).sum()) ** 2\n    xy = np.outer(x, y)\n    ab = np.outer(a[idx], b[idx])\n    return (xy * (M - ab)).sum() / np.sqrt(vara * varb)\n", "path": "networkx/algorithms/assortativity/correlation.py"}]}