dgl.DGLHeteroGraph.incidence_matrix

DGLHeteroGraph.incidence_matrix(typestr, ctx=device(type='cpu'), etype=None)[source]

Return the incidence matrix representation of edges with the given edge type.

An incidence matrix is an n-by-m sparse matrix, where n is the number of nodes and m is the number of edges. Each nnz value indicating whether the edge is incident to the node or not.

There are three types of incidence matrices \(I\):

  • in:

    • \(I[v, e] = 1\) if \(e\) is the in-edge of \(v\) (or \(v\) is the dst node of \(e\));
    • \(I[v, e] = 0\) otherwise.
  • out:

    • \(I[v, e] = 1\) if \(e\) is the out-edge of \(v\) (or \(v\) is the src node of \(e\));
    • \(I[v, e] = 0\) otherwise.
  • both (only if source and destination node type are the same):

    • \(I[v, e] = 1\) if \(e\) is the in-edge of \(v\);
    • \(I[v, e] = -1\) if \(e\) is the out-edge of \(v\);
    • \(I[v, e] = 0\) otherwise (including self-loop).
Parameters:
  • typestr (str) – Can be either in, out or both
  • ctx (context, optional) – The context of returned incidence matrix. (Default: cpu)
  • etype (str, optional) – The edge type. Can be omitted if there is only one edge type in the graph.
Returns:

The incidence matrix.

Return type:

Framework SparseTensor

Examples

>>> g = dgl.graph([(0, 0), (1, 2)], 'user', 'follows')
>>> g.incidence_matrix('in')
tensor(indices=tensor([[0, 2],
                       [0, 1]]),
       values=tensor([1., 1.]),
       size=(3, 2), nnz=2, layout=torch.sparse_coo)
>>> g.incidence_matrix('out')
tensor(indices=tensor([[0, 1],
                       [0, 1]]),
       values=tensor([1., 1.]),
       size=(3, 2), nnz=2, layout=torch.sparse_coo)
>>> g.incidence_matrix('both')
tensor(indices=tensor([[1, 2],
                       [1, 1]]),
       values=tensor([-1.,  1.]),
       size=(3, 2), nnz=2, layout=torch.sparse_coo)