Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement check to prevent infinite loop cases #43

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .bumpversion.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[bumpversion]
current_version = 1.2.0
commit = True
tag = True

[bumpversion:file:pyproject.toml]
45 changes: 45 additions & 0 deletions munkres.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ def compute(self, cost_matrix: Matrix) -> Sequence[Tuple[int, int]]:
A list of `(row, column)` tuples that describe the lowest cost path
through the matrix
"""
self.__check_unsolvability(cost_matrix)
self.C = self.pad_matrix(cost_matrix)
self.n = len(self.C)
self.original_length = len(cost_matrix)
Expand Down Expand Up @@ -181,6 +182,44 @@ def __make_matrix(self, n: int, val: AnyNum) -> Matrix:
matrix += [[val for j in range(n)]]
return matrix

def __transpose_matrix(self, matrix: Matrix):
return [list(row) for row in zip(*matrix)]

def __check_unsolvability(self, matrix: Matrix):
"""Checks additional conditions to see if an input Munkres cost matrix is unsolvable.

This check identifies potential infinite loop edge cases and raises a ``munkres.UnsolvableMatrix`` error.


Args:
matrix (Matrix): a Matrix object, representing a cost matrix (or a profit matrix) suitable
for Munkres optimization.

Raises:
munkres.UnsolvableMatrix: if the matrix is unsolvable.
"""

def _check_one_dimension_solvability(matrix):

non_disallowed_indices = [] # (in possibly-offending rows)

for row in matrix:

# check to see if all but 1 cell in the row are DISALLOWED

indices = [i for i, val in enumerate(row) if not isinstance(val, type(DISALLOWED))]

if len(indices) == 1:

if indices[0] in non_disallowed_indices:
raise UnsolvableMatrix(
"This matrix cannot be solved and will loop infinitely"
)

non_disallowed_indices.append(indices[0])

_check_one_dimension_solvability(matrix)

def __step1(self) -> int:
"""
For each row of the matrix, find the smallest element and
Expand Down Expand Up @@ -342,11 +381,17 @@ def __step6(self) -> int:
def __find_smallest(self) -> AnyNum:
"""Find the smallest uncovered value in the matrix."""
minval = sys.maxsize
uncovered_vals = []
for i in range(self.n):
for j in range(self.n):
if (not self.row_covered[i]) and (not self.col_covered[j]):
uncovered_vals.append(self.C[i][j])
if self.C[i][j] is not DISALLOWED and minval > self.C[i][j]:
minval = self.C[i][j]
if all(map(lambda val: type(val) is DISALLOWED_OBJ, uncovered_vals)):
raise UnsolvableMatrix(
"The only uncovered values are disallowed. This matrix will loop infinitely!"
)
return minval


Expand Down
23 changes: 23 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# pyproject.toml

[build-system]
requires = ["setuptools>=61.2.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "jk-munkres"
version = "1.2.0"
description = "A fork of munkres"
readme = "README.md"
authors = [{ name = "Jonathan Kerr" }]
license = { file = "LICENSE" }
classifiers = [
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
]
keywords = ["munkres", "assignment problem"]
requires-python = ">=3.9"

[project.optional-dependencies]
dev = ["black", "bumpver", "isort", "pip-tools", "pytest"]
5 changes: 0 additions & 5 deletions setup.cfg

This file was deleted.

112 changes: 0 additions & 112 deletions setup.py

This file was deleted.

25 changes: 20 additions & 5 deletions test/test_munkres.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,27 @@ def test_rectangular_float():
assert padded_cost == pytest.approx(cost)
assert cost == pytest.approx(70.42)

def test_unsolvable():
with pytest.raises(UnsolvableMatrix):
matrix = [[5, 9, DISALLOWED],

@pytest.mark.parametrize(
"unsolvable_matrix",
(
[
[5, 9, DISALLOWED],
[10, DISALLOWED, 2],
[DISALLOWED, DISALLOWED, DISALLOWED]]
m.compute(matrix)
[DISALLOWED, DISALLOWED, DISALLOWED]
],

[
[DISALLOWED, 161, DISALLOWED],
[DISALLOWED, 1, DISALLOWED],
[DISALLOWED, 157, DISALLOWED],
[37, DISALLOWED, 5]
]
)
)
def test_unsolvable(unsolvable_matrix):
with pytest.raises(UnsolvableMatrix):
m.compute(unsolvable_matrix)

def test_unsolvable_float():
with pytest.raises(UnsolvableMatrix):
Expand Down