Build a CSR graph from a deduplicated undirected edge list. */
| 10029 | |
| 10030 | /* Build a CSR graph from a deduplicated undirected edge list. */ |
| 10031 | static int lg_build(int n, const int *wsi, const int *wdi, const double *ww, int wn, |
| 10032 | cbm_lg_t *out) { |
| 10033 | int *off = calloc((size_t)n + 1, sizeof(int)); |
| 10034 | double *k = calloc((size_t)n, sizeof(double)); |
| 10035 | int *fill = malloc((size_t)n * sizeof(int)); |
| 10036 | if (!off || !k || !fill) { |
| 10037 | free(off); |
| 10038 | free(k); |
| 10039 | free(fill); |
| 10040 | return CBM_NOT_FOUND; |
| 10041 | } |
| 10042 | for (int e = 0; e < wn; e++) { |
| 10043 | off[wsi[e] + 1]++; |
| 10044 | off[wdi[e] + 1]++; |
| 10045 | } |
| 10046 | for (int i = 0; i < n; i++) { |
| 10047 | off[i + 1] += off[i]; |
| 10048 | } |
| 10049 | int total = off[n]; |
| 10050 | /* calloc, not malloc: every slot IS written (off[n] equals the summed |
| 10051 | * degrees, two writes per edge), but that invariant is invisible to |
| 10052 | * path-sensitive analysis, and zero-filled backing turns any future |
| 10053 | * degree-miscount bug into a benign self-loop instead of UB. */ |
| 10054 | int *nbr = calloc((size_t)(total > 0 ? total : 1), sizeof(int)); |
| 10055 | double *w = calloc((size_t)(total > 0 ? total : 1), sizeof(double)); |
| 10056 | if (!nbr || !w) { |
| 10057 | free(off); |
| 10058 | free(k); |
| 10059 | free(fill); |
| 10060 | free(nbr); |
| 10061 | free(w); |
| 10062 | return CBM_NOT_FOUND; |
| 10063 | } |
| 10064 | memcpy(fill, off, (size_t)n * sizeof(int)); |
| 10065 | for (int e = 0; e < wn; e++) { |
| 10066 | int a = wsi[e]; |
| 10067 | int b = wdi[e]; |
| 10068 | double we = ww[e]; |
| 10069 | nbr[fill[a]] = b; |
| 10070 | w[fill[a]] = we; |
| 10071 | fill[a]++; |
| 10072 | nbr[fill[b]] = a; |
| 10073 | w[fill[b]] = we; |
| 10074 | fill[b]++; |
| 10075 | k[a] += we; |
| 10076 | k[b] += we; |
| 10077 | } |
| 10078 | free(fill); |
| 10079 | out->n = n; |
| 10080 | out->off = off; |
| 10081 | out->nbr = nbr; |
| 10082 | out->w = w; |
| 10083 | out->k = k; |
| 10084 | return CBM_STORE_OK; |
| 10085 | } |
| 10086 | |
| 10087 | /* Local-moving phase: greedily move each node to the neighbouring community |
| 10088 | * with the highest modularity gain, using a work queue seeded with every node |