MCPcopy Create free account
hub / github.com/alibaba/GraphScope / to_numpy_array

Function to_numpy_array

python/graphscope/nx/convert_matrix.py:96–182  ·  view source on GitHub ↗
(
    G,
    nodelist=None,
    dtype=None,
    order=None,
    multigraph_weight=sum,
    weight="weight",
    nonedge=0.0,
)

Source from the content-addressed store, hash-verified

94
95
96def to_numpy_array(
97 G,
98 nodelist=None,
99 dtype=None,
100 order=None,
101 multigraph_weight=sum,
102 weight="weight",
103 nonedge=0.0,
104):
105 import numpy as np
106
107 if nodelist is None:
108 nodelist = list(G)
109 nodeset = G
110 nlen = len(G)
111 else:
112 nlen = len(nodelist)
113 nodeset = set(G.nbunch_iter(nodelist))
114 if nlen != len(nodeset):
115 for n in nodelist:
116 if n not in G:
117 raise nx.NetworkXError(f"Node {n} in nodelist is not in G")
118 raise nx.NetworkXError("nodelist contains duplicates.")
119
120 A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order)
121
122 # Corner cases: empty nodelist or graph without any edges
123 if nlen == 0 or G.number_of_edges() == 0:
124 return A
125
126 # If dtype is structured and weight is None, use dtype field names as
127 # edge attributes
128 edge_attrs = None # Only single edge attribute by default
129 if A.dtype.names:
130 if weight is None:
131 edge_attrs = dtype.names
132 else:
133 raise ValueError(
134 "Specifying `weight` not supported for structured dtypes\n."
135 "To create adjacency matrices from structured dtypes, use `weight=None`."
136 )
137
138 idx = dict(zip(sorted(nodelist), range(nlen)))
139 if len(nodelist) < len(G):
140 G = G.subgraph(nodelist) # A real subgraph, not view
141
142 # Collect all edge weights and reduce with `multigraph_weights`
143 if G.is_multigraph():
144 if edge_attrs:
145 raise nx.NetworkXError(
146 "Structured arrays are not supported for MultiGraphs"
147 )
148 d = defaultdict(list)
149 for u, v, wt in G.edges(data=weight, default=1.0):
150 d[(idx[u], idx[v])].append(wt)
151 i, j = np.array(list(d.keys())).T # indices
152 wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights
153 else:

Callers 1

to_numpy_matrixFunction · 0.85

Calls 10

nbunch_iterMethod · 0.80
number_of_edgesMethod · 0.80
appendMethod · 0.65
getMethod · 0.65
subgraphMethod · 0.45
is_multigraphMethod · 0.45
edgesMethod · 0.45
keysMethod · 0.45
valuesMethod · 0.45
is_directedMethod · 0.45

Tested by

no test coverage detected