'''
摘自https://docs.dgl.ai/en/0.6.x/guide_cn/graph-feature.html
'''
import dgl
import torch as th
# ========================= 无权图 ======================================
g = dgl.graph(([0, 0, 1, 5], [1, 2, 2, 0])) # 6个节点,4条边
# each graph can have many 'node features'
g.ndata['x'] = th.ones(g.num_nodes(), 3) # 节点特征x, 特征长度为3
g.ndata['y'] = th.randn(g.num_nodes(), 5) # 节点特征y,特征长度为5
# similarly, each graph can have many 'edge features'
g.edata['x'] = th.ones(g.num_edges(), dtype=th.int32) # 标量整型边特征x
g.edata['z'] = th.ones(g.num_edges(), dtype=th.float32) # 浮点型型边特征z
print('g:\n', g)
print(g.ndata['x'][1]) # 获取节点特征x的节点1特征
print(g.ndata['y'][1]) # 获取节点特征y的节点1特征
print(g.edata['x'][th.tensor([0, 3])]) # 获取边特征x下的0和3节点特征
print()
# ========================= 有权图 ======================================
# edges 0->1, 0->2, 0->3, 1->3
edges = th.tensor([0, 0, 0, 1]), th.tensor([1, 2, 3, 3])
weights = th.tensor([0.1, 0.6, 0.9, 0.7]) # weight of each edge
g = dgl.graph(edges)
g.edata['w'] = weights # give it a name 'w'
print('weighted graph:\n', g)