_linprog_rs.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. """Revised simplex method for linear programming
  2. The *revised simplex* method uses the method described in [1]_, except
  3. that a factorization [2]_ of the basis matrix, rather than its inverse,
  4. is efficiently maintained and used to solve the linear systems at each
  5. iteration of the algorithm.
  6. .. versionadded:: 1.3.0
  7. References
  8. ----------
  9. .. [1] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
  10. programming." Athena Scientific 1 (1997): 997.
  11. .. [2] Bartels, Richard H. "A stabilization of the simplex method."
  12. Journal in Numerische Mathematik 16.5 (1971): 414-434.
  13. """
  14. # Author: Matt Haberland
  15. import numpy as np
  16. from numpy.linalg import LinAlgError
  17. from scipy.linalg import solve
  18. from ._optimize import _check_unknown_options
  19. from ._bglu_dense import LU
  20. from ._bglu_dense import BGLU as BGLU
  21. from ._linprog_util import _postsolve
  22. from ._optimize import OptimizeResult
  23. def _phase_one(A, b, x0, callback, postsolve_args, maxiter, tol, disp,
  24. maxupdate, mast, pivot):
  25. """
  26. The purpose of phase one is to find an initial basic feasible solution
  27. (BFS) to the original problem.
  28. Generates an auxiliary problem with a trivial BFS and an objective that
  29. minimizes infeasibility of the original problem. Solves the auxiliary
  30. problem using the main simplex routine (phase two). This either yields
  31. a BFS to the original problem or determines that the original problem is
  32. infeasible. If feasible, phase one detects redundant rows in the original
  33. constraint matrix and removes them, then chooses additional indices as
  34. necessary to complete a basis/BFS for the original problem.
  35. """
  36. m, n = A.shape
  37. status = 0
  38. # generate auxiliary problem to get initial BFS
  39. A, b, c, basis, x, status = _generate_auxiliary_problem(A, b, x0, tol)
  40. if status == 6:
  41. residual = c.dot(x)
  42. iter_k = 0
  43. return x, basis, A, b, residual, status, iter_k
  44. # solve auxiliary problem
  45. phase_one_n = n
  46. iter_k = 0
  47. x, basis, status, iter_k = _phase_two(c, A, x, basis, callback,
  48. postsolve_args,
  49. maxiter, tol, disp,
  50. maxupdate, mast, pivot,
  51. iter_k, phase_one_n)
  52. # check for infeasibility
  53. residual = c.dot(x)
  54. if status == 0 and residual > tol:
  55. status = 2
  56. # drive artificial variables out of basis
  57. # TODO: test redundant row removal better
  58. # TODO: make solve more efficient with BGLU? This could take a while.
  59. keep_rows = np.ones(m, dtype=bool)
  60. for basis_column in basis[basis >= n]:
  61. B = A[:, basis]
  62. try:
  63. basis_finder = np.abs(solve(B, A)) # inefficient
  64. pertinent_row = np.argmax(basis_finder[:, basis_column])
  65. eligible_columns = np.ones(n, dtype=bool)
  66. eligible_columns[basis[basis < n]] = 0
  67. eligible_column_indices = np.where(eligible_columns)[0]
  68. index = np.argmax(basis_finder[:, :n]
  69. [pertinent_row, eligible_columns])
  70. new_basis_column = eligible_column_indices[index]
  71. if basis_finder[pertinent_row, new_basis_column] < tol:
  72. keep_rows[pertinent_row] = False
  73. else:
  74. basis[basis == basis_column] = new_basis_column
  75. except LinAlgError:
  76. status = 4
  77. # form solution to original problem
  78. A = A[keep_rows, :n]
  79. basis = basis[keep_rows]
  80. x = x[:n]
  81. m = A.shape[0]
  82. return x, basis, A, b, residual, status, iter_k
  83. def _get_more_basis_columns(A, basis):
  84. """
  85. Called when the auxiliary problem terminates with artificial columns in
  86. the basis, which must be removed and replaced with non-artificial
  87. columns. Finds additional columns that do not make the matrix singular.
  88. """
  89. m, n = A.shape
  90. # options for inclusion are those that aren't already in the basis
  91. a = np.arange(m+n)
  92. bl = np.zeros(len(a), dtype=bool)
  93. bl[basis] = 1
  94. options = a[~bl]
  95. options = options[options < n] # and they have to be non-artificial
  96. # form basis matrix
  97. B = np.zeros((m, m))
  98. B[:, 0:len(basis)] = A[:, basis]
  99. if (basis.size > 0 and
  100. np.linalg.matrix_rank(B[:, :len(basis)]) < len(basis)):
  101. raise Exception("Basis has dependent columns")
  102. rank = 0 # just enter the loop
  103. for i in range(n): # somewhat arbitrary, but we need another way out
  104. # permute the options, and take as many as needed
  105. new_basis = np.random.permutation(options)[:m-len(basis)]
  106. B[:, len(basis):] = A[:, new_basis] # update the basis matrix
  107. rank = np.linalg.matrix_rank(B) # check the rank
  108. if rank == m:
  109. break
  110. return np.concatenate((basis, new_basis))
  111. def _generate_auxiliary_problem(A, b, x0, tol):
  112. """
  113. Modifies original problem to create an auxiliary problem with a trivial
  114. initial basic feasible solution and an objective that minimizes
  115. infeasibility in the original problem.
  116. Conceptually, this is done by stacking an identity matrix on the right of
  117. the original constraint matrix, adding artificial variables to correspond
  118. with each of these new columns, and generating a cost vector that is all
  119. zeros except for ones corresponding with each of the new variables.
  120. A initial basic feasible solution is trivial: all variables are zero
  121. except for the artificial variables, which are set equal to the
  122. corresponding element of the right hand side `b`.
  123. Runnning the simplex method on this auxiliary problem drives all of the
  124. artificial variables - and thus the cost - to zero if the original problem
  125. is feasible. The original problem is declared infeasible otherwise.
  126. Much of the complexity below is to improve efficiency by using singleton
  127. columns in the original problem where possible, thus generating artificial
  128. variables only as necessary, and using an initial 'guess' basic feasible
  129. solution.
  130. """
  131. status = 0
  132. m, n = A.shape
  133. if x0 is not None:
  134. x = x0
  135. else:
  136. x = np.zeros(n)
  137. r = b - A@x # residual; this must be all zeros for feasibility
  138. A[r < 0] = -A[r < 0] # express problem with RHS positive for trivial BFS
  139. b[r < 0] = -b[r < 0] # to the auxiliary problem
  140. r[r < 0] *= -1
  141. # Rows which we will need to find a trivial way to zero.
  142. # This should just be the rows where there is a nonzero residual.
  143. # But then we would not necessarily have a column singleton in every row.
  144. # This makes it difficult to find an initial basis.
  145. if x0 is None:
  146. nonzero_constraints = np.arange(m)
  147. else:
  148. nonzero_constraints = np.where(r > tol)[0]
  149. # these are (at least some of) the initial basis columns
  150. basis = np.where(np.abs(x) > tol)[0]
  151. if len(nonzero_constraints) == 0 and len(basis) <= m: # already a BFS
  152. c = np.zeros(n)
  153. basis = _get_more_basis_columns(A, basis)
  154. return A, b, c, basis, x, status
  155. elif (len(nonzero_constraints) > m - len(basis) or
  156. np.any(x < 0)): # can't get trivial BFS
  157. c = np.zeros(n)
  158. status = 6
  159. return A, b, c, basis, x, status
  160. # chooses existing columns appropriate for inclusion in initial basis
  161. cols, rows = _select_singleton_columns(A, r)
  162. # find the rows we need to zero that we _can_ zero with column singletons
  163. i_tofix = np.isin(rows, nonzero_constraints)
  164. # these columns can't already be in the basis, though
  165. # we are going to add them to the basis and change the corresponding x val
  166. i_notinbasis = np.logical_not(np.isin(cols, basis))
  167. i_fix_without_aux = np.logical_and(i_tofix, i_notinbasis)
  168. rows = rows[i_fix_without_aux]
  169. cols = cols[i_fix_without_aux]
  170. # indices of the rows we can only zero with auxiliary variable
  171. # these rows will get a one in each auxiliary column
  172. arows = nonzero_constraints[np.logical_not(
  173. np.isin(nonzero_constraints, rows))]
  174. n_aux = len(arows)
  175. acols = n + np.arange(n_aux) # indices of auxiliary columns
  176. basis_ng = np.concatenate((cols, acols)) # basis columns not from guess
  177. basis_ng_rows = np.concatenate((rows, arows)) # rows we need to zero
  178. # add auxiliary singleton columns
  179. A = np.hstack((A, np.zeros((m, n_aux))))
  180. A[arows, acols] = 1
  181. # generate initial BFS
  182. x = np.concatenate((x, np.zeros(n_aux)))
  183. x[basis_ng] = r[basis_ng_rows]/A[basis_ng_rows, basis_ng]
  184. # generate costs to minimize infeasibility
  185. c = np.zeros(n_aux + n)
  186. c[acols] = 1
  187. # basis columns correspond with nonzeros in guess, those with column
  188. # singletons we used to zero remaining constraints, and any additional
  189. # columns to get a full set (m columns)
  190. basis = np.concatenate((basis, basis_ng))
  191. basis = _get_more_basis_columns(A, basis) # add columns as needed
  192. return A, b, c, basis, x, status
  193. def _select_singleton_columns(A, b):
  194. """
  195. Finds singleton columns for which the singleton entry is of the same sign
  196. as the right-hand side; these columns are eligible for inclusion in an
  197. initial basis. Determines the rows in which the singleton entries are
  198. located. For each of these rows, returns the indices of the one singleton
  199. column and its corresponding row.
  200. """
  201. # find indices of all singleton columns and corresponding row indicies
  202. column_indices = np.nonzero(np.sum(np.abs(A) != 0, axis=0) == 1)[0]
  203. columns = A[:, column_indices] # array of singleton columns
  204. row_indices = np.zeros(len(column_indices), dtype=int)
  205. nonzero_rows, nonzero_columns = np.nonzero(columns)
  206. row_indices[nonzero_columns] = nonzero_rows # corresponding row indicies
  207. # keep only singletons with entries that have same sign as RHS
  208. # this is necessary because all elements of BFS must be non-negative
  209. same_sign = A[row_indices, column_indices]*b[row_indices] >= 0
  210. column_indices = column_indices[same_sign][::-1]
  211. row_indices = row_indices[same_sign][::-1]
  212. # Reversing the order so that steps below select rightmost columns
  213. # for initial basis, which will tend to be slack variables. (If the
  214. # guess corresponds with a basic feasible solution but a constraint
  215. # is not satisfied with the corresponding slack variable zero, the slack
  216. # variable must be basic.)
  217. # for each row, keep rightmost singleton column with an entry in that row
  218. unique_row_indices, first_columns = np.unique(row_indices,
  219. return_index=True)
  220. return column_indices[first_columns], unique_row_indices
  221. def _find_nonzero_rows(A, tol):
  222. """
  223. Returns logical array indicating the locations of rows with at least
  224. one nonzero element.
  225. """
  226. return np.any(np.abs(A) > tol, axis=1)
  227. def _select_enter_pivot(c_hat, bl, a, rule="bland", tol=1e-12):
  228. """
  229. Selects a pivot to enter the basis. Currently Bland's rule - the smallest
  230. index that has a negative reduced cost - is the default.
  231. """
  232. if rule.lower() == "mrc": # index with minimum reduced cost
  233. return a[~bl][np.argmin(c_hat)]
  234. else: # smallest index w/ negative reduced cost
  235. return a[~bl][c_hat < -tol][0]
  236. def _display_iter(phase, iteration, slack, con, fun):
  237. """
  238. Print indicators of optimization status to the console.
  239. """
  240. header = True if not iteration % 20 else False
  241. if header:
  242. print("Phase",
  243. "Iteration",
  244. "Minimum Slack ",
  245. "Constraint Residual",
  246. "Objective ")
  247. # :<X.Y left aligns Y digits in X digit spaces
  248. fmt = '{0:<6}{1:<10}{2:<20.13}{3:<20.13}{4:<20.13}'
  249. try:
  250. slack = np.min(slack)
  251. except ValueError:
  252. slack = "NA"
  253. print(fmt.format(phase, iteration, slack, np.linalg.norm(con), fun))
  254. def _display_and_callback(phase_one_n, x, postsolve_args, status,
  255. iteration, disp, callback):
  256. if phase_one_n is not None:
  257. phase = 1
  258. x_postsolve = x[:phase_one_n]
  259. else:
  260. phase = 2
  261. x_postsolve = x
  262. x_o, fun, slack, con = _postsolve(x_postsolve,
  263. postsolve_args)
  264. if callback is not None:
  265. res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
  266. 'con': con, 'nit': iteration,
  267. 'phase': phase, 'complete': False,
  268. 'status': status, 'message': "",
  269. 'success': False})
  270. callback(res)
  271. if disp:
  272. _display_iter(phase, iteration, slack, con, fun)
  273. def _phase_two(c, A, x, b, callback, postsolve_args, maxiter, tol, disp,
  274. maxupdate, mast, pivot, iteration=0, phase_one_n=None):
  275. """
  276. The heart of the simplex method. Beginning with a basic feasible solution,
  277. moves to adjacent basic feasible solutions successively lower reduced cost.
  278. Terminates when there are no basic feasible solutions with lower reduced
  279. cost or if the problem is determined to be unbounded.
  280. This implementation follows the revised simplex method based on LU
  281. decomposition. Rather than maintaining a tableau or an inverse of the
  282. basis matrix, we keep a factorization of the basis matrix that allows
  283. efficient solution of linear systems while avoiding stability issues
  284. associated with inverted matrices.
  285. """
  286. m, n = A.shape
  287. status = 0
  288. a = np.arange(n) # indices of columns of A
  289. ab = np.arange(m) # indices of columns of B
  290. if maxupdate:
  291. # basis matrix factorization object; similar to B = A[:, b]
  292. B = BGLU(A, b, maxupdate, mast)
  293. else:
  294. B = LU(A, b)
  295. for iteration in range(iteration, maxiter):
  296. if disp or callback is not None:
  297. _display_and_callback(phase_one_n, x, postsolve_args, status,
  298. iteration, disp, callback)
  299. bl = np.zeros(len(a), dtype=bool)
  300. bl[b] = 1
  301. xb = x[b] # basic variables
  302. cb = c[b] # basic costs
  303. try:
  304. v = B.solve(cb, transposed=True) # similar to v = solve(B.T, cb)
  305. except LinAlgError:
  306. status = 4
  307. break
  308. # TODO: cythonize?
  309. c_hat = c - v.dot(A) # reduced cost
  310. c_hat = c_hat[~bl]
  311. # Above is much faster than:
  312. # N = A[:, ~bl] # slow!
  313. # c_hat = c[~bl] - v.T.dot(N)
  314. # Can we perform the multiplication only on the nonbasic columns?
  315. if np.all(c_hat >= -tol): # all reduced costs positive -> terminate
  316. break
  317. j = _select_enter_pivot(c_hat, bl, a, rule=pivot, tol=tol)
  318. u = B.solve(A[:, j]) # similar to u = solve(B, A[:, j])
  319. i = u > tol # if none of the u are positive, unbounded
  320. if not np.any(i):
  321. status = 3
  322. break
  323. th = xb[i]/u[i]
  324. l = np.argmin(th) # implicitly selects smallest subscript
  325. th_star = th[l] # step size
  326. x[b] = x[b] - th_star*u # take step
  327. x[j] = th_star
  328. B.update(ab[i][l], j) # modify basis
  329. b = B.b # similar to b[ab[i][l]] =
  330. else:
  331. # If the end of the for loop is reached (without a break statement),
  332. # then another step has been taken, so the iteration counter should
  333. # increment, info should be displayed, and callback should be called.
  334. iteration += 1
  335. status = 1
  336. if disp or callback is not None:
  337. _display_and_callback(phase_one_n, x, postsolve_args, status,
  338. iteration, disp, callback)
  339. return x, b, status, iteration
  340. def _linprog_rs(c, c0, A, b, x0, callback, postsolve_args,
  341. maxiter=5000, tol=1e-12, disp=False,
  342. maxupdate=10, mast=False, pivot="mrc",
  343. **unknown_options):
  344. """
  345. Solve the following linear programming problem via a two-phase
  346. revised simplex algorithm.::
  347. minimize: c @ x
  348. subject to: A @ x == b
  349. 0 <= x < oo
  350. User-facing documentation is in _linprog_doc.py.
  351. Parameters
  352. ----------
  353. c : 1-D array
  354. Coefficients of the linear objective function to be minimized.
  355. c0 : float
  356. Constant term in objective function due to fixed (and eliminated)
  357. variables. (Currently unused.)
  358. A : 2-D array
  359. 2-D array which, when matrix-multiplied by ``x``, gives the values of
  360. the equality constraints at ``x``.
  361. b : 1-D array
  362. 1-D array of values representing the RHS of each equality constraint
  363. (row) in ``A_eq``.
  364. x0 : 1-D array, optional
  365. Starting values of the independent variables, which will be refined by
  366. the optimization algorithm. For the revised simplex method, these must
  367. correspond with a basic feasible solution.
  368. callback : callable, optional
  369. If a callback function is provided, it will be called within each
  370. iteration of the algorithm. The callback function must accept a single
  371. `scipy.optimize.OptimizeResult` consisting of the following fields:
  372. x : 1-D array
  373. Current solution vector.
  374. fun : float
  375. Current value of the objective function ``c @ x``.
  376. success : bool
  377. True only when an algorithm has completed successfully,
  378. so this is always False as the callback function is called
  379. only while the algorithm is still iterating.
  380. slack : 1-D array
  381. The values of the slack variables. Each slack variable
  382. corresponds to an inequality constraint. If the slack is zero,
  383. the corresponding constraint is active.
  384. con : 1-D array
  385. The (nominally zero) residuals of the equality constraints,
  386. that is, ``b - A_eq @ x``.
  387. phase : int
  388. The phase of the algorithm being executed.
  389. status : int
  390. For revised simplex, this is always 0 because if a different
  391. status is detected, the algorithm terminates.
  392. nit : int
  393. The number of iterations performed.
  394. message : str
  395. A string descriptor of the exit status of the optimization.
  396. postsolve_args : tuple
  397. Data needed by _postsolve to convert the solution to the standard-form
  398. problem into the solution to the original problem.
  399. Options
  400. -------
  401. maxiter : int
  402. The maximum number of iterations to perform in either phase.
  403. tol : float
  404. The tolerance which determines when a solution is "close enough" to
  405. zero in Phase 1 to be considered a basic feasible solution or close
  406. enough to positive to serve as an optimal solution.
  407. disp : bool
  408. Set to ``True`` if indicators of optimization status are to be printed
  409. to the console each iteration.
  410. maxupdate : int
  411. The maximum number of updates performed on the LU factorization.
  412. After this many updates is reached, the basis matrix is factorized
  413. from scratch.
  414. mast : bool
  415. Minimize Amortized Solve Time. If enabled, the average time to solve
  416. a linear system using the basis factorization is measured. Typically,
  417. the average solve time will decrease with each successive solve after
  418. initial factorization, as factorization takes much more time than the
  419. solve operation (and updates). Eventually, however, the updated
  420. factorization becomes sufficiently complex that the average solve time
  421. begins to increase. When this is detected, the basis is refactorized
  422. from scratch. Enable this option to maximize speed at the risk of
  423. nondeterministic behavior. Ignored if ``maxupdate`` is 0.
  424. pivot : "mrc" or "bland"
  425. Pivot rule: Minimum Reduced Cost (default) or Bland's rule. Choose
  426. Bland's rule if iteration limit is reached and cycling is suspected.
  427. unknown_options : dict
  428. Optional arguments not used by this particular solver. If
  429. `unknown_options` is non-empty a warning is issued listing all
  430. unused options.
  431. Returns
  432. -------
  433. x : 1-D array
  434. Solution vector.
  435. status : int
  436. An integer representing the exit status of the optimization::
  437. 0 : Optimization terminated successfully
  438. 1 : Iteration limit reached
  439. 2 : Problem appears to be infeasible
  440. 3 : Problem appears to be unbounded
  441. 4 : Numerical difficulties encountered
  442. 5 : No constraints; turn presolve on
  443. 6 : Guess x0 cannot be converted to a basic feasible solution
  444. message : str
  445. A string descriptor of the exit status of the optimization.
  446. iteration : int
  447. The number of iterations taken to solve the problem.
  448. """
  449. _check_unknown_options(unknown_options)
  450. messages = ["Optimization terminated successfully.",
  451. "Iteration limit reached.",
  452. "The problem appears infeasible, as the phase one auxiliary "
  453. "problem terminated successfully with a residual of {0:.1e}, "
  454. "greater than the tolerance {1} required for the solution to "
  455. "be considered feasible. Consider increasing the tolerance to "
  456. "be greater than {0:.1e}. If this tolerance is unnaceptably "
  457. "large, the problem is likely infeasible.",
  458. "The problem is unbounded, as the simplex algorithm found "
  459. "a basic feasible solution from which there is a direction "
  460. "with negative reduced cost in which all decision variables "
  461. "increase.",
  462. "Numerical difficulties encountered; consider trying "
  463. "method='interior-point'.",
  464. "Problems with no constraints are trivially solved; please "
  465. "turn presolve on.",
  466. "The guess x0 cannot be converted to a basic feasible "
  467. "solution. "
  468. ]
  469. if A.size == 0: # address test_unbounded_below_no_presolve_corrected
  470. return np.zeros(c.shape), 5, messages[5], 0
  471. x, basis, A, b, residual, status, iteration = (
  472. _phase_one(A, b, x0, callback, postsolve_args,
  473. maxiter, tol, disp, maxupdate, mast, pivot))
  474. if status == 0:
  475. x, basis, status, iteration = _phase_two(c, A, x, basis, callback,
  476. postsolve_args,
  477. maxiter, tol, disp,
  478. maxupdate, mast, pivot,
  479. iteration)
  480. return x, status, messages[status].format(residual, tol), iteration