(
G,
nodelist=None,
dtype=None,
order=None,
multigraph_weight=sum,
weight="weight",
nonedge=0.0,
)
| 94 | |
| 95 | |
| 96 | def 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: |
no test coverage detected