Unverified Commit 8f9f2e2a authored by Hongzhi (Steve), Chen's avatar Hongzhi (Steve), Chen Committed by GitHub
Browse files

[Misc] Rename number_of_edges and number_of_nodes to num_edges and num_nodes. (#5472)



* core

* revert

---------
Co-authored-by: default avatarUbuntu <ubuntu@ip-172-31-28-63.ap-northeast-1.compute.internal>
parent 690f37bb
...@@ -221,7 +221,7 @@ def _gspmm(gidx, op, reduce_op, u, e): ...@@ -221,7 +221,7 @@ def _gspmm(gidx, op, reduce_op, u, e):
u_shp = F.shape(u) if use_u else (0,) u_shp = F.shape(u) if use_u else (0,)
e_shp = F.shape(e) if use_e else (0,) e_shp = F.shape(e) if use_e else (0,)
_, dsttype = gidx.metagraph.find_edge(0) _, dsttype = gidx.metagraph.find_edge(0)
v_shp = (gidx.number_of_nodes(dsttype),) + infer_broadcast_shape( v_shp = (gidx.num_nodes(dsttype),) + infer_broadcast_shape(
op, u_shp[1:], e_shp[1:] op, u_shp[1:], e_shp[1:]
) )
v = F.zeros(v_shp, dtype, ctx) v = F.zeros(v_shp, dtype, ctx)
...@@ -235,7 +235,7 @@ def _gspmm(gidx, op, reduce_op, u, e): ...@@ -235,7 +235,7 @@ def _gspmm(gidx, op, reduce_op, u, e):
arg_e = F.zeros(v_shp, idtype, ctx) arg_e = F.zeros(v_shp, idtype, ctx)
arg_u_nd = to_dgl_nd_for_write(arg_u) arg_u_nd = to_dgl_nd_for_write(arg_u)
arg_e_nd = to_dgl_nd_for_write(arg_e) arg_e_nd = to_dgl_nd_for_write(arg_e)
if gidx.number_of_edges(0) > 0: if gidx.num_edges(0) > 0:
_CAPI_DGLKernelSpMM( _CAPI_DGLKernelSpMM(
gidx, gidx,
op, op,
...@@ -359,7 +359,7 @@ def _gspmm_hetero(gidx, op, reduce_op, u_len, u_and_e_tuple): ...@@ -359,7 +359,7 @@ def _gspmm_hetero(gidx, op, reduce_op, u_len, u_and_e_tuple):
) # TODO(Israt): Put outside of loop ) # TODO(Israt): Put outside of loop
u_shp = F.shape(u) if use_u else (0,) u_shp = F.shape(u) if use_u else (0,)
e_shp = F.shape(e) if use_e else (0,) e_shp = F.shape(e) if use_e else (0,)
v_shp = (gidx.number_of_nodes(dst_id),) + infer_broadcast_shape( v_shp = (gidx.num_nodes(dst_id),) + infer_broadcast_shape(
op, u_shp[1:], e_shp[1:] op, u_shp[1:], e_shp[1:]
) )
list_v[dst_id] = F.zeros(v_shp, dtype, ctx) list_v[dst_id] = F.zeros(v_shp, dtype, ctx)
...@@ -379,7 +379,7 @@ def _gspmm_hetero(gidx, op, reduce_op, u_len, u_and_e_tuple): ...@@ -379,7 +379,7 @@ def _gspmm_hetero(gidx, op, reduce_op, u_len, u_and_e_tuple):
list_arg_e_etype[dst_id] list_arg_e_etype[dst_id]
) )
if gidx.number_of_edges(0) > 0: if gidx.num_edges(0) > 0:
_CAPI_DGLKernelSpMMHetero( _CAPI_DGLKernelSpMMHetero(
gidx, gidx,
op, op,
...@@ -546,11 +546,11 @@ def _gsddmm(gidx, op, lhs, rhs, lhs_target="u", rhs_target="v"): ...@@ -546,11 +546,11 @@ def _gsddmm(gidx, op, lhs, rhs, lhs_target="u", rhs_target="v"):
dtype = F.dtype(lhs) if use_lhs else F.dtype(rhs) dtype = F.dtype(lhs) if use_lhs else F.dtype(rhs)
lhs_shp = F.shape(lhs) if use_lhs else (0,) lhs_shp = F.shape(lhs) if use_lhs else (0,)
rhs_shp = F.shape(rhs) if use_rhs else (0,) rhs_shp = F.shape(rhs) if use_rhs else (0,)
out_shp = (gidx.number_of_edges(0),) + infer_broadcast_shape( out_shp = (gidx.num_edges(0),) + infer_broadcast_shape(
op, lhs_shp[1:], rhs_shp[1:] op, lhs_shp[1:], rhs_shp[1:]
) )
out = F.empty(out_shp, dtype, ctx) out = F.empty(out_shp, dtype, ctx)
if gidx.number_of_edges(0) > 0: if gidx.num_edges(0) > 0:
_CAPI_DGLKernelSDDMM( _CAPI_DGLKernelSDDMM(
gidx, gidx,
op, op,
...@@ -612,11 +612,11 @@ def _gsddmm_hetero( ...@@ -612,11 +612,11 @@ def _gsddmm_hetero(
rhs_shp = F.shape(rhs) if use_rhs else (0,) rhs_shp = F.shape(rhs) if use_rhs else (0,)
lhs_list[lhs_id] = lhs if use_lhs else None lhs_list[lhs_id] = lhs if use_lhs else None
rhs_list[rhs_id] = rhs if use_rhs else None rhs_list[rhs_id] = rhs if use_rhs else None
out_shp = (gidx.number_of_edges(etid),) + infer_broadcast_shape( out_shp = (gidx.num_edges(etid),) + infer_broadcast_shape(
op, lhs_shp[1:], rhs_shp[1:] op, lhs_shp[1:], rhs_shp[1:]
) )
out_list[etid] = F.empty(out_shp, dtype, ctx) out_list[etid] = F.empty(out_shp, dtype, ctx)
if gidx.number_of_edges(0) > 0: if gidx.num_edges(0) > 0:
_CAPI_DGLKernelSDDMMHetero( _CAPI_DGLKernelSDDMMHetero(
gidx, gidx,
op, op,
......
...@@ -190,13 +190,11 @@ def batch(graphs, ndata=ALL, edata=ALL): ...@@ -190,13 +190,11 @@ def batch(graphs, ndata=ALL, edata=ALL):
# Batch node feature # Batch node feature
if ndata is not None: if ndata is not None:
for ntype_id, ntype in zip(ntype_ids, ntypes): for ntype_id, ntype in zip(ntype_ids, ntypes):
all_empty = all( all_empty = all(g._graph.num_nodes(ntype_id) == 0 for g in graphs)
g._graph.number_of_nodes(ntype_id) == 0 for g in graphs
)
frames = [ frames = [
g._node_frames[ntype_id] g._node_frames[ntype_id]
for g in graphs for g in graphs
if g._graph.number_of_nodes(ntype_id) > 0 or all_empty if g._graph.num_nodes(ntype_id) > 0 or all_empty
] ]
# TODO: do we require graphs with no nodes/edges to have the same schema? Currently # TODO: do we require graphs with no nodes/edges to have the same schema? Currently
# we allow empty graphs to have no features during batching. # we allow empty graphs to have no features during batching.
...@@ -208,13 +206,11 @@ def batch(graphs, ndata=ALL, edata=ALL): ...@@ -208,13 +206,11 @@ def batch(graphs, ndata=ALL, edata=ALL):
# Batch edge feature # Batch edge feature
if edata is not None: if edata is not None:
for etype_id, etype in zip(relation_ids, relations): for etype_id, etype in zip(relation_ids, relations):
all_empty = all( all_empty = all(g._graph.num_edges(etype_id) == 0 for g in graphs)
g._graph.number_of_edges(etype_id) == 0 for g in graphs
)
frames = [ frames = [
g._edge_frames[etype_id] g._edge_frames[etype_id]
for g in graphs for g in graphs
if g._graph.number_of_edges(etype_id) > 0 or all_empty if g._graph.num_edges(etype_id) > 0 or all_empty
] ]
# TODO: do we require graphs with no nodes/edges to have the same schema? Currently # TODO: do we require graphs with no nodes/edges to have the same schema? Currently
# we allow empty graphs to have no features during batching. # we allow empty graphs to have no features during batching.
......
...@@ -971,7 +971,7 @@ def to_homogeneous( ...@@ -971,7 +971,7 @@ def to_homogeneous(
-------- --------
to_heterogeneous to_heterogeneous
""" """
num_nodes_per_ntype = [G.number_of_nodes(ntype) for ntype in G.ntypes] num_nodes_per_ntype = [G.num_nodes(ntype) for ntype in G.ntypes]
offset_per_ntype = np.insert(np.cumsum(num_nodes_per_ntype), 0, 0) offset_per_ntype = np.insert(np.cumsum(num_nodes_per_ntype), 0, 0)
srcs = [] srcs = []
dsts = [] dsts = []
...@@ -986,7 +986,7 @@ def to_homogeneous( ...@@ -986,7 +986,7 @@ def to_homogeneous(
total_num_nodes = 0 total_num_nodes = 0
for ntype_id, ntype in enumerate(G.ntypes): for ntype_id, ntype in enumerate(G.ntypes):
num_nodes = G.number_of_nodes(ntype) num_nodes = G.num_nodes(ntype)
total_num_nodes += num_nodes total_num_nodes += num_nodes
if store_type: if store_type:
# Type ID is always in int64 # Type ID is always in int64
...@@ -1376,7 +1376,7 @@ def from_networkx( ...@@ -1376,7 +1376,7 @@ def from_networkx(
if node_attrs is not None: if node_attrs is not None:
# mapping from feature name to a list of tensors to be concatenated # mapping from feature name to a list of tensors to be concatenated
attr_dict = defaultdict(list) attr_dict = defaultdict(list)
for nid in range(g.number_of_nodes()): for nid in range(g.num_nodes()):
for attr in node_attrs: for attr in node_attrs:
attr_dict[attr].append(nx_graph.nodes[nid][attr]) attr_dict[attr].append(nx_graph.nodes[nid][attr])
for attr in node_attrs: for attr in node_attrs:
...@@ -1384,12 +1384,12 @@ def from_networkx( ...@@ -1384,12 +1384,12 @@ def from_networkx(
if edge_attrs is not None: if edge_attrs is not None:
# mapping from feature name to a list of tensors to be concatenated # mapping from feature name to a list of tensors to be concatenated
attr_dict = defaultdict(lambda: [None] * g.number_of_edges()) attr_dict = defaultdict(lambda: [None] * g.num_edges())
# each defaultdict value is initialized to be a list of None # each defaultdict value is initialized to be a list of None
# None here serves as placeholder to be replaced by feature with # None here serves as placeholder to be replaced by feature with
# corresponding edge id # corresponding edge id
if has_edge_id: if has_edge_id:
num_edges = g.number_of_edges() num_edges = g.num_edges()
for _, _, attrs in nx_graph.edges(data=True): for _, _, attrs in nx_graph.edges(data=True):
if attrs[edge_id_attr_name] >= num_edges: if attrs[edge_id_attr_name] >= num_edges:
raise DGLError( raise DGLError(
...@@ -1618,7 +1618,7 @@ def bipartite_from_networkx( ...@@ -1618,7 +1618,7 @@ def bipartite_from_networkx(
if e_attrs is not None: if e_attrs is not None:
# mapping from feature name to a list of tensors to be concatenated # mapping from feature name to a list of tensors to be concatenated
attr_dict = defaultdict(lambda: [None] * g.number_of_edges()) attr_dict = defaultdict(lambda: [None] * g.num_edges())
# each defaultdict value is initialized to be a list of None # each defaultdict value is initialized to be a list of None
# None here serves as placeholder to be replaced by feature with # None here serves as placeholder to be replaced by feature with
# corresponding edge id # corresponding edge id
...@@ -1700,7 +1700,7 @@ def to_networkx(g, node_attrs=None, edge_attrs=None): ...@@ -1700,7 +1700,7 @@ def to_networkx(g, node_attrs=None, edge_attrs=None):
dst = F.asnumpy(dst) dst = F.asnumpy(dst)
# xiangsx: Always treat graph as multigraph # xiangsx: Always treat graph as multigraph
nx_graph = nx.MultiDiGraph() nx_graph = nx.MultiDiGraph()
nx_graph.add_nodes_from(range(g.number_of_nodes())) nx_graph.add_nodes_from(range(g.num_nodes()))
for eid, (u, v) in enumerate(zip(src, dst)): for eid, (u, v) in enumerate(zip(src, dst)):
nx_graph.add_edge(u, v, id=eid) nx_graph.add_edge(u, v, id=eid)
......
...@@ -492,7 +492,7 @@ class EdgeCollator(Collator): ...@@ -492,7 +492,7 @@ class EdgeCollator(Collator):
} }
neg_pair_graph = heterograph( neg_pair_graph = heterograph(
neg_edges, neg_edges,
{ntype: self.g.number_of_nodes(ntype) for ntype in self.g.ntypes}, {ntype: self.g.num_nodes(ntype) for ntype in self.g.ntypes},
) )
pair_graph, neg_pair_graph = transforms.compact_graphs( pair_graph, neg_pair_graph = transforms.compact_graphs(
......
...@@ -44,14 +44,14 @@ class GraphIndex(ObjectBase): ...@@ -44,14 +44,14 @@ class GraphIndex(ObjectBase):
def __getstate__(self): def __getstate__(self):
src, dst, _ = self.edges() src, dst, _ = self.edges()
n_nodes = self.number_of_nodes() n_nodes = self.num_nodes()
readonly = self.is_readonly() readonly = self.is_readonly()
return n_nodes, readonly, src, dst return n_nodes, readonly, src, dst
def __setstate__(self, state): def __setstate__(self, state):
"""The pickle state of GraphIndex is defined as a triplet """The pickle state of GraphIndex is defined as a triplet
(number_of_nodes, readonly, src_nodes, dst_nodes) (num_nodes, readonly, src_nodes, dst_nodes)
""" """
# Pickle compatibility check # Pickle compatibility check
# TODO: we should store a storage version number in later releases. # TODO: we should store a storage version number in later releases.
...@@ -687,14 +687,14 @@ class GraphIndex(ObjectBase): ...@@ -687,14 +687,14 @@ class GraphIndex(ObjectBase):
if return_edge_ids if return_edge_ids
else np.ones_like(indices) else np.ones_like(indices)
) )
n = self.number_of_nodes() n = self.num_nodes()
return scipy.sparse.csr_matrix( return scipy.sparse.csr_matrix(
(data, indices, indptr), shape=(n, n) (data, indices, indptr), shape=(n, n)
) )
elif fmt == "coo": elif fmt == "coo":
idx = utils.toindex(rst(0)).tonumpy() idx = utils.toindex(rst(0)).tonumpy()
n = self.number_of_nodes() n = self.num_nodes()
m = self.number_of_edges() m = self.num_edges()
row, col = np.reshape(idx, (2, m)) row, col = np.reshape(idx, (2, m))
data = np.arange(0, m) if return_edge_ids else np.ones_like(row) data = np.arange(0, m) if return_edge_ids else np.ones_like(row)
return scipy.sparse.coo_matrix((data, (row, col)), shape=(n, n)) return scipy.sparse.coo_matrix((data, (row, col)), shape=(n, n))
...@@ -772,16 +772,16 @@ class GraphIndex(ObjectBase): ...@@ -772,16 +772,16 @@ class GraphIndex(ObjectBase):
spmat = F.sparse_matrix( spmat = F.sparse_matrix(
dat, dat,
("csr", indices, indptr), ("csr", indices, indptr),
(self.number_of_nodes(), self.number_of_nodes()), (self.num_nodes(), self.num_nodes()),
)[0] )[0]
return spmat, shuffle return spmat, shuffle
elif fmt == "coo": elif fmt == "coo":
## FIXME(minjie): data type ## FIXME(minjie): data type
idx = F.copy_to(utils.toindex(rst(0)).tousertensor(), ctx) idx = F.copy_to(utils.toindex(rst(0)).tousertensor(), ctx)
m = self.number_of_edges() m = self.num_edges()
idx = F.reshape(idx, (2, m)) idx = F.reshape(idx, (2, m))
dat = F.ones((m,), dtype=F.float32, ctx=ctx) dat = F.ones((m,), dtype=F.float32, ctx=ctx)
n = self.number_of_nodes() n = self.num_nodes()
adj, shuffle_idx = F.sparse_matrix(dat, ("coo", idx), (n, n)) adj, shuffle_idx = F.sparse_matrix(dat, ("coo", idx), (n, n))
shuffle_idx = ( shuffle_idx = (
utils.toindex(shuffle_idx) if shuffle_idx is not None else None utils.toindex(shuffle_idx) if shuffle_idx is not None else None
...@@ -829,8 +829,8 @@ class GraphIndex(ObjectBase): ...@@ -829,8 +829,8 @@ class GraphIndex(ObjectBase):
src = src.tousertensor(ctx) # the index of the ctx will be cached src = src.tousertensor(ctx) # the index of the ctx will be cached
dst = dst.tousertensor(ctx) # the index of the ctx will be cached dst = dst.tousertensor(ctx) # the index of the ctx will be cached
eid = eid.tousertensor(ctx) # the index of the ctx will be cached eid = eid.tousertensor(ctx) # the index of the ctx will be cached
n = self.number_of_nodes() n = self.num_nodes()
m = self.number_of_edges() m = self.num_edges()
if typestr == "in": if typestr == "in":
row = F.unsqueeze(dst, 0) row = F.unsqueeze(dst, 0)
col = F.unsqueeze(eid, 0) col = F.unsqueeze(eid, 0)
...@@ -881,7 +881,7 @@ class GraphIndex(ObjectBase): ...@@ -881,7 +881,7 @@ class GraphIndex(ObjectBase):
src, dst, eid = self.edges() src, dst, eid = self.edges()
# xiangsx: Always treat graph as multigraph # xiangsx: Always treat graph as multigraph
ret = nx.MultiDiGraph() ret = nx.MultiDiGraph()
ret.add_nodes_from(range(self.number_of_nodes())) ret.add_nodes_from(range(self.num_nodes()))
for u, v, e in zip(src, dst, eid): for u, v, e in zip(src, dst, eid):
ret.add_edge(u, v, id=e) ret.add_edge(u, v, id=e)
return ret return ret
...@@ -991,10 +991,7 @@ class GraphIndex(ObjectBase): ...@@ -991,10 +991,7 @@ class GraphIndex(ObjectBase):
int int
The number of bits needed The number of bits needed
""" """
if ( if self.num_edges() >= 0x80000000 or self.num_nodes() >= 0x80000000:
self.number_of_edges() >= 0x80000000
or self.number_of_nodes() >= 0x80000000
):
return 64 return 64
else: else:
return 32 return 32
......
...@@ -196,9 +196,7 @@ class DGLGraph(object): ...@@ -196,9 +196,7 @@ class DGLGraph(object):
if node_frames is None: if node_frames is None:
node_frames = [None] * len(self._ntypes) node_frames = [None] * len(self._ntypes)
node_frames = [ node_frames = [
Frame(num_rows=self._graph.number_of_nodes(i)) Frame(num_rows=self._graph.num_nodes(i)) if frame is None else frame
if frame is None
else frame
for i, frame in enumerate(node_frames) for i, frame in enumerate(node_frames)
] ]
self._node_frames = node_frames self._node_frames = node_frames
...@@ -206,9 +204,7 @@ class DGLGraph(object): ...@@ -206,9 +204,7 @@ class DGLGraph(object):
if edge_frames is None: if edge_frames is None:
edge_frames = [None] * len(self._etypes) edge_frames = [None] * len(self._etypes)
edge_frames = [ edge_frames = [
Frame(num_rows=self._graph.number_of_edges(i)) Frame(num_rows=self._graph.num_edges(i)) if frame is None else frame
if frame is None
else frame
for i, frame in enumerate(edge_frames) for i, frame in enumerate(edge_frames)
] ]
self._edge_frames = edge_frames self._edge_frames = edge_frames
...@@ -250,8 +246,8 @@ class DGLGraph(object): ...@@ -250,8 +246,8 @@ class DGLGraph(object):
" edata_schemes={edata})" " edata_schemes={edata})"
) )
return ret.format( return ret.format(
node=self.number_of_nodes(), node=self.num_nodes(),
edge=self.number_of_edges(), edge=self.num_edges(),
ndata=str(self.node_attr_schemes()), ndata=str(self.node_attr_schemes()),
edata=str(self.edge_attr_schemes()), edata=str(self.edge_attr_schemes()),
) )
...@@ -262,11 +258,11 @@ class DGLGraph(object): ...@@ -262,11 +258,11 @@ class DGLGraph(object):
" metagraph={meta})" " metagraph={meta})"
) )
nnode_dict = { nnode_dict = {
self.ntypes[i]: self._graph.number_of_nodes(i) self.ntypes[i]: self._graph.num_nodes(i)
for i in range(len(self.ntypes)) for i in range(len(self.ntypes))
} }
nedge_dict = { nedge_dict = {
self.canonical_etypes[i]: self._graph.number_of_edges(i) self.canonical_etypes[i]: self._graph.num_edges(i)
for i in range(len(self.etypes)) for i in range(len(self.etypes))
} }
meta = str(self.metagraph().edges(keys=True)) meta = str(self.metagraph().edges(keys=True))
...@@ -393,9 +389,9 @@ class DGLGraph(object): ...@@ -393,9 +389,9 @@ class DGLGraph(object):
num_nodes_per_type = [] num_nodes_per_type = []
for c_ntype in self.ntypes: for c_ntype in self.ntypes:
if self.get_ntype_id(c_ntype) == ntid: if self.get_ntype_id(c_ntype) == ntid:
num_nodes_per_type.append(self.number_of_nodes(c_ntype) + num) num_nodes_per_type.append(self.num_nodes(c_ntype) + num)
else: else:
num_nodes_per_type.append(self.number_of_nodes(c_ntype)) num_nodes_per_type.append(self.num_nodes(c_ntype))
relation_graphs = [] relation_graphs = []
for c_etype in self.canonical_etypes: for c_etype in self.canonical_etypes:
...@@ -407,9 +403,9 @@ class DGLGraph(object): ...@@ -407,9 +403,9 @@ class DGLGraph(object):
u, v = self.edges(form="uv", order="eid", etype=c_etype) u, v = self.edges(form="uv", order="eid", etype=c_etype)
hgidx = heterograph_index.create_unitgraph_from_coo( hgidx = heterograph_index.create_unitgraph_from_coo(
1 if c_etype[0] == c_etype[2] else 2, 1 if c_etype[0] == c_etype[2] else 2,
self.number_of_nodes(c_etype[0]) self.num_nodes(c_etype[0])
+ (num if self.get_ntype_id(c_etype[0]) == ntid else 0), + (num if self.get_ntype_id(c_etype[0]) == ntid else 0),
self.number_of_nodes(c_etype[2]) self.num_nodes(c_etype[2])
+ (num if self.get_ntype_id(c_etype[2]) == ntid else 0), + (num if self.get_ntype_id(c_etype[2]) == ntid else 0),
u, u,
v, v,
...@@ -529,10 +525,10 @@ class DGLGraph(object): ...@@ -529,10 +525,10 @@ class DGLGraph(object):
>>> g.add_edges(torch.tensor([3]), torch.tensor([3])) >>> g.add_edges(torch.tensor([3]), torch.tensor([3]))
DGLError: Edge type name must be specified DGLError: Edge type name must be specified
if there are more than one edge types. if there are more than one edge types.
>>> g.number_of_edges('plays') >>> g.num_edges('plays')
4 4
>>> g.add_edges(torch.tensor([3]), torch.tensor([3]), etype='plays') >>> g.add_edges(torch.tensor([3]), torch.tensor([3]), etype='plays')
>>> g.number_of_edges('plays') >>> g.num_edges('plays')
5 5
See Also See Also
...@@ -573,8 +569,8 @@ class DGLGraph(object): ...@@ -573,8 +569,8 @@ class DGLGraph(object):
u_type, e_type, v_type = self.to_canonical_etype(etype) u_type, e_type, v_type = self.to_canonical_etype(etype)
# if end nodes of adding edges does not exists # if end nodes of adding edges does not exists
# use add_nodes to add new nodes first. # use add_nodes to add new nodes first.
num_of_u = self.number_of_nodes(u_type) num_of_u = self.num_nodes(u_type)
num_of_v = self.number_of_nodes(v_type) num_of_v = self.num_nodes(v_type)
u_max = F.as_scalar(F.max(u, dim=0)) + 1 u_max = F.as_scalar(F.max(u, dim=0)) + 1
v_max = F.as_scalar(F.max(v, dim=0)) + 1 v_max = F.as_scalar(F.max(v, dim=0)) + 1
...@@ -592,7 +588,7 @@ class DGLGraph(object): ...@@ -592,7 +588,7 @@ class DGLGraph(object):
metagraph = self._graph.metagraph metagraph = self._graph.metagraph
num_nodes_per_type = [] num_nodes_per_type = []
for ntype in self.ntypes: for ntype in self.ntypes:
num_nodes_per_type.append(self.number_of_nodes(ntype)) num_nodes_per_type.append(self.num_nodes(ntype))
# update graph idx # update graph idx
relation_graphs = [] relation_graphs = []
for c_etype in self.canonical_etypes: for c_etype in self.canonical_etypes:
...@@ -601,8 +597,8 @@ class DGLGraph(object): ...@@ -601,8 +597,8 @@ class DGLGraph(object):
old_u, old_v = self.edges(form="uv", order="eid", etype=c_etype) old_u, old_v = self.edges(form="uv", order="eid", etype=c_etype)
hgidx = heterograph_index.create_unitgraph_from_coo( hgidx = heterograph_index.create_unitgraph_from_coo(
1 if u_type == v_type else 2, 1 if u_type == v_type else 2,
self.number_of_nodes(u_type), self.num_nodes(u_type),
self.number_of_nodes(v_type), self.num_nodes(v_type),
F.cat([old_u, u], dim=0), F.cat([old_u, u], dim=0),
F.cat([old_v, v], dim=0), F.cat([old_v, v], dim=0),
["coo", "csr", "csc"], ["coo", "csr", "csc"],
...@@ -718,10 +714,10 @@ class DGLGraph(object): ...@@ -718,10 +714,10 @@ class DGLGraph(object):
if len(eids) == 0: if len(eids) == 0:
# no edge to delete # no edge to delete
return return
assert self.number_of_edges(etype) > F.as_scalar( assert self.num_edges(etype) > F.as_scalar(
F.max(eids, dim=0) F.max(eids, dim=0)
), "The input eid {} is out of the range [0:{})".format( ), "The input eid {} is out of the range [0:{})".format(
F.as_scalar(F.max(eids, dim=0)), self.number_of_edges(etype) F.as_scalar(F.max(eids, dim=0)), self.num_edges(etype)
) )
# edge_subgraph # edge_subgraph
...@@ -860,10 +856,10 @@ class DGLGraph(object): ...@@ -860,10 +856,10 @@ class DGLGraph(object):
if len(nids) == 0: if len(nids) == 0:
# no node to delete # no node to delete
return return
assert self.number_of_nodes(ntype) > F.as_scalar( assert self.num_nodes(ntype) > F.as_scalar(
F.max(nids, dim=0) F.max(nids, dim=0)
), "The input nids {} is out of the range [0:{})".format( ), "The input nids {} is out of the range [0:{})".format(
F.as_scalar(F.max(nids, dim=0)), self.number_of_nodes(ntype) F.as_scalar(F.max(nids, dim=0)), self.num_nodes(ntype)
) )
ntid = self.get_ntype_id(ntype) ntid = self.get_ntype_id(ntype)
...@@ -898,7 +894,7 @@ class DGLGraph(object): ...@@ -898,7 +894,7 @@ class DGLGraph(object):
) )
# Record old num_edges to check later whether some edges were removed # Record old num_edges to check later whether some edges were removed
old_num_edges = { old_num_edges = {
c_etype: self._graph.number_of_edges(self.get_etype_id(c_etype)) c_etype: self._graph.num_edges(self.get_etype_id(c_etype))
for c_etype in self.canonical_etypes for c_etype in self.canonical_etypes
} }
...@@ -914,12 +910,12 @@ class DGLGraph(object): ...@@ -914,12 +910,12 @@ class DGLGraph(object):
canonical_etypes = [ canonical_etypes = [
c_etype c_etype
for c_etype in self.canonical_etypes for c_etype in self.canonical_etypes
if self._graph.number_of_edges(self.get_etype_id(c_etype)) if self._graph.num_edges(self.get_etype_id(c_etype))
!= old_num_edges[c_etype] != old_num_edges[c_etype]
] ]
for c_etype in canonical_etypes: for c_etype in canonical_etypes:
if self._graph.number_of_edges(self.get_etype_id(c_etype)) == 0: if self._graph.num_edges(self.get_etype_id(c_etype)) == 0:
self._batch_num_edges[c_etype] = F.zeros( self._batch_num_edges[c_etype] = F.zeros(
(self.batch_size,), F.int64, self.device (self.batch_size,), F.int64, self.device
) )
...@@ -1515,7 +1511,7 @@ class DGLGraph(object): ...@@ -1515,7 +1511,7 @@ class DGLGraph(object):
self._batch_num_nodes = {} self._batch_num_nodes = {}
for ty in self.ntypes: for ty in self.ntypes:
bnn = F.copy_to( bnn = F.copy_to(
F.tensor([self.number_of_nodes(ty)], F.int64), self.device F.tensor([self.num_nodes(ty)], F.int64), self.device
) )
self._batch_num_nodes[ty] = bnn self._batch_num_nodes[ty] = bnn
if ntype is None: if ntype is None:
...@@ -1664,7 +1660,7 @@ class DGLGraph(object): ...@@ -1664,7 +1660,7 @@ class DGLGraph(object):
self._batch_num_edges = {} self._batch_num_edges = {}
for ty in self.canonical_etypes: for ty in self.canonical_etypes:
bne = F.copy_to( bne = F.copy_to(
F.tensor([self.number_of_edges(ty)], F.int64), self.device F.tensor([self.num_edges(ty)], F.int64), self.device
) )
self._batch_num_edges[ty] = bne self._batch_num_edges[ty] = bne
if etype is None: if etype is None:
...@@ -2533,12 +2529,12 @@ class DGLGraph(object): ...@@ -2533,12 +2529,12 @@ class DGLGraph(object):
if ntype is None: if ntype is None:
return sum( return sum(
[ [
self._graph.number_of_nodes(ntid) self._graph.num_nodes(ntid)
for ntid in range(len(self.ntypes)) for ntid in range(len(self.ntypes))
] ]
) )
else: else:
return self._graph.number_of_nodes(self.get_ntype_id(ntype)) return self._graph.num_nodes(self.get_ntype_id(ntype))
def number_of_src_nodes(self, ntype=None): def number_of_src_nodes(self, ntype=None):
"""Alias of :meth:`num_src_nodes`""" """Alias of :meth:`num_src_nodes`"""
...@@ -2603,14 +2599,12 @@ class DGLGraph(object): ...@@ -2603,14 +2599,12 @@ class DGLGraph(object):
if ntype is None: if ntype is None:
return sum( return sum(
[ [
self._graph.number_of_nodes(self.get_ntype_id_from_src(nty)) self._graph.num_nodes(self.get_ntype_id_from_src(nty))
for nty in self.srctypes for nty in self.srctypes
] ]
) )
else: else:
return self._graph.number_of_nodes( return self._graph.num_nodes(self.get_ntype_id_from_src(ntype))
self.get_ntype_id_from_src(ntype)
)
def number_of_dst_nodes(self, ntype=None): def number_of_dst_nodes(self, ntype=None):
"""Alias of :func:`num_dst_nodes`""" """Alias of :func:`num_dst_nodes`"""
...@@ -2675,14 +2669,12 @@ class DGLGraph(object): ...@@ -2675,14 +2669,12 @@ class DGLGraph(object):
if ntype is None: if ntype is None:
return sum( return sum(
[ [
self._graph.number_of_nodes(self.get_ntype_id_from_dst(nty)) self._graph.num_nodes(self.get_ntype_id_from_dst(nty))
for nty in self.dsttypes for nty in self.dsttypes
] ]
) )
else: else:
return self._graph.number_of_nodes( return self._graph.num_nodes(self.get_ntype_id_from_dst(ntype))
self.get_ntype_id_from_dst(ntype)
)
def number_of_edges(self, etype=None): def number_of_edges(self, etype=None):
"""Alias of :func:`num_edges`""" """Alias of :func:`num_edges`"""
...@@ -2741,12 +2733,12 @@ class DGLGraph(object): ...@@ -2741,12 +2733,12 @@ class DGLGraph(object):
if etype is None: if etype is None:
return sum( return sum(
[ [
self._graph.number_of_edges(etid) self._graph.num_edges(etid)
for etid in range(len(self.canonical_etypes)) for etid in range(len(self.canonical_etypes))
] ]
) )
else: else:
return self._graph.number_of_edges(self.get_etype_id(etype)) return self._graph.num_edges(self.get_etype_id(etype))
@property @property
def is_multigraph(self): def is_multigraph(self):
...@@ -4272,7 +4264,7 @@ class DGLGraph(object): ...@@ -4272,7 +4264,7 @@ class DGLGraph(object):
Node representation. Node representation.
""" """
if is_all(u): if is_all(u):
num_nodes = self._graph.number_of_nodes(ntid) num_nodes = self._graph.num_nodes(ntid)
else: else:
u = utils.prepare_tensor(self, u, "u") u = utils.prepare_tensor(self, u, "u")
num_nodes = len(u) num_nodes = len(u)
...@@ -4386,7 +4378,7 @@ class DGLGraph(object): ...@@ -4386,7 +4378,7 @@ class DGLGraph(object):
) )
if is_all(edges): if is_all(edges):
num_edges = self._graph.number_of_edges(etid) num_edges = self._graph.num_edges(etid)
else: else:
num_edges = len(eid) num_edges = len(eid)
for key, val in data.items(): for key, val in data.items():
...@@ -5838,7 +5830,7 @@ class DGLGraph(object): ...@@ -5838,7 +5830,7 @@ class DGLGraph(object):
metagraph = graph_index.from_edge_list(meta_edges, True) metagraph = graph_index.from_edge_list(meta_edges, True)
# rebuild graph idx # rebuild graph idx
num_nodes_per_type = [ num_nodes_per_type = [
self.number_of_nodes(c_ntype) for c_ntype in self.ntypes self.num_nodes(c_ntype) for c_ntype in self.ntypes
] ]
relation_graphs = [ relation_graphs = [
self._graph.get_relation_graph(self.get_etype_id(c_etype)) self._graph.get_relation_graph(self.get_etype_id(c_etype))
...@@ -6306,18 +6298,18 @@ def make_canonical_etypes(etypes, ntypes, metagraph): ...@@ -6306,18 +6298,18 @@ def make_canonical_etypes(etypes, ntypes, metagraph):
list of tuples (srctype, etype, dsttype) list of tuples (srctype, etype, dsttype)
""" """
# sanity check # sanity check
if len(etypes) != metagraph.number_of_edges(): if len(etypes) != metagraph.num_edges():
raise DGLError( raise DGLError(
"Length of edge type list must match the number of " "Length of edge type list must match the number of "
"edges in the metagraph. {} vs {}".format( "edges in the metagraph. {} vs {}".format(
len(etypes), metagraph.number_of_edges() len(etypes), metagraph.num_edges()
) )
) )
if len(ntypes) != metagraph.number_of_nodes(): if len(ntypes) != metagraph.num_nodes():
raise DGLError( raise DGLError(
"Length of nodes type list must match the number of " "Length of nodes type list must match the number of "
"nodes in the metagraph. {} vs {}".format( "nodes in the metagraph. {} vs {}".format(
len(ntypes), metagraph.number_of_nodes() len(ntypes), metagraph.num_nodes()
) )
) )
if len(etypes) == 1 and len(ntypes) == 1: if len(etypes) == 1 and len(ntypes) == 1:
...@@ -6532,7 +6524,7 @@ class DGLBlock(DGLGraph): ...@@ -6532,7 +6524,7 @@ class DGLBlock(DGLGraph):
return ret.format( return ret.format(
srcnode=self.number_of_src_nodes(), srcnode=self.number_of_src_nodes(),
dstnode=self.number_of_dst_nodes(), dstnode=self.number_of_dst_nodes(),
edge=self.number_of_edges(), edge=self.num_edges(),
) )
else: else:
ret = ( ret = (
...@@ -6550,8 +6542,7 @@ class DGLBlock(DGLGraph): ...@@ -6550,8 +6542,7 @@ class DGLBlock(DGLGraph):
for ntype in self.dsttypes for ntype in self.dsttypes
} }
nedge_dict = { nedge_dict = {
etype: self.number_of_edges(etype) etype: self.num_edges(etype) for etype in self.canonical_etypes
for etype in self.canonical_etypes
} }
meta = str(self.metagraph().edges(keys=True)) meta = str(self.metagraph().edges(keys=True))
return ret.format( return ret.format(
......
...@@ -47,15 +47,15 @@ class HeteroGraphIndex(ObjectBase): ...@@ -47,15 +47,15 @@ class HeteroGraphIndex(ObjectBase):
self.__init_handle_by_constructor__(_CAPI_DGLHeteroUnpickle, state) self.__init_handle_by_constructor__(_CAPI_DGLHeteroUnpickle, state)
elif isinstance(state, tuple) and len(state) == 3: elif isinstance(state, tuple) and len(state) == 3:
# pre-0.4.2 # pre-0.4.2
metagraph, number_of_nodes, edges = state metagraph, num_nodes, edges = state
self._cache = {} self._cache = {}
# loop over etypes and recover unit graphs # loop over etypes and recover unit graphs
rel_graphs = [] rel_graphs = []
for i, edges_per_type in enumerate(edges): for i, edges_per_type in enumerate(edges):
src_ntype, dst_ntype = metagraph.find_edge(i) src_ntype, dst_ntype = metagraph.find_edge(i)
num_src = number_of_nodes[src_ntype] num_src = num_nodes[src_ntype]
num_dst = number_of_nodes[dst_ntype] num_dst = num_nodes[dst_ntype]
src_id, dst_id, _ = edges_per_type src_id, dst_id, _ = edges_per_type
rel_graphs.append( rel_graphs.append(
create_unitgraph_from_coo( create_unitgraph_from_coo(
...@@ -88,11 +88,11 @@ class HeteroGraphIndex(ObjectBase): ...@@ -88,11 +88,11 @@ class HeteroGraphIndex(ObjectBase):
def number_of_ntypes(self): def number_of_ntypes(self):
"""Return number of node types.""" """Return number of node types."""
return self.metagraph.number_of_nodes() return self.metagraph.num_nodes()
def number_of_etypes(self): def number_of_etypes(self):
"""Return number of edge types.""" """Return number of edge types."""
return self.metagraph.number_of_edges() return self.metagraph.num_edges()
def get_relation_graph(self, etype): def get_relation_graph(self, etype):
"""Get the unitgraph graph of the given edge/relation type. """Get the unitgraph graph of the given edge/relation type.
...@@ -212,9 +212,9 @@ class HeteroGraphIndex(ObjectBase): ...@@ -212,9 +212,9 @@ class HeteroGraphIndex(ObjectBase):
""" """
stype, dtype = self.metagraph.find_edge(etype) stype, dtype = self.metagraph.find_edge(etype)
if ( if (
self.number_of_edges(etype) >= 0x80000000 self.num_edges(etype) >= 0x80000000
or self.number_of_nodes(stype) >= 0x80000000 or self.num_nodes(stype) >= 0x80000000
or self.number_of_nodes(dtype) >= 0x80000000 or self.num_nodes(dtype) >= 0x80000000
): ):
return 64 return 64
else: else:
...@@ -757,16 +757,12 @@ class HeteroGraphIndex(ObjectBase): ...@@ -757,16 +757,12 @@ class HeteroGraphIndex(ObjectBase):
# convert to framework-specific sparse matrix # convert to framework-specific sparse matrix
srctype, dsttype = self.metagraph.find_edge(etype) srctype, dsttype = self.metagraph.find_edge(etype)
nrows = ( nrows = (
self.number_of_nodes(dsttype) self.num_nodes(dsttype) if transpose else self.num_nodes(srctype)
if transpose
else self.number_of_nodes(srctype)
) )
ncols = ( ncols = (
self.number_of_nodes(srctype) self.num_nodes(srctype) if transpose else self.num_nodes(dsttype)
if transpose
else self.number_of_nodes(dsttype)
) )
nnz = self.number_of_edges(etype) nnz = self.num_edges(etype)
if fmt == "csr": if fmt == "csr":
indptr = F.copy_to(F.from_dgl_nd(rst(0)), ctx) indptr = F.copy_to(F.from_dgl_nd(rst(0)), ctx)
indices = F.copy_to(F.from_dgl_nd(rst(1)), ctx) indices = F.copy_to(F.from_dgl_nd(rst(1)), ctx)
...@@ -831,16 +827,12 @@ class HeteroGraphIndex(ObjectBase): ...@@ -831,16 +827,12 @@ class HeteroGraphIndex(ObjectBase):
rst = _CAPI_DGLHeteroGetAdj(self, int(etype), transpose, fmt) rst = _CAPI_DGLHeteroGetAdj(self, int(etype), transpose, fmt)
srctype, dsttype = self.metagraph.find_edge(etype) srctype, dsttype = self.metagraph.find_edge(etype)
nrows = ( nrows = (
self.number_of_nodes(dsttype) self.num_nodes(dsttype) if transpose else self.num_nodes(srctype)
if transpose
else self.number_of_nodes(srctype)
) )
ncols = ( ncols = (
self.number_of_nodes(srctype) self.num_nodes(srctype) if transpose else self.num_nodes(dsttype)
if transpose
else self.number_of_nodes(dsttype)
) )
nnz = self.number_of_edges(etype) nnz = self.num_edges(etype)
if fmt == "csr": if fmt == "csr":
indptr = F.from_dgl_nd(rst(0)) indptr = F.from_dgl_nd(rst(0))
indices = F.from_dgl_nd(rst(1)) indices = F.from_dgl_nd(rst(1))
...@@ -900,7 +892,7 @@ class HeteroGraphIndex(ObjectBase): ...@@ -900,7 +892,7 @@ class HeteroGraphIndex(ObjectBase):
# Check if edge ID is omitted # Check if edge ID is omitted
if return_edge_ids and data.shape[0] == 0: if return_edge_ids and data.shape[0] == 0:
data = np.arange(self.number_of_edges(etype)) data = np.arange(self.num_edges(etype))
else: else:
data = np.ones_like(indices) data = np.ones_like(indices)
...@@ -914,7 +906,7 @@ class HeteroGraphIndex(ObjectBase): ...@@ -914,7 +906,7 @@ class HeteroGraphIndex(ObjectBase):
row = F.asnumpy(row) row = F.asnumpy(row)
col = F.asnumpy(col) col = F.asnumpy(col)
data = ( data = (
np.arange(self.number_of_edges(etype)) np.arange(self.num_edges(etype))
if return_edge_ids if return_edge_ids
else np.ones_like(row) else np.ones_like(row)
) )
...@@ -964,9 +956,9 @@ class HeteroGraphIndex(ObjectBase): ...@@ -964,9 +956,9 @@ class HeteroGraphIndex(ObjectBase):
src, dst, eid = self.edges(etype) src, dst, eid = self.edges(etype)
srctype, dsttype = self.metagraph.find_edge(etype) srctype, dsttype = self.metagraph.find_edge(etype)
m = self.number_of_edges(etype) m = self.num_edges(etype)
if typestr == "in": if typestr == "in":
n = self.number_of_nodes(dsttype) n = self.num_nodes(dsttype)
row = F.unsqueeze(dst, 0) row = F.unsqueeze(dst, 0)
col = F.unsqueeze(eid, 0) col = F.unsqueeze(eid, 0)
idx = F.copy_to(F.cat([row, col], dim=0), ctx) idx = F.copy_to(F.cat([row, col], dim=0), ctx)
...@@ -974,7 +966,7 @@ class HeteroGraphIndex(ObjectBase): ...@@ -974,7 +966,7 @@ class HeteroGraphIndex(ObjectBase):
dat = F.ones((m,), dtype=F.float32, ctx=ctx) dat = F.ones((m,), dtype=F.float32, ctx=ctx)
inc, shuffle_idx = F.sparse_matrix(dat, ("coo", idx), (n, m)) inc, shuffle_idx = F.sparse_matrix(dat, ("coo", idx), (n, m))
elif typestr == "out": elif typestr == "out":
n = self.number_of_nodes(srctype) n = self.num_nodes(srctype)
row = F.unsqueeze(src, 0) row = F.unsqueeze(src, 0)
col = F.unsqueeze(eid, 0) col = F.unsqueeze(eid, 0)
idx = F.copy_to(F.cat([row, col], dim=0), ctx) idx = F.copy_to(F.cat([row, col], dim=0), ctx)
...@@ -985,7 +977,7 @@ class HeteroGraphIndex(ObjectBase): ...@@ -985,7 +977,7 @@ class HeteroGraphIndex(ObjectBase):
assert ( assert (
srctype == dsttype srctype == dsttype
), "'both' is supported only if source and destination type are the same" ), "'both' is supported only if source and destination type are the same"
n = self.number_of_nodes(srctype) n = self.num_nodes(srctype)
# first remove entries for self loops # first remove entries for self loops
mask = F.logical_not(F.equal(src, dst)) mask = F.logical_not(F.equal(src, dst))
src = F.boolean_mask(src, mask) src = F.boolean_mask(src, mask)
......
...@@ -109,9 +109,7 @@ def gspmm(g, op, reduce_op, lhs_data, rhs_data): ...@@ -109,9 +109,7 @@ def gspmm(g, op, reduce_op, lhs_data, rhs_data):
if reduce_op == "mean": if reduce_op == "mean":
ret_shape = F.shape(ret) ret_shape = F.shape(ret)
deg = g.in_degrees() deg = g.in_degrees()
deg = F.astype( deg = F.astype(F.clamp(deg, 1, max(g.num_edges(), 1)), F.dtype(ret))
F.clamp(deg, 1, max(g.number_of_edges(), 1)), F.dtype(ret)
)
deg_shape = (ret_shape[0],) + (1,) * (len(ret_shape) - 1) deg_shape = (ret_shape[0],) + (1,) * (len(ret_shape) - 1)
return ret / F.reshape(deg, deg_shape) return ret / F.reshape(deg, deg_shape)
else: else:
......
...@@ -535,7 +535,7 @@ class SparseAdagrad(SparseGradOptimizer): ...@@ -535,7 +535,7 @@ class SparseAdagrad(SparseGradOptimizer):
>>> def initializer(emb): >>> def initializer(emb):
th.nn.init.xavier_uniform_(emb) th.nn.init.xavier_uniform_(emb)
return emb return emb
>>> emb = dgl.nn.NodeEmbedding(g.number_of_nodes(), 10, 'emb', init_func=initializer) >>> emb = dgl.nn.NodeEmbedding(g.num_nodes(), 10, 'emb', init_func=initializer)
>>> optimizer = dgl.optim.SparseAdagrad([emb], lr=0.001) >>> optimizer = dgl.optim.SparseAdagrad([emb], lr=0.001)
>>> for blocks in dataloader: >>> for blocks in dataloader:
... ... ... ...
...@@ -690,7 +690,7 @@ class SparseAdam(SparseGradOptimizer): ...@@ -690,7 +690,7 @@ class SparseAdam(SparseGradOptimizer):
>>> def initializer(emb): >>> def initializer(emb):
th.nn.init.xavier_uniform_(emb) th.nn.init.xavier_uniform_(emb)
return emb return emb
>>> emb = dgl.nn.NodeEmbedding(g.number_of_nodes(), 10, 'emb', init_func=initializer) >>> emb = dgl.nn.NodeEmbedding(g.num_nodes(), 10, 'emb', init_func=initializer)
>>> optimizer = dgl.optim.SparseAdam([emb], lr=0.001) >>> optimizer = dgl.optim.SparseAdam([emb], lr=0.001)
>>> for blocks in dataloader: >>> for blocks in dataloader:
... ... ... ...
......
...@@ -37,13 +37,13 @@ def reorder_nodes(g, new_node_ids): ...@@ -37,13 +37,13 @@ def reorder_nodes(g, new_node_ids):
The graph with new node IDs. The graph with new node IDs.
""" """
assert ( assert (
len(new_node_ids) == g.number_of_nodes() len(new_node_ids) == g.num_nodes()
), "The number of new node ids must match #nodes in the graph." ), "The number of new node ids must match #nodes in the graph."
new_node_ids = utils.toindex(new_node_ids) new_node_ids = utils.toindex(new_node_ids)
sorted_ids, idx = F.sort_1d(new_node_ids.tousertensor()) sorted_ids, idx = F.sort_1d(new_node_ids.tousertensor())
assert ( assert (
F.asnumpy(sorted_ids[0]) == 0 F.asnumpy(sorted_ids[0]) == 0
and F.asnumpy(sorted_ids[-1]) == g.number_of_nodes() - 1 and F.asnumpy(sorted_ids[-1]) == g.num_nodes() - 1
), "The new node IDs are incorrect." ), "The new node IDs are incorrect."
new_gidx = _CAPI_DGLReorderGraph_Hetero( new_gidx = _CAPI_DGLReorderGraph_Hetero(
g._graph, new_node_ids.todgltensor() g._graph, new_node_ids.todgltensor()
...@@ -81,8 +81,8 @@ def reshuffle_graph(g, node_part=None): ...@@ -81,8 +81,8 @@ def reshuffle_graph(g, node_part=None):
""" """
# In this case, we don't need to reshuffle node IDs and edge IDs. # In this case, we don't need to reshuffle node IDs and edge IDs.
if node_part is None: if node_part is None:
g.ndata["orig_id"] = F.arange(0, g.number_of_nodes()) g.ndata["orig_id"] = F.arange(0, g.num_nodes())
g.edata["orig_id"] = F.arange(0, g.number_of_edges()) g.edata["orig_id"] = F.arange(0, g.num_edges())
return g, None return g, None
start = time.time() start = time.time()
...@@ -109,8 +109,8 @@ def reshuffle_graph(g, node_part=None): ...@@ -109,8 +109,8 @@ def reshuffle_graph(g, node_part=None):
g.edata["orig_id"] = g.edata[EID] g.edata["orig_id"] = g.edata[EID]
return g, None return g, None
new_node_ids = np.zeros((g.number_of_nodes(),), dtype=np.int64) new_node_ids = np.zeros((g.num_nodes(),), dtype=np.int64)
new_node_ids[F.asnumpy(new2old_map)] = np.arange(0, g.number_of_nodes()) new_node_ids[F.asnumpy(new2old_map)] = np.arange(0, g.num_nodes())
# If the input graph is homogneous, we only need to create an empty array, so that # If the input graph is homogneous, we only need to create an empty array, so that
# _CAPI_DGLReassignEdges_Hetero knows how to handle it. # _CAPI_DGLReassignEdges_Hetero knows how to handle it.
etype = ( etype = (
...@@ -174,7 +174,7 @@ def partition_graph_with_halo(g, node_part, extra_cached_hops, reshuffle=False): ...@@ -174,7 +174,7 @@ def partition_graph_with_halo(g, node_part, extra_cached_hops, reshuffle=False):
1D tensor that stores the mapping between the reshuffled edge IDs and 1D tensor that stores the mapping between the reshuffled edge IDs and
the original edge IDs if 'reshuffle=True'. Otherwise, return None. the original edge IDs if 'reshuffle=True'. Otherwise, return None.
""" """
assert len(node_part) == g.number_of_nodes() assert len(node_part) == g.num_nodes()
if reshuffle: if reshuffle:
g, node_part = reshuffle_graph(g, node_part) g, node_part = reshuffle_graph(g, node_part)
orig_nids = g.ndata["orig_id"] orig_nids = g.ndata["orig_id"]
...@@ -196,7 +196,7 @@ def partition_graph_with_halo(g, node_part, extra_cached_hops, reshuffle=False): ...@@ -196,7 +196,7 @@ def partition_graph_with_halo(g, node_part, extra_cached_hops, reshuffle=False):
# An edge is assigned to a partition based on its destination node. If its destination node # An edge is assigned to a partition based on its destination node. If its destination node
# is assigned to a partition, we assign the edge to the partition as well. # is assigned to a partition, we assign the edge to the partition as well.
def get_inner_edge(subg, inner_node): def get_inner_edge(subg, inner_node):
inner_edge = F.zeros((subg.number_of_edges(),), F.int8, F.cpu()) inner_edge = F.zeros((subg.num_edges(),), F.int8, F.cpu())
inner_nids = F.nonzero_1d(inner_node) inner_nids = F.nonzero_1d(inner_node)
# TODO(zhengda) we need to fix utils.toindex() to avoid the dtype cast below. # TODO(zhengda) we need to fix utils.toindex() to avoid the dtype cast below.
inner_nids = F.astype(inner_nids, F.int64) inner_nids = F.astype(inner_nids, F.int64)
...@@ -248,7 +248,7 @@ def partition_graph_with_halo(g, node_part, extra_cached_hops, reshuffle=False): ...@@ -248,7 +248,7 @@ def partition_graph_with_halo(g, node_part, extra_cached_hops, reshuffle=False):
if extra_cached_hops >= 1: if extra_cached_hops >= 1:
inner_edge = get_inner_edge(subg, inner_node) inner_edge = get_inner_edge(subg, inner_node)
else: else:
inner_edge = F.ones((subg.number_of_edges(),), F.int8, F.cpu()) inner_edge = F.ones((subg.num_edges(),), F.int8, F.cpu())
subg.edata["inner_edge"] = inner_edge subg.edata["inner_edge"] = inner_edge
subg_dict[i] = subg subg_dict[i] = subg
print("Construct subgraphs: {:.3f} seconds".format(time.time() - start)) print("Construct subgraphs: {:.3f} seconds".format(time.time() - start))
...@@ -344,7 +344,7 @@ def metis_partition_assignment( ...@@ -344,7 +344,7 @@ def metis_partition_assignment(
start = time.time() start = time.time()
if balance_ntypes is not None: if balance_ntypes is not None:
assert ( assert (
len(balance_ntypes) == g.number_of_nodes() len(balance_ntypes) == g.num_nodes()
), "The length of balance_ntypes should be equal to #nodes in the graph" ), "The length of balance_ntypes should be equal to #nodes in the graph"
balance_ntypes = F.tensor(balance_ntypes) balance_ntypes = F.tensor(balance_ntypes)
uniq_ntypes = F.unique(balance_ntypes) uniq_ntypes = F.unique(balance_ntypes)
...@@ -358,7 +358,7 @@ def metis_partition_assignment( ...@@ -358,7 +358,7 @@ def metis_partition_assignment(
else: else:
for ntype in uniq_ntypes: for ntype in uniq_ntypes:
nids = F.asnumpy(F.nonzero_1d(balance_ntypes == ntype)) nids = F.asnumpy(F.nonzero_1d(balance_ntypes == ntype))
degs = np.zeros((g.number_of_nodes(),), np.int64) degs = np.zeros((g.num_nodes(),), np.int64)
degs[nids] = F.asnumpy(g.in_degrees(nids)) degs[nids] = F.asnumpy(g.in_degrees(nids))
vwgt.append(F.zerocopy_from_numpy(degs)) vwgt.append(F.zerocopy_from_numpy(degs))
......
...@@ -761,7 +761,7 @@ def select_topk( ...@@ -761,7 +761,7 @@ def select_topk(
# Rectify nodes to a dictionary # Rectify nodes to a dictionary
if nodes is None: if nodes is None:
nodes = { nodes = {
ntype: F.astype(F.arange(0, g.number_of_nodes(ntype)), g.idtype) ntype: F.astype(F.arange(0, g.num_nodes(ntype)), g.idtype)
for ntype in g.ntypes for ntype in g.ntypes
} }
elif not isinstance(nodes, dict): elif not isinstance(nodes, dict):
......
...@@ -156,7 +156,7 @@ class RandomWalkNeighborSampler(object): ...@@ -156,7 +156,7 @@ class RandomWalkNeighborSampler(object):
) )
neighbor_graph = convert.heterograph( neighbor_graph = convert.heterograph(
{(self.ntype, "_E", self.ntype): (src, dst)}, {(self.ntype, "_E", self.ntype): (src, dst)},
{self.ntype: self.G.number_of_nodes(self.ntype)}, {self.ntype: self.G.num_nodes(self.ntype)},
) )
neighbor_graph.edata[self.weight_column] = counts neighbor_graph.edata[self.weight_column] = counts
......
...@@ -1154,7 +1154,7 @@ def edge_type_subgraph(graph, etypes, output_device=None): ...@@ -1154,7 +1154,7 @@ def edge_type_subgraph(graph, etypes, output_device=None):
graph._etypes[i] for i in etype_ids graph._etypes[i] for i in etype_ids
] # get the "name" of edge type ] # get the "name" of edge type
num_nodes_per_induced_type = [ num_nodes_per_induced_type = [
graph.number_of_nodes(ntype) for ntype in induced_ntypes graph.num_nodes(ntype) for ntype in induced_ntypes
] ]
metagraph = graph_index.from_edge_list( metagraph = graph_index.from_edge_list(
......
...@@ -1039,9 +1039,7 @@ def add_reverse_edges( ...@@ -1039,9 +1039,7 @@ def add_reverse_edges(
for c_etype in canonical_etypes: for c_etype in canonical_etypes:
if c_etype[0] != c_etype[2]: if c_etype[0] != c_etype[2]:
eids.append( eids.append(
F.copy_to( F.copy_to(F.arange(0, g.num_edges(c_etype)), new_g.device)
F.arange(0, g.number_of_edges(c_etype)), new_g.device
)
) )
else: else:
eids.append(rev_eids[c_etype]) eids.append(rev_eids[c_etype])
...@@ -1235,7 +1233,7 @@ def khop_graph(g, k, copy_ndata=True): ...@@ -1235,7 +1233,7 @@ def khop_graph(g, k, copy_ndata=True):
edata_schemes={}) edata_schemes={})
""" """
assert g.is_homogeneous, "only homogeneous graph is supported" assert g.is_homogeneous, "only homogeneous graph is supported"
n = g.number_of_nodes() n = g.num_nodes()
adj_k = g.adj(transpose=False, scipy_fmt=g.formats()["created"][0]) ** k adj_k = g.adj(transpose=False, scipy_fmt=g.formats()["created"][0]) ** k
adj_k = adj_k.tocoo() adj_k = adj_k.tocoo()
multiplicity = adj_k.data multiplicity = adj_k.data
...@@ -1447,7 +1445,7 @@ def laplacian_lambda_max(g): ...@@ -1447,7 +1445,7 @@ def laplacian_lambda_max(g):
g_arr = batch.unbatch(g) g_arr = batch.unbatch(g)
rst = [] rst = []
for g_i in g_arr: for g_i in g_arr:
n = g_i.number_of_nodes() n = g_i.num_nodes()
adj = g_i.adj( adj = g_i.adj(
transpose=True, scipy_fmt=g_i.formats()["created"][0] transpose=True, scipy_fmt=g_i.formats()["created"][0]
).astype(float) ).astype(float)
...@@ -1721,10 +1719,10 @@ def add_edges(g, u, v, data=None, etype=None): ...@@ -1721,10 +1719,10 @@ def add_edges(g, u, v, data=None, etype=None):
... ('developer', 'develops', 'game'): (torch.tensor([0, 1]), ... ('developer', 'develops', 'game'): (torch.tensor([0, 1]),
... torch.tensor([0, 1])) ... torch.tensor([0, 1]))
... }) ... })
>>> g.number_of_edges('plays') >>> g.num_edges('plays')
4 4
>>> g = dgl.add_edges(g, torch.tensor([3]), torch.tensor([3]), etype='plays') >>> g = dgl.add_edges(g, torch.tensor([3]), torch.tensor([3]), etype='plays')
>>> g.number_of_edges('plays') >>> g.num_edges('plays')
5 5
See Also See Also
...@@ -2797,7 +2795,7 @@ def adj_sum_graph(graphs, weight_name): ...@@ -2797,7 +2795,7 @@ def adj_sum_graph(graphs, weight_name):
metagraph = graphs[0]._graph.metagraph metagraph = graphs[0]._graph.metagraph
num_nodes = utils.toindex( num_nodes = utils.toindex(
[ [
graphs[0]._graph.number_of_nodes(i) graphs[0]._graph.num_nodes(i)
for i in range(graphs[0]._graph.number_of_ntypes()) for i in range(graphs[0]._graph.number_of_ntypes())
] ]
) )
......
...@@ -48,7 +48,7 @@ class HeteroNodeView(object): ...@@ -48,7 +48,7 @@ class HeteroNodeView(object):
ntid = self._typeid_getter(ntype) ntid = self._typeid_getter(ntype)
ret = F.arange( ret = F.arange(
0, 0,
self._graph._graph.number_of_nodes(ntid), self._graph._graph.num_nodes(ntid),
dtype=self._graph.idtype, dtype=self._graph.idtype,
ctx=self._graph.device, ctx=self._graph.device,
) )
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment