hungarian.c 11.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/********************************************************************
 ********************************************************************
 **
 ** libhungarian by Cyrill Stachniss, 2004
 **
 ** Added and adapted to libFirm by Christian Wuerdig, 2006
 **
 ** Solving the Minimum Assignment Problem using the
 ** Hungarian Method.
 **
 ** ** This file may be freely copied and distributed! **
 **
 ** Parts of the used code was originally provided by the
 ** "Stanford GraphGase", but I made changes to this code.
 ** As asked by  the copyright node of the "Stanford GraphGase",
 ** I hereby proclaim that this file are *NOT* part of the
 ** "Stanford GraphGase" distrubition!
 **
 ** This file is distributed in the hope that it will be useful,
 ** but WITHOUT ANY WARRANTY; without even the implied
 ** warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 ** PURPOSE.
 **
 ********************************************************************
 ********************************************************************/

27
28
29
30
31
/**
 * @file
 * @brief   Solving the Minimum Assignment Problem using the Hungarian Method.
 * @version $Id$
 */
Matthias Braun's avatar
Matthias Braun committed
32
#include "config.h"
33

34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "irtools.h"
#include "xmalloc.h"
#include "debug.h"
41
#include "bitset.h"
42
#include "error.h"
43
44
45

#include "hungarian.h"

46
DEBUG_ONLY(static firm_dbg_module_t *dbg;)
47

48
struct hungarian_problem_t {
49
50
51
52
53
54
55
56
57
	unsigned      num_rows;      /**< number of rows */
	unsigned      num_cols;      /**< number of columns */
	unsigned     *cost;          /**< the cost matrix */
	unsigned      max_cost;      /**< the maximal costs in the matrix */
	match_type_t  match_type;    /**< PERFECT or NORMAL matching */
	unsigned     *missing_left;  /**< bitset: left side nodes having no edge to
	                                  the right side */
	unsigned     *missing_right; /**< bitset: right side nodes having no edge to
	                              the left side */
58
59
};

60
61
static void hungarian_dump_f(FILE *f, const unsigned *cost,
                             unsigned num_rows, unsigned num_cols, int width)
62
{
63
	unsigned r, c;
64
65

	fprintf(f , "\n");
66
	for (r = 0; r < num_rows; r++) {
67
		fprintf(f, " [");
68
69
		for (c = 0; c < num_cols; c++) {
			fprintf(f, "%*u", width, cost[r*num_cols + c]);
70
71
72
73
74
75
		}
		fprintf(f, "]\n");
	}
	fprintf(f, "\n");
}

76
77
void hungarian_print_cost_matrix(hungarian_problem_t *p, int width)
{
Matthias Braun's avatar
Matthias Braun committed
78
	hungarian_dump_f(stderr, p->cost, p->num_rows, p->num_cols, width);
79
80
}

81
hungarian_problem_t *hungarian_new(unsigned num_rows, unsigned num_cols,
82
                                   match_type_t match_type)
83
{
84
	hungarian_problem_t *p = XMALLOCZ(hungarian_problem_t);
85

86
	FIRM_DBG_REGISTER(dbg, "firm.hungarian");
87
88
89
90
91

	/*
		Is the number of cols  not equal to number of rows ?
		If yes, expand with 0 - cols / 0 - cols
	*/
92
93
	num_rows = MAX(num_cols, num_rows);
	num_cols = num_rows;
94

95
96
	p->num_rows   = num_rows;
	p->num_cols   = num_cols;
97
98
99
100
101
102
103
104
	p->match_type = match_type;

	/*
		In case of normal matching, we have to keep
		track of nodes without edges to kill them in
		the assignment later.
	*/
	if (match_type == HUNGARIAN_MATCH_NORMAL) {
105
106
107
108
		p->missing_left  = rbitset_malloc(num_rows);
		p->missing_right = rbitset_malloc(num_cols);
		rbitset_set_all(p->missing_left,  num_rows);
		rbitset_set_all(p->missing_right, num_cols);
109
	}
110
111

	/* allocate space for cost matrix */
112
	p->cost = XMALLOCNZ(unsigned, num_rows * num_cols);
113
114
115
	return p;
}

