cobyla.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. '''
  2. This module provides Powell's COBYLA algorithm.
  3. Translated from Zaikun Zhang's modern-Fortran reference implementation in PRIMA.
  4. Dedicated to late Professor M. J. D. Powell FRS (1936--2015).
  5. Python translation by Nickolai Belakovski.
  6. N.B.:
  7. 1. The modern-Fortran reference implementation in PRIMA contains bug fixes and improvements over the
  8. original Fortran 77 implementation by Powell. Consequently, the PRIMA implementation behaves differently
  9. from the original Fortran 77 implementation by Powell. Therefore, it is important to point out that
  10. you are using PRIMA rather than the original solvers if you want your results to be reproducible.
  11. 2. Compared to Powell's Fortran 77 implementation, the modern-Fortran implementation and hence any
  12. faithful translation like this one generally produce better solutions with fewer function evaluations,
  13. making them preferable for applications with expensive function evaluations. However, if function
  14. evaluations are not the dominant cost in your application, the Fortran 77 solvers are likely to be
  15. faster, as they are more efficient in terms of memory usage and flops thanks to the careful and
  16. ingenious (but unmaintained and unmaintainable) implementation by Powell.
  17. See the PRIMA documentation (www.libprima.net) for more information.
  18. '''
  19. from ..common.evaluate import evaluate, moderatex, moderatef, moderatec
  20. from ..common.consts import (EPS, RHOBEG_DEFAULT, RHOEND_DEFAULT, CTOL_DEFAULT,
  21. CWEIGHT_DEFAULT, FTARGET_DEFAULT, IPRINT_DEFAULT,
  22. MAXFUN_DIM_DEFAULT, DEBUGGING, BOUNDMAX,
  23. ETA1_DEFAULT, ETA2_DEFAULT, GAMMA1_DEFAULT,
  24. GAMMA2_DEFAULT)
  25. from ..common.preproc import preproc
  26. from ..common.present import present
  27. from ..common.linalg import matprod
  28. from .cobylb import cobylb
  29. import numpy as np
  30. from dataclasses import dataclass
  31. from copy import copy
  32. @dataclass
  33. class COBYLAResult:
  34. x: np.ndarray
  35. f: float
  36. constr: np.ndarray
  37. cstrv: float
  38. nf: int
  39. xhist: np.ndarray | None
  40. fhist: np.ndarray | None
  41. chist: np.ndarray | None
  42. conhist: np.ndarray | None
  43. info: int
  44. def cobyla(calcfc, m_nlcon, x, Aineq=None, bineq=None, Aeq=None, beq=None,
  45. xl=None, xu=None, f0=None, nlconstr0=None, rhobeg=None, rhoend=None,
  46. ftarget=FTARGET_DEFAULT, ctol=CTOL_DEFAULT, cweight=CWEIGHT_DEFAULT,
  47. maxfun=None, iprint=IPRINT_DEFAULT, eta1=None, eta2=None,
  48. gamma1=GAMMA1_DEFAULT, gamma2=GAMMA2_DEFAULT, maxhist=None, maxfilt=2000,
  49. callback=None):
  50. """
  51. Among all the arguments, only CALCFC, M_NLCON, and X are obligatory. The others are
  52. OPTIONAL and you can neglect them unless you are familiar with the algorithm. Any
  53. unspecified optional input will take the default value detailed below. For
  54. instance, we may invoke the solver as follows.
  55. # First define CALCFC, M_NLCON, and X, and then do the following.
  56. result = cobyla(calcfc, m_nlcon, x)
  57. or
  58. # First define CALCFC, M_NLCON, X, Aineq, and Bineq, and then do the following.
  59. result = cobyla(calcfc, m_nlcon, x, Aineq=Aineq, bineq=bineq, rhobeg=1.0e0,
  60. rhoend=1.0e-6)
  61. ####################################################################################
  62. # IMPORTANT NOTICE: The user must set M_NLCON correctly to the number of nonlinear
  63. # constraints, namely the size of NLCONSTR introduced below. Set it to 0 if there
  64. # is no nonlinear constraint.
  65. ####################################################################################
  66. See examples/cobyla/cobyla_example.py for a concrete example.
  67. A detailed introduction to the arguments is as follows.
  68. ####################################################################################
  69. # INPUTS
  70. ####################################################################################
  71. CALCFC
  72. Input, function.
  73. f, nlconstr = CALCFC(X) should evaluate the objective function and nonlinear
  74. constraints at the given vector X; it should return a tuple consisting of the
  75. objective function value and the nonlinear constraint value. It must be provided
  76. by the user, and its definition must conform to the following interface:
  77. #-------------------------------------------------------------------------#
  78. def calcfc(x):
  79. f = 0.0
  80. nlconstr = np.zeros(m_nlcon)
  81. return f, nlconstr
  82. #-------------------------------------------------------------------------#
  83. M_NLCON
  84. Input, scalar.
  85. M_NLCON must be set to the number of nonlinear constraints, namely the size of
  86. NLCONSTR(X).
  87. N.B.:
  88. 1. Why don't we define M_NLCON as optional and default it to 0 when it is absent?
  89. This is because we need to allocate memory for CONSTR_LOC using M_NLCON. To
  90. ensure that the size of CONSTR_LOC is correct, we require the user to specify
  91. M_NLCON explicitly.
  92. X
  93. Input, vector.
  94. As an input, X should be an N-dimensional vector that contains the starting
  95. point, N being the dimension of the problem.
  96. Aineq, Bineq
  97. Input, matrix of size [Mineq, N] and vector of size Mineq unless they are both
  98. empty, default: None and None.
  99. Aineq and Bineq represent the linear inequality constraints: Aineq*X <= Bineq.
  100. Aeq, Beq
  101. Input, matrix of size [Meq, N] and vector of size Meq unless they are both
  102. empty, default: None and None.
  103. Aeq and Beq represent the linear equality constraints: Aeq*X = Beq.
  104. XL, XU
  105. Input, vectors of size N unless they are both None, default: None and None.
  106. XL is the lower bound for X. If XL is None, X has no
  107. lower bound. Any entry of XL that is NaN or below -BOUNDMAX will be taken as
  108. -BOUNDMAX, which effectively means there is no lower bound for the corresponding
  109. entry of X. The value of BOUNDMAX is 0.25*HUGE(X), which is about 8.6E37 for
  110. single precision and 4.5E307 for double precision. XU is similar.
  111. F0
  112. Input, scalar.
  113. F0, if present, should be set to the objective function value of the starting X.
  114. NLCONSTR0
  115. Input, vector.
  116. NLCONSTR0, if present, should be set to the nonlinear constraint value at the
  117. starting X; in addition, SIZE(NLCONSTR0) must be M_NLCON, or the solver will
  118. abort.
  119. RHOBEG, RHOEND
  120. Inputs, scalars, default: RHOBEG = 1, RHOEND = 10^-6. RHOBEG and RHOEND must be
  121. set to the initial and final values of a trust-region radius, both being positive
  122. and RHOEND <= RHOBEG. Typically RHOBEG should be about one tenth of the greatest
  123. expected change to a variable, and RHOEND should indicate the accuracy that is
  124. required in the final values of the variables.
  125. FTARGET
  126. Input, scalar, default: -Inf.
  127. FTARGET is the target function value. The algorithm will terminate when a
  128. feasible point with a function value <= FTARGET is found.
  129. CTOL
  130. Input, scalar, default: sqrt(machine epsilon).
  131. CTOL is the tolerance of constraint violation. X is considered feasible if
  132. CSTRV(X) <= CTOL.
  133. N.B.:
  134. 1. CTOL is absolute, not relative.
  135. 2. CTOL is used only when selecting the returned X. It does not affect the
  136. iterations of the algorithm.
  137. CWEIGHT
  138. Input, scalar, default: CWEIGHT_DFT defined in common/consts.py.
  139. CWEIGHT is the weight that the constraint violation takes in the selection of the
  140. returned X.
  141. MAXFUN
  142. Input, integer scalar, default: MAXFUN_DIM_DFT*N with MAXFUN_DIM_DFT defined in
  143. common/consts.py. MAXFUN is the maximal number of calls of CALCFC.
  144. IPRINT
  145. Input, integer scalar, default: 0.
  146. The value of IPRINT should be set to 0, 1, -1, 2, -2, 3, or -3, which controls
  147. how much information will be printed during the computation:
  148. 0: there will be no printing;
  149. 1: a message will be printed to the screen at the return, showing the best vector
  150. of variables found and its objective function value;
  151. 2: in addition to 1, each new value of RHO is printed to the screen, with the
  152. best vector of variables so far and its objective function value; each new
  153. value of CPEN is also printed;
  154. 3: in addition to 2, each function evaluation with its variables will be printed
  155. to the screen; -1, -2, -3: the same information as 1, 2, 3 will be printed,
  156. not to the screen but to a file named COBYLA_output.txt; the file will be
  157. created if it does not exist; the new output will be appended to the end of
  158. this file if it already exists.
  159. Note that IPRINT = +/-3 can be costly in terms of time and/or space.
  160. ETA1, ETA2, GAMMA1, GAMMA2
  161. Input, scalars, default: ETA1 = 0.1, ETA2 = 0.7, GAMMA1 = 0.5, and GAMMA2 = 2.
  162. ETA1, ETA2, GAMMA1, and GAMMA2 are parameters in the updating scheme of the
  163. trust-region radius detailed in the subroutine TRRAD in trustregion.py. Roughly
  164. speaking, the trust-region radius is contracted by a factor of GAMMA1 when the
  165. reduction ratio is below ETA1, and enlarged by a factor of GAMMA2 when the
  166. reduction ratio is above ETA2. It is required that 0 < ETA1 <= ETA2 < 1 and
  167. 0 < GAMMA1 < 1 < GAMMA2. Normally, ETA1 <= 0.25. It is NOT advised to set
  168. ETA1 >= 0.5.
  169. MAXFILT
  170. Input, scalar.
  171. MAXFILT is a nonnegative integer indicating the maximal length of the filter used
  172. for selecting the returned solution; default: MAXFILT_DFT (a value lower than
  173. MIN_MAXFILT is not recommended);
  174. see common/consts.py for the definitions of MAXFILT_DFT and MIN_MAXFILT.
  175. CALLBACK
  176. Input, function to report progress and optionally request termination.
  177. ####################################################################################
  178. # OUTPUTS
  179. ####################################################################################
  180. The output is a single data structure, COBYLAResult, with the following fields:
  181. X
  182. Output, vector.
  183. As an output, X will be set to an approximate minimizer.
  184. F
  185. Output, scalar.
  186. F will be set to the objective function value of X at exit.
  187. CONSTR
  188. Output, vector.
  189. CONSTR will be set to the constraint value of X at exit.
  190. CSTRV
  191. Output, scalar.
  192. CSTRV will be set to the constraint violation of X at exit, i.e.,
  193. max([0, XL - X, X - XU, Aineq*X - Bineq, ABS(Aeq*X -Beq), NLCONSTR(X)]).
  194. NF
  195. Output, scalar.
  196. NF will be set to the number of calls of CALCFC at exit.
  197. XHIST, FHIST, CHIST, CONHIST, MAXHIST
  198. XHIST: Output, rank 2 array;
  199. FHIST: Output, rank 1 array;
  200. CHIST: Output, rank 1 array;
  201. CONHIST: Output, rank 2 array;
  202. MAXHIST: Input, scalar, default: MAXFUN
  203. XHIST, if present, will output the history of iterates; FHIST, if present, will
  204. output the history function values; CHIST, if present, will output the history of
  205. constraint violations; CONHIST, if present, will output the history of constraint
  206. values; MAXHIST should be a nonnegative integer, and XHIST/FHIST/CHIST/CONHIST
  207. will output only the history of the last MAXHIST iterations.
  208. Therefore, MAXHIST= 0 means XHIST/FHIST/CONHIST/CHIST will output
  209. nothing, while setting MAXHIST = MAXFUN requests XHIST/FHIST/CHIST/CONHIST to
  210. output all the history. If XHIST is present, its size at exit will be
  211. (N, min(NF, MAXHIST)); if FHIST is present, its size at exit will be
  212. min(NF, MAXHIST); if CHIST is present, its size at exit will be min(NF, MAXHIST);
  213. if CONHIST is present, its size at exit will be (M, min(NF, MAXHIST)).
  214. IMPORTANT NOTICE:
  215. Setting MAXHIST to a large value can be costly in terms of memory for large
  216. problems.
  217. MAXHIST will be reset to a smaller value if the memory needed exceeds MAXHISTMEM
  218. defined in common/consts.py
  219. Use *HIST with caution!!! (N.B.: the algorithm is NOT designed for large
  220. problems).
  221. INFO
  222. Output, scalar.
  223. INFO is the exit flag. It will be set to one of the following values defined in
  224. common/infos.py:
  225. SMALL_TR_RADIUS: the lower bound for the trust region radius is reached;
  226. FTARGET_ACHIEVED: the target function value is reached;
  227. MAXFUN_REACHED: the objective function has been evaluated MAXFUN times;
  228. MAXTR_REACHED: the trust region iteration has been performed MAXTR times (MAXTR = 2*MAXFUN);
  229. NAN_INF_X: NaN or Inf occurs in X;
  230. DAMAGING_ROUNDING: rounding errors are becoming damaging.
  231. #--------------------------------------------------------------------------#
  232. The following case(s) should NEVER occur unless there is a bug.
  233. NAN_INF_F: the objective function returns NaN or +Inf;
  234. NAN_INF_MODEL: NaN or Inf occurs in the model;
  235. TRSUBP_FAILED: a trust region step failed to reduce the model
  236. #--------------------------------------------------------------------------#
  237. """
  238. # Local variables
  239. solver = "COBYLA"
  240. srname = "COBYLA"
  241. # Sizes
  242. mineq = len(bineq) if present(bineq) else 0
  243. meq = len(beq) if present(beq) else 0
  244. mxl = sum(xl > -BOUNDMAX) if present(xl) else 0
  245. mxu = sum(xu < BOUNDMAX) if present(xu) else 0
  246. mmm = mxu + mxl + 2*meq + mineq + m_nlcon
  247. num_vars = len(x)
  248. # Preconditions
  249. if DEBUGGING:
  250. assert m_nlcon >= 0, f'{srname} M_NLCON >= 0'
  251. assert num_vars >= 1, f'{srname} N >= 1'
  252. assert present(Aineq) == present(bineq), \
  253. f'{srname} Aineq and Bineq are both present or both absent'
  254. if (present(Aineq)):
  255. assert Aineq.shape == (mineq, num_vars), f'{srname} SIZE(Aineq) == [Mineq, N]'
  256. assert present(Aeq) == present(beq), \
  257. f'{srname} Aeq and Beq are both present or both absent'
  258. if (present(Aeq)):
  259. assert Aeq.shape == (meq, num_vars), f'{srname} SIZE(Aeq) == [Meq, N]'
  260. if (present(xl)):
  261. assert len(xl) == num_vars, f'{srname} SIZE(XL) == N'
  262. if (present(xu)):
  263. assert len(xu) == num_vars, f'{srname} SIZE(XU) == N'
  264. # N.B.: If NLCONSTR0 is present, then F0 must be present, and we assume that
  265. # F(X0) = F0 even if F0 is NaN; if NLCONSTR0 is absent, then F0 must be either
  266. # absent or NaN, both of which will be interpreted as F(X0) is not provided.
  267. if present(nlconstr0):
  268. assert present(f0), f'{srname} If NLCONSTR0 is present, then F0 is present'
  269. if present(f0):
  270. assert np.isnan(f0) or present(nlconstr0), \
  271. f'{srname} If F0 is present and not NaN, then NLCONSTR0 is present'
  272. # Exit if the size of NLCONSTR0 is inconsistent with M_NLCON.
  273. if present(nlconstr0):
  274. assert np.size(nlconstr0) == m_nlcon
  275. # Read the inputs.
  276. if xl is not None:
  277. xl = copy(xl)
  278. xl[np.isnan(xl)] = -BOUNDMAX
  279. xl[xl < -BOUNDMAX] = -BOUNDMAX
  280. if xu is not None:
  281. xu = copy(xu)
  282. xu[np.isnan(xu)] = BOUNDMAX
  283. xu[xu > BOUNDMAX] = BOUNDMAX
  284. # Wrap the linear and bound constraints into a single constraint: AMAT@X <= BVEC.
  285. amat, bvec = get_lincon(Aeq, Aineq, beq, bineq, xl, xu)
  286. # Create constraint vector
  287. constr = np.zeros(mmm)
  288. # Set [F_LOC, CONSTR_LOC] to [F(X0), CONSTR(X0)] after evaluating the latter if
  289. # needed. In this way, COBYLB only needs one interface.
  290. # N.B.: Due to the preconditions above, there are two possibilities for F0 and
  291. # NLCONSTR0.
  292. # If NLCONSTR0 is present, then F0 must be present, and we assume that F(X0) = F0
  293. # even if F0 is NaN.
  294. # If NLCONSTR0 is absent, then F0 must be either absent or NaN, both of which will
  295. # be interpreted as F(X0) is not provided and we have to evaluate F(X0) and
  296. # NLCONSTR(X0) now.
  297. if (present(f0) and present(nlconstr0) and all(np.isfinite(x))):
  298. f = moderatef(f0)
  299. if amat is not None:
  300. constr[:mmm - m_nlcon] = moderatec(matprod(amat, x) - bvec)
  301. constr[mmm - m_nlcon:] = moderatec(nlconstr0)
  302. else:
  303. x = moderatex(x)
  304. f, constr = evaluate(calcfc, x, m_nlcon, amat, bvec)
  305. constr[:mmm - m_nlcon] = moderatec(constr[:mmm - m_nlcon])
  306. # N.B.: Do NOT call FMSG, SAVEHIST, or SAVEFILT for the function/constraint evaluation at X0.
  307. # They will be called during the initialization, which will read the function/constraint at X0.
  308. cstrv = max(np.append(0, constr))
  309. # If RHOBEG is present, use it; otherwise, RHOBEG takes the default value for
  310. # RHOBEG, taking the value of RHOEND into account. Note that RHOEND is considered
  311. # only if it is present and it is VALID (i.e., finite and positive). The other
  312. # inputs are read similarly.
  313. if present(rhobeg):
  314. rhobeg = rhobeg
  315. elif present(rhoend) and np.isfinite(rhoend) and rhoend > 0:
  316. rhobeg = max(10 * rhoend, RHOBEG_DEFAULT)
  317. else:
  318. rhobeg = RHOBEG_DEFAULT
  319. if present(rhoend):
  320. rhoend = rhoend
  321. elif rhobeg > 0:
  322. rhoend = max(EPS, min(RHOEND_DEFAULT/RHOBEG_DEFAULT * rhobeg, RHOEND_DEFAULT))
  323. else:
  324. rhoend = RHOEND_DEFAULT
  325. maxfun = maxfun if present(maxfun) else MAXFUN_DIM_DEFAULT * num_vars
  326. if present(eta1):
  327. eta1 = eta1
  328. elif present(eta2) and 0 < eta2 < 1:
  329. eta1 = max(EPS, eta2 / 7)
  330. else:
  331. eta1 = ETA1_DEFAULT
  332. if present(eta2):
  333. eta2 = eta2
  334. elif 0 < eta1 < 1:
  335. eta2 = (eta1 + 2) / 3
  336. else:
  337. eta2 = ETA2_DEFAULT
  338. maxhist = (
  339. maxhist
  340. if present(maxhist)
  341. else max(maxfun, num_vars + 2, MAXFUN_DIM_DEFAULT * num_vars)
  342. )
  343. # Preprocess the inputs in case some of them are invalid. It does nothing if all
  344. # inputs are valid.
  345. (
  346. iprint,
  347. maxfun,
  348. maxhist,
  349. ftarget,
  350. rhobeg,
  351. rhoend,
  352. npt, # Unused in COBYLA
  353. maxfilt,
  354. ctol,
  355. cweight,
  356. eta1,
  357. eta2,
  358. gamma1,
  359. gamma2,
  360. _x0, # Unused in COBYLA
  361. ) = preproc(
  362. solver,
  363. num_vars,
  364. iprint,
  365. maxfun,
  366. maxhist,
  367. ftarget,
  368. rhobeg,
  369. rhoend,
  370. num_constraints=mmm,
  371. maxfilt=maxfilt,
  372. ctol=ctol,
  373. cweight=cweight,
  374. eta1=eta1,
  375. eta2=eta2,
  376. gamma1=gamma1,
  377. gamma2=gamma2,
  378. is_constrained=(mmm > 0),
  379. )
  380. # Further revise MAXHIST according to MAXHISTMEM, and allocate memory for the history.
  381. # In MATLAB/Python/Julia/R implementation, we should simply set MAXHIST = MAXFUN and initialize
  382. # CHIST = NaN(1, MAXFUN), CONHIST = NaN(M, MAXFUN), FHIST = NaN(1, MAXFUN), XHIST = NaN(N, MAXFUN)
  383. # if they are requested; replace MAXFUN with 0 for the history that is not requested.
  384. # prehist(maxhist, num_vars, present(xhist), xhist_loc, present(fhist), fhist_loc, &
  385. # & present(chist), chist_loc, m, present(conhist), conhist_loc)
  386. # call cobylb, which performs the real calculations
  387. x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info = cobylb(
  388. calcfc,
  389. iprint,
  390. maxfilt,
  391. maxfun,
  392. amat,
  393. bvec,
  394. ctol,
  395. cweight,
  396. eta1,
  397. eta2,
  398. ftarget,
  399. gamma1,
  400. gamma2,
  401. rhobeg,
  402. rhoend,
  403. constr,
  404. f,
  405. x,
  406. maxhist,
  407. callback
  408. )
  409. return COBYLAResult(x, f, constr, cstrv, nf, xhist, fhist, chist, conhist, info)
  410. def get_lincon(Aeq=None, Aineq=None, beq=None, bineq=None, xl=None, xu=None):
  411. """
  412. This subroutine wraps the linear and bound constraints into a single constraint:
  413. AMAT*X <= BVEC.
  414. N.B.:
  415. LINCOA normalizes the linear constraints so that each constraint has a gradient
  416. of norm 1. However, COBYLA does not do this.
  417. """
  418. # Sizes
  419. if Aeq is not None:
  420. num_vars = Aeq.shape[1]
  421. elif Aineq is not None:
  422. num_vars = Aineq.shape[1]
  423. elif xl is not None:
  424. num_vars = len(xl)
  425. elif xu is not None:
  426. num_vars = len(xu)
  427. else:
  428. return None, None
  429. # Preconditions
  430. if DEBUGGING:
  431. assert Aineq is None or Aineq.shape == (len(bineq), num_vars)
  432. assert Aeq is None or Aeq.shape == (len(beq), num_vars)
  433. assert (xl is None or xu is None) or len(xl) == len(xu) == num_vars
  434. #====================#
  435. # Calculation starts #
  436. #====================#
  437. # Define the indices of the nontrivial bound constraints.
  438. ixl = np.where(xl > -BOUNDMAX)[0] if xl is not None else None
  439. ixu = np.where(xu < BOUNDMAX)[0] if xu is not None else None
  440. # Wrap the linear constraints.
  441. # The bound constraint XL <= X <= XU is handled as two constraints:
  442. # -X <= -XL, X <= XU.
  443. # The equality constraint Aeq*X = Beq is handled as two constraints:
  444. # -Aeq*X <= -Beq, Aeq*X <= Beq.
  445. # N.B.:
  446. # 1. The treatment of the equality constraints is naive. One may choose to
  447. # eliminate them instead.
  448. idmat = np.eye(num_vars)
  449. amat = np.vstack([
  450. -idmat[ixl, :] if ixl is not None else np.empty((0, num_vars)),
  451. idmat[ixu, :] if ixu is not None else np.empty((0, num_vars)),
  452. -Aeq if Aeq is not None else np.empty((0, num_vars)),
  453. Aeq if Aeq is not None else np.empty((0, num_vars)),
  454. Aineq if Aineq is not None else np.empty((0, num_vars))
  455. ])
  456. bvec = np.hstack([
  457. -xl[ixl] if ixl is not None else np.empty(0),
  458. xu[ixu] if ixu is not None else np.empty(0),
  459. -beq if beq is not None else np.empty(0),
  460. beq if beq is not None else np.empty(0),
  461. bineq if bineq is not None else np.empty(0)
  462. ])
  463. amat = amat if amat.shape[0] > 0 else None
  464. bvec = bvec if bvec.shape[0] > 0 else None
  465. #==================#
  466. # Calculation ends #
  467. #==================#
  468. # Postconditions
  469. if DEBUGGING:
  470. assert (amat is None and bvec is None) or amat.shape == (len(bvec), num_vars)
  471. return amat, bvec