Repository: networkx/networkx

Issue:
non_randomness fail with ValueError: math domain error on simple network
The calculation of non_randomness fails with a simple network.

```python
import networkx as nx
g = nx.Graph()
g.add_edges_from([
    ('A', 'B'),
    ('B', 'C'),
    ('B', 'D'),
    ('D', 'E')
    ])
print(nx.algorithms.non_randomness(g))
```
throws:
```
.venv\lib\site-packages\networkx\algorithms\non_randomness.py in non_randomness(G, k)
     88 
     89     # eq. 4.5
---> 90     nr_rd = (nr - ((n - 2 * k) * p + k)) / math.sqrt(2 * k * p * (1 - p))
     91 
     92     return nr, nr_rd

ValueError: math domain error
```



Discussion:
I get:
```
print(nx.non_randomness(g))                                                                                                        
(-1.847759065022571, -5.842436964513824)
```
I too get the correct result. What versions of nx and Python are you using @javieriserte ?
I'm using:
networkx==2.4 and python 3.7.2

I was looking into the code for the problem and i think i found it.

Consider the code below:
```python
import networkx as nx

# Works Fine !!
g = nx.Graph()
edges_case_1 = [
    ('A', 'B'),
    ('B', 'C'),
    ('B', 'D'),
    ('D', 'E')
    ]
g.add_edges_from(edges_case_1)
k = len(tuple(nx.community.label_propagation_communities(g)))
print("Case 1")
print(f"Number of comminities: {k}")
print(f"NonRandomness:{nx.algorithms.non_randomness(g)}")
print("\n")

# Fails !!
g = nx.Graph()
edges_case_2 = [
    ('A', 'B'),
    ('B', 'D'),
    ('B', 'C'),
    ('D', 'E')
]
g.add_edges_from(edges_case_2)
k = len(tuple(nx.community.label_propagation_communities(g)))
print("Case 1")
print(f"Number of comminities: {k}")
try:
    print(f"NonRandomness:{nx.algorithms.non_randomness(g)}")
except Exception as e:
    print(f"Fails with {e}")
```

I have two identical graphs, but the order of the edges is different when they are added to the graph.
For me, the first case is Ok, and the second one fails.

The code of non_randomness function tries to find communities in the graph. In the first case, one community is found, in the second case, two comunities are found. It uses label_propagation_communities function to do this. I don't know why this function gives two different results for the same graph. 

Later in the code the number of communities (k) is used to compute another value ```p = (2 * k * m) / (n * (n - k))``` (where n and m are the number of nodes and edges). And p is used inside a square root ```math.sqrt(2 * k * p * (1 - p))```. In the case that fails,
p is larger than 1 and (1-p) is negative, this makes the square root to be undefined.


