././@PaxHeader0000000000000000000000000000003400000000000011452 xustar000000000000000028 mtime=1600182719.0867817 munkres-1.1.4/0000755000076500000240000000000000000000000013066 5ustar00bmcstaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600182688.0 munkres-1.1.4/CHANGELOG.md0000644000076500000240000001224500000000000014703 0ustar00bmcstaff00000000000000# Change Log, munkres.py Version 1.1.4 (September, 2020) - Switched from Nose to Pytest for testing. Patch courtesy @kmosiejczuk, [PR #32](https://github.com/bmc/munkres/pull/32), with some additional cleanup by me. - Fix to [Issue #34](https://github.com/bmc/munkres/issues/34), in which `print_matrix` wasn't handling non-integral values. Patch courtesy @finn0, via [PR #35](https://github.com/bmc/munkres/pull/35). - Various changes from `http:` URLs to `https:` URLs, courtesy @finn0 via [PR #36](https://github.com/bmc/munkres/pull/36/). Version 1.1.3: **Nonexistent**. Accidentally published before check-in. Deleted from PyPI. Use version 1.1.4. Version 1.1.2 (February, 2019) - Removed `NoReturn` type annotations, to allow compatibility with Python 3.5 releases prior to 3.5.4. Thanks to @jackwilsdon for catching that issue. Version 1.1.1 (February, 2019) - Version bump to get past a PyPI publishing issue. (Can't republish partially published 1.1.0.) Version 1.1.0 (February, 2019) - Only supports Python 3.5 or better, from this version forward (since Python 2 is at end of life in 11 months). - Added `typing` type hints. - Updated docs to use `pdoc`, since `epydoc` is pretty much dead. Version 1.0.12 (June, 2017) - Merged [Pull Request #11](https://github.com/bmc/munkres/pull/11), from [@brunokim](https://github.com/brunokim), which simplifies conversion of a profit matrix to a cost matrix, in the default case. - Merged [Pull Request #7](https://github.com/bmc/munkres/pull/7), from [@mdxs](https://github.com/mdxs), which fixes a message. - Added more tests. Version 1.0.11 (June, 2017) - Docs are now generated with [pdoc](https://github.com/BurntSushi/pdoc). - Merged [Pull Request 24](https://github.com/bmc/munkres/pull/24), from [@czlee](https://github.com/czlee): - Change to step 4: When it looks for a uncovered zero, rather than starting at row 0, column 0, it starts where it left off, i.e. at the last uncovered zero it found. Since it doesn't start at (0,0), when it gets to the last column it now loops around to the first, and exits unsuccessfully if it got back to where it started. This change reduces this reduces the solving time for (certain) large matrices. For instance, in tests, solving a matrix of size 394×394 goes from about 2 minutes to about 4 seconds. - Since Python 3 started cracking down on unnatural comparisons, the `DISALLOWED` constant added in [Pull Request 19](https://github.com/bmc/munkres/issues/19) no longer works. (It raises a TypeError for unorderable types, as is expected in Python 3.) Since this constant is meant to act like infinity, this modification just changes the two lines where it would otherwise try to make an illegal (in Python 3) comparison between a number and `DISALLOWED_OBJ()` and gets it to behave as if `DISALLOWED` is always larger. - Added Travis CI integration. - Added some unit tests. See `tests` and `tests/README.md`. Version 1.0.10 (May, 2017) - Updated `setup.py` to produce a wheel. Version 1.0.9 (Jan, 2017) - Fixed URL to original implementation. Addresses [Issue #4](https://github.com/bmc/munkres/issues/4). - Fixes from [@kylemcdonald](https://github.com/kylemcdonald): - `print_matrix()` no longer crashes on 0. Fixes [Issue #1](https://github.com/bmc/munkres/issues/4). - Fixed bug where step 3 could quit early. Fixes [Issue #16](https://github.com/bmc/munkres/issues/16). - Added step 2 break for a small optimization. - Added time bound to README. Addresses [Issue #15](https://github.com/bmc/munkres/issues/15). - Versioning will now adhere to [semantic version specification](https://semver.org). Version 1.0.8 (June, 2016) - License is now ASL. Version 1.0.7 (December, 2014) Fix from Stephan Porz (s.porz /at/ uni-bonn.de): - Fix pad_matrix: pad_value now actually used Version 1.0.6 (December, 2013) Fixes from Markus Padourek (markus.padourek /at/ gmail.com): - sys.maxsize fix and bump to 1.0.6 - Updated to Python 3.x Version 1.0.5.3 (2 August, 2009) - Fixed documentation of print_matrix() in module docs. Version 1.0.5.2 (30 June, 2008): - Incorporated some suggestions optimizations from Mark Summerfield (mark /at/ qtrac.eu) - Munkres.make_cost_matrix() is now deprecated, in favor of a module-level function. - The module now provides a print_matrix() convenience function. - Fixed some bugs related to the padding of non-square matrics. Version 1.0.5.1 (26 June, 2008) - Some minor doc changes. Version 1.0.5 (26 June, 2008) - Now handles non-square cost matrices by padding them with zeros. - Converted Epydocs to use reStructuredText. Version 1.0.4 (13 June, 2008) - Minor bug fix in main (tester) program in munkres.py Version 1.0.3 (16 March, 2008) - Minor change to prevent shadowing of built-in min() function. Thanks to Nelson Castillo (nelson /at/ emqbit.com) for pointing it out. Version 1.0.2 (21 February, 2008) - Fixed an overindexing bug reported by Chris Willmore (willmc rpi.edu) Version 1.0.1 (16 February, 2008) - Documentation now processed by Epydoc. Version 1.0 (January, 2008) - Initial release. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600181242.0 munkres-1.1.4/LICENSE.md0000644000076500000240000000106500000000000014474 0ustar00bmcstaff00000000000000Copyright © 2008-2019 Brian M. Clapper 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 https://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. ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1549996138.0 munkres-1.1.4/MANIFEST.in0000644000076500000240000000010600000000000014621 0ustar00bmcstaff00000000000000recursive-include test *.md include LICENSE.md README.md CHANGELOG.md ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1600182719.086983 munkres-1.1.4/PKG-INFO0000644000076500000240000000204700000000000014166 0ustar00bmcstaff00000000000000Metadata-Version: 2.1 Name: munkres Version: 1.1.4 Summary: Munkres (Hungarian) algorithm for the Assignment Problem Home-page: https://software.clapper.org/munkres/ Author: Brian Clapper Author-email: bmc@clapper.org License: Apache Software License Description: Introduction ============ The Munkres module provides an implementation of the Munkres algorithm (also called the Hungarian algorithm or the Kuhn-Munkres algorithm), useful for solving the Assignment Problem. For complete usage documentation, see: https://software.clapper.org/munkres/ Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Scientific/Engineering :: Mathematics Classifier: Topic :: Software Development :: Libraries :: Python Modules Description-Content-Type: text/markdown ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600181242.0 munkres-1.1.4/README.md0000644000076500000240000000270700000000000014353 0ustar00bmcstaff00000000000000Munkres implementation for Python --------------------------------- ## Introduction The Munkres module provides an O(n^3) implementation of the Munkres algorithm (also called the [Hungarian algorithm][] or the Kuhn-Munkres algorithm). The algorithm models an assignment problem as an NxM cost matrix, where each element represents the cost of assigning the ith worker to the jth job, and it figures out the least-cost solution, choosing a single item from each row and column in the matrix, such that no row and no column are used more than once. This particular implementation is based on . [Hungarian algorithm]: https://en.wikipedia.org/wiki/Hungarian_algorithm See the docs on the [project page][] for more details. **WARNING**: As of version 1.1.0, _munkres_ no longer supports Python 2. If you need to use this package with Python 2, install an earlier version. See [the installation instructions](http://software.clapper.org/munkres/#installing) for details. [project page]: https://software.clapper.org/munkres/ ## Copyright © 2008-2019 Brian M. Clapper ## License Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE.md) for details. ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1600182719.085672 munkres-1.1.4/munkres.egg-info/0000755000076500000240000000000000000000000016244 5ustar00bmcstaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600182718.0 munkres-1.1.4/munkres.egg-info/PKG-INFO0000644000076500000240000000204700000000000017344 0ustar00bmcstaff00000000000000Metadata-Version: 2.1 Name: munkres Version: 1.1.4 Summary: Munkres (Hungarian) algorithm for the Assignment Problem Home-page: https://software.clapper.org/munkres/ Author: Brian Clapper Author-email: bmc@clapper.org License: Apache Software License Description: Introduction ============ The Munkres module provides an implementation of the Munkres algorithm (also called the Hungarian algorithm or the Kuhn-Munkres algorithm), useful for solving the Assignment Problem. For complete usage documentation, see: https://software.clapper.org/munkres/ Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Scientific/Engineering :: Mathematics Classifier: Topic :: Software Development :: Libraries :: Python Modules Description-Content-Type: text/markdown ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600182718.0 munkres-1.1.4/munkres.egg-info/SOURCES.txt0000644000076500000240000000035300000000000020131 0ustar00bmcstaff00000000000000CHANGELOG.md LICENSE.md MANIFEST.in README.md munkres.py setup.cfg setup.py munkres.egg-info/PKG-INFO munkres.egg-info/SOURCES.txt munkres.egg-info/dependency_links.txt munkres.egg-info/top_level.txt test/README.md test/test_munkres.py././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600182718.0 munkres-1.1.4/munkres.egg-info/dependency_links.txt0000644000076500000240000000000100000000000022312 0ustar00bmcstaff00000000000000 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600182718.0 munkres-1.1.4/munkres.egg-info/top_level.txt0000644000076500000240000000001000000000000020765 0ustar00bmcstaff00000000000000munkres ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600182695.0 munkres-1.1.4/munkres.py0000644000076500000240000004571600000000000015141 0ustar00bmcstaff00000000000000""" Introduction ============ The Munkres module provides an implementation of the Munkres algorithm (also called the Hungarian algorithm or the Kuhn-Munkres algorithm), useful for solving the Assignment Problem. For complete usage documentation, see: https://software.clapper.org/munkres/ """ __docformat__ = 'markdown' # --------------------------------------------------------------------------- # Imports # --------------------------------------------------------------------------- import sys import copy from typing import Union, NewType, Sequence, Tuple, Optional, Callable # --------------------------------------------------------------------------- # Exports # --------------------------------------------------------------------------- __all__ = ['Munkres', 'make_cost_matrix', 'DISALLOWED'] # --------------------------------------------------------------------------- # Globals # --------------------------------------------------------------------------- AnyNum = NewType('AnyNum', Union[int, float]) Matrix = NewType('Matrix', Sequence[Sequence[AnyNum]]) # Info about the module __version__ = "1.1.4" __author__ = "Brian Clapper, bmc@clapper.org" __url__ = "https://software.clapper.org/munkres/" __copyright__ = "(c) 2008-2020 Brian M. Clapper" __license__ = "Apache Software License" # Constants class DISALLOWED_OBJ(object): pass DISALLOWED = DISALLOWED_OBJ() DISALLOWED_PRINTVAL = "D" # --------------------------------------------------------------------------- # Exceptions # --------------------------------------------------------------------------- class UnsolvableMatrix(Exception): """ Exception raised for unsolvable matrices """ pass # --------------------------------------------------------------------------- # Classes # --------------------------------------------------------------------------- class Munkres: """ Calculate the Munkres solution to the classical assignment problem. See the module documentation for usage. """ def __init__(self): """Create a new instance""" self.C = None self.row_covered = [] self.col_covered = [] self.n = 0 self.Z0_r = 0 self.Z0_c = 0 self.marked = None self.path = None def pad_matrix(self, matrix: Matrix, pad_value: int=0) -> Matrix: """ Pad a possibly non-square matrix to make it square. **Parameters** - `matrix` (list of lists of numbers): matrix to pad - `pad_value` (`int`): value to use to pad the matrix **Returns** a new, possibly padded, matrix """ max_columns = 0 total_rows = len(matrix) for row in matrix: max_columns = max(max_columns, len(row)) total_rows = max(max_columns, total_rows) new_matrix = [] for row in matrix: row_len = len(row) new_row = row[:] if total_rows > row_len: # Row too short. Pad it. new_row += [pad_value] * (total_rows - row_len) new_matrix += [new_row] while len(new_matrix) < total_rows: new_matrix += [[pad_value] * total_rows] return new_matrix def compute(self, cost_matrix: Matrix) -> Sequence[Tuple[int, int]]: """ Compute the indexes for the lowest-cost pairings between rows and columns in the database. Returns a list of `(row, column)` tuples that can be used to traverse the matrix. **WARNING**: This code handles square and rectangular matrices. It does *not* handle irregular matrices. **Parameters** - `cost_matrix` (list of lists of numbers): The cost matrix. If this cost matrix is not square, it will be padded with zeros, via a call to `pad_matrix()`. (This method does *not* modify the caller's matrix. It operates on a copy of the matrix.) **Returns** A list of `(row, column)` tuples that describe the lowest cost path through the matrix """ self.C = self.pad_matrix(cost_matrix) self.n = len(self.C) self.original_length = len(cost_matrix) self.original_width = len(cost_matrix[0]) self.row_covered = [False for i in range(self.n)] self.col_covered = [False for i in range(self.n)] self.Z0_r = 0 self.Z0_c = 0 self.path = self.__make_matrix(self.n * 2, 0) self.marked = self.__make_matrix(self.n, 0) done = False step = 1 steps = { 1 : self.__step1, 2 : self.__step2, 3 : self.__step3, 4 : self.__step4, 5 : self.__step5, 6 : self.__step6 } while not done: try: func = steps[step] step = func() except KeyError: done = True # Look for the starred columns results = [] for i in range(self.original_length): for j in range(self.original_width): if self.marked[i][j] == 1: results += [(i, j)] return results def __copy_matrix(self, matrix: Matrix) -> Matrix: """Return an exact copy of the supplied matrix""" return copy.deepcopy(matrix) def __make_matrix(self, n: int, val: AnyNum) -> Matrix: """Create an *n*x*n* matrix, populating it with the specific value.""" matrix = [] for i in range(n): matrix += [[val for j in range(n)]] return matrix def __step1(self) -> int: """ For each row of the matrix, find the smallest element and subtract it from every element in its row. Go to Step 2. """ C = self.C n = self.n for i in range(n): vals = [x for x in self.C[i] if x is not DISALLOWED] if len(vals) == 0: # All values in this row are DISALLOWED. This matrix is # unsolvable. raise UnsolvableMatrix( "Row {0} is entirely DISALLOWED.".format(i) ) minval = min(vals) # Find the minimum value for this row and subtract that minimum # from every element in the row. for j in range(n): if self.C[i][j] is not DISALLOWED: self.C[i][j] -= minval return 2 def __step2(self) -> int: """ Find a zero (Z) in the resulting matrix. If there is no starred zero in its row or column, star Z. Repeat for each element in the matrix. Go to Step 3. """ n = self.n for i in range(n): for j in range(n): if (self.C[i][j] == 0) and \ (not self.col_covered[j]) and \ (not self.row_covered[i]): self.marked[i][j] = 1 self.col_covered[j] = True self.row_covered[i] = True break self.__clear_covers() return 3 def __step3(self) -> int: """ Cover each column containing a starred zero. If K columns are covered, the starred zeros describe a complete set of unique assignments. In this case, Go to DONE, otherwise, Go to Step 4. """ n = self.n count = 0 for i in range(n): for j in range(n): if self.marked[i][j] == 1 and not self.col_covered[j]: self.col_covered[j] = True count += 1 if count >= n: step = 7 # done else: step = 4 return step def __step4(self) -> int: """ 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. Save the smallest uncovered value and Go to Step 6. """ step = 0 done = False row = 0 col = 0 star_col = -1 while not done: (row, col) = self.__find_a_zero(row, col) if row < 0: done = True step = 6 else: self.marked[row][col] = 2 star_col = self.__find_star_in_row(row) if star_col >= 0: col = star_col self.row_covered[row] = True self.col_covered[col] = False else: done = True self.Z0_r = row self.Z0_c = col step = 5 return step def __step5(self) -> int: """ 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 """ count = 0 path = self.path path[count][0] = self.Z0_r path[count][1] = self.Z0_c done = False while not done: row = self.__find_star_in_col(path[count][1]) if row >= 0: count += 1 path[count][0] = row path[count][1] = path[count-1][1] else: done = True if not done: col = self.__find_prime_in_row(path[count][0]) count += 1 path[count][0] = path[count-1][0] path[count][1] = col self.__convert_path(path, count) self.__clear_covers() self.__erase_primes() return 3 def __step6(self) -> int: """ Add the value found in Step 4 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. """ minval = self.__find_smallest() events = 0 # track actual changes to matrix for i in range(self.n): for j in range(self.n): if self.C[i][j] is DISALLOWED: continue if self.row_covered[i]: self.C[i][j] += minval events += 1 if not self.col_covered[j]: self.C[i][j] -= minval events += 1 if self.row_covered[i] and not self.col_covered[j]: events -= 2 # change reversed, no real difference if (events == 0): raise UnsolvableMatrix("Matrix cannot be solved!") return 4 def __find_smallest(self) -> AnyNum: """Find the smallest uncovered value in the matrix.""" minval = sys.maxsize for i in range(self.n): for j in range(self.n): if (not self.row_covered[i]) and (not self.col_covered[j]): if self.C[i][j] is not DISALLOWED and minval > self.C[i][j]: minval = self.C[i][j] return minval def __find_a_zero(self, i0: int = 0, j0: int = 0) -> Tuple[int, int]: """Find the first uncovered element with value 0""" row = -1 col = -1 i = i0 n = self.n done = False while not done: j = j0 while True: if (self.C[i][j] == 0) and \ (not self.row_covered[i]) and \ (not self.col_covered[j]): row = i col = j done = True j = (j + 1) % n if j == j0: break i = (i + 1) % n if i == i0: done = True return (row, col) def __find_star_in_row(self, row: Sequence[AnyNum]) -> int: """ Find the first starred element in the specified row. Returns the column index, or -1 if no starred element was found. """ col = -1 for j in range(self.n): if self.marked[row][j] == 1: col = j break return col def __find_star_in_col(self, col: Sequence[AnyNum]) -> int: """ Find the first starred element in the specified row. Returns the row index, or -1 if no starred element was found. """ row = -1 for i in range(self.n): if self.marked[i][col] == 1: row = i break return row def __find_prime_in_row(self, row) -> int: """ Find the first prime element in the specified row. Returns the column index, or -1 if no starred element was found. """ col = -1 for j in range(self.n): if self.marked[row][j] == 2: col = j break return col def __convert_path(self, path: Sequence[Sequence[int]], count: int) -> None: for i in range(count+1): if self.marked[path[i][0]][path[i][1]] == 1: self.marked[path[i][0]][path[i][1]] = 0 else: self.marked[path[i][0]][path[i][1]] = 1 def __clear_covers(self) -> None: """Clear all covered matrix cells""" for i in range(self.n): self.row_covered[i] = False self.col_covered[i] = False def __erase_primes(self) -> None: """Erase all prime markings""" for i in range(self.n): for j in range(self.n): if self.marked[i][j] == 2: self.marked[i][j] = 0 # --------------------------------------------------------------------------- # Functions # --------------------------------------------------------------------------- def make_cost_matrix( profit_matrix: Matrix, inversion_function: Optional[Callable[[AnyNum], AnyNum]] = None ) -> Matrix: """ Create a cost matrix from a profit matrix by calling `inversion_function()` to invert each value. The inversion function must take one numeric argument (of any type) and return another numeric argument which is presumed to be the cost inverse of the original profit value. If the inversion function is not provided, a given cell's inverted value is calculated as `max(matrix) - value`. This is a static method. Call it like this: from munkres import Munkres cost_matrix = Munkres.make_cost_matrix(matrix, inversion_func) For example: from munkres import Munkres cost_matrix = Munkres.make_cost_matrix(matrix, lambda x : sys.maxsize - x) **Parameters** - `profit_matrix` (list of lists of numbers): The matrix to convert from profit to cost values. - `inversion_function` (`function`): The function to use to invert each entry in the profit matrix. **Returns** A new matrix representing the inversion of `profix_matrix`. """ if not inversion_function: maximum = max(max(row) for row in profit_matrix) inversion_function = lambda x: maximum - x cost_matrix = [] for row in profit_matrix: cost_matrix.append([inversion_function(value) for value in row]) return cost_matrix def print_matrix(matrix: Matrix, msg: Optional[str] = None) -> None: """ Convenience function: Displays the contents of a matrix. **Parameters** - `matrix` (list of lists of numbers): The matrix to print - `msg` (`str`): Optional message to print before displaying the matrix """ import math if msg is not None: print(msg) # Calculate the appropriate format width. width = 0 for row in matrix: for val in row: if val is DISALLOWED: val = DISALLOWED_PRINTVAL width = max(width, len(str(val))) # Make the format string format = ('%%%d' % width) # Print the matrix for row in matrix: sep = '[' for val in row: if val is DISALLOWED: val = DISALLOWED_PRINTVAL formatted = ((format + 's') % val) sys.stdout.write(sep + formatted) sep = ', ' sys.stdout.write(']\n') # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- if __name__ == '__main__': matrices = [ # Square ([[400, 150, 400], [400, 450, 600], [300, 225, 300]], 850), # expected cost # Rectangular variant ([[400, 150, 400, 1], [400, 450, 600, 2], [300, 225, 300, 3]], 452), # expected cost # Square ([[10, 10, 8], [9, 8, 1], [9, 7, 4]], 18), # Square variant with floating point value ([[10.1, 10.2, 8.3], [9.4, 8.5, 1.6], [9.7, 7.8, 4.9]], 19.5), # Rectangular variant ([[10, 10, 8, 11], [9, 8, 1, 1], [9, 7, 4, 10]], 15), # Rectangular variant with floating point value ([[10.01, 10.02, 8.03, 11.04], [9.05, 8.06, 1.07, 1.08], [9.09, 7.1, 4.11, 10.12]], 15.2), # Rectangular with DISALLOWED ([[4, 5, 6, DISALLOWED], [1, 9, 12, 11], [DISALLOWED, 5, 4, DISALLOWED], [12, 12, 12, 10]], 20), # Rectangular variant with DISALLOWED and floating point value ([[4.001, 5.002, 6.003, DISALLOWED], [1.004, 9.005, 12.006, 11.007], [DISALLOWED, 5.008, 4.009, DISALLOWED], [12.01, 12.011, 12.012, 10.013]], 20.028), # DISALLOWED to force pairings ([[1, DISALLOWED, DISALLOWED, DISALLOWED], [DISALLOWED, 2, DISALLOWED, DISALLOWED], [DISALLOWED, DISALLOWED, 3, DISALLOWED], [DISALLOWED, DISALLOWED, DISALLOWED, 4]], 10), # DISALLOWED to force pairings with floating point value ([[1.1, DISALLOWED, DISALLOWED, DISALLOWED], [DISALLOWED, 2.2, DISALLOWED, DISALLOWED], [DISALLOWED, DISALLOWED, 3.3, DISALLOWED], [DISALLOWED, DISALLOWED, DISALLOWED, 4.4]], 11.0)] m = Munkres() for cost_matrix, expected_total in matrices: print_matrix(cost_matrix, msg='cost matrix') indexes = m.compute(cost_matrix) total_cost = 0 for r, c in indexes: x = cost_matrix[r][c] total_cost += x print(('(%d, %d) -> %s' % (r, c, x))) print(('lowest cost=%s' % total_cost)) assert expected_total == total_cost ././@PaxHeader0000000000000000000000000000003200000000000011450 xustar000000000000000026 mtime=1600182719.08913 munkres-1.1.4/setup.cfg0000644000076500000240000000013400000000000014705 0ustar00bmcstaff00000000000000[sdist] formats = gztar [bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600181427.0 munkres-1.1.4/setup.py0000644000076500000240000000612200000000000014601 0ustar00bmcstaff00000000000000#!/usr/bin/env python # # Distutils setup script for Munkres # --------------------------------------------------------------------------- from setuptools import setup import re import os import sys from distutils.cmd import Command from abc import abstractmethod if sys.version_info[0:2] < (3, 5): columns = int(os.environ.get('COLUMNS', '80')) - 1 msg = ('As of version 1.1.0, this munkres package no longer supports ' + 'Python 2. Either upgrade to Python 3.5 or better, or use an ' + 'older version of munkres (e.g., 1.0.12).') sys.stderr.write(msg + '\n') raise Exception(msg) # Load the module. here = os.path.dirname(os.path.abspath(sys.argv[0])) def import_from_file(file, name): # See https://stackoverflow.com/a/19011259/53495 import importlib.machinery import importlib.util loader = importlib.machinery.SourceFileLoader(name, file) spec = importlib.util.spec_from_loader(loader.name, loader) mod = importlib.util.module_from_spec(spec) loader.exec_module(mod) return mod mf = os.path.join(here, 'munkres.py') munkres = import_from_file(mf, 'munkres') long_description = munkres.__doc__ version = str(munkres.__version__) (author, email) = re.match('^(.*),\s*(.*)$', munkres.__author__).groups() url = munkres.__url__ license = munkres.__license__ API_DOCS_BUILD = 'apidocs' class CommandHelper(Command): user_options = [] def __init__(self, dist): Command.__init__(self, dist) def initialize_options(self): pass def finalize_options(self): pass @abstractmethod def run(self): pass class Doc(CommandHelper): description = 'create the API docs' def run(self): os.environ['PYTHONPATH'] = '.' cmd = 'pdoc --html --html-dir {} --overwrite --html-no-source munkres'.format( API_DOCS_BUILD ) print('+ {}'.format(cmd)) rc = os.system(cmd) if rc != 0: raise Exception("Failed to run pdoc. rc={}".format(rc)) class Test(CommandHelper): def run(self): import pytest os.environ['PYTHONPATH'] = '.' rc = pytest.main(['-W', 'ignore', '-ra', '--cache-clear', 'test', '.']) if rc != 0: raise Exception('*** Tests failed.') # Run setup setup( name="munkres", version=version, description="Munkres (Hungarian) algorithm for the Assignment Problem", long_description=long_description, long_description_content_type='text/markdown', url=url, license=license, author=author, author_email=email, py_modules=["munkres"], cmdclass = { 'doc': Doc, 'docs': Doc, 'apidoc': Doc, 'apidocs': Doc, 'test': Test }, classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) ././@PaxHeader0000000000000000000000000000003300000000000011451 xustar000000000000000027 mtime=1600182719.086403 munkres-1.1.4/test/0000755000076500000240000000000000000000000014045 5ustar00bmcstaff00000000000000././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600181242.0 munkres-1.1.4/test/README.md0000644000076500000240000000022400000000000015322 0ustar00bmcstaff00000000000000The tests in this directory are intended to be run via [pytest][]. ``` pip install pytest python -m pytest ``` [pytest]: https://docs.pytest.org/ ././@PaxHeader0000000000000000000000000000002600000000000011453 xustar000000000000000022 mtime=1600182219.0 munkres-1.1.4/test/test_munkres.py0000644000076500000240000002662400000000000017154 0ustar00bmcstaff00000000000000from munkres import Munkres, DISALLOWED, UnsolvableMatrix import munkres import pytest m = Munkres() def _get_cost(matrix): indices = m.compute(matrix) return sum([matrix[row][column] for row, column in indices]) def test_documented_example(): ''' Test the matrix in the documented example. ''' matrix = [[5, 9, 1], [10, 3, 2], [8, 7, 4]] cost = _get_cost(matrix) assert cost == 12 def float_example(): ''' Test a matrix with float values ''' matrix = [[5.1, 9.2, 1.3], [10.4, 3.5, 2.6], [8.7, 7.8, 4.9]] cost = _get_cost(matrix) assert_almost_equal(cost, 13.5) def test_5_x_5(): matrix = [[12, 9, 27, 10, 23], [7, 13, 13, 30, 19], [25, 18, 26, 11, 26], [9, 28, 26, 23, 13], [16, 16, 24, 6, 9]] cost = _get_cost(matrix) assert cost == 51 def test_5_x_5_float(): matrix = [[12.01, 9.02, 27.03, 10.04, 23.05], [7.06, 13.07, 13.08, 30.09, 19.1], [25.11, 18.12, 26.13, 11.14, 26.15], [9.16, 28.17, 26.18, 23.19, 13.2], [16.21, 16.22, 24.23, 6.24, 9.25]] cost = _get_cost(matrix) assert cost == pytest.approx(51.65) def test_10_x_10(): matrix = [[37, 34, 29, 26, 19, 8, 9, 23, 19, 29], [9, 28, 20, 8, 18, 20, 14, 33, 23, 14], [15, 26, 12, 28, 6, 17, 9, 13, 21, 7], [2, 8, 38, 36, 39, 5, 36, 2, 38, 27], [30, 3, 33, 16, 21, 39, 7, 23, 28, 36], [7, 5, 19, 22, 36, 36, 24, 19, 30, 2], [34, 20, 13, 36, 12, 33, 9, 10, 23, 5], [7, 37, 22, 39, 33, 39, 10, 3, 13, 26], [21, 25, 23, 39, 31, 37, 32, 33, 38, 1], [17, 34, 40, 10, 29, 37, 40, 3, 25, 3]] cost = _get_cost(matrix) assert cost == 66 def test_10_x_10_float(): matrix = [[37.001, 34.002, 29.003, 26.004, 19.005, 8.006, 9.007, 23.008, 19.009, 29.01], [9.011, 28.012, 20.013, 8.014, 18.015, 20.016, 14.017, 33.018, 23.019, 14.02], [15.021, 26.022, 12.023, 28.024, 6.025, 17.026, 9.027, 13.028, 21.029, 7.03], [2.031, 8.032, 38.033, 36.034, 39.035, 5.036, 36.037, 2.038, 38.039, 27.04], [30.041, 3.042, 33.043, 16.044, 21.045, 39.046, 7.047, 23.048, 28.049, 36.05], [7.051, 5.052, 19.053, 22.054, 36.055, 36.056, 24.057, 19.058, 30.059, 2.06], [34.061, 20.062, 13.063, 36.064, 12.065, 33.066, 9.067, 10.068, 23.069, 5.07], [7.071, 37.072, 22.073, 39.074, 33.075, 39.076, 10.077, 3.078, 13.079, 26.08], [21.081, 25.082, 23.083, 39.084, 31.085, 37.086, 32.087, 33.088, 38.089, 1.09], [17.091, 34.092, 40.093, 10.094, 29.095, 37.096, 40.097, 3.098, 25.099, 3.1]] cost = _get_cost(matrix) assert cost == pytest.approx(66.505) def test_20_x_20(): matrix = [[5, 4, 3, 9, 8, 9, 3, 5, 6, 9, 4, 10, 3, 5, 6, 6, 1, 8, 10, 2], [10, 9, 9, 2, 8, 3, 9, 9, 10, 1, 7, 10, 8, 4, 2, 1, 4, 8, 4, 8], [10, 4, 4, 3, 1, 3, 5, 10, 6, 8, 6, 8, 4, 10, 7, 2, 4, 5, 1, 8], [2, 1, 4, 2, 3, 9, 3, 4, 7, 3, 4, 1, 3, 2, 9, 8, 6, 5, 7, 8], [3, 4, 4, 1, 4, 10, 1, 2, 6, 4, 5, 10, 2, 2, 3, 9, 10, 9, 9, 10], [1, 10, 1, 8, 1, 3, 1, 7, 1, 1, 2, 1, 2, 6, 3, 3, 4, 4, 8, 6], [1, 8, 7, 10, 10, 3, 4, 6, 1, 6, 6, 4, 9, 6, 9, 6, 4, 5, 4, 7], [8, 10, 3, 9, 4, 9, 3, 3, 4, 6, 4, 2, 6, 7, 7, 4, 4, 3, 4, 7], [1, 3, 8, 2, 6, 9, 2, 7, 4, 8, 10, 8, 10, 5, 1, 3, 10, 10, 2, 9], [2, 4, 1, 9, 2, 9, 7, 8, 2, 1, 4, 10, 5, 2, 7, 6, 5, 7, 2, 6], [4, 5, 1, 4, 2, 3, 3, 4, 1, 8, 8, 2, 6, 9, 5, 9, 6, 3, 9, 3], [3, 1, 1, 8, 6, 8, 8, 7, 9, 3, 2, 1, 8, 2, 4, 7, 3, 1, 2, 4], [5, 9, 8, 6, 10, 4, 10, 3, 4, 10, 10, 10, 1, 7, 8, 8, 7, 7, 8, 8], [1, 4, 6, 1, 6, 1, 2, 10, 5, 10, 2, 6, 2, 4, 5, 5, 3, 5, 1, 5], [5, 6, 9, 10, 6, 6, 10, 6, 4, 1, 5, 3, 9, 5, 2, 10, 9, 9, 5, 1], [10, 9, 4, 6, 9, 5, 3, 7, 10, 1, 6, 8, 1, 1, 10, 9, 5, 7, 7, 5], [2, 6, 6, 6, 6, 2, 9, 4, 7, 5, 3, 2, 10, 3, 4, 5, 10, 9, 1, 7], [5, 2, 4, 9, 8, 4, 8, 2, 4, 1, 3, 7, 6, 8, 1, 6, 8, 8, 10, 10], [9, 6, 3, 1, 8, 5, 7, 8, 7, 2, 1, 8, 2, 8, 3, 7, 4, 8, 7, 7], [8, 4, 4, 9, 7, 10, 6, 2, 1, 5, 8, 5, 1, 1, 1, 9, 1, 3, 5, 3]] cost = _get_cost(matrix) assert cost == 22 def test_20_x_20_float(): matrix = [[5.0001, 4.0002, 3.0003, 9.0004, 8.0005, 9.0006, 3.0007, 5.0008, 6.0009, 9.001, 4.0011, 10.0012, 3.0013, 5.0014, 6.0015, 6.0016, 1.0017, 8.0018, 10.0019, 2.002], [10.0021, 9.0022, 9.0023, 2.0024, 8.0025, 3.0026, 9.0027, 9.0028, 10.0029, 1.003, 7.0031, 10.0032, 8.0033, 4.0034, 2.0035, 1.0036, 4.0037, 8.0038, 4.0039, 8.004], [10.0041, 4.0042, 4.0043, 3.0044, 1.0045, 3.0046, 5.0047, 10.0048, 6.0049, 8.005, 6.0051, 8.0052, 4.0053, 10.0054, 7.0055, 2.0056, 4.0057, 5.0058, 1.0059, 8.006], [2.0061, 1.0062, 4.0063, 2.0064, 3.0065, 9.0066, 3.0067, 4.0068, 7.0069, 3.007, 4.0071, 1.0072, 3.0073, 2.0074, 9.0075, 8.0076, 6.0077, 5.0078, 7.0079, 8.008], [3.0081, 4.0082, 4.0083, 1.0084, 4.0085, 10.0086, 1.0087, 2.0088, 6.0089, 4.009, 5.0091, 10.0092, 2.0093, 2.0094, 3.0095, 9.0096, 10.0097, 9.0098, 9.0099, 10.01], [1.0101, 10.0102, 1.0103, 8.0104, 1.0105, 3.0106, 1.0107, 7.0108, 1.0109, 1.011, 2.0111, 1.0112, 2.0113, 6.0114, 3.0115, 3.0116, 4.0117, 4.0118, 8.0119, 6.012], [1.0121, 8.0122, 7.0123, 10.0124, 10.0125, 3.0126, 4.0127, 6.0128, 1.0129, 6.013, 6.0131, 4.0132, 9.0133, 6.0134, 9.0135, 6.0136, 4.0137, 5.0138, 4.0139, 7.014], [8.0141, 10.0142, 3.0143, 9.0144, 4.0145, 9.0146, 3.0147, 3.0148, 4.0149, 6.015, 4.0151, 2.0152, 6.0153, 7.0154, 7.0155, 4.0156, 4.0157, 3.0158, 4.0159, 7.016], [1.0161, 3.0162, 8.0163, 2.0164, 6.0165, 9.0166, 2.0167, 7.0168, 4.0169, 8.017, 10.0171, 8.0172, 10.0173, 5.0174, 1.0175, 3.0176, 10.0177, 10.0178, 2.0179, 9.018], [2.0181, 4.0182, 1.0183, 9.0184, 2.0185, 9.0186, 7.0187, 8.0188, 2.0189, 1.019, 4.0191, 10.0192, 5.0193, 2.0194, 7.0195, 6.0196, 5.0197, 7.0198, 2.0199, 6.02], [4.0201, 5.0202, 1.0203, 4.0204, 2.0205, 3.0206, 3.0207, 4.0208, 1.0209, 8.021, 8.0211, 2.0212, 6.0213, 9.0214, 5.0215, 9.0216, 6.0217, 3.0218, 9.0219, 3.022], [3.0221, 1.0222, 1.0223, 8.0224, 6.0225, 8.0226, 8.0227, 7.0228, 9.0229, 3.023, 2.0231, 1.0232, 8.0233, 2.0234, 4.0235, 7.0236, 3.0237, 1.0238, 2.0239, 4.024], [5.0241, 9.0242, 8.0243, 6.0244, 10.0245, 4.0246, 10.0247, 3.0248, 4.0249, 10.025, 10.0251, 10.0252, 1.0253, 7.0254, 8.0255, 8.0256, 7.0257, 7.0258, 8.0259, 8.026], [1.0261, 4.0262, 6.0263, 1.0264, 6.0265, 1.0266, 2.0267, 10.0268, 5.0269, 10.027, 2.0271, 6.0272, 2.0273, 4.0274, 5.0275, 5.0276, 3.0277, 5.0278, 1.0279, 5.028], [5.0281, 6.0282, 9.0283, 10.0284, 6.0285, 6.0286, 10.0287, 6.0288, 4.0289, 1.029, 5.0291, 3.0292, 9.0293, 5.0294, 2.0295, 10.0296, 9.0297, 9.0298, 5.0299, 1.03], [10.0301, 9.0302, 4.0303, 6.0304, 9.0305, 5.0306, 3.0307, 7.0308, 10.0309, 1.031, 6.0311, 8, 1.0312, 1.0313, 10.0314, 9.0315, 5.0316, 7.0317, 7.0318, 5.0319, 1.032], [2.0321, 6.0322, 6.0323, 6.0324, 6.0325, 2.0326, 9.0327, 4.0328, 7.0329, 5.033, 3.0331, 2.0332, 10.0333, 3.0334, 4.0335, 5.0336, 10.0337, 9.0338, 1.0339, 7.034], [5.0341, 2.0342, 4.0343, 9.0344, 8.0345, 4.0346, 8.0347, 2.0348, 4.0349, 1.035, 3.0351, 7.0352, 6.0353, 8.0354, 1.0355, 6.0356, 8.0357, 8.0358, 10.0359, 10.036], [9.0361, 6.0362, 3.0363, 1.0364, 8.0365, 5.0366, 7.0367, 8.0368, 7.0369, 2.037, 1.0371, 8.0372, 2.0373, 8.0374, 3.0375, 7.0376, 4.0377, 8.0378, 7.0379, 7.038], [8.0381, 4.0382, 4.0383, 9.0384, 7.0385, 10.0386, 6.0387, 2.0388, 1.0389, 5.039, 8.0391, 5.0392, 1.0393, 1.0394, 1.0395, 9.0396, 1.0397, 3.0398, 5.0399, 3.04]] cost = _get_cost(matrix) ''' Here, it becomes mandatory to set "places" argument, otherwise test might fails. It happens because float values in this example have more number of digits after decimal point than other float examples. ''' assert cost == pytest.approx(20.362, rel=1e-3) def test_disallowed(): matrix = [[5, 9, DISALLOWED], [10, DISALLOWED, 2], [8, DISALLOWED, 4]] cost = _get_cost(matrix) assert cost == 19 def test_disallowed_float(): matrix = [[5.1, 9.2, DISALLOWED], [10.3, DISALLOWED, 2.4], [8.5, DISALLOWED, 4.6]] cost = _get_cost(matrix) assert cost == pytest.approx(20.1) def test_profit(): profit_matrix = [[94, 66, 100, 18, 48], [51, 63, 97, 79, 11], [37, 53, 57, 78, 28], [59, 43, 97, 88, 48], [52, 19, 89, 60, 60]] import sys cost_matrix = munkres.make_cost_matrix( profit_matrix, lambda cost: sys.maxsize - cost ) indices = m.compute(cost_matrix) profit = sum([profit_matrix[row][column] for row, column in indices]) assert profit == 392 def test_profit_float(): profit_matrix = [[94.01, 66.02, 100.03, 18.04, 48.05], [51.06, 63.07, 97.08, 79.09, 11.1], [37.11, 53.12, 57.13, 78.14, 28.15], [59.16, 43.17, 97.18, 88.19, 48.2], [52.21, 19.22, 89.23, 60.24, 60.25]] import sys cost_matrix = munkres.make_cost_matrix( profit_matrix, lambda cost: sys.maxsize - cost ) indices = m.compute(cost_matrix) profit = sum([profit_matrix[row][column] for row, column in indices]) assert profit == pytest.approx(362.65) def test_irregular(): matrix = [[12, 26, 17], [49, 43, 36, 10, 5], [97, 9, 66, 34], [52, 42, 19, 36], [15, 93, 55, 80]] cost = _get_cost(matrix) assert cost == 43 def test_irregular_float(): matrix = [[12.01, 26.02, 17.03], [49.04, 43.05, 36.06, 10.07, 5.08], [97.09, 9.1, 66.11, 34.12], [52.13, 42.14, 19.15, 36.16], [15.17, 93.18, 55.19, 80.2]] cost = _get_cost(matrix) assert cost == pytest.approx(43.42) def test_rectangular(): matrix = [[34, 26, 17, 12], [43, 43, 36, 10], [97, 47, 66, 34], [52, 42, 19, 36], [15, 93, 55, 80]] padded_matrix = m.pad_matrix(matrix, 0) padded_cost = _get_cost(padded_matrix) cost = _get_cost(matrix) assert padded_cost == cost assert cost == 70 def test_rectangular_float(): matrix = [[34.01, 26.02, 17.03, 12.04], [43.05, 43.06, 36.07, 10.08], [97.09, 47.1, 66.11, 34.12], [52.13, 42.14, 19.15, 36.16], [15.17, 93.18, 55.19, 80.2]] padded_matrix = m.pad_matrix(matrix, 0) padded_cost = _get_cost(padded_matrix) cost = _get_cost(matrix) assert padded_cost == pytest.approx(cost) assert cost == pytest.approx(70.42) def test_unsolvable(): with pytest.raises(UnsolvableMatrix): matrix = [[5, 9, DISALLOWED], [10, DISALLOWED, 2], [DISALLOWED, DISALLOWED, DISALLOWED]] m.compute(matrix) def test_unsolvable_float(): with pytest.raises(UnsolvableMatrix): matrix = [[5.1, 9.2, DISALLOWED], [10.3, DISALLOWED, 2.4], [DISALLOWED, DISALLOWED, DISALLOWED]] m.compute(matrix)