116
117
void hungarian_prepare_cost_matrix(hungarian_problem_t *p,
                                   hungarian_mode_t mode)
118
{
119
	if (mode == HUNGARIAN_MODE_MAXIMIZE_UTIL) {
120
121
122
123
		unsigned  r, c;
		unsigned  num_cols = p->num_cols;
		unsigned *cost     = p->cost;
		unsigned  max_cost = p->max_cost;
124
125
		for (r = 0; r < p->num_rows; r++) {
			for (c = 0; c < p->num_cols; c++) {
126
				cost[r*num_cols + c] = max_cost - cost[r*num_cols + c];
127
128
			}
		}
129
	} else if (mode == HUNGARIAN_MODE_MINIMIZE_COST) {
130
		/* nothing to do */
131
132
	} else {
		panic("Unknown hungarian problem mode\n");
133
134
135
	}
}

136
void hungarian_add(hungarian_problem_t *p, unsigned left, unsigned right,
137
                   unsigned cost)
138
{
139
140
141
	assert(p->num_rows > left  && "Invalid row selected.");
	assert(p->num_cols > right && "Invalid column selected.");

142
143
	p->cost[left*p->num_cols + right] = cost;
	p->max_cost                       = MAX(p->max_cost, cost);
144
145

	if (p->match_type == HUNGARIAN_MATCH_NORMAL) {
146
147
		rbitset_clear(p->missing_left, left);
		rbitset_clear(p->missing_right, right);
148
	}
149
150
}

151
void hungarian_remove(hungarian_problem_t *p, unsigned left, unsigned right)
152
{
153
154
155
	assert(p->num_rows > left  && "Invalid row selected.");
	assert(p->num_cols > right && "Invalid column selected.");

156
	p->cost[left*p->num_cols + right] = 0;
157
158

	if (p->match_type == HUNGARIAN_MATCH_NORMAL) {
159
160
		rbitset_set(p->missing_left, left);
		rbitset_set(p->missing_right, right);
161
	}
162
163
}

164
165
void hungarian_free(hungarian_problem_t* p)
{
166
167
168
	xfree(p->missing_left);
	xfree(p->missing_right);
	xfree(p->cost);
169
170
171
	xfree(p);
}

172
int hungarian_solve(hungarian_problem_t* p, unsigned *assignment,
173
                    unsigned *final_cost, unsigned cost_threshold)
