python-igraph icon indicating copy to clipboard operation
python-igraph copied to clipboard

Check for symmetry in `_graph_from_weighted_sparse_matrix`

Open psl-schaefer opened this issue 1 year ago • 1 comments

If one creates a weighted, undirected graph from an adjacency matrix, wouldn't it make sense to check if the adjacency matrix is symmetric? This check was also introduced in rigraph I think, see https://github.com/igraph/rigraph/issues/182.

I am referring to this function: https://github.com/igraph/python-igraph/blob/4c82c9d34062cc45bb069af8e6fc923885281225/src/igraph/sparse_matrix.py#L154

A simple check could be something like symmetric = not np.any((matrix!=matrix.T).data) (here assuming that it is scipy.sparse.csr_matrix).

Here is a simple example (not the most efficient way to check the behavior though):

import numpy as np
from scipy.sparse import csr_matrix
import igraph as ig
rng = np.random.default_rng(0)
n = int(1e3)
sparse_adj = rng.choice(np.array([0, 1, 2]),
                        size=(n**2), replace=True, 
                        p=np.array([0.9, 0.05, 0.05])).reshape(n, n).astype(np.float64)
sparse_adj = csr_matrix(sparse_adj)
symmetric = not np.any((sparse_adj!=sparse_adj.T).data)
print(f"{symmetric=}")
g = ig.Graph.Weighted_Adjacency(sparse_adj, 
                                mode="undirected",
                                attr="weight")

psl-schaefer avatar Jun 05 '24 08:06 psl-schaefer

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Apr 27 '25 17:04 stale[bot]