The article [referenced in the docstring](https://epubs.siam.org/doi/10.1137/1.9781611972795.61) discusses this quantity in Theorem 1 where they show that a quantity follows a normal distribution in the limit k << n and n large.  So clearly, this case doesn't follow that.  Perhaps we should include a maximum limit on p (not 1, or we divide by 0 and have the same problem).  Or, we could raise an exception when the value is bigger than 1.  
What makes the most sense here?  
What does it mean to have an infinite nonrandomness?

The different results for different orders of the same graph must be due to a community algorithm that depends on ordering of edges/nodes. I haven't looked at this in this case yet. But many of those methods do depend on ordering. So I'm not so surprised. 



Patch:
diff --git a/doc/reference/algorithms/non_randomness.rst b/doc/reference/algorithms/non_randomness.rst
index 090707cdf19..79ac8d1a9e3 100644
--- a/doc/reference/algorithms/non_randomness.rst
+++ b/doc/reference/algorithms/non_randomness.rst
@@ -1,5 +1,5 @@
 **************
-non-randomness
+Non-randomness
 **************
 
 .. automodule:: networkx.algorithms.non_randomness
diff --git a/networkx/algorithms/non_randomness.py b/networkx/algorithms/non_randomness.py
index 13799115774..3b3a94f0d78 100644
--- a/networkx/algorithms/non_randomness.py
+++ b/networkx/algorithms/non_randomness.py
@@ -1,4 +1,4 @@
-r"""Computation of graph non-randomness"""
+r"""Computation of graph non-randomness."""
 
 import math
 
@@ -12,45 +12,56 @@
 @not_implemented_for("multigraph")
 @nx._dispatchable(edge_attrs="weight")
 def non_randomness(G, k=None, weight="weight"):
-    """Compute the non-randomness of graph G.
+    """Compute the non-randomness of a graph.
 
-    The first returned value nr is the sum of non-randomness values of all
+    The first value $R_G$ is the sum of non-randomness values of all
     edges within the graph (where the non-randomness of an edge tends to be
     small when the two nodes linked by that edge are from two different
     communities).
 
-    The second computed value nr_rd is a relative measure that indicates
-    to what extent graph G is different from random graphs in terms
-    of probability. When it is close to 0, the graph tends to be more
-    likely generated by an Erdos Renyi model.
+    The second value $R_G^*$ is a relative measure that indicates
+    to what extent `G` is different from a random graph in terms
+    of probability. The closer it is to 0, the higher the likelihood
+    the graph was generated by an Erdős--Rényi model.
 
     Parameters
     ----------
     G : NetworkX graph
-        Graph must be symmetric, connected, and without self-loops.
+        Graph must be undirected, connected, and without self-loops.
 
-    k : int
-        The number of communities in G.
-        If k is not set, the function will use a default community
-        detection algorithm to set it.
+    k : int or None, optional (default=None)
+        The number of communities in `G`.
+        If `k` is not set, the function uses a default community detection
+        algorithm (:func:`~networkx.algorithms.community.label_propagation_communities`)
+        to set it.
 
-    weight : string or None, optional (default=None)
+    weight : string or None, optional (default="weight")
         The name of an edge attribute that holds the numerical value used
-        as a weight. If None, then each edge has weight 1, i.e., the graph is
+        as a weight. If `None`, then each edge has weight 1, i.e., the graph is
         binary.
 
     Returns
     -------
-    non-randomness : (float, float) tuple
-        Non-randomness, Relative non-randomness w.r.t.
-        Erdos Renyi random graphs.
+    (float, float) tuple
+        The first value is $R_G$, the non-randomness of the graph,
+        the second is $R_G^*$, the relative non-randomness
+        w.r.t. the Erdős--Rényi model.
 
     Raises
     ------
+    NetworkXNotImplemented
+        If the input graph is directed or a multigraph.
+
     NetworkXException
-        if the input graph is not connected.
+        If the input graph is not connected.
+
     NetworkXError
-        if the input graph contains self-loops or if graph has no edges.
+        If the input graph contains self-loops or has no edges.
+
+    ValueError
+        If `k` is not in $\\{1, \\dots, n-1\\}$, where $n$ is the number of nodes,
+        or if `k` is such that the computed edge probability
+        $p = \\frac{2km}{n(n-k)}$ does not satisfy $0 < p < 1$.
 
     Examples
     --------
@@ -58,18 +69,60 @@ def non_randomness(G, k=None, weight="weight"):
     >>> nr, nr_rd = nx.non_randomness(G, 2)
     >>> nr, nr_rd = nx.non_randomness(G, 2, "weight")
 
+    When the number of communities `k` is not specified,
+    :func:`~networkx.algorithms.community.label_propagation_communities`
+    is used to compute it.
+    This algorithm can give different results depending on
+    the order of nodes and edges in the graph.
+    For example, while the following graphs are identical,
+    computing the non-randomness of each of them yields different results:
+
+    >>> G1, G2 = nx.Graph(), nx.Graph()
+    >>> G1.add_edges_from([(0, 1), (1, 2), (1, 3), (3, 4)])
+    >>> G2.add_edges_from([(0, 1), (1, 3), (1, 2), (3, 4)])
+    >>> [round(r, 6) for r in nx.non_randomness(G1)]
+    [-1.847759, -5.842437]
+    >>> [round(r, 6) for r in nx.non_randomness(G2)]
+    Traceback (most recent call last):
+     ...
+    ValueError: invalid number of communities for graph with 5 nodes and 4 edges: 2
+
+    This is because the community detection algorithm finds
+    1 community in `G1` and 2 communities in `G2`.
+    This can be resolved by specifying the number of communities `k`:
+
+    >>> [round(r, 6) for r in nx.non_randomness(G2, k=1)]
+    [-1.847759, -5.842437]
+
     Notes
     -----
-    This computes Eq. (4.4) and (4.5) in Ref. [1]_.
-
-    If a weight field is passed, this algorithm will use the eigenvalues
-    of the weighted adjacency matrix to compute Eq. (4.4) and (4.5).
+    If a `weight` argument is passed, this algorithm will use the eigenvalues
+    of the weighted adjacency matrix instead.
+
+    The output of this function corresponds to (4.4) and (4.5) in [1]_.
+    A lower value of $R^*_G$ indicates a more random graph;
+    one can think of $1 - \\Phi(R_G^*)$ as the similarity
+    between the graph and a random graph,
+    where $\\Phi(x)$ is the cumulative distribution function
+    of the standard normal distribution.
+
+    Theorem 2 in [2]_ states that for any graph $G$
+    with $n$ nodes, $m$ edges, and $k$ communities,
+    its non-randomness is bounded below by the non-randomness of an
+    $r$-regular graph (a graph where each node has degree $r$),
+    and bounded above by the non-randomness of an $l$-complete graph
+    (a graph where each community is a clique of $l$ nodes).
 
     References
     ----------
     .. [1] Xiaowei Ying and Xintao Wu,
            On Randomness Measures for Social Networks,
            SIAM International Conference on Data Mining. 2009
+           https://doi.org/10.1137/1.9781611972795.61
+    .. [2] Ying, Xiaowei & Wu, Leting & Wu, Xintao. (2012).
+           A Spectrum-Based Framework for Quantifying Randomness of Social Networks.
+           IEEE Transactions on Knowledge and Data Engineering 23(12):1842--1856.
+           https://dl.acm.org/doi/abs/10.1109/TKDE.2010.218
     """
     import numpy as np
 
@@ -81,17 +134,21 @@ def non_randomness(G, k=None, weight="weight"):
     if len(list(nx.selfloop_edges(G))) > 0:
         raise nx.NetworkXError("Graph must not contain self-loops")
 
+    n = G.number_of_nodes()
+    m = G.number_of_edges()
+
     if k is None:
         k = len(tuple(nx.community.label_propagation_communities(G)))
+    if not 1 <= k < n or not 0 < (p := (2 * k * m) / (n * (n - k))) < 1:
+        err = (
+            f"invalid number of communities for graph with {n} nodes and {m} edges: {k}"
+        )
+        raise ValueError(err)
 
     # eq. 4.4
     eigenvalues = np.linalg.eigvals(nx.to_numpy_array(G, weight=weight))
     nr = float(np.real(np.sum(eigenvalues[:k])))
 
-    n = G.number_of_nodes()
-    m = G.number_of_edges()
-    p = (2 * k * m) / (n * (n - k))
-
     # eq. 4.5
     nr_rd = (nr - ((n - 2 * k) * p + k)) / math.sqrt(2 * k * p * (1 - p))
 


Test patch:
diff --git a/networkx/algorithms/tests/test_non_randomness.py b/networkx/algorithms/tests/test_non_randomness.py
index 2f495be28d5..bdbcdaf1544 100644
--- a/networkx/algorithms/tests/test_non_randomness.py
+++ b/networkx/algorithms/tests/test_non_randomness.py
@@ -40,3 +40,21 @@ def test_empty_graph():
     G = nx.empty_graph(1)
     with pytest.raises(nx.NetworkXError, match=".*not applicable to empty graphs"):
         nx.non_randomness(G)
+
+
+@pytest.mark.parametrize("k", [-1, 0, 2, 5])
+def test_value_error(k):
+    """
+    Check that invalid values of k raise (must be between 1 and n - 1, inclusive,
+    and such that the probability is between 0 and 1, exclusive).
+    """
+    G = nx.path_graph(5)
+    with pytest.raises(ValueError, match=r"invalid number of communities"):
+        nx.non_randomness(G, k=k)
+
+
+@pytest.mark.parametrize("G", [nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()])
+def test_not_implemented(G):
+    """Check that non-randomness is not implemented for directed or multigraphs."""
+    with pytest.raises(nx.NetworkXNotImplemented, match=r"not implemented for"):
+        nx.non_randomness(G)