dgl.DGLGraph.__getitem__

DGLGraph.__getitem__(key)[source]

返回此图的关系切片。

你可以使用self[srctype, etype, dsttype]获取一个关系切片,其中 srctypeetypedsttype可以是字符串或完整的 切片(:),表示通配符(即任何源/边/目标类型)。

关系切片是从原始异构图转换而来的同质(具有一种节点类型和一种边类型)或二分(具有两种节点类型和一种边类型)图。

如果只找到一种规范边类型,那么返回的关系切片将是从原始图中导出的子图。也就是说,它等同于self.edge_type_subgraph(etype)。返回的图的节点和边特征将与原始图共享。

如果找到多个规范的边类型,那么源/边/目标节点类型将是原始节点/边类型的连接。新的源/目标节点类型将通过调用dgl.combine_names()在原始源/目标类型上确定其名称。源/目标节点将通过连接原始源/目标类型的共同特征来形成。因此,它们不与原始图共享。边类型类似。

Parameters:

key (strtuple) – 可以是一个表示边类型名称的字符串,或者是一个形式为 (srctype, etype, dsttype) 的元组,其中 srctype, etype, dsttype 可以是 表示类型名称的字符串或一个完整的切片对象 (:)。

Returns:

关系切片。

Return type:

DGLGraph

注释

此函数返回一个新图。更改此图的内容不会反映到原始图上。

如果图将多种节点类型或边类型结合在一起,它将具有从新图到原始图的节点/边类型和ID的映射。 这些映射的名称为dgl.NTYPEdgl.NIDdgl.ETYPEdgl.EID, 类似于函数dgl.to_homogenenous()

示例

>>> g = dgl.heterograph({
...     ('A1', 'AB1', 'B'): ([0, 1, 2], [1, 2, 3]),
...     ('A1', 'AB2', 'B'): ([1, 2, 3], [3, 4, 5]),
...     ('A2', 'AB2', 'B'): ([1, 3, 5], [2, 4, 6])})
>>> new_g = g['A1', :, 'B']         # combines all edge types between A1 and B
>>> new_g
Graph(num_nodes={'A1': 4, 'B': 7},
      num_edges={('A1', 'AB1+AB2', 'B'): 6},
      metagraph=[('A1', 'B', 'AB1+AB2')])
>>> new_g.edges()
(tensor([0, 1, 2, 1, 2, 3]), tensor([1, 2, 3, 3, 4, 5]))
>>> new_g2 = g[:, 'AB2', 'B']        # combines all node types that are source of AB2
>>> new_g2
Graph(num_nodes={'A1+A2': 10, 'B': 7},
      num_edges={('A1+A2', 'AB2+AB2', 'B'): 6},
      metagraph=[('A1+A2', 'B', 'AB2+AB2')])
>>> new_g2.edges()
(tensor([1, 2, 3, 5, 7, 9]), tensor([3, 4, 5, 2, 4, 6]))

如果出现多种节点类型和边类型的组合,可以像下面这样找到到原始节点类型和ID的映射:

>>> new_g1.edges['AB1+AB2'].data[dgl.EID]
tensor([0, 1, 2, 0, 1, 2])
>>> new_g1.edges['AB1+AB2'].data[dgl.ETYPE]
tensor([0, 0, 0, 1, 1, 1])
>>> new_g2.nodes['A1+A2'].data[dgl.NID]
tensor([0, 1, 2, 3, 0, 1, 2, 3, 4, 5])
>>> new_g2.nodes['A1+A2'].data[dgl.NTYPE]
tensor([0, 0, 0, 0, 1, 1, 1, 1, 1, 1])