MCPcopy Create free account
hub / github.com/easy-graph/Easy-Graph / from_scipy_sparse_array

Function from_scipy_sparse_array

easygraph/utils/convert_to_matrix.py:906–943  ·  view source on GitHub ↗
(
    A, parallel_edges=False, create_using=None, edge_attribute="weight"
)

Source from the content-addressed store, hash-verified

904
905
906def from_scipy_sparse_array(
907 A, parallel_edges=False, create_using=None, edge_attribute="weight"
908):
909 G = eg.empty_graph(0, create_using)
910 n, m = A.shape
911 if n != m:
912 raise eg.EasyGraphError(f"Adjacency matrix not square: nx,ny={A.shape}")
913 # Make sure we get even the isolated nodes of the graph.
914 G.add_nodes_from(range(n))
915 # Create an iterable over (u, v, w) triples and for each triple, add an
916 # edge from u to v with weight w.
917 triples = _generate_weighted_edges(A)
918 # If the entries in the adjacency matrix are integers, the graph is a
919 # multigraph, and parallel_edges is True, then create parallel edges, each
920 # with weight 1, for each entry in the adjacency matrix. Otherwise, create
921 # one edge for each positive entry in the adjacency matrix and set the
922 # weight of that edge to be the entry in the matrix.
923 if A.dtype.kind in ("i", "u") and G.is_multigraph() and parallel_edges:
924 chain = itertools.chain.from_iterable
925 # The following line is equivalent to:
926 #
927 # for (u, v) in edges:
928 # for d in range(A[u, v]):
929 # G.add_edge(u, v, weight=1)
930 #
931 triples = chain(((u, v, 1) for d in range(w)) for (u, v, w) in triples)
932 # If we are creating an undirected multigraph, only add the edges from the
933 # upper triangle of the matrix. Otherwise, add all the edges. This relies
934 # on the fact that the vertices created in the
935 # `_generated_weighted_edges()` function are actually the row/column
936 # indices for the matrix `A`.
937 #
938 # Without this check, we run into a problem where each edge is added twice
939 # when `G.add_weighted_edges_from()` is invoked below.
940 if G.is_multigraph() and not G.is_directed():
941 triples = ((u, v, d) for u, v, d in triples if u <= v)
942 G.add_edges_from(((u, v, {"weight": d}) for u, v, d in triples))
943 return G
944
945
946def _generate_weighted_edges(A):

Callers 1

from_scipy_sparse_matrixFunction · 0.85

Calls 5

_generate_weighted_edgesFunction · 0.85
add_nodes_fromMethod · 0.45
is_multigraphMethod · 0.45
is_directedMethod · 0.45
add_edges_fromMethod · 0.45

Tested by

no test coverage detected