We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Mistake in computation of average neighbor degree for directed networks (migrated from Trac #639)
Original ticket https://networkx.lanl.gov/trac/ticket/639
Reported 2011-09-27 by Oleguer Sagarra <oleguer.sagarra, assigned to @hagberg.

There is a problem in the algorithm to compute the negihbor degree (and average neighbor degree) for directed networks. The thing is that as networkx is based on a dict of dicts one may follow the neighbors of a node "forward" but not "backwards", meaning that with the functions such as G.in_degree(G[n]) one lists the incoming degree of the neighbors of the node "n", neighbors meaning destination of directed edges starting at node n. For all this, the normalization factor used is wrong. Additionally, it has some bugs with division over zero values.

These features need to be better redefined for various reasons:

a) With directed networks one can compute 4 types of features divided into two subgroups:
       a.1) For the neighbors of a node n (by neighbors meaning ending points of directed edges starting at node n) one can compute the Incoming our outgoing degree of a node.
       a.2) For all predecessors of node n (meaning all sources of edges finishing in node n) one can compute the very same thing.

b) Additionally, accounting for the average connectivity (or average neighbor degree as a function of degree of a node) things get messy, because then one may compute 8 different features divided into two groups, providing different information:
        b.1) Consider all the neighbors (defined earlier) of node n. Consider all the nodes n in the net. For each node n compute the (in-degree, out-degree) of their neighbors, then average over all n nodes of (in-degree, out-degree) 'k'.
       b.2) The same for predecessors of degree n.

The current code can be adapted to do so, using the function G.reverse() to overcome the difficulty in quickly computing the predecessors of a node while keeping the code structure. But the documentation need to be rewritten and the normalization of the averages redone.

Reference :  Serrano, M.A., Maguitman, A., Boguna, M., Fortunato, S. & Vespignani, A. Decoding the structure of the WWW: facts versus sampling biases. Main 10 (2005).at http://arxiv.org/abs/cs/0511035

Simple example showing what I mean:
Case 1: Error in normalization division by 0

In [1]: import networkx as nx

In [2]: G=nx.DiGraph()

In [3]: G.add_edges_from(([1,2],[1,3],[1,4]))
## In [6]: nx.average_in_degree_connectivity(G)

ZeroDivisionError                         Traceback (most recent call last)
/Users/ugalss/<ipython-input-6-e2e455d286f8> in <module>()
----> 1 nx.average_in_degree_connectivity(G)

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/networkx-1.5-py2.7.egg/networkx/algorithms/neighbor_degree.pyc in average_in_degree_connectivity(G, nodes, weighted)
    205         raise nx.NetworkXError("Not defined for undirected graphs.")
    206     degree_method = G.in_degree
--> 207     return _avg_deg_conn(G, degree_method, nodes=nodes, weighted=weighted)
    208 average_in_degree_connectivity.__doc__=average_degree_connectivity.**doc**
    209 

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/networkx-1.5-py2.7.egg/networkx/algorithms/neighbor_degree.pyc in _avg_deg_conn(G, degree_method, nodes, weighted)
    141         dc[k]=avg
    142         if avg > 0:
--> 143             dc[k]/=dnorm[k]
    144     return dc
    145 

ZeroDivisionError: float division by zero

Case 2: Wrong computation of neighbor degree (incoming):

In [7]: G.add_edges_from(([2,3],[3,4],[4,2]))
In [8]: nx.average_neighbor_in_degree(G)
Out[8]: {1: 6.0, 2: 1.0, 3: 1.0, 4: 1.0} # This is wrong. The average in-degree should be 2 for neighbors of node 1.

I attach a new version of neighbor_degree.py with proposed (and commented) changes...


