Debian Codegraph @

packages/seacas/libraries/chaco/klspiff/nway_kl.c

raw
1 /*
2 * Copyright(C) 1999-2020, 2022, 2023 National Technology & Engineering Solutions
3 * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
4 * NTESS, the U.S. Government retains certain rights in this software.
5 *
6 * See packages/seacas/LICENSE for details
7 */
8
9 #include "defs.h"
10 #include "params.h"
11 #include "smalloc.h"
12 #include "structs.h"
13 #include <math.h>
14 #include <stdio.h>
15
16 /* Idea:
17 'buckets[i][j]' is a set of buckets to sort moves from i to j.
18 listspace[i] is space for lists in buckets[i][j].
19 Loop through all nonequal pairs [i][j], taking the first element
20 in each list. Compare them all to find the largest allowed move.
21 Make that move, and save it in movelist.
22 */
23
24 int KL_MAX_PASS = -1; /* max KL passes; infinite if <= 0 */
25
26 int nway_kl(struct vtx_data **graph, /* data structure for graph */
27 int nvtxs, /* number of vtxs in graph */
28 struct bilist ****buckets, /* array of lists for bucket sort */
29 struct bilist **listspace, /* list data structure for each vertex */
30 int **tops, /* 2-D array of top of each set of buckets */
31 int **dvals, /* d-values for each transition */
32 int *sets, /* processor each vertex is assigned to */
33 int maxdval, /* maximum d-value for a vertex */
34 int nsets, /* number of sets divided into */
35 double *goal, /* desired set sizes */
36 float *term_wgts[], /* weights for terminal propagation */
37 int (*hops)[MAXSETS], /* cost of set transitions */
38 int max_dev, /* largest allowed deviation from balance */
39 int using_ewgts, /* are edge weights being used? */
40 int **bndy_list, /* list of vertices on boundary (0 ends) */
41 double *startweight /* sum of vweights in each set (in and out) */
42 )
43
44 /* Suaris and Kedem algorithm for quadrisection, generalized to an */
45 /* arbitrary number of sets, with intra-set cost function specified by hops. */
46 /* Note: this is for a single divide step. */
47 /* Also, sets contains an initial (possibly crummy) partitioning. */
48
49 {
50 extern double kl_bucket_time; /* time spent in KL bucketsort */
51 extern int KL_BAD_MOVES; /* # bad moves in a row to stop KL */
52 extern int DEBUG_KL; /* debug flag for KL */
53 extern int KL_RANDOM; /* use randomness in KL? */
54 extern int KL_NTRIES_BAD; /* number of unhelpful passes before quitting */
55 extern int KL_UNDO_LIST; /* should I back out of changes or start over? */
56 extern int KL_MAX_PASS; /* maximum number of outer KL loops */
57 extern double CUT_TO_HOP_COST; /* if term_prop; cut/hop importance */
58 struct bilist *movelist; /* list of vtxs to be moved */
59 struct bilist **endlist; /* end of movelists */
60 struct bilist *bestptr; /* best vertex in linked list */
61 struct bilist *bptr; /* loops through bucket list */
62 float *ewptr = NULL; /* loops through edge weights */
63 double *locked = NULL; /* weight of vertices locked in a set */
64 double *loose = NULL; /* weight of vtxs that can move from a set */
65 int *bspace = NULL; /* list of active vertices for bucketsort */
66 double *weightsum = NULL; /* sum of vweights for each partition */
67 int *edges = NULL; /* edge list for a vertex */
68 int *bdy_ptr = NULL; /* loops through bndy_list */
69 double time; /* timing parameter */
70 double delta; /* desire of sets to change size */
71 double bestdelta = -1; /* strongest delta value */
72 double deltaplus; /* largest negative deviation from goal size */
73 double deltaminus; /* largest negative deviation from goal size */
74 int list_length; /* how long is list of vertices to bucketsort? */
75 int balanced; /* is partition balanced? */
76 int temp_balanced; /* is intermediate partition balanced? */
77 int ever_balanced; /* has any partition been balanced? */
78 int bestvtx = -1; /* best vertex to move */
79 int bestval = -1; /* best change in value for a vtx move */
80 int bestfrom = -1, bestto = -1; /* sets best vertex moves between */
81 int vweight; /* weight of best vertex */
82 int gtotal; /* sum of changes from moving */
83 int improved; /* total improvement from KL */
84 double balance_val = 0.0; /* how imbalanced is it */
85 double balance_best; /* best balance yet if trying hard */
86 double bestg; /* maximum gtotal found in KL loop */
87 double bestg_min; /* smaller than any possible bestg */
88 int beststep; /* step where maximum value occurred */
89 int neighbor; /* neighbor of a vertex */
90 int step_cutoff; /* number of negative steps in a row allowed */
91 int cost_cutoff; /* amount of negative d-values allowed */
92 int neg_steps; /* number of negative steps in a row */
93 int neg_cost; /* decrease in sum of d-values */
94 int vtx; /* vertex number */
95 int dval; /* dval of a vertex */
96 int group; /* set that a vertex is assigned to */
97 double cut_cost; /* if term_prop; relative cut/hop importance */
98 int diff; /* change in a d-value */
99 int stuck1st, stuck2nd; /* how soon will moves be disallowed? */
100 int beststuck1 = -1, beststuck2 = -1; /* best stuck values for tie-breaking */
101 int eweight; /* a particular edge weight */
102 int worth_undoing; /* is it worth undoing list? */
103 float undo_frac; /* fraction of vtxs indicating worth of undoing */
104 int step; /* loops through movements of vertices */
105 int parity; /* sort forwards or backwards? */
106 int done; /* has termination criteria been achieved? */
107 int nbad; /* number of unhelpful passes in a row */
108 int npass; /* total number of passes */
109 int nbadtries; /* number of unhelpful passes before quitting */
110 int enforce_balance; /* force a balanced partition? */
111 int enforce_balance_hard; /* really force a balanced partition? */
112 int balance_trouble; /* even balance_hard isn't working */
113 int size; /* array spacing */
114 int i, j, k, l; /* loop counters */
115
116 nbadtries = KL_NTRIES_BAD;
117
118 enforce_balance = FALSE;
119 temp_balanced = FALSE;
120 enforce_balance_hard = FALSE;
121 balance_trouble = FALSE;
122
123 size = (int)(&(listspace[0][1]) - &(listspace[0][0]));
124
125 undo_frac = .3;
126
127 cut_cost = 1;
128 if (term_wgts[1] != NULL) {
129 if (CUT_TO_HOP_COST > 1) {
130 cut_cost = CUT_TO_HOP_COST;
131 }
132 }
133
134 bspace = smalloc_ret(nvtxs * sizeof(int));
135 weightsum = smalloc_ret(nsets * sizeof(double));
136 locked = smalloc_ret(nsets * sizeof(double));
137 loose = smalloc_ret(nsets * sizeof(double));
138
139 if (bspace == NULL || weightsum == NULL || locked == NULL || loose == NULL) {
140 sfree(loose);
141 sfree(locked);
142 sfree(weightsum);
143 sfree(bspace);
144 return (1);
145 }
146
147 if (*bndy_list != NULL) {
148 bdy_ptr = *bndy_list;
149 list_length = 0;
150 while (*bdy_ptr != 0) {
151 bspace[list_length++] = *bdy_ptr++;
152 }
153 sfree(*bndy_list);
154
155 if (list_length == 0) { /* No boundary -> make everybody bndy. */
156 for (i = 0; i < nvtxs; i++) {
157 bspace[i] = i + 1;
158 }
159 list_length = nvtxs;
160 }
161 /* Set dvals to flag uninitialized vertices. */
162 for (i = 1; i <= nvtxs; i++) {
163 dvals[i][0] = 3 * maxdval;
164 }
165 }
166 else {
167 list_length = nvtxs;
168 }
169
170 step_cutoff = KL_BAD_MOVES;
171 cost_cutoff = maxdval * step_cutoff / 7;
172 if (cost_cutoff < step_cutoff) {
173 cost_cutoff = step_cutoff;
174 }
175
176 deltaminus = deltaplus = 0;
177 for (i = 0; i < nsets; i++) {
178 if (startweight[i] - goal[i] > deltaplus) {
179 deltaplus = startweight[i] - goal[i];
180 }
181 else if (goal[i] - startweight[i] > deltaminus) {
182 deltaminus = goal[i] - startweight[i];
183 }
184 }
185 balanced = (deltaplus + deltaminus <= max_dev);
186
187 bestg_min = -2.0 * nvtxs * maxdval;
188 parity = FALSE;
189 eweight = cut_cost + .5;
190 nbad = 0;
191 npass = 0;
192 improved = 0;
193 done = FALSE;
194 while (!done) {
195 npass++;
196 ever_balanced = FALSE;
197
198 /* Initialize various quantities. */
199 balance_best = 0;
200 for (i = 0; i < nsets; i++) {
201 for (j = 0; j < nsets; j++) {
202 tops[i][j] = 2 * maxdval;
203 }
204 weightsum[i] = startweight[i];
205 loose[i] = weightsum[i];
206 locked[i] = 0;
207 balance_best += goal[i];
208 }
209
210 gtotal = 0;
211 bestg = bestg_min;
212 beststep = -1;
213
214 movelist = NULL;
215 endlist = &movelist;
216
217 neg_steps = 0;
218
219 /* Compute the initial d-values, and bucket-sort them. */
220 time = seconds();
221 if (nsets == 2) {
222 bucketsorts_bi(graph, nvtxs, buckets, listspace, dvals, sets, term_wgts, maxdval, nsets,
223 parity, hops, bspace, list_length, npass, using_ewgts);
224 }
225 else {
226 bucketsorts(graph, nvtxs, buckets, listspace, dvals, sets, term_wgts, maxdval, nsets, parity,
227 hops, bspace, list_length, npass, using_ewgts);
228 }
229 parity = !parity;
230 kl_bucket_time += seconds() - time;
231
232 if (DEBUG_KL > 2) {
233 pbuckets(buckets, listspace, maxdval, nsets);
234 }
235
236 /* Now determine the set of K-L moves. */
237
238 for (step = 1;; step++) {
239
240 /* Find the highest d-value in each set. */
241 /* But only consider moves from large to small sets, or moves */
242 /* in which balance is preserved. */
243 /* Break ties in some nonarbitrary manner. */
244 bestval = -maxdval - 1;
245 for (i = 0; i < nsets; i++) {
246 for (j = 0; j < nsets; j++) {
247 /* Only allow moves from large sets to small sets, or */
248 /* moves which preserve balance. */
249 if (i != j) {
250 /* Find the best move from i to j. */
251 for (k = tops[i][j]; k >= 0 && buckets[i][j][k] == NULL; k--) {
252 ;
253 }
254 tops[i][j] = k;
255
256 if (k >= 0) {
257 l = (j > i) ? j - 1 : j;
258 vtx = ((int)(buckets[i][j][k] - listspace[l])) / size;
259 vweight = graph[vtx]->vwgt;
260
261 if ((enforce_balance_hard && weightsum[i] >= goal[i] && weightsum[j] <= goal[j] &&
262 weightsum[i] - goal[i] - (weightsum[j] - goal[j]) > max_dev) ||
263 (!enforce_balance_hard && weightsum[i] >= goal[i] && weightsum[j] <= goal[j]) ||
264 (!enforce_balance_hard &&
265 weightsum[i] - vweight - goal[i] > -(double)((max_dev + 1) / 2) &&
266 weightsum[j] + vweight - goal[j] < (double)((max_dev + 1) / 2))) {
267
268 /* Is it the best move seen so far? */
269 if (k - maxdval > bestval) {
270 bestval = k - maxdval;
271 bestvtx = vtx;
272 bestto = j;
273 /* DO I NEED ALL THIS DATA? Just to break ties. */
274 bestdelta = fabs(weightsum[i] - vweight - goal[i]) +
275 fabs(weightsum[j] + vweight - goal[j]);
276 beststuck1 = min(loose[i], goal[j] - locked[j]);
277 beststuck2 = max(loose[i], goal[j] - locked[j]);
278 }
279
280 else if (k - maxdval == bestval) {
281 /* Tied. Is better balanced than current best? */
282 /* If tied, move among sets with most freedom. */
283 stuck1st = min(loose[i], goal[j] - locked[j]);
284 stuck2nd = max(loose[i], goal[j] - locked[j]);
285 delta = fabs(weightsum[i] - vweight - goal[i]) +
286 fabs(weightsum[j] + vweight - goal[j]);
287
288 /* NOTE: Randomization in this check isn't ideal */
289 /* if more than two guys are tied. */
290 if (delta < bestdelta ||
291 (delta == bestdelta &&
292 (stuck1st > beststuck1 ||
293 (stuck1st == beststuck1 &&
294 (stuck2nd > beststuck2 ||
295 (stuck2nd == beststuck2 && (KL_RANDOM && drandom() < .5))))))) {
296 bestval = k - maxdval;
297 bestvtx = vtx;
298 bestto = j;
299 bestdelta = delta;
300 beststuck1 = stuck1st;
301 beststuck2 = stuck2nd;
302 }
303 }
304 }
305 }
306 }
307 }
308 }
309 if (bestval == -maxdval - 1) { /* No allowed moves */
310 if (DEBUG_KL > 0) {
311 printf("No KL moves at step %d. bestg = %g at step %d.\n", step, bestg, beststep);
312 }
313 break;
314 }
315
316 bestptr = &(listspace[0][bestvtx]);
317 bestfrom = sets[bestvtx];
318
319 vweight = graph[bestvtx]->vwgt;
320 weightsum[bestto] += vweight;
321 weightsum[bestfrom] -= vweight;
322 loose[bestfrom] -= vweight;
323 locked[bestto] += vweight;
324
325 if (enforce_balance) { /* Check if this partition is balanced. */
326 deltaminus = deltaplus = 0;
327 for (i = 0; i < nsets; i++) {
328 if (weightsum[i] - goal[i] > deltaplus) {
329 deltaplus = weightsum[i] - goal[i];
330 }
331 else if (goal[i] - weightsum[i] > deltaminus) {
332 deltaminus = goal[i] - weightsum[i];
333 }
334 }
335 balance_val = deltaminus + deltaplus;
336 temp_balanced = (balance_val <= max_dev);
337 ever_balanced = (ever_balanced || temp_balanced);
338 }
339
340 gtotal += bestval;
341 if (((gtotal > bestg && (!enforce_balance || temp_balanced)) ||
342 (enforce_balance_hard && balance_val < balance_best)) &&
343 step != nvtxs) {
344 bestg = gtotal;
345 beststep = step;
346 if (enforce_balance_hard) {
347 balance_best = balance_val;
348 }
349 if (temp_balanced) {
350 enforce_balance_hard = FALSE;
351 }
352 }
353
354 if (DEBUG_KL > 1) {
355 printf("At KL step %d, bestvtx=%d, bestval=%d (%d-> %d)\n", step, bestvtx, bestval,
356 bestfrom, bestto);
357 }
358
359 /* Monitor the stopping criteria. */
360 if (bestval < 0) {
361 if (!enforce_balance || ever_balanced) {
362 neg_steps++;
363 }
364 if (bestg != bestg_min) {
365 neg_cost = bestg - gtotal;
366 }
367 else {
368 neg_cost = -maxdval - 1;
369 }
370 if ((neg_steps > step_cutoff || neg_cost > cost_cutoff) &&
371 !(enforce_balance && bestg == bestg_min) && (beststep != step)) {
372 if (DEBUG_KL > 0) {
373 if (neg_steps > step_cutoff) {
374 printf("KL step cutoff at step %d. bestg = %g at step %d.\n", step, bestg, beststep);
375 }
376 else if (neg_cost > cost_cutoff) {
377 printf("KL cost cutoff at step %d. bestg = %g at step %d.\n", step, bestg, beststep);
378 }
379 }
380 break;
381 }
382 }
383 else if (bestval > 0) {
384 neg_steps = 0;
385 }
386
387 /* Remove vertex from its buckets, and flag it as finished. */
388 l = 0;
389 for (k = 0; k < nsets; k++) {
390 if (k != bestfrom) {
391 dval = dvals[bestvtx][l] + maxdval;
392 removebilist(&listspace[l][bestvtx], &buckets[bestfrom][k][dval]);
393 l++;
394 }
395 }
396
397 /* Is there a better way to do this? */
398 sets[bestvtx] = -sets[bestvtx] - 1;
399
400 /* Set up the linked list of moved vertices. */
401 bestptr->next = NULL;
402 bestptr->prev = (struct bilist *)(unsigned long long)bestto;
403 *endlist = bestptr;
404 endlist = &(bestptr->next);
405
406 /* Now update the d-values of all the neighbors */
407 edges = graph[bestvtx]->edges;
408 if (using_ewgts) {
409 ewptr = graph[bestvtx]->ewgts;
410 }
411 for (j = graph[bestvtx]->nedges - 1; j; j--) {
412 neighbor = *(++edges);
413 if (using_ewgts) {
414 eweight = *(++ewptr) * cut_cost + .5;
415 }
416
417 /* First make sure neighbor is alive. */
418 if (sets[neighbor] >= 0) {
419 group = sets[neighbor];
420
421 if (dvals[neighbor][0] >= 3 * maxdval) {
422 /* New vertex, not yet in buckets. */
423 /* Can't be neighbor of moved vtx, so compute */
424 /* initial dvals and buckets, then update. */
425 bucketsort1(graph, neighbor, buckets, listspace, dvals, sets, term_wgts, maxdval, nsets,
426 hops, using_ewgts);
427 }
428
429 l = 0;
430 for (k = 0; k < nsets; k++) {
431 if (k != group) {
432 diff = eweight * (hops[k][bestfrom] - hops[group][bestfrom] + hops[group][bestto] -
433 hops[k][bestto]);
434 dval = dvals[neighbor][l] + maxdval;
435 movebilist(&listspace[l][neighbor], &buckets[group][k][dval],
436 &buckets[group][k][dval + diff]);
437 dvals[neighbor][l] += diff;
438 dval += diff;
439 if (dval > tops[group][k]) {
440 tops[group][k] = dval;
441 }
442 l++;
443 }
444 }
445 }
446 }
447 if (DEBUG_KL > 2) {
448 pbuckets(buckets, listspace, maxdval, nsets);
449 }
450 }
451
452 /* Done with a pass; should we actually perform any swaps? */
453 bptr = movelist;
454 if (bestg > 0 || (bestg != bestg_min && !balanced && enforce_balance) ||
455 (bestg != bestg_min && balance_trouble)) {
456 improved += bestg;
457 for (i = 1; i <= beststep; i++) {
458 vtx = ((int)(bptr - listspace[0])) / size;
459 bestto = (int)(unsigned long long)bptr->prev;
460 startweight[bestto] += graph[vtx]->vwgt;
461 startweight[-sets[vtx] - 1] -= graph[vtx]->vwgt;
462 sets[vtx] = bestto;
463 bptr = bptr->next;
464 }
465
466 deltaminus = deltaplus = 0;
467 for (i = 0; i < nsets; i++) {
468 if (startweight[i] - goal[i] > deltaplus) {
469 deltaplus = startweight[i] - goal[i];
470 }
471 else if (goal[i] - startweight[i] > deltaminus) {
472 deltaminus = goal[i] - startweight[i];
473 }
474 }
475 /*
476 printf(" deltaplus = %f, deltaminus = %f, max_dev = %d\n", deltaplus, deltaminus, max_dev);
477 */
478 balanced = (deltaplus + deltaminus <= max_dev);
479 }
480 else {
481 nbad++;
482 }
483
484 if (!balanced || bptr == movelist) {
485 if (enforce_balance) {
486 if (enforce_balance_hard) {
487 balance_trouble = TRUE;
488 }
489 enforce_balance_hard = TRUE;
490 }
491 enforce_balance = TRUE;
492 nbad++;
493 }
494
495 worth_undoing = (step < undo_frac * nvtxs);
496 done = (nbad >= nbadtries && balanced);
497 if (KL_MAX_PASS > 0) {
498 done = done || (npass == KL_MAX_PASS && balanced);
499 }
500 if (!done) { /* Prepare for next pass. */
501 if (KL_UNDO_LIST && worth_undoing && !balance_trouble) {
502 /* Make a list of modified vertices for next bucketsort. */
503 /* Also, ensure these vertices are removed from their buckets. */
504 list_length =
505 make_kl_list(graph, movelist, buckets, listspace, sets, nsets, bspace, dvals, maxdval);
506 }
507 }
508 if (done || !(KL_UNDO_LIST && worth_undoing && !balance_trouble)) {
509 /* Restore set numbers of remaining, altered vertices. */
510 while (bptr != NULL) {
511 vtx = ((int)(bptr - listspace[0])) / size;
512 sets[vtx] = -sets[vtx] - 1;
513 bptr = bptr->next;
514 }
515 list_length = nvtxs;
516 }
517
518 if (done && *bndy_list != NULL) {
519 make_bndy_list(graph, movelist, buckets, listspace, sets, nsets, bspace, tops, bndy_list);
520 }
521 }
522
523 if (DEBUG_KL > 0) {
524 printf(" KL required %d passes to improve by %d.\n", npass, improved);
525 }
526
527 sfree(loose);
528 sfree(locked);
529 sfree(weightsum);
530 sfree(bspace);
531 return (0);
532 }