Local-moving phase: greedily move each node to the neighbouring community * with the highest modularity gain, using a work queue seeded with every node * and re-queueing only the neighbours of a node that actually moved. Mutates * comm[] in place. */
| 10089 | * and re-queueing only the neighbours of a node that actually moved. Mutates |
| 10090 | * comm[] in place. */ |
| 10091 | static void leiden_move(const cbm_lg_t *g, int *comm, double gamma, double twom) { |
| 10092 | int n = g->n; |
| 10093 | double *stot = calloc((size_t)n, sizeof(double)); |
| 10094 | double *acc = calloc((size_t)n, sizeof(double)); |
| 10095 | int *queue = malloc((size_t)n * sizeof(int)); |
| 10096 | int *dirty = malloc((size_t)n * sizeof(int)); |
| 10097 | bool *inq = calloc((size_t)n, sizeof(bool)); |
| 10098 | if (!stot || !acc || !queue || !dirty || !inq) { |
| 10099 | free(stot); |
| 10100 | free(acc); |
| 10101 | free(queue); |
| 10102 | free(dirty); |
| 10103 | free(inq); |
| 10104 | return; |
| 10105 | } |
| 10106 | for (int i = 0; i < n; i++) { |
| 10107 | stot[comm[i]] += g->k[i]; |
| 10108 | queue[i] = i; |
| 10109 | inq[i] = true; |
| 10110 | } |
| 10111 | int qhead = 0; |
| 10112 | int qcount = n; |
| 10113 | long cap = (long)n * LEIDEN_MOVE_PASS_CAP + LEIDEN_MAX_LEVELS; |
| 10114 | while (qcount > 0 && cap-- > 0) { |
| 10115 | int v = queue[qhead]; |
| 10116 | qhead = (qhead + 1) % n; |
| 10117 | qcount--; |
| 10118 | inq[v] = false; |
| 10119 | int cv = comm[v]; |
| 10120 | int ndirty = 0; |
| 10121 | for (int e = g->off[v]; e < g->off[v + 1]; e++) { |
| 10122 | int u = g->nbr[e]; |
| 10123 | if (u == v) { |
| 10124 | continue; |
| 10125 | } |
| 10126 | int cu = comm[u]; |
| 10127 | if (acc[cu] == 0.0) { |
| 10128 | dirty[ndirty++] = cu; |
| 10129 | } |
| 10130 | acc[cu] += g->w[e]; |
| 10131 | } |
| 10132 | stot[cv] -= g->k[v]; |
| 10133 | double kv = g->k[v]; |
| 10134 | int best_c = cv; |
| 10135 | double best_gain = acc[cv] - gamma * kv * stot[cv] / twom; |
| 10136 | for (int d = 0; d < ndirty; d++) { |
| 10137 | int c = dirty[d]; |
| 10138 | double gain = acc[c] - gamma * kv * stot[c] / twom; |
| 10139 | if (gain > best_gain) { |
| 10140 | best_gain = gain; |
| 10141 | best_c = c; |
| 10142 | } |
| 10143 | } |
| 10144 | stot[best_c] += kv; |
| 10145 | comm[v] = best_c; |
| 10146 | if (best_c != cv) { |
| 10147 | for (int e = g->off[v]; e < g->off[v + 1]; e++) { |
| 10148 | int u = g->nbr[e]; |