forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hungarian.cc
693 lines (582 loc) · 21.6 KB
/
hungarian.cc
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// See: //depot/google3/java/com/google/wireless/genie/frontend
// /mixer/matching/HungarianOptimizer.java
#include "ortools/algorithms/hungarian.h"
#include <algorithm>
#include <cstdio>
#include <limits>
#include "absl/strings/str_format.h"
#include "ortools/base/logging.h"
namespace operations_research {
class HungarianOptimizer {
static constexpr int kHungarianOptimizerRowNotFound = -1;
static constexpr int kHungarianOptimizerColNotFound = -2;
public:
// Setup the initial conditions for the algorithm.
// Parameters: costs is a matrix of the cost of assigning each agent to
// each task. costs[i][j] is the cost of assigning agent i to task j.
// All the costs must be non-negative. This matrix does not have to
// be square (i.e. we can have different numbers of agents and tasks), but it
// must be regular (i.e. there must be the same number of entries in each row
// of the matrix).
explicit HungarianOptimizer(const std::vector<std::vector<double>>& costs);
// Find an assignment which maximizes the total cost.
// Returns the assignment in the two vectors passed as argument.
// preimage[i] is assigned to image[i].
void Maximize(std::vector<int>* preimage, std::vector<int>* image);
// Like Maximize(), but minimizing the cost instead.
void Minimize(std::vector<int>* preimage, std::vector<int>* image);
private:
typedef void (HungarianOptimizer::*Step)();
typedef enum { NONE, PRIME, STAR } Mark;
// Convert the final cost matrix into a set of assignments of preimage->image.
// Returns the assignment in the two vectors passed as argument, the same as
// Minimize and Maximize
void FindAssignments(std::vector<int>* preimage, std::vector<int>* image);
// Is the cell (row, col) starred?
bool IsStarred(int row, int col) const { return marks_[row][col] == STAR; }
// Mark cell (row, col) with a star
void Star(int row, int col) {
marks_[row][col] = STAR;
stars_in_col_[col]++;
}
// Remove a star from cell (row, col)
void UnStar(int row, int col) {
marks_[row][col] = NONE;
stars_in_col_[col]--;
}
// Find a column in row 'row' containing a star, or return
// kHungarianOptimizerColNotFound if no such column exists.
int FindStarInRow(int row) const;
// Find a row in column 'col' containing a star, or return
// kHungarianOptimizerRowNotFound if no such row exists.
int FindStarInCol(int col) const;
// Is cell (row, col) marked with a prime?
bool IsPrimed(int row, int col) const { return marks_[row][col] == PRIME; }
// Mark cell (row, col) with a prime.
void Prime(int row, int col) { marks_[row][col] = PRIME; }
// Find a column in row containing a prime, or return
// kHungarianOptimizerColNotFound if no such column exists.
int FindPrimeInRow(int row) const;
// Remove the prime marks_ from every cell in the matrix.
void ClearPrimes();
// Does column col contain a star?
bool ColContainsStar(int col) const { return stars_in_col_[col] > 0; }
// Is row 'row' covered?
bool RowCovered(int row) const { return rows_covered_[row]; }
// Cover row 'row'.
void CoverRow(int row) { rows_covered_[row] = true; }
// Uncover row 'row'.
void UncoverRow(int row) { rows_covered_[row] = false; }
// Is column col covered?
bool ColCovered(int col) const { return cols_covered_[col]; }
// Cover column col.
void CoverCol(int col) { cols_covered_[col] = true; }
// Uncover column col.
void UncoverCol(int col) { cols_covered_[col] = false; }
// Uncover ever row and column in the matrix.
void ClearCovers();
// Find the smallest uncovered cell in the matrix.
double FindSmallestUncovered() const;
// Find an uncovered zero and store its coordinates in (zeroRow_, zeroCol_)
// and return true, or return false if no such cell exists.
bool FindZero(int* zero_row, int* zero_col) const;
// Print the matrix to stdout (for debugging.)
void PrintMatrix();
// Run the Munkres algorithm!
void DoMunkres();
// Step 1.
// For each row of the matrix, find the smallest element and subtract it
// from every element in its row. Go to Step 2.
void ReduceRows();
// Step 2.
// Find a zero (Z) in the matrix. If there is no starred zero in its row
// or column, star Z. Repeat for every element in the matrix. Go to step 3.
// Note: profiling shows this method to use 9.2% of the CPU - the next
// slowest step takes 0.6%. I can't think of a way of speeding it up though.
void StarZeroes();
// Step 3.
// Cover each column containing a starred zero. If all columns are
// covered, the starred zeros describe a complete set of unique assignments.
// In this case, terminate the algorithm. Otherwise, go to step 4.
void CoverStarredZeroes();
// Step 4.
// Find a noncovered zero and prime it. If there is no starred zero in the
// row containing this primed zero, Go to Step 5. Otherwise, cover this row
// and uncover the column containing the starred zero. Continue in this manner
// until there are no uncovered zeros left, then go to Step 6.
void PrimeZeroes();
// Step 5.
// Construct a series of alternating primed and starred zeros as follows.
// Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote
// the starred zero in the column of Z0 (if any). Let Z2 denote the primed
// zero in the row of Z1 (there will always be one). Continue until the
// series terminates at a primed zero that has no starred zero in its column.
// Unstar each starred zero of the series, star each primed zero of the
// series, erase all primes and uncover every line in the matrix. Return to
// Step 3.
void MakeAugmentingPath();
// Step 6.
// Add the smallest uncovered value in the matrix to every element of each
// covered row, and subtract it from every element of each uncovered column.
// Return to Step 4 without altering any stars, primes, or covered lines.
void AugmentPath();
// The size of the problem, i.e. max(#agents, #tasks).
int matrix_size_;
// The expanded cost matrix.
std::vector<std::vector<double>> costs_;
// The greatest cost in the initial cost matrix.
double max_cost_;
// Which rows and columns are currently covered.
std::vector<bool> rows_covered_;
std::vector<bool> cols_covered_;
// The marks_ (star/prime/none) on each element of the cost matrix.
std::vector<std::vector<Mark>> marks_;
// The number of stars in each column - used to speed up coverStarredZeroes.
std::vector<int> stars_in_col_;
// Representation of a path_ through the matrix - used in step 5.
std::vector<int> preimage_; // i.e. the agents
std::vector<int> image_; // i.e. the tasks
// The width_ and height_ of the initial (non-expanded) cost matrix.
int width_;
int height_;
// The current state of the algorithm
HungarianOptimizer::Step state_;
};
HungarianOptimizer::HungarianOptimizer(
const std::vector<std::vector<double>>& costs)
: matrix_size_(0),
costs_(),
max_cost_(0),
rows_covered_(),
cols_covered_(),
marks_(),
stars_in_col_(),
preimage_(),
image_(),
width_(0),
height_(0),
state_(nullptr) {
width_ = costs.size();
if (width_ > 0) {
height_ = costs[0].size();
} else {
height_ = 0;
}
matrix_size_ = std::max(width_, height_);
max_cost_ = 0;
// Generate the expanded cost matrix by adding extra 0-valued elements in
// order to make a square matrix. At the same time, find the greatest cost
// in the matrix (used later if we want to maximize rather than minimize the
// overall cost.)
costs_.resize(matrix_size_);
for (int row = 0; row < matrix_size_; ++row) {
costs_[row].resize(matrix_size_);
}
for (int row = 0; row < matrix_size_; ++row) {
for (int col = 0; col < matrix_size_; ++col) {
if ((row >= width_) || (col >= height_)) {
costs_[row][col] = 0;
} else {
costs_[row][col] = costs[row][col];
max_cost_ = std::max(max_cost_, costs_[row][col]);
}
}
}
// Initially, none of the cells of the matrix are marked.
marks_.resize(matrix_size_);
for (int row = 0; row < matrix_size_; ++row) {
marks_[row].resize(matrix_size_);
for (int col = 0; col < matrix_size_; ++col) {
marks_[row][col] = NONE;
}
}
stars_in_col_.resize(matrix_size_);
rows_covered_.resize(matrix_size_);
cols_covered_.resize(matrix_size_);
preimage_.resize(matrix_size_ * 2);
image_.resize(matrix_size_ * 2);
}
// Find an assignment which maximizes the total cost.
// Return an array of pairs of integers. Each pair (i, j) corresponds to
// assigning agent i to task j.
void HungarianOptimizer::Maximize(std::vector<int>* preimage,
std::vector<int>* image) {
// Find a maximal assignment by subtracting each of the
// original costs from max_cost_ and then minimizing.
for (int row = 0; row < width_; ++row) {
for (int col = 0; col < height_; ++col) {
costs_[row][col] = max_cost_ - costs_[row][col];
}
}
Minimize(preimage, image);
}
// Find an assignment which minimizes the total cost.
// Return an array of pairs of integers. Each pair (i, j) corresponds to
// assigning agent i to task j.
void HungarianOptimizer::Minimize(std::vector<int>* preimage,
std::vector<int>* image) {
DoMunkres();
FindAssignments(preimage, image);
}
// Convert the final cost matrix into a set of assignments of agents -> tasks.
// Return an array of pairs of integers, the same as the return values of
// Minimize() and Maximize()
void HungarianOptimizer::FindAssignments(std::vector<int>* preimage,
std::vector<int>* image) {
preimage->clear();
image->clear();
for (int row = 0; row < width_; ++row) {
for (int col = 0; col < height_; ++col) {
if (IsStarred(row, col)) {
preimage->push_back(row);
image->push_back(col);
break;
}
}
}
// TODO(user)
// result_size = min(width_, height_);
// CHECK image.size() == result_size
// CHECK preimage.size() == result_size
}
// Find a column in row 'row' containing a star, or return
// kHungarianOptimizerColNotFound if no such column exists.
int HungarianOptimizer::FindStarInRow(int row) const {
for (int col = 0; col < matrix_size_; ++col) {
if (IsStarred(row, col)) {
return col;
}
}
return kHungarianOptimizerColNotFound;
}
// Find a row in column 'col' containing a star, or return
// kHungarianOptimizerRowNotFound if no such row exists.
int HungarianOptimizer::FindStarInCol(int col) const {
if (!ColContainsStar(col)) {
return kHungarianOptimizerRowNotFound;
}
for (int row = 0; row < matrix_size_; ++row) {
if (IsStarred(row, col)) {
return row;
}
}
// NOTREACHED
return kHungarianOptimizerRowNotFound;
}
// Find a column in row containing a prime, or return
// kHungarianOptimizerColNotFound if no such column exists.
int HungarianOptimizer::FindPrimeInRow(int row) const {
for (int col = 0; col < matrix_size_; ++col) {
if (IsPrimed(row, col)) {
return col;
}
}
return kHungarianOptimizerColNotFound;
}
// Remove the prime marks from every cell in the matrix.
void HungarianOptimizer::ClearPrimes() {
for (int row = 0; row < matrix_size_; ++row) {
for (int col = 0; col < matrix_size_; ++col) {
if (IsPrimed(row, col)) {
marks_[row][col] = NONE;
}
}
}
}
// Uncovery ever row and column in the matrix.
void HungarianOptimizer::ClearCovers() {
for (int x = 0; x < matrix_size_; x++) {
UncoverRow(x);
UncoverCol(x);
}
}
// Find the smallest uncovered cell in the matrix.
double HungarianOptimizer::FindSmallestUncovered() const {
double minval = std::numeric_limits<double>::max();
for (int row = 0; row < matrix_size_; ++row) {
if (RowCovered(row)) {
continue;
}
for (int col = 0; col < matrix_size_; ++col) {
if (ColCovered(col)) {
continue;
}
minval = std::min(minval, costs_[row][col]);
}
}
return minval;
}
// Find an uncovered zero and store its co-ordinates in (zeroRow, zeroCol)
// and return true, or return false if no such cell exists.
bool HungarianOptimizer::FindZero(int* zero_row, int* zero_col) const {
for (int row = 0; row < matrix_size_; ++row) {
if (RowCovered(row)) {
continue;
}
for (int col = 0; col < matrix_size_; ++col) {
if (ColCovered(col)) {
continue;
}
if (costs_[row][col] == 0) {
*zero_row = row;
*zero_col = col;
return true;
}
}
}
return false;
}
// Print the matrix to stdout (for debugging.)
void HungarianOptimizer::PrintMatrix() {
for (int row = 0; row < matrix_size_; ++row) {
for (int col = 0; col < matrix_size_; ++col) {
absl::PrintF("%g ", costs_[row][col]);
if (IsStarred(row, col)) {
absl::PrintF("*");
}
if (IsPrimed(row, col)) {
absl::PrintF("'");
}
}
absl::PrintF("\n");
}
}
// Run the Munkres algorithm!
void HungarianOptimizer::DoMunkres() {
state_ = &HungarianOptimizer::ReduceRows;
while (state_ != nullptr) {
(this->*state_)();
}
}
// Step 1.
// For each row of the matrix, find the smallest element and subtract it
// from every element in its row. Go to Step 2.
void HungarianOptimizer::ReduceRows() {
for (int row = 0; row < matrix_size_; ++row) {
double min_cost = costs_[row][0];
for (int col = 1; col < matrix_size_; ++col) {
min_cost = std::min(min_cost, costs_[row][col]);
}
for (int col = 0; col < matrix_size_; ++col) {
costs_[row][col] -= min_cost;
}
}
state_ = &HungarianOptimizer::StarZeroes;
}
// Step 2.
// Find a zero (Z) in the matrix. If there is no starred zero in its row
// or column, star Z. Repeat for every element in the matrix. Go to step 3.
// of the CPU - the next slowest step takes 0.6%. I can't think of a way
// of speeding it up though.
void HungarianOptimizer::StarZeroes() {
// Since no rows or columns are covered on entry to this step, we use the
// covers as a quick way of marking which rows & columns have stars in them.
for (int row = 0; row < matrix_size_; ++row) {
if (RowCovered(row)) {
continue;
}
for (int col = 0; col < matrix_size_; ++col) {
if (ColCovered(col)) {
continue;
}
if (costs_[row][col] == 0) {
Star(row, col);
CoverRow(row);
CoverCol(col);
break;
}
}
}
ClearCovers();
state_ = &HungarianOptimizer::CoverStarredZeroes;
}
// Step 3.
// Cover each column containing a starred zero. If all columns are
// covered, the starred zeros describe a complete set of unique assignments.
// In this case, terminate the algorithm. Otherwise, go to step 4.
void HungarianOptimizer::CoverStarredZeroes() {
int num_covered = 0;
for (int col = 0; col < matrix_size_; ++col) {
if (ColContainsStar(col)) {
CoverCol(col);
num_covered++;
}
}
if (num_covered >= matrix_size_) {
state_ = nullptr;
return;
}
state_ = &HungarianOptimizer::PrimeZeroes;
}
// Step 4.
// Find a noncovered zero and prime it. If there is no starred zero in the
// row containing this primed zero, Go to Step 5. Otherwise, cover this row
// and uncover the column containing the starred zero. Continue in this manner
// until there are no uncovered zeros left, then go to Step 6.
void HungarianOptimizer::PrimeZeroes() {
// This loop is guaranteed to terminate in at most matrix_size_ iterations,
// as findZero() returns a location only if there is at least one uncovered
// zero in the matrix. Each iteration, either one row is covered or the
// loop terminates. Since there are matrix_size_ rows, after that many
// iterations there are no uncovered cells and hence no uncovered zeroes,
// so the loop terminates.
for (;;) {
int zero_row, zero_col;
if (!FindZero(&zero_row, &zero_col)) {
// No uncovered zeroes.
state_ = &HungarianOptimizer::AugmentPath;
return;
}
Prime(zero_row, zero_col);
int star_col = FindStarInRow(zero_row);
if (star_col != kHungarianOptimizerColNotFound) {
CoverRow(zero_row);
UncoverCol(star_col);
} else {
preimage_[0] = zero_row;
image_[0] = zero_col;
state_ = &HungarianOptimizer::MakeAugmentingPath;
return;
}
}
}
// Step 5.
// Construct a series of alternating primed and starred zeros as follows.
// Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote
// the starred zero in the column of Z0 (if any). Let Z2 denote the primed
// zero in the row of Z1 (there will always be one). Continue until the
// series terminates at a primed zero that has no starred zero in its column.
// Unstar each starred zero of the series, star each primed zero of the
// series, erase all primes and uncover every line in the matrix. Return to
// Step 3.
void HungarianOptimizer::MakeAugmentingPath() {
bool done = false;
int count = 0;
// Note: this loop is guaranteed to terminate within matrix_size_ iterations
// because:
// 1) on entry to this step, there is at least 1 column with no starred zero
// (otherwise we would have terminated the algorithm already.)
// 2) each row containing a star also contains exactly one primed zero.
// 4) each column contains at most one starred zero.
//
// Since the path_ we construct visits primed and starred zeroes alternately,
// and terminates if we reach a primed zero in a column with no star, our
// path_ must either contain matrix_size_ or fewer stars (in which case the
// loop iterates fewer than matrix_size_ times), or it contains more. In
// that case, because (1) implies that there are fewer than
// matrix_size_ stars, we must have visited at least one star more than once.
// Consider the first such star that we visit more than once; it must have
// been reached immediately after visiting a prime in the same row. By (2),
// this prime is unique and so must have also been visited more than once.
// Therefore, that prime must be in the same column as a star that has been
// visited more than once, contradicting the assumption that we chose the
// first multiply visited star, or it must be in the same column as more
// than one star, contradicting (3). Therefore, we never visit any star
// more than once and the loop terminates within matrix_size_ iterations.
while (!done) {
// First construct the alternating path...
int row = FindStarInCol(image_[count]);
if (row != kHungarianOptimizerRowNotFound) {
count++;
preimage_[count] = row;
image_[count] = image_[count - 1];
} else {
done = true;
}
if (!done) {
int col = FindPrimeInRow(preimage_[count]);
count++;
preimage_[count] = preimage_[count - 1];
image_[count] = col;
}
}
// Then modify it.
for (int i = 0; i <= count; ++i) {
int row = preimage_[i];
int col = image_[i];
if (IsStarred(row, col)) {
UnStar(row, col);
} else {
Star(row, col);
}
}
ClearCovers();
ClearPrimes();
state_ = &HungarianOptimizer::CoverStarredZeroes;
}
// Step 6
// Add the smallest uncovered value in the matrix to every element of each
// covered row, and subtract it from every element of each uncovered column.
// Return to Step 4 without altering any stars, primes, or covered lines.
void HungarianOptimizer::AugmentPath() {
double minval = FindSmallestUncovered();
for (int row = 0; row < matrix_size_; ++row) {
for (int col = 0; col < matrix_size_; ++col) {
if (RowCovered(row)) {
costs_[row][col] += minval;
}
if (!ColCovered(col)) {
costs_[row][col] -= minval;
}
}
}
state_ = &HungarianOptimizer::PrimeZeroes;
}
bool InputContainsNan(const std::vector<std::vector<double>>& input) {
for (const auto& subvector : input) {
for (const auto& num : subvector) {
if (std::isnan(num)) {
LOG(ERROR) << "The provided input contains " << num << ".";
return true;
}
}
}
return false;
}
void MinimizeLinearAssignment(
const std::vector<std::vector<double>>& cost,
absl::flat_hash_map<int, int>* direct_assignment,
absl::flat_hash_map<int, int>* reverse_assignment) {
if (InputContainsNan(cost)) {
LOG(ERROR) << "Returning before invoking the Hungarian optimizer.";
return;
}
std::vector<int> agent;
std::vector<int> task;
HungarianOptimizer hungarian_optimizer(cost);
hungarian_optimizer.Minimize(&agent, &task);
for (int i = 0; i < agent.size(); ++i) {
(*direct_assignment)[agent[i]] = task[i];
(*reverse_assignment)[task[i]] = agent[i];
}
}
void MaximizeLinearAssignment(
const std::vector<std::vector<double>>& cost,
absl::flat_hash_map<int, int>* direct_assignment,
absl::flat_hash_map<int, int>* reverse_assignment) {
if (InputContainsNan(cost)) {
LOG(ERROR) << "Returning before invoking the Hungarian optimizer.";
return;
}
std::vector<int> agent;
std::vector<int> task;
HungarianOptimizer hungarian_optimizer(cost);
hungarian_optimizer.Maximize(&agent, &task);
for (int i = 0; i < agent.size(); ++i) {
(*direct_assignment)[agent[i]] = task[i];
(*reverse_assignment)[task[i]] = agent[i];
}
}
} // namespace operations_research