MCPcopy Create free account
hub / github.com/RedisGraph/RedisGraph / IsAcyclicGraph

Function IsAcyclicGraph

src/algorithms/detect_cycle.c:13–66  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11#include "../../deps/GraphBLAS/Include/GraphBLAS.h"
12
13bool IsAcyclicGraph(const QueryGraph *qg) {
14 ASSERT(qg);
15
16 bool acyclic = true;
17
18 // Give an ID for each node, abuse of `labelID`.
19 uint node_count = QueryGraph_NodeCount(qg);
20 uint edge_count = QueryGraph_EdgeCount(qg);
21
22 GrB_Info res;
23 GrB_Matrix m; // Matrix representation of QueryGraph.
24 GrB_Matrix c; // Intermidate matrix, c = m^i.
25 GrB_Matrix t; // Temporary matrix, t = c .* i. elementwise boolean multiplication.
26
27 // Build matrix representation of query graph.
28 m = QueryGraph_MatrixRepresentation(qg);
29 res = GrB_Matrix_dup(&c, m);
30 UNUSED(res);
31 ASSERT(res == GrB_SUCCESS);
32 res = GrB_Matrix_new(&t, GrB_BOOL, node_count, node_count);
33 ASSERT(res == GrB_SUCCESS);
34
35 /* Perform traversals, stop when:
36 * 1. Node i manged to reach itself, x[i,i] is set (cycle detected).
37 * 2. After edge_count multiplications, no cycles. */
38 for(uint i = 0; i < edge_count; i++) {
39 // c = c * m.
40 res = GrB_mxm(c, GrB_NULL, GrB_NULL, GxB_ANY_PAIR_BOOL, c, m, GrB_NULL);
41 ASSERT(res == GrB_SUCCESS);
42
43 /* Extract main diagonal of `c` into `t`.
44 * Check if C[i,i] is set.
45 * t = c<identity> */
46 res = GxB_Matrix_select(t, GrB_NULL, GrB_NULL, GxB_DIAG, c, GrB_NULL, GrB_NULL);
47 ASSERT(res == GrB_SUCCESS);
48
49 /* How many entries are there in `t`?
50 * if there are any entires in `t` this means node `k` was able to reach itself cycle! */
51 GrB_Index nvals = 0;
52 res = GrB_Matrix_nvals(&nvals, t);
53 ASSERT(res == GrB_SUCCESS);
54 if(nvals != 0) {
55 acyclic = false;
56 break;
57 }
58 }
59
60 // Cleanup.
61 GrB_free(&m);
62 GrB_free(&c);
63 GrB_free(&t);
64
65 return acyclic;
66}
67

Callers 3

test_acyclicGraphFunction · 0.85
test_cyclicGraphFunction · 0.85

Calls 8

QueryGraph_NodeCountFunction · 0.85
QueryGraph_EdgeCountFunction · 0.85
GrB_Matrix_dupFunction · 0.85
GrB_Matrix_newFunction · 0.85
GrB_mxmFunction · 0.85
GxB_Matrix_selectFunction · 0.85
GrB_Matrix_nvalsFunction · 0.85

Tested by 2

test_acyclicGraphFunction · 0.68
test_cyclicGraphFunction · 0.68