--- 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/connectivity.py`
Content:
```
1 #-*- coding: utf-8 -*-
2 #    Copyright (C) 2011 by 
3 #    Jordi Torrents <jtorrents@milnou.net>
4 #    Aric Hagberg <hagberg@lanl.gov>
5 #    All rights reserved.
6 #    BSD license.
7 from collections import defaultdict
8 import networkx as nx
9 __author__ = """\n""".join(['Jordi Torrents <jtorrents@milnou.net>',
10                             'Aric Hagberg (hagberg@lanl.gov)'])
11 __all__ = ['average_degree_connectivity',
12            'k_nearest_neighbors']
13 
14 def _avg_deg_conn(G, neighbors, source_degree, target_degree, 
15                   nodes=None, weight=None):
16     # "k nearest neighbors, or neighbor_connectivity
17     dsum = defaultdict(float)
18     dnorm = defaultdict(float)
19     for n,k in source_degree(nodes).items():
20         nbrdeg = target_degree(neighbors(n))
21         if weight is None:
22             s = float(sum(nbrdeg.values()))
23         else: # weight nbr degree by weight of (n,nbr) edge
24             s = float(sum((G[n][nbr].get(weight,1)*d 
25                            for nbr,d in nbrdeg.items())))
26         dnorm[k] += source_degree(n, weight=weight)
27         dsum[k] += s
28         
29     # normalize
30     dc = {}
31     for k,avg in dsum.items():
32         dc[k]=avg
33         norm = dnorm[k]
34         if avg > 0 and norm > 0:
35             dc[k]/=norm
36     return dc
37 
38 def average_degree_connectivity(G, source="in+out", target="in+out",
39                                 nodes=None, weight=None):
40     r"""Compute the average degree connectivity of graph.
41 
42     The average degree connectivity is the average nearest neighbor degree of
43     nodes with degree k. For weighted graphs, an analogous measure can 
44     be computed using the weighted average neighbors degree defined in 
45     [1]_, for a node `i`, as:
46 
47     .. math::
48 
49         k_{nn,i}^{w} = \frac{1}{s_i} \sum_{j \in N(i)} w_{ij} k_j
50 
51     where `s_i` is the weighted degree of node `i`, 
52     `w_{ij}` is the weight of the edge that links `i` and `j`,
53     and `N(i)` are the neighbors of node `i`.
54 
55     Parameters
56     ----------
57     G : NetworkX graph
58 
59     source :  "in"|"out"|"in+out" (default:"in+out")
60        Directed graphs only. Use "in"- or "out"-degree for source node.
61 
62     target : "in"|"out"|"in+out" (default:"in+out"
63        Directed graphs only. Use "in"- or "out"-degree for target node.
64 
65     nodes: list or iterable (optional)
66         Compute neighbor connectivity for these nodes. The default is all nodes.
67 
68     weight : string or None, optional (default=None)
69        The edge attribute that holds the numerical value used as a weight.
70        If None, then each edge has weight 1.
71 
72     Returns
73     -------
74     d: dict
75        A dictionary keyed by degree k with the value of average connectivity.
76     
77     Examples
78     --------
79     >>> G=nx.path_graph(4)
80     >>> G.edge[1][2]['weight'] = 3
81     >>> nx.k_nearest_neighbors(G)
82     {1: 2.0, 2: 1.5}
83     >>> nx.k_nearest_neighbors(G, weight='weight')
84     {1: 2.0, 2: 1.75}
85 
86     See also
87     --------
88     neighbors_average_degree
89 
90     Notes
91     -----
92     This algorithm is sometimes called "k nearest neighbors'.
93 
94     References
95     ----------    
96     .. [1] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, 
97        "The architecture of complex weighted networks". 
98        PNAS 101 (11): 3747–3752 (2004).
99     """
100     source_degree = G.degree
101     target_degree = G.degree
102     neighbors = G.neighbors
103     if G.is_directed():
104         direction = {'out':G.out_degree,
105                      'in':G.in_degree,
106                      'in+out': G.degree}
107         source_degree = direction[source]
108         target_degree = direction[target]
109         if source == 'in':
110             neighbors=G.predecessors
111         elif source == 'out':
112             neighbors=G.successors
113     return _avg_deg_conn(G, neighbors, source_degree, target_degree,
114                          nodes=nodes, weight=weight)
115 
116 k_nearest_neighbors=average_degree_connectivity
117
```
--- 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/connectivity.py b/networkx/algorithms/assortativity/connectivity.py
--- a/networkx/algorithms/assortativity/connectivity.py
+++ b/networkx/algorithms/assortativity/connectivity.py
@@ -21,8 +21,15 @@
         if weight is None:
             s = float(sum(nbrdeg.values()))
         else: # weight nbr degree by weight of (n,nbr) edge
-            s = float(sum((G[n][nbr].get(weight,1)*d 
-                           for nbr,d in nbrdeg.items())))
+            if neighbors == G.neighbors:
+                s = float(sum((G[n][nbr].get(weight,1)*d 
+                               for nbr,d in nbrdeg.items())))
+            elif neighbors == G.successors:
+                s = float(sum((G[n][nbr].get(weight,1)*d 
+                               for nbr,d in nbrdeg.items())))
+            elif neighbors == G.predecessors:
+                s = float(sum((G[nbr][n].get(weight,1)*d 
+                               for nbr,d in nbrdeg.items())))
         dnorm[k] += source_degree(n, weight=weight)
         dsum[k] += s

{"golden_diff": "diff --git a/networkx/algorithms/assortativity/connectivity.py b/networkx/algorithms/assortativity/connectivity.py\n--- a/networkx/algorithms/assortativity/connectivity.py\n+++ b/networkx/algorithms/assortativity/connectivity.py\n@@ -21,8 +21,15 @@\n         if weight is None:\n             s = float(sum(nbrdeg.values()))\n         else: # weight nbr degree by weight of (n,nbr) edge\n-            s = float(sum((G[n][nbr].get(weight,1)*d \n-                           for nbr,d in nbrdeg.items())))\n+            if neighbors == G.neighbors:\n+                s = float(sum((G[n][nbr].get(weight,1)*d \n+                               for nbr,d in nbrdeg.items())))\n+            elif neighbors == G.successors:\n+                s = float(sum((G[n][nbr].get(weight,1)*d \n+                               for nbr,d in nbrdeg.items())))\n+            elif neighbors == G.predecessors:\n+                s = float(sum((G[nbr][n].get(weight,1)*d \n+                               for nbr,d in nbrdeg.items())))\n         dnorm[k] += source_degree(n, weight=weight)\n         dsum[k] += s\n", "issue": "Mistake in computation of average neighbor degree for directed networks (migrated from Trac #639)\nOriginal ticket https://networkx.lanl.gov/trac/ticket/639\nReported 2011-09-27 by Oleguer Sagarra <oleguer.sagarra, assigned to @hagberg.\n\nThere is a problem in the algorithm to compute the negihbor degree (and average neighbor degree) for directed networks. The thing is that as networkx is based on a dict of dicts one may follow the neighbors of a node \"forward\" but not \"backwards\", meaning that with the functions such as G.in_degree(G[n]) one lists the incoming degree of the neighbors of the node \"n\", neighbors meaning destination of directed edges starting at node n. For all this, the normalization factor used is wrong. Additionally, it has some bugs with division over zero values.\n\nThese features need to be better redefined for various reasons:\n\na) With directed networks one can compute 4 types of features divided into two subgroups:\n       a.1) For the neighbors of a node n (by neighbors meaning ending points of directed edges starting at node n) one can compute the Incoming our outgoing degree of a node.\n       a.2) For all predecessors of node n (meaning all sources of edges finishing in node n) one can compute the very same thing.\n\nb) Additionally, accounting for the average connectivity (or average neighbor degree as a function of degree of a node) things get messy, because then one may compute 8 different features divided into two groups, providing different information:\n        b.1) Consider all the neighbors (defined earlier) of node n. Consider all the nodes n in the net. For each node n compute the (in-degree, out-degree) of their neighbors, then average over all n nodes of (in-degree, out-degree) 'k'.\n       b.2) The same for predecessors of degree n.\n\nThe current code can be adapted to do so, using the function G.reverse() to overcome the difficulty in quickly computing the predecessors of a node while keeping the code structure. But the documentation need to be rewritten and the normalization of the averages redone.\n\nReference :  Serrano, M.A., Maguitman, A., Boguna, M., Fortunato, S. & Vespignani, A. Decoding the structure of the WWW: facts versus sampling biases. Main 10 (2005).at http://arxiv.org/abs/cs/0511035\n\nSimple example showing what I mean:\nCase 1: Error in normalization division by 0\n\nIn [1]: import networkx as nx\n\nIn [2]: G=nx.DiGraph()\n\nIn [3]: G.add_edges_from(([1,2],[1,3],[1,4]))\n## In [6]: nx.average_in_degree_connectivity(G)\n\nZeroDivisionError                         Traceback (most recent call last)\n/Users/ugalss/<ipython-input-6-e2e455d286f8> in <module>()\n----> 1 nx.average_in_degree_connectivity(G)\n\n/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/networkx-1.5-py2.7.egg/networkx/algorithms/neighbor_degree.pyc in average_in_degree_connectivity(G, nodes, weighted)\n    205         raise nx.NetworkXError(\"Not defined for undirected graphs.\")\n    206     degree_method = G.in_degree\n--> 207     return _avg_deg_conn(G, degree_method, nodes=nodes, weighted=weighted)\n    208 average_in_degree_connectivity.__doc__=average_degree_connectivity.**doc**\n    209 \n\n/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/networkx-1.5-py2.7.egg/networkx/algorithms/neighbor_degree.pyc in _avg_deg_conn(G, degree_method, nodes, weighted)\n    141         dc[k]=avg\n    142         if avg > 0:\n--> 143             dc[k]/=dnorm[k]\n    144     return dc\n    145 \n\nZeroDivisionError: float division by zero\n\nCase 2: Wrong computation of neighbor degree (incoming):\n\nIn [7]: G.add_edges_from(([2,3],[3,4],[4,2]))\nIn [8]: nx.average_neighbor_in_degree(G)\nOut[8]: {1: 6.0, 2: 1.0, 3: 1.0, 4: 1.0} # This is wrong. The average in-degree should be 2 for neighbors of node 1.\n\nI attach a new version of neighbor_degree.py with proposed (and commented) changes...\n\n", "before_files": [{"content": "#-*- coding: utf-8 -*-\n#    Copyright (C) 2011 by \n#    Jordi Torrents <jtorrents@milnou.net>\n#    Aric Hagberg <hagberg@lanl.gov>\n#    All rights reserved.\n#    BSD license.\nfrom collections import defaultdict\nimport networkx as nx\n__author__ = \"\"\"\\n\"\"\".join(['Jordi Torrents <jtorrents@milnou.net>',\n                            'Aric Hagberg (hagberg@lanl.gov)'])\n__all__ = ['average_degree_connectivity',\n           'k_nearest_neighbors']\n\ndef _avg_deg_conn(G, neighbors, source_degree, target_degree, \n                  nodes=None, weight=None):\n    # \"k nearest neighbors, or neighbor_connectivity\n    dsum = defaultdict(float)\n    dnorm = defaultdict(float)\n    for n,k in source_degree(nodes).items():\n        nbrdeg = target_degree(neighbors(n))\n        if weight is None:\n            s = float(sum(nbrdeg.values()))\n        else: # weight nbr degree by weight of (n,nbr) edge\n            s = float(sum((G[n][nbr].get(weight,1)*d \n                           for nbr,d in nbrdeg.items())))\n        dnorm[k] += source_degree(n, weight=weight)\n        dsum[k] += s\n        \n    # normalize\n    dc = {}\n    for k,avg in dsum.items():\n        dc[k]=avg\n        norm = dnorm[k]\n        if avg > 0 and norm > 0:\n            dc[k]/=norm\n    return dc\n\ndef average_degree_connectivity(G, source=\"in+out\", target=\"in+out\",\n                                nodes=None, weight=None):\n    r\"\"\"Compute the average degree connectivity of graph.\n\n    The average degree connectivity is the average nearest neighbor degree of\n    nodes with degree k. For weighted graphs, an analogous measure can \n    be computed using the weighted average neighbors degree defined in \n    [1]_, for a node `i`, as:\n\n    .. math::\n\n        k_{nn,i}^{w} = \\frac{1}{s_i} \\sum_{j \\in N(i)} w_{ij} k_j\n\n    where `s_i` is the weighted degree of node `i`, \n    `w_{ij}` is the weight of the edge that links `i` and `j`,\n    and `N(i)` are the neighbors of node `i`.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    source :  \"in\"|\"out\"|\"in+out\" (default:\"in+out\")\n       Directed graphs only. Use \"in\"- or \"out\"-degree for source node.\n\n    target : \"in\"|\"out\"|\"in+out\" (default:\"in+out\"\n       Directed graphs only. Use \"in\"- or \"out\"-degree for target node.\n\n    nodes: list or iterable (optional)\n        Compute neighbor connectivity for these nodes. The default is all nodes.\n\n    weight : string or None, optional (default=None)\n       The edge attribute that holds the numerical value used as a weight.\n       If None, then each edge has weight 1.\n\n    Returns\n    -------\n    d: dict\n       A dictionary keyed by degree k with the value of average connectivity.\n    \n    Examples\n    --------\n    >>> G=nx.path_graph(4)\n    >>> G.edge[1][2]['weight'] = 3\n    >>> nx.k_nearest_neighbors(G)\n    {1: 2.0, 2: 1.5}\n    >>> nx.k_nearest_neighbors(G, weight='weight')\n    {1: 2.0, 2: 1.75}\n\n    See also\n    --------\n    neighbors_average_degree\n\n    Notes\n    -----\n    This algorithm is sometimes called \"k nearest neighbors'.\n\n    References\n    ----------    \n    .. [1] A. Barrat, M. Barth\u00e9lemy, R. Pastor-Satorras, and A. Vespignani, \n       \"The architecture of complex weighted networks\". \n       PNAS 101 (11): 3747\u20133752 (2004).\n    \"\"\"\n    source_degree = G.degree\n    target_degree = G.degree\n    neighbors = G.neighbors\n    if G.is_directed():\n        direction = {'out':G.out_degree,\n                     'in':G.in_degree,\n                     'in+out': G.degree}\n        source_degree = direction[source]\n        target_degree = direction[target]\n        if source == 'in':\n            neighbors=G.predecessors\n        elif source == 'out':\n            neighbors=G.successors\n    return _avg_deg_conn(G, neighbors, source_degree, target_degree,\n                         nodes=nodes, weight=weight)\n\nk_nearest_neighbors=average_degree_connectivity\n", "path": "networkx/algorithms/assortativity/connectivity.py"}], "after_files": [{"content": "#-*- coding: utf-8 -*-\n#    Copyright (C) 2011 by \n#    Jordi Torrents <jtorrents@milnou.net>\n#    Aric Hagberg <hagberg@lanl.gov>\n#    All rights reserved.\n#    BSD license.\nfrom collections import defaultdict\nimport networkx as nx\n__author__ = \"\"\"\\n\"\"\".join(['Jordi Torrents <jtorrents@milnou.net>',\n                            'Aric Hagberg (hagberg@lanl.gov)'])\n__all__ = ['average_degree_connectivity',\n           'k_nearest_neighbors']\n\ndef _avg_deg_conn(G, neighbors, source_degree, target_degree, \n                  nodes=None, weight=None):\n    # \"k nearest neighbors, or neighbor_connectivity\n    dsum = defaultdict(float)\n    dnorm = defaultdict(float)\n    for n,k in source_degree(nodes).items():\n        nbrdeg = target_degree(neighbors(n))\n        if weight is None:\n            s = float(sum(nbrdeg.values()))\n        else: # weight nbr degree by weight of (n,nbr) edge\n            if neighbors == G.neighbors:\n                s = float(sum((G[n][nbr].get(weight,1)*d \n                               for nbr,d in nbrdeg.items())))\n            elif neighbors == G.successors:\n                s = float(sum((G[n][nbr].get(weight,1)*d \n                               for nbr,d in nbrdeg.items())))\n            elif neighbors == G.predecessors:\n                s = float(sum((G[nbr][n].get(weight,1)*d \n                               for nbr,d in nbrdeg.items())))\n        dnorm[k] += source_degree(n, weight=weight)\n        dsum[k] += s\n        \n    # normalize\n    dc = {}\n    for k,avg in dsum.items():\n        dc[k]=avg\n        norm = dnorm[k]\n        if avg > 0 and norm > 0:\n            dc[k]/=norm\n    return dc\n\ndef average_degree_connectivity(G, source=\"in+out\", target=\"in+out\",\n                                nodes=None, weight=None):\n    r\"\"\"Compute the average degree connectivity of graph.\n\n    The average degree connectivity is the average nearest neighbor degree of\n    nodes with degree k. For weighted graphs, an analogous measure can \n    be computed using the weighted average neighbors degree defined in \n    [1]_, for a node `i`, as:\n\n    .. math::\n\n        k_{nn,i}^{w} = \\frac{1}{s_i} \\sum_{j \\in N(i)} w_{ij} k_j\n\n    where `s_i` is the weighted degree of node `i`, \n    `w_{ij}` is the weight of the edge that links `i` and `j`,\n    and `N(i)` are the neighbors of node `i`.\n\n    Parameters\n    ----------\n    G : NetworkX graph\n\n    source :  \"in\"|\"out\"|\"in+out\" (default:\"in+out\")\n       Directed graphs only. Use \"in\"- or \"out\"-degree for source node.\n\n    target : \"in\"|\"out\"|\"in+out\" (default:\"in+out\"\n       Directed graphs only. Use \"in\"- or \"out\"-degree for target node.\n\n    nodes: list or iterable (optional)\n        Compute neighbor connectivity for these nodes. The default is all nodes.\n\n    weight : string or None, optional (default=None)\n       The edge attribute that holds the numerical value used as a weight.\n       If None, then each edge has weight 1.\n\n    Returns\n    -------\n    d: dict\n       A dictionary keyed by degree k with the value of average connectivity.\n    \n    Examples\n    --------\n    >>> G=nx.path_graph(4)\n    >>> G.edge[1][2]['weight'] = 3\n    >>> nx.k_nearest_neighbors(G)\n    {1: 2.0, 2: 1.5}\n    >>> nx.k_nearest_neighbors(G, weight='weight')\n    {1: 2.0, 2: 1.75}\n\n    See also\n    --------\n    neighbors_average_degree\n\n    Notes\n    -----\n    This algorithm is sometimes called \"k nearest neighbors'.\n\n    References\n    ----------    \n    .. [1] A. Barrat, M. Barth\u00e9lemy, R. Pastor-Satorras, and A. Vespignani, \n       \"The architecture of complex weighted networks\". \n       PNAS 101 (11): 3747\u20133752 (2004).\n    \"\"\"\n    source_degree = G.degree\n    target_degree = G.degree\n    neighbors = G.neighbors\n    if G.is_directed():\n        direction = {'out':G.out_degree,\n                     'in':G.in_degree,\n                     'in+out': G.degree}\n        source_degree = direction[source]\n        target_degree = direction[target]\n        if source == 'in':\n            neighbors=G.predecessors\n        elif source == 'out':\n            neighbors=G.successors\n    return _avg_deg_conn(G, neighbors, source_degree, target_degree,\n                         nodes=nodes, weight=weight)\n\nk_nearest_neighbors=average_degree_connectivity\n", "path": "networkx/algorithms/assortativity/connectivity.py"}]}