Skip to content

Commit a132cda

Browse files
iggisv9tntamas
authored andcommitted
re-add sparse adjacency func
1 parent 5d2fcd8 commit a132cda

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

src/igraph/__init__.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,36 @@ def get_adjacency(self, type=GET_ADJACENCY_BOTH, attribute=None, \
592592

593593
return Matrix(data)
594594

595+
def get_adjacency_sparse(self, attribute=None):
596+
"""Returns the adjacency matrix of a graph as scipy csr matrix.
597+
@param attribute: if C{None}, returns the ordinary adjacency
598+
matrix. When the name of a valid edge attribute is given
599+
here, the matrix returned will contain the default value
600+
at the places where there is no edge or the value of the
601+
given attribute where there is an edge.
602+
@return: the adjacency matrix as a L{scipy.sparse.csr_matrix}."""
603+
try:
604+
from scipy.sparse import csr_matrix
605+
except ImportError:
606+
raise ImportError('You should install scipy package in order to use this function')
607+
608+
edges = self.get_edgelist()
609+
if attribute is None:
610+
weights = np.ones(len(edges))
611+
else:
612+
if attribute not in self.es.attribute_names():
613+
raise ValueError("Attribute does not exist")
614+
615+
weights = self.es[attribute]
616+
617+
N = self.vcount()
618+
sparse_matrix = csr_matrix((weights, zip(*edges)), shape=(N, N))
619+
620+
if not self.is_directed():
621+
sparse_matrix = sparse_matrix + sparse_matrix.T
622+
di = np.diag_indices(len(edges))
623+
sparse_matrix[di] /= 2
624+
return sparse_matrix
595625

596626
def get_adjlist(self, mode=OUT):
597627
"""get_adjlist(mode=OUT)

0 commit comments

Comments
 (0)