test_milp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. """
  2. Unit test for Mixed Integer Linear Programming
  3. """
  4. import re
  5. import numpy as np
  6. from numpy.testing import assert_allclose, assert_array_equal
  7. import pytest
  8. from .test_linprog import magic_square
  9. from scipy.optimize import milp, Bounds, LinearConstraint
  10. def test_milp_iv():
  11. message = "`c` must be a one-dimensional array of finite numbers with"
  12. with pytest.raises(ValueError, match=message):
  13. milp(np.zeros((3, 4)))
  14. with pytest.raises(ValueError, match=message):
  15. milp([])
  16. with pytest.raises(ValueError, match=message):
  17. milp(None)
  18. message = "`bounds` must be convertible into an instance of..."
  19. with pytest.raises(ValueError, match=message):
  20. milp(1, bounds=10)
  21. message = "`constraints` (or each element within `constraints`) must be"
  22. with pytest.raises(ValueError, match=re.escape(message)):
  23. milp(1, constraints=10)
  24. with pytest.raises(ValueError, match=re.escape(message)):
  25. milp(np.zeros(3), constraints=([[1, 2, 3]], [2, 3], [2, 3]))
  26. message = "The shape of `A` must be (len(b_l), len(c))."
  27. with pytest.raises(ValueError, match=re.escape(message)):
  28. milp(np.zeros(3), constraints=([[1, 2]], [2], [2]))
  29. message = ("`integrality` must contain integers 0-3 and be broadcastable "
  30. "to `c.shape`.")
  31. with pytest.raises(ValueError, match=message):
  32. milp([1, 2, 3], integrality=[1, 2])
  33. with pytest.raises(ValueError, match=message):
  34. milp([1, 2, 3], integrality=[1, 5, 3])
  35. message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
  36. with pytest.raises(ValueError, match=message):
  37. milp([1, 2, 3], bounds=([1, 2], [3, 4, 5]))
  38. with pytest.raises(ValueError, match=message):
  39. milp([1, 2, 3], bounds=([1, 2, 3], [4, 5]))
  40. message = "`bounds.lb` and `bounds.ub` must contain reals and..."
  41. with pytest.raises(ValueError, match=message):
  42. milp([1, 2, 3], bounds=([1, 2], [3, 4]))
  43. with pytest.raises(ValueError, match=message):
  44. milp([1, 2, 3], bounds=([1, 2, 3], ["3+4", 4, 5]))
  45. with pytest.raises(ValueError, match=message):
  46. milp([1, 2, 3], bounds=([1, 2, 3], [set(), 4, 5]))
  47. @pytest.mark.xfail(run=False,
  48. reason="Needs to be fixed in `_highs_wrapper`")
  49. def test_milp_options(capsys):
  50. # run=False now because of gh-16347
  51. message = "Unrecognized options detected: {'ekki'}..."
  52. options = {'ekki': True}
  53. with pytest.warns(RuntimeWarning, match=message):
  54. milp(1, options=options)
  55. A, b, c, numbers, M = magic_square(3)
  56. options = {"disp": True, "presolve": False, "time_limit": 0.05}
  57. res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1,
  58. options=options)
  59. captured = capsys.readouterr()
  60. assert "Presolve is switched off" in captured.out
  61. assert "Time Limit Reached" in captured.out
  62. assert not res.success
  63. def test_result():
  64. A, b, c, numbers, M = magic_square(3)
  65. res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1)
  66. assert res.status == 0
  67. assert res.success
  68. msg = "Optimization terminated successfully. (HiGHS Status 7:"
  69. assert res.message.startswith(msg)
  70. assert isinstance(res.x, np.ndarray)
  71. assert isinstance(res.fun, float)
  72. assert isinstance(res.mip_node_count, int)
  73. assert isinstance(res.mip_dual_bound, float)
  74. assert isinstance(res.mip_gap, float)
  75. A, b, c, numbers, M = magic_square(6)
  76. res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1,
  77. options={'time_limit': 0.05})
  78. assert res.status == 1
  79. assert not res.success
  80. msg = "Time limit reached. (HiGHS Status 13:"
  81. assert res.message.startswith(msg)
  82. assert (res.fun is res.mip_dual_bound is res.mip_gap
  83. is res.mip_node_count is res.x is None)
  84. res = milp(1, bounds=(1, -1))
  85. assert res.status == 2
  86. assert not res.success
  87. msg = "The problem is infeasible. (HiGHS Status 8:"
  88. assert res.message.startswith(msg)
  89. assert (res.fun is res.mip_dual_bound is res.mip_gap
  90. is res.mip_node_count is res.x is None)
  91. res = milp(-1)
  92. assert res.status == 3
  93. assert not res.success
  94. msg = "The problem is unbounded. (HiGHS Status 10:"
  95. assert res.message.startswith(msg)
  96. assert (res.fun is res.mip_dual_bound is res.mip_gap
  97. is res.mip_node_count is res.x is None)
  98. def test_milp_optional_args():
  99. # check that arguments other than `c` are indeed optional
  100. res = milp(1)
  101. assert res.fun == 0
  102. assert_array_equal(res.x, [0])
  103. def test_milp_1():
  104. # solve magic square problem
  105. n = 3
  106. A, b, c, numbers, M = magic_square(n)
  107. res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1)
  108. # check that solution is a magic square
  109. x = np.round(res.x)
  110. s = (numbers.flatten() * x).reshape(n**2, n, n)
  111. square = np.sum(s, axis=0)
  112. np.testing.assert_allclose(square.sum(axis=0), M)
  113. np.testing.assert_allclose(square.sum(axis=1), M)
  114. np.testing.assert_allclose(np.diag(square).sum(), M)
  115. np.testing.assert_allclose(np.diag(square[:, ::-1]).sum(), M)
  116. def test_milp_2():
  117. # solve MIP with inequality constraints and all integer constraints
  118. # source: slide 5,
  119. # https://www.cs.upc.edu/~erodri/webpage/cps/theory/lp/milp/slides.pdf
  120. # also check that `milp` accepts all valid ways of specifying constraints
  121. c = -np.ones(2)
  122. A = [[-2, 2], [-8, 10]]
  123. b_l = [1, -np.inf]
  124. b_u = [np.inf, 13]
  125. linear_constraint = LinearConstraint(A, b_l, b_u)
  126. # solve original problem
  127. res1 = milp(c=c, constraints=(A, b_l, b_u), integrality=True)
  128. res2 = milp(c=c, constraints=linear_constraint, integrality=True)
  129. res3 = milp(c=c, constraints=[(A, b_l, b_u)], integrality=True)
  130. res4 = milp(c=c, constraints=[linear_constraint], integrality=True)
  131. res5 = milp(c=c, integrality=True,
  132. constraints=[(A[:1], b_l[:1], b_u[:1]),
  133. (A[1:], b_l[1:], b_u[1:])])
  134. res6 = milp(c=c, integrality=True,
  135. constraints=[LinearConstraint(A[:1], b_l[:1], b_u[:1]),
  136. LinearConstraint(A[1:], b_l[1:], b_u[1:])])
  137. res7 = milp(c=c, integrality=True,
  138. constraints=[(A[:1], b_l[:1], b_u[:1]),
  139. LinearConstraint(A[1:], b_l[1:], b_u[1:])])
  140. xs = np.array([res1.x, res2.x, res3.x, res4.x, res5.x, res6.x, res7.x])
  141. funs = np.array([res1.fun, res2.fun, res3.fun,
  142. res4.fun, res5.fun, res6.fun, res7.fun])
  143. np.testing.assert_allclose(xs, np.broadcast_to([1, 2], xs.shape))
  144. np.testing.assert_allclose(funs, -3)
  145. # solve relaxed problem
  146. res = milp(c=c, constraints=(A, b_l, b_u))
  147. np.testing.assert_allclose(res.x, [4, 4.5])
  148. np.testing.assert_allclose(res.fun, -8.5)
  149. def test_milp_3():
  150. # solve MIP with inequality constraints and all integer constraints
  151. # source: https://en.wikipedia.org/wiki/Integer_programming#Example
  152. c = [0, -1]
  153. A = [[-1, 1], [3, 2], [2, 3]]
  154. b_u = [1, 12, 12]
  155. b_l = np.full_like(b_u, -np.inf, dtype=np.float64)
  156. constraints = LinearConstraint(A, b_l, b_u)
  157. integrality = np.ones_like(c)
  158. # solve original problem
  159. res = milp(c=c, constraints=constraints, integrality=integrality)
  160. assert_allclose(res.fun, -2)
  161. # two optimal solutions possible, just need one of them
  162. assert np.allclose(res.x, [1, 2]) or np.allclose(res.x, [2, 2])
  163. # solve relaxed problem
  164. res = milp(c=c, constraints=constraints)
  165. assert_allclose(res.fun, -2.8)
  166. assert_allclose(res.x, [1.8, 2.8])
  167. def test_milp_4():
  168. # solve MIP with inequality constraints and only one integer constraint
  169. # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
  170. c = [8, 1]
  171. integrality = [0, 1]
  172. A = [[1, 2], [-4, -1], [2, 1]]
  173. b_l = [-14, -np.inf, -np.inf]
  174. b_u = [np.inf, -33, 20]
  175. constraints = LinearConstraint(A, b_l, b_u)
  176. bounds = Bounds(-np.inf, np.inf)
  177. res = milp(c, integrality=integrality, bounds=bounds,
  178. constraints=constraints)
  179. assert_allclose(res.fun, 59)
  180. assert_allclose(res.x, [6.5, 7])
  181. def test_milp_5():
  182. # solve MIP with inequality and equality constraints
  183. # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
  184. c = [-3, -2, -1]
  185. integrality = [0, 0, 1]
  186. lb = [0, 0, 0]
  187. ub = [np.inf, np.inf, 1]
  188. bounds = Bounds(lb, ub)
  189. A = [[1, 1, 1], [4, 2, 1]]
  190. b_l = [-np.inf, 12]
  191. b_u = [7, 12]
  192. constraints = LinearConstraint(A, b_l, b_u)
  193. res = milp(c, integrality=integrality, bounds=bounds,
  194. constraints=constraints)
  195. # there are multiple solutions
  196. assert_allclose(res.fun, -12)
  197. @pytest.mark.slow
  198. @pytest.mark.timeout(120) # prerelease_deps_coverage_64bit_blas job
  199. def test_milp_6():
  200. # solve a larger MIP with only equality constraints
  201. # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
  202. integrality = 1
  203. A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
  204. [39, 16, 22, 28, 26, 30, 23, 24],
  205. [18, 14, 29, 27, 30, 38, 26, 26],
  206. [41, 26, 28, 36, 18, 38, 16, 26]])
  207. b_eq = np.array([7872, 10466, 11322, 12058])
  208. c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
  209. res = milp(c=c, constraints=(A_eq, b_eq, b_eq), integrality=integrality)
  210. np.testing.assert_allclose(res.fun, 1854)
  211. def test_infeasible_prob_16609():
  212. # Ensure presolve does not mark trivially infeasible problems
  213. # as Optimal -- see gh-16609
  214. c = [1.0, 0.0]
  215. integrality = [0, 1]
  216. lb = [0, -np.inf]
  217. ub = [np.inf, np.inf]
  218. bounds = Bounds(lb, ub)
  219. A_eq = [[0.0, 1.0]]
  220. b_eq = [0.5]
  221. constraints = LinearConstraint(A_eq, b_eq, b_eq)
  222. res = milp(c, integrality=integrality, bounds=bounds,
  223. constraints=constraints)
  224. np.testing.assert_equal(res.status, 2)
  225. _msg_time = "Time limit reached. (HiGHS Status 13:"
  226. _msg_iter = "Iteration limit reached. (HiGHS Status 14:"
  227. @pytest.mark.skipif(np.intp(0).itemsize < 8,
  228. reason="Unhandled 32-bit GCC FP bug")
  229. @pytest.mark.slow
  230. @pytest.mark.timeout(360)
  231. @pytest.mark.parametrize(["options", "msg"], [({"time_limit": 10}, _msg_time),
  232. ({"node_limit": 1}, _msg_iter)])
  233. def test_milp_timeout_16545(options, msg):
  234. # Ensure solution is not thrown away if MILP solver times out
  235. # -- see gh-16545
  236. rng = np.random.default_rng(5123833489170494244)
  237. A = rng.integers(0, 5, size=(100, 100))
  238. b_lb = np.full(100, fill_value=-np.inf)
  239. b_ub = np.full(100, fill_value=25)
  240. constraints = LinearConstraint(A, b_lb, b_ub)
  241. variable_lb = np.zeros(100)
  242. variable_ub = np.ones(100)
  243. variable_bounds = Bounds(variable_lb, variable_ub)
  244. integrality = np.ones(100)
  245. c_vector = -np.ones(100)
  246. res = milp(
  247. c_vector,
  248. integrality=integrality,
  249. bounds=variable_bounds,
  250. constraints=constraints,
  251. options=options,
  252. )
  253. assert res.message.startswith(msg)
  254. assert res["x"] is not None
  255. # ensure solution is feasible
  256. x = res["x"]
  257. tol = 1e-8 # sometimes needed due to finite numerical precision
  258. assert np.all(b_lb - tol <= A @ x) and np.all(A @ x <= b_ub + tol)
  259. assert np.all(variable_lb - tol <= x) and np.all(x <= variable_ub + tol)
  260. assert np.allclose(x, np.round(x))
  261. def test_three_constraints_16878():
  262. # `milp` failed when exactly three constraints were passed
  263. # Ensure that this is no longer the case.
  264. rng = np.random.default_rng(5123833489170494244)
  265. A = rng.integers(0, 5, size=(6, 6))
  266. bl = np.full(6, fill_value=-np.inf)
  267. bu = np.full(6, fill_value=10)
  268. constraints = [LinearConstraint(A[:2], bl[:2], bu[:2]),
  269. LinearConstraint(A[2:4], bl[2:4], bu[2:4]),
  270. LinearConstraint(A[4:], bl[4:], bu[4:])]
  271. constraints2 = [(A[:2], bl[:2], bu[:2]),
  272. (A[2:4], bl[2:4], bu[2:4]),
  273. (A[4:], bl[4:], bu[4:])]
  274. lb = np.zeros(6)
  275. ub = np.ones(6)
  276. variable_bounds = Bounds(lb, ub)
  277. c = -np.ones(6)
  278. res1 = milp(c, bounds=variable_bounds, constraints=constraints)
  279. res2 = milp(c, bounds=variable_bounds, constraints=constraints2)
  280. ref = milp(c, bounds=variable_bounds, constraints=(A, bl, bu))
  281. assert res1.success and res2.success
  282. assert_allclose(res1.x, ref.x)
  283. assert_allclose(res2.x, ref.x)
  284. @pytest.mark.xslow
  285. def test_mip_rel_gap_passdown():
  286. # Solve problem with decreasing mip_gap to make sure mip_rel_gap decreases
  287. # Adapted from test_linprog::TestLinprogHiGHSMIP::test_mip_rel_gap_passdown
  288. # MIP taken from test_mip_6 above
  289. A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
  290. [39, 16, 22, 28, 26, 30, 23, 24],
  291. [18, 14, 29, 27, 30, 38, 26, 26],
  292. [41, 26, 28, 36, 18, 38, 16, 26]])
  293. b_eq = np.array([7872, 10466, 11322, 12058])
  294. c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
  295. mip_rel_gaps = [0.25, 0.01, 0.001]
  296. sol_mip_gaps = []
  297. for mip_rel_gap in mip_rel_gaps:
  298. res = milp(c=c, bounds=(0, np.inf), constraints=(A_eq, b_eq, b_eq),
  299. integrality=True, options={"mip_rel_gap": mip_rel_gap})
  300. # assert that the solution actually has mip_gap lower than the
  301. # required mip_rel_gap supplied
  302. assert res.mip_gap <= mip_rel_gap
  303. # check that `res.mip_gap` is as defined in the documentation
  304. assert res.mip_gap == (res.fun - res.mip_dual_bound)/res.fun
  305. sol_mip_gaps.append(res.mip_gap)
  306. # make sure that the mip_rel_gap parameter is actually doing something
  307. # check that differences between solution gaps are declining
  308. # monotonically with the mip_rel_gap parameter.
  309. assert np.all(np.diff(sol_mip_gaps) < 0)