Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Hungarian.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
72#ifndef HUNGARIAN_H
73#define HUNGARIAN_H
74
75#include <cmath>
76#include <limits>
77#include <type_traits>
78#include <utility>
79#include <initializer_list>
80#include <tpl_dynMat.H>
81#include <tpl_array.H>
82#include <htlist.H>
83#include <ah-errors.H>
84#include <ahFunction.H>
85
86namespace Aleph {
96template <typename Cost_Type = double>
98{
99 static_assert(std::is_signed_v<std::remove_cv_t<Cost_Type>> or
100 std::is_floating_point_v<std::remove_cv_t<Cost_Type>>,
101 "Cost_Type must be signed or floating-point to avoid "
102 "underflow when negating costs");
103 Cost_Type total_cost = Cost_Type{0};
106 size_t orig_rows = 0;
107 size_t orig_cols = 0;
108
117 {
119 for (size_t i = 0; i < orig_rows; ++i)
120 if (const long j = row_to_col[i]; j >= 0 and static_cast<size_t>(j) < orig_cols)
121 pairs.append(std::make_pair(i, static_cast<size_t>(j)));
122 return pairs;
123 }
124};
125
140template <typename Cost_Type = double>
142
143{
144 static_assert(std::is_signed_v<std::remove_cv_t<Cost_Type>> or
145 std::is_floating_point_v<std::remove_cv_t<Cost_Type>>,
146 "Cost_Type must be signed or floating-point to avoid "
147 "underflow when negating costs");
148 size_t n_ = 0; // Padded square dimension
149 size_t orig_rows_ = 0; // Original row count
150 size_t orig_cols_ = 0; // Original column count
151 Cost_Type total_cost_ = Cost_Type{0};
152 Array<long> row_to_col_; // row i -> column (or -1 if dummy)
153 Array<long> col_to_row_; // column j -> row (or -1 if dummy)
154
155 static constexpr bool Integer = std::is_integral_v<Cost_Type>;
156
157 // The type of the potentials and of the reduced costs: long long for an
158 // integer type narrower than it, so that they are far from its limits;
159 // else Cost_Type
160 using Wide = std::conditional_t<Integer and sizeof(Cost_Type) < sizeof(long long),
161 long long, Cost_Type>;
162
163 // The least and the largest of the costs and zero, of an integer type
165 {
166 Cost_Type lo{0};
167 Cost_Type hi{0};
168
169 void add(const Cost_Type & c) noexcept
170 {
171 if constexpr (Integer)
172 {
173 lo = c < lo ? c : lo;
174 hi = c > hi ? c : hi;
175 }
176 }
177 };
178
179 [[noreturn, gnu::noinline, gnu::cold]] static void throw_beyond()
180 {
181 ah_overflow_error() << "Hungarian_Assignment: the costs, with the potentials, come too "
182 << "near the limits of their integer type";
183 }
184
190 void solve(const DynMatrix<Cost_Type> &cost, [[maybe_unused]] const Cost_Range & range)
191 {
192 const long n = static_cast<long>(n_);
193 const auto sz = static_cast<size_t>(n + 1);
194
195 // Dual variables (potentials), 1-indexed
196 Array<Wide> u(sz, Wide{0});
197 Array<Wide> v(sz, Wide{0});
198
199 // p[j] = row matched to column j (0 = unmatched)
200 Array<long> p(sz, 0L);
201
202 const Wide Inf = std::numeric_limits<Wide>::max() / 2;
203
204 // With an integer type, each step moves each potential by delta at
205 // most, so that the sum of the |delta| bounds the potentials, and a
206 // reduced cost is within twice that sum of a cost. While a bound of
207 // the costs and twice the sum add up to at most max() / 4 of Wide,
208 // every sum is in Wide and every reduced cost below Inf, so that the
209 // answer is exact; a step beyond that throws overflow_error. An
210 // integer type narrower than long long keeps its sums in long long,
211 // which they do not come near: it throws only if the optimum does not
212 // fit in it
213 constexpr Wide Wide_Max = std::numeric_limits<Wide>::max();
214 [[maybe_unused]] Wide room{-1}; // what the sum may still grow; none below 0
215 if constexpr (Integer)
216 if (Wide(range.lo) != std::numeric_limits<Wide>::lowest())
217 {
218 const Wide c = std::max(Wide(range.hi), Wide(-Wide(range.lo)));
219 if (c <= Wide_Max / 4)
220 room = Wide((Wide_Max / 4 - c) / 2);
221 }
222
223 // For each row, find the shortest augmenting path
224 for (long i = 1; i <= n; ++i)
225 {
226 // "Virtual" column 0 is matched to row i
227 p(0) = i;
228
229 // Minimum reduced cost to reach each column
230 Array<Wide> dist(sz, Inf);
231 dist(0) = Wide{0};
232
233 // way[j] = previous column on the shortest path to j
234 Array<long> way(sz, 0L);
235
236 // visited[j] = true if column j is in the "tree"
237 Array<bool> visited(sz, false);
238
239 // Dijkstra-like scan
240 long j0 = 0; // current column (start at virtual column 0)
241 do
242 {
243 visited(j0) = true;
244 const long i0 = p(j0); // row matched to current column
245 Wide delta = Inf;
246 long j1 = -1;
247
248 if constexpr (Integer)
249 if (room < 0)
250 throw_beyond();
251
252 for (long j = 1; j <= n; ++j)
253 {
254 if (visited(j))
255 continue;
256
257 // Reduced cost: c[i0][j] - u[i0] - v[j]
258 const Wide reduced =
259 Wide(cost.read(static_cast<size_t>(i0 - 1), static_cast<size_t>(j - 1)))
260 - u(i0) - v(j);
261
262 if (reduced < dist(j))
263 {
264 dist(j) = reduced;
265 way(j) = j0;
266 }
267
268 if (dist(j) < delta)
269 {
270 delta = dist(j);
271 j1 = j;
272 }
273 }
274
275 // Update potentials
276 for (long j = 0; j <= n; ++j)
277 if (visited(j))
278 {
279 u(p(j)) += delta;
280 v(j) -= delta;
281 }
282 else
283 dist(j) -= delta;
284
285 // Every reduced cost left is at the infinity or above it: the
286 // costs do not fit in Cost_Type with room for the potentials
288 << "Hungarian_Assignment: the costs are too large for their type";
289
290 if constexpr (Integer) // |delta| <= Wide_Max / 4, and room too
291 room -= delta >= 0 ? delta : Wide(-delta);
292
293 j0 = j1;
294 } while (p(j0) != 0); // until we reach a free column
295
296 // Augment along the path
297 do
298 {
299 const long j1 = way(j0);
300 p(j0) = p(j1);
301 j0 = j1;
302 } while (j0 != 0);
303 }
304
305 // Extract results: v[0] accumulates the total cost, which, with an
306 // integer type, must fit in Cost_Type
307 if constexpr (Integer)
308 if (-v(0) > Wide(std::numeric_limits<Cost_Type>::max())
309 or -v(0) < Wide(std::numeric_limits<Cost_Type>::lowest()))
310 throw_beyond();
311 total_cost_ = Cost_Type(-v(0));
312
315
316 for (long j = 1; j <= n; ++j)
317 {
318 const long row = p(j) - 1; // convert to 0-based
319 const long col = j - 1;
320
321 if (row >= 0 and static_cast<size_t>(row) < orig_rows_ and col >= 0 and
322 static_cast<size_t>(col) < orig_cols_)
323 {
324 row_to_col_(static_cast<size_t>(row)) = col;
325 col_to_row_(static_cast<size_t>(col)) = row;
326 }
327 }
328 }
329
330public:
345 {
346 orig_rows_ = cost.rows();
347 orig_cols_ = cost.cols();
349 << "Hungarian_Assignment: cost matrix must not be empty";
350
351 if constexpr (std::is_floating_point_v<Cost_Type>)
352 for (size_t i = 0; i < orig_rows_; ++i)
353 for (size_t j = 0; j < orig_cols_; ++j)
354 ah_invalid_argument_if(not std::isfinite(cost.read(i, j)))
355 << "Hungarian_Assignment: cost[" << i << "][" << j << "] is not finite";
356
358
359 // Build padded square matrix (zeros for padding)
360 DynMatrix<Cost_Type> padded(n_, n_, Cost_Type{0});
361 padded.allocate();
363 for (size_t i = 0; i < orig_rows_; ++i)
364 for (size_t j = 0; j < orig_cols_; ++j)
365 {
366 const Cost_Type c = cost.read(i, j);
367 padded(i, j) = c;
368 range.add(c);
369 }
370
371 solve(padded, range);
372 }
373
397 Hungarian_Assignment(std::initializer_list<std::initializer_list<Cost_Type>> rows)
398 {
399 ah_invalid_argument_if(rows.size() == 0)
400 << "Hungarian_Assignment: cost matrix must not be empty";
401
402 orig_rows_ = rows.size();
403 orig_cols_ = rows.begin()->size();
405 << "Hungarian_Assignment: cost matrix must not have zero columns";
407
408 DynMatrix<Cost_Type> padded(n_, n_, Cost_Type{0});
409 padded.allocate();
411
412 size_t i = 0;
413 for (const auto &row : rows)
414 {
416 << "Hungarian_Assignment: all rows must have the same length";
417 size_t j = 0;
418 for (const auto &val : row)
419 {
420 if constexpr (std::is_floating_point_v<Cost_Type>)
421 ah_invalid_argument_if(not std::isfinite(val))
422 << "Hungarian_Assignment: non-finite cost value at row " << i;
423 padded(i, j++) = val;
424 range.add(val);
425 }
426 ++i;
427 }
428
429 solve(padded, range);
430 }
431
437
447 : n_(std::exchange(other.n_, 0)), orig_rows_(std::exchange(other.orig_rows_, 0)),
448 orig_cols_(std::exchange(other.orig_cols_, 0)),
449 total_cost_(std::exchange(other.total_cost_, Cost_Type{0})),
450 row_to_col_(std::move(other.row_to_col_)), col_to_row_(std::move(other.col_to_row_))
451 {}
452
459
466 {
467 swap(other);
468 return *this;
469 }
470
474 void swap(Hungarian_Assignment & other) noexcept
475 {
476 std::swap(n_, other.n_);
477 std::swap(orig_rows_, other.orig_rows_);
478 std::swap(orig_cols_, other.orig_cols_);
479 std::swap(total_cost_, other.total_cost_);
480 row_to_col_.swap(other.row_to_col_);
481 col_to_row_.swap(other.col_to_row_);
482 }
483
487 [[nodiscard]] Cost_Type get_total_cost() const noexcept
488 {
489 return total_cost_;
490 }
491
498 [[nodiscard]] long get_assignment(const size_t row) const
499 {
500 ah_out_of_range_error_if(row >= orig_rows_) << "Hungarian_Assignment::get_assignment: row "
501 << row << " out of range [0, " << orig_rows_ << ")";
502 return row_to_col_[row];
503 }
504
513 {
515 for (size_t i = 0; i < orig_rows_; ++i)
516 if (const long j = row_to_col_[i]; j >= 0 and static_cast<size_t>(j) < orig_cols_)
517 pairs.append(std::make_pair(i, static_cast<size_t>(j)));
518 return pairs;
519 }
520
525 [[nodiscard]] const Array<long> &get_row_assignments() const noexcept
526 {
527 return row_to_col_;
528 }
529
534 [[nodiscard]] const Array<long> &get_col_assignments() const noexcept
535 {
536 return col_to_row_;
537 }
538
546 [[nodiscard]] Array<long> extract_row_assignments() && noexcept
547 {
548 return std::move(row_to_col_);
549 }
550
558 [[nodiscard]] Array<long> extract_col_assignments() && noexcept
559 {
560 return std::move(col_to_row_);
561 }
562
566 [[nodiscard]] size_t dimension() const noexcept
567 {
568 return n_;
569 }
570
574 [[nodiscard]] size_t rows() const noexcept
575 {
576 return orig_rows_;
577 }
578
582 [[nodiscard]] size_t cols() const noexcept
583 {
584 return orig_cols_;
585 }
586};
587
606template <typename Cost_Type>
608{
609 static_assert(std::is_signed_v<std::remove_cv_t<Cost_Type>> or
610 std::is_floating_point_v<std::remove_cv_t<Cost_Type>>,
611 "Cost_Type must be signed or floating-point to avoid "
612 "underflow when negating costs");
613
616 // Read scalar fields before moving from ha.
617 result.total_cost = ha.get_total_cost();
618 result.orig_rows = ha.rows();
619 result.orig_cols = ha.cols();
620 result.row_to_col = std::move(ha).extract_row_assignments();
621 result.col_to_row = std::move(ha).extract_col_assignments();
622 return result;
623}
624
647template <typename Cost_Type>
649{
650 static_assert(std::is_signed_v<std::remove_cv_t<Cost_Type>> or
651 std::is_floating_point_v<std::remove_cv_t<Cost_Type>>,
652 "Cost_Type must be signed or floating-point to avoid "
653 "underflow when negating costs");
654
655 // Use a promoted signed type for negation to avoid overflow when
656 // Cost_Type is a signed integer and a cell contains its minimum value.
657 using Common = std::common_type_t<Cost_Type, long long>;
658 using Promoted = typename std::conditional_t<std::is_floating_point_v<Common>,
659 std::type_identity<Common>,
660 std::make_signed<Common>>::type;
661
662 const size_t rows = cost.rows();
663 const size_t cols = cost.cols();
664 DynMatrix<Promoted> negated(rows, cols);
665 negated.allocate();
666 for (size_t i = 0; i < rows; ++i)
667 for (size_t j = 0; j < cols; ++j)
668 {
669 if constexpr (std::is_integral_v<Promoted> and std::is_signed_v<Promoted>)
670 {
671 auto v = static_cast<Promoted>(cost.read(i, j));
672 ah_overflow_error_if(v == std::numeric_limits<Promoted>::min())
673 << "Cannot negate minimum integer value";
674 negated(i, j) = -v;
675 }
676 else
677 negated(i, j) = -static_cast<Promoted>(cost.read(i, j));
678 }
679
680 auto inner = hungarian_assignment(negated);
681
682 // the maximum, the opposite of the minimum of the negated costs, must fit
683 // in Cost_Type
684 if constexpr (std::is_integral_v<Promoted>)
685 ah_overflow_error_if(inner.total_cost == std::numeric_limits<Promoted>::min()
686 or -inner.total_cost > Promoted(std::numeric_limits<Cost_Type>::max())
687 or -inner.total_cost < Promoted(std::numeric_limits<Cost_Type>::lowest()))
688 << "hungarian_max_assignment(): the maximum does not fit in the type of the costs";
689
691 result.total_cost = static_cast<Cost_Type>(-inner.total_cost);
692 result.row_to_col = std::move(inner.row_to_col);
693 result.col_to_row = std::move(inner.col_to_row);
694 result.orig_rows = inner.orig_rows;
695 result.orig_cols = inner.orig_cols;
696 return result;
697}
698} // end namespace Aleph
699
700#endif // HUNGARIAN_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_overflow_error()
Throws std::overflow_error unconditionally.
Definition ah-errors.H:643
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
Standard functor implementations and comparison objects.
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
size_t size_t col
Definition ca-c-api.h:116
size_t cols
Definition ca-c-api.h:105
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Dynamic matrix with sparse storage.
Definition tpl_dynMat.H:122
const T & read(const size_t i, const size_t j) const
Read the entry at position (i, j).
Definition tpl_dynMat.H:480
constexpr size_t cols() const noexcept
Get the number of columns.
Definition tpl_dynMat.H:447
void allocate()
Pre-allocate memory for the entire matrix.
Definition tpl_dynMat.H:271
constexpr size_t rows() const noexcept
Get the number of rows.
Definition tpl_dynMat.H:441
Implementation of the Hungarian (Munkres) algorithm.
Definition Hungarian.H:143
void solve(const DynMatrix< Cost_Type > &cost, const Cost_Range &range)
Core algorithm: shortest augmenting paths with dual variables.
Definition Hungarian.H:190
DynList< std::pair< size_t, size_t > > get_assignments() const
Get all assignment pairs.
Definition Hungarian.H:512
long get_assignment(const size_t row) const
Get the column assigned to a given row.
Definition Hungarian.H:498
const Array< long > & get_row_assignments() const noexcept
Get the row-to-column assignment array.
Definition Hungarian.H:525
Hungarian_Assignment & operator=(Hungarian_Assignment &&other) noexcept
Exchange this solver with another, which is left with the previous assignment of this one.
Definition Hungarian.H:465
Hungarian_Assignment(std::initializer_list< std::initializer_list< Cost_Type > > rows)
Construct and solve from an initializer list of rows.
Definition Hungarian.H:397
Array< long > extract_col_assignments() &&noexcept
Move out the column-to-row assignment array.
Definition Hungarian.H:558
const Array< long > & get_col_assignments() const noexcept
Get the column-to-row assignment array.
Definition Hungarian.H:534
size_t cols() const noexcept
Get the original number of columns.
Definition Hungarian.H:582
Hungarian_Assignment(const Hungarian_Assignment &other)=default
Copy the assignment of another solver.
Hungarian_Assignment & operator=(const Hungarian_Assignment &other)=default
Copy the assignment of another solver.
size_t dimension() const noexcept
Get the padded square dimension.
Definition Hungarian.H:566
Array< long > extract_row_assignments() &&noexcept
Move out the row-to-column assignment array.
Definition Hungarian.H:546
size_t rows() const noexcept
Get the original number of rows.
Definition Hungarian.H:574
Hungarian_Assignment(Hungarian_Assignment &&other) noexcept
Take the assignment of another solver, which is left empty.
Definition Hungarian.H:446
Hungarian_Assignment(const DynMatrix< Cost_Type > &cost)
Construct and solve from a DynMatrix cost matrix.
Definition Hungarian.H:344
Cost_Type get_total_cost() const noexcept
Get the optimal total cost.
Definition Hungarian.H:487
std::conditional_t< Integer and sizeof(Cost_Type)< sizeof(long long), long long, Cost_Type > Wide
Definition Hungarian.H:161
void swap(Hungarian_Assignment &other) noexcept
Exchange in O(1) this solver and another.
Definition Hungarian.H:474
static constexpr bool Integer
Definition Hungarian.H:155
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_j0_function > > j0(const __gmp_expr< T, U > &expr)
Definition gmpfrxx.h:4177
__gmp_expr< T, __gmp_unary_expr< __gmp_expr< T, U >, __gmp_j1_function > > j1(const __gmp_expr< T, U > &expr)
Definition gmpfrxx.h:4178
Hungarian_Result< Cost_Type > hungarian_max_assignment(const DynMatrix< Cost_Type > &cost)
Compute maximum-profit assignment (free function).
Definition Hungarian.H:648
Hungarian_Result< Cost_Type > hungarian_assignment(const DynMatrix< Cost_Type > &cost)
Compute minimum-cost assignment (free function).
Definition Hungarian.H:607
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
Container< T > range(const T start, const T end, const T step=1)
Generate a range of values [start, end] with a given step.
void add(const Cost_Type &c) noexcept
Definition Hungarian.H:169
Result of the Hungarian assignment algorithm.
Definition Hungarian.H:98
Array< long > col_to_row
column j is assigned to row col_to_row[j]
Definition Hungarian.H:105
Cost_Type total_cost
Optimal total cost.
Definition Hungarian.H:103
Array< long > row_to_col
row i is assigned to column row_to_col[i]
Definition Hungarian.H:104
DynList< std::pair< size_t, size_t > > get_pairs() const
Get the assignment pairs, excluding dummy entries.
Definition Hungarian.H:116
size_t orig_rows
Original number of rows.
Definition Hungarian.H:106
size_t orig_cols
Original number of columns.
Definition Hungarian.H:107
Dynamic array container with automatic resizing.
Dynamic matrix with lazy allocation.