|
| 1 | +from graphblas import Matrix, select, monoid, semiring |
| 2 | +from graphblas_algorithms.classes.graph import to_undirected_graph, Graph |
| 3 | +from graphblas_algorithms.utils import get_all, not_implemented_for |
| 4 | + |
| 5 | + |
| 6 | +def k_truss_core(G, k): |
| 7 | + # Ignore self-edges |
| 8 | + S = G.get_property("offdiag") |
| 9 | + |
| 10 | + if k < 3: |
| 11 | + # Most implementations consider k < 3 invalid, |
| 12 | + # but networkx leaves the graph unchanged |
| 13 | + C = S |
| 14 | + else: |
| 15 | + # Remove edges not in k-truss |
| 16 | + nvals_last = S.nvals |
| 17 | + # TODO: choose dtype based on max number of triangles |
| 18 | + plus_pair = semiring.plus_pair["int32"] |
| 19 | + C = Matrix("int32", S.nrows, S.ncols) |
| 20 | + while True: |
| 21 | + C(S.S, replace=True) << plus_pair(S @ S.T) |
| 22 | + C << select.value(C >= k - 2) |
| 23 | + if C.nvals == nvals_last: |
| 24 | + break |
| 25 | + nvals_last = C.nvals |
| 26 | + S = C |
| 27 | + |
| 28 | + # Remove isolate nodes |
| 29 | + indices, _ = C.reduce_rowwise(monoid.any).to_values() |
| 30 | + Ktruss = C[indices, indices].new() |
| 31 | + |
| 32 | + # Convert back to networkx graph with correct node ids |
| 33 | + keys = G.list_to_keys(indices) |
| 34 | + key_to_id = dict(zip(keys, range(len(indices)))) |
| 35 | + return Graph.from_graphblas(Ktruss, key_to_id=key_to_id) |
| 36 | + |
| 37 | + |
| 38 | +@not_implemented_for("directed") |
| 39 | +@not_implemented_for("multigraph") |
| 40 | +def k_truss(G, k): |
| 41 | + G = to_undirected_graph(G, dtype=bool) |
| 42 | + result = k_truss_core(G, k) |
| 43 | + return result.to_networkx() |
| 44 | + |
| 45 | + |
| 46 | +__all__ = get_all(__name__) |
0 commit comments