174
{
175
176
177
178
179
180
181
182
183
184
185
186
	unsigned  res_cost     = 0;
	unsigned  num_rows     = p->num_rows;
	unsigned  num_cols     = p->num_cols;
	unsigned *cost         = p->cost;
	unsigned *col_mate     = XMALLOCNZ(unsigned, num_rows);
	unsigned *row_mate     = XMALLOCNZ(unsigned, num_cols);
	unsigned *parent_row   = XMALLOCNZ(unsigned, num_cols);
	unsigned *unchosen_row = XMALLOCNZ(unsigned, num_rows);
	int      *row_dec      = XMALLOCNZ(int, num_rows);
	int      *col_inc      = XMALLOCNZ(int, num_cols);
	int      *slack        = XMALLOCNZ(int, num_cols);
	unsigned *slack_row    = XMALLOCNZ(unsigned, num_rows);
187
188
189
190
191
192
	unsigned  r;
	unsigned  c;
	unsigned  t;
	unsigned  unmatched;

	memset(assignment, -1, num_rows * sizeof(assignment[0]));
193
194

	/* Begin subtract column minima in order to start with lots of zeros 12 */
195
	DBG((dbg, LEVEL_1, "Using heuristic\n"));
196

197
	for (c = 0; c < num_cols; ++c) {
198
		unsigned col_mininum = cost[0*num_cols + c];
199

200
		for (r = 1; r < num_rows; ++r) {
201
202
			if (cost[r*num_cols + c] < col_mininum)
				col_mininum = cost[r*num_cols + c];
203
204
		}

205
		if (col_mininum == 0)
206
			continue;
207

208
		res_cost += col_mininum;
209
		for (r = 0; r < num_rows; ++r)
210
			cost[r*num_cols + c] -= col_mininum;
211
212
213
214
	}
	/* End subtract column minima in order to start with lots of zeros 12 */

	/* Begin initial state 16 */
215
	unmatched = 0;
216
217
218
219
220
	for (c = 0; c < num_cols; ++c) {
		row_mate[c]   = (unsigned) -1;
		parent_row[c] = (unsigned) -1;
		col_inc[c]    = 0;
		slack[c]      = INT_MAX;
221
222
	}

223
	for (r = 0; r < num_rows; ++r) {
224
		unsigned row_minimum = cost[r*num_cols + 0];
225

226
		for (c = 1; c < num_cols; ++c) {
227
228
			if (cost[r*num_cols + c] < row_minimum)
				row_minimum = cost[r*num_cols + c];
229
230
		}

231
		row_dec[r] = row_minimum;
232

233
		for (c = 0; c < num_cols; ++c) {
234
235
236
237
238
239
240
241
242
			if (cost[r*num_cols + c] != row_minimum)
				continue;
			if (row_mate[c] != (unsigned)-1)
				continue;

			col_mate[r] = c;
			row_mate[c] = r;
			DBG((dbg, LEVEL_1, "matching col %u == row %u\n", c, r));
			goto row_done;
243
244
		}

245
		col_mate[r] = (unsigned)-1;
246
247
		DBG((dbg, LEVEL_1, "node %u: unmatched row %u\n", unmatched, r));
		unchosen_row[unmatched++] = r;
248
249
250
251
252
row_done: ;
	}
	/* End initial state 16 */

	/* Begin Hungarian algorithm 18 */
253
	if (unmatched == 0)
254
255
		goto done;

256
	t = unmatched;
257
	for (;;) {
258
259
		unsigned q = 0;
		unsigned j;
260
		DBG((dbg, LEVEL_1, "Matched %u rows.\n", num_rows - t));
261

262
		for (;;) {
263
			int s;
264
265
			while (q < t) {
				/* Begin explore node q of the forest 19 */
266
267
				r = unchosen_row[q];
				s = row_dec[r];
268

269
270
				for (c = 0; c < num_cols; ++c) {
					if (slack[c]) {
271
						int del = cost[r*num_cols + c] - s + col_inc[c];
272

273
						if (del < slack[c]) {
274
							if (del == 0) {
275
								if (row_mate[c] == (unsigned)-1)
276
277
									goto breakthru;

278
279
								slack[c]      = 0;
								parent_row[c] = r;
280
								DBG((dbg, LEVEL_1, "node %u: row %u == col %u -- row %u\n", t, row_mate[c], c, r));
281
282
283
284
								unchosen_row[t++] = row_mate[c];
							} else {
								slack[c]     = del;
								slack_row[c] = r;
285
286
287
288
289
290
291
292
293
							}
						}
					}
				}
				/* End explore node q of the forest 19 */
				q++;
			}

			/* Begin introduce a new zero into the matrix 21 */
294
295
296
297
			s = INT_MAX;
			for (c = 0; c < num_cols; ++c) {
				if (slack[c] && slack[c] < s)
					s = slack[c];
298
299
300
301
302
			}

			for (q = 0; q < t; ++q)
				row_dec[unchosen_row[q]] += s;

303
304
305
306
			for (c = 0; c < num_cols; ++c) {
				if (slack[c]) {
					slack[c] -= s;
					if (slack[c] == 0) {
307
						/* Begin look at a new zero 22 */
308
						r = slack_row[c];
309
						DBG((dbg, LEVEL_1, "Decreasing uncovered elements by %d produces zero at [%u, %u]\n", s, r, c));
310
311
						if (row_mate[c] == (unsigned)-1) {
							for (j = c + 1; j < num_cols; ++j) {
312
313
314
315
								if (slack[j] == 0)
									col_inc[j] += s;
							}
							goto breakthru;
316
317
						} else {
							parent_row[c] = r;
318
							DBG((dbg, LEVEL_1, "node %u: row %u == col %u -- row %u\n", t, row_mate[c], c, r));
319
							unchosen_row[t++] = row_mate[c];
320
321
322
						}
						/* End look at a new zero 22 */
					}
323
324
				} else {
					col_inc[c] += s;
325
326
327
328
329
330
				}
			}
			/* End introduce a new zero into the matrix 21 */
		}
breakthru:
		/* Begin update the matching 20 */
331
		DBG((dbg, LEVEL_1, "Breakthrough at node %u of %u.\n", q, t));
332
		for (;;) {
333
334
335
			j           = col_mate[r];
			col_mate[r] = c;
			row_mate[c] = r;
336

337
			DBG((dbg, LEVEL_1, "rematching col %u == row %u\n", c, r));
338
			if (j == (unsigned)-1)
339
340
				break;

341
342
			r = parent_row[j];
			c = j;
343
344
345
346
347
348
349
350
		}
		/* End update the matching 20 */

		if (--unmatched == 0)
			goto done;

		/* Begin get ready for another stage 17 */
		t = 0;
351
		for (c = 0; c < num_cols; ++c) {
352
			parent_row[c] = (unsigned) -1;
353
			slack[c]      = INT_MAX;
354
355
		}

356
357
		for (r = 0; r < num_rows; ++r) {
			if (col_mate[r] == (unsigned)-1) {
358
				DBG((dbg, LEVEL_1, "node %u: unmatched row %u\n", t, r));
359
				unchosen_row[t++] = r;
360
361
362
363
364
365
366
			}
		}
		/* End get ready for another stage 17 */
	}
done:

	/* Begin double check the solution 23 */
367
368
	for (r = 0; r < num_rows; ++r) {
		for (c = 0; c < num_cols; ++c) {
369
			if ((int) cost[r*num_cols + c] < row_dec[r] - col_inc[c])
370
371
372
373
				return -1;
		}
	}

374
375
	for (r = 0; r < num_rows; ++r) {
		c = col_mate[r];
376
377
		if (c == (unsigned)-1
		    || cost[r*num_cols + c] != (unsigned) (row_dec[r] - col_inc[c]))
378
379
380
			return -2;
	}

381
382
383
	for (r = c = 0; c < num_cols; ++c) {
		if (col_inc[c])
			r++;
384
385
	}

386
	if (r > num_rows)
387
388
389
390
391
392
		return -3;
	/* End double check the solution 23 */

	/* End Hungarian algorithm 18 */

	/* collect the assigned values */
393
	for (r = 0; r < num_rows; ++r) {
394
395
		if (cost_threshold > 0
		    && cost[r*num_cols + col_mate[r]] >= cost_threshold)
396
			assignment[r] = -1; /* remove matching having cost > threshold */
Christian Würdig's avatar
Christian Würdig committed
397
		else
398
			assignment[r] = col_mate[r];
399
400
	}

401
402
	/* In case of normal matching: remove impossible ones */
	if (p->match_type == HUNGARIAN_MATCH_NORMAL) {
403
		for (r = 0; r < num_rows; ++r) {
404
405
			if (rbitset_is_set(p->missing_left, r)
			        || rbitset_is_set(p->missing_right, col_mate[r]))
406
				assignment[r] = -1;
407
408
409
		}
	}

410
411
	for (r = 0; r < num_rows; ++r) {
		for (c = 0; c < num_cols; ++c) {
412
			cost[r*num_cols + c] = cost[r*num_cols + c] - row_dec[r] + col_inc[c];
413
414
415
		}
	}

416
	for (r = 0; r < num_rows; ++r)
417
		res_cost += row_dec[r];
418

419
	for (c = 0; c < num_cols; ++c)
420
		res_cost -= col_inc[c];
421

422
	DBG((dbg, LEVEL_1, "Cost is %d\n", res_cost));
423
424
425
426
427
428
429
430
431
432

	xfree(slack);
	xfree(col_inc);
	xfree(parent_row);
	xfree(row_mate);
	xfree(slack_row);
	xfree(row_dec);
	xfree(unchosen_row);
	xfree(col_mate);

433
	if (final_cost != NULL)
434
		*final_cost = res_cost;
435
436

	return 0;
437
}