Skip to content

Allow isolate creation during export to networkx. #476

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion graphblas/io/_networkx.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def from_networkx(G, nodelist=None, dtype=None, weight="weight", name=None):


# TODO: add parameters to allow different networkx classes and attribute names
def to_networkx(m, edge_attribute="weight"):
def to_networkx(m, edge_attribute="weight", create_isolates=False):
"""Create a networkx DiGraph from a square adjacency Matrix.

Parameters
Expand All @@ -41,6 +41,11 @@ def to_networkx(m, edge_attribute="weight"):
edge_attribute : str, optional
Name of edge attribute from values of Matrix. If None, values will be skipped.
Default is "weight".
create_isolates : bool, optional
If row $i$ and column $i$ are both empty, then node $i$ is an isolate. By default,
these isolate nodes are ignored. If True, then the graph will also contain the
isolate nodes. Note that for very large adjacency matrices, creating isolates
will increase the memory footprint of the graph.

Returns
-------
Expand All @@ -56,4 +61,6 @@ def to_networkx(m, edge_attribute="weight"):
G.add_edges_from(zip(rows, cols))
else:
G.add_weighted_edges_from(zip(rows, cols, vals.tolist()), weight=edge_attribute)
if create_isolates:
G.add_nodes_from(range(max(m.shape)))
return G
11 changes: 11 additions & 0 deletions graphblas/tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,17 @@ def test_matrix_to_from_networkx():
assert M.nvals == 0
assert M.shape == (1, 1)

# test creation of isolates
M = gb.Matrix.from_edgelist([(0,1),(3,0)],nrows=5,ncols=5)
G = gb.io.to_networkx(M, create_isolates=True)
G_nx = nx.DiGraph()
G_nx.add_edges_from([(0,1),(3,0)])
G_nx.add_nodes_from(range(5))
assert G.number_of_edges() == G_nx.number_of_edges() == 2
assert G.number_of_nodes() == G_nx.number_of_nodes() == 5
from networkx.utils import graphs_equal
assert graphs_equal(G, G_nx)


@pytest.mark.skipif("not ss")
@pytest.mark.parametrize("engine", ["auto", "scipy", "fmm"])
Expand Down