dgl.DGLGraph.inc

DGLGraph.inc(typestr, ctx=device(type='cpu'), etype=None)

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 or (str, str, str), optional) –

    The type names of the edges. The allowed type name formats are:

    • (str, str, str) for source node type, edge type and destination node type.

    • or one str edge type name if the name can uniquely identify a triplet format in the graph.

    Can be omitted if the graph has only one type of edges.

Returns

The incidence matrix.

Return type

Framework SparseTensor

Examples

The following example uses PyTorch backend.

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