Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Fix bug with 0s in sparse matrix for LCC calculation #805

Merged
merged 6 commits into from
Jul 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions graspologic/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,13 @@ def largest_connected_component(
inds: (optional)
Indices/nodes from the original adjacency matrix that were kept after taking
the largest connected component.

Notes
-----
For networks input in ``scipy.sparse.csr_matrix`` format, explicit zeros are removed
prior to finding the largest connected component, thus they are not treated as
edges. This differs from the convention in
:func:`scipy.sparse.csgraph.connected_components`.
"""

if isinstance(graph, (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)):
Expand Down Expand Up @@ -539,6 +546,9 @@ def _largest_connected_component_adjacency(
adjacency: Union[np.ndarray, csr_matrix],
return_inds: bool = False,
):
if isinstance(adjacency, csr_matrix):
adjacency.eliminate_zeros()

# If you treat an undirected graph as directed and take the largest weakly connected
# component, you'll get the same answer as taking the largest connected component of
# that undirected graph. So I wrote it this way to avoid the cost of checking for
Expand Down
12 changes: 12 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,18 @@ def test_lcc_scipy(self):
np.testing.assert_array_equal(lcc_matrix.toarray(), expected_lcc_matrix)
np.testing.assert_array_equal(nodelist, expected_nodelist)

def test_lcc_scipy_empty(self):
adjacency = np.array([[0, 1], [1, 0]])
adjacency = csr_matrix(adjacency)

# remove the actual connecting edges. this is now a disconnected graph
# with two nodes. however, scipy still stores the entry that now has a 0 in it
# as having a 'nonempty' value, which is used in the lcc calculation
adjacency[0, 1] = 0
adjacency[1, 0] = 0
lcc_adjacency = gus.largest_connected_component(adjacency)
assert lcc_adjacency.shape[0] == 1

def test_multigraph_lcc_numpystack(self):
expected_g_matrix = np.array(
[[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0]]
Expand Down