quadprog.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "quadprog.h"
  9. #include <vector>
  10. /*
  11. FILE eiquadprog.hh
  12. NOTE: this is a modified of uQuadProg++ package, working with Eigen data structures.
  13. uQuadProg++ is itself a port made by Angelo Furfaro of QuadProg++ originally developed by
  14. Luca Di Gaspero, working with ublas data structures.
  15. The quadprog_solve() function implements the algorithm of Goldfarb and Idnani
  16. for the solution of a (convex) Quadratic Programming problem
  17. by means of a dual method.
  18. The problem is in the form:
  19. min 0.5 * x G x + g0 x
  20. s.t.
  21. CE^T x + ce0 = 0
  22. CI^T x + ci0 >= 0
  23. The matrix and vectors dimensions are as follows:
  24. G: n * n
  25. g0: n
  26. CE: n * p
  27. ce0: p
  28. CI: n * m
  29. ci0: m
  30. x: n
  31. The function will return the cost of the solution written in the x vector or
  32. std::numeric_limits::infinity() if the problem is infeasible. In the latter case
  33. the value of the x vector is not correct.
  34. References: D. Goldfarb, A. Idnani. A numerically stable dual method for solving
  35. strictly convex quadratic programs. Mathematical Programming 27 (1983) pp. 1-33.
  36. Notes:
  37. 1. pay attention in setting up the vectors ce0 and ci0.
  38. If the constraints of your problem are specified in the form
  39. A^T x = b and C^T x >= d, then you should set ce0 = -b and ci0 = -d.
  40. 2. The matrix G is modified within the function since it is used to compute
  41. the G = L^T L cholesky factorization for further computations inside the function.
  42. If you need the original matrix G you should make a copy of it and pass the copy
  43. to the function.
  44. The author will be grateful if the researchers using this software will
  45. acknowledge the contribution of this modified function and of Di Gaspero's
  46. original version in their research papers.
  47. LICENSE
  48. Copyright (2010) Gael Guennebaud
  49. Copyright (2008) Angelo Furfaro
  50. Copyright (2006) Luca Di Gaspero
  51. This file is a porting of QuadProg++ routine, originally developed
  52. by Luca Di Gaspero, exploiting uBlas data structures for vectors and
  53. matrices instead of native C++ array.
  54. uquadprog is free software; you can redistribute it and/or modify
  55. it under the terms of the GNU General Public License as published by
  56. the Free Software Foundation; either version 2 of the License, or
  57. (at your option) any later version.
  58. uquadprog is distributed in the hope that it will be useful,
  59. but WITHOUT ANY WARRANTY; without even the implied warranty of
  60. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  61. GNU General Public License for more details.
  62. You should have received a copy of the GNU General Public License
  63. along with uquadprog; if not, write to the Free Software
  64. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  65. */
  66. #include <Eigen/Dense>
  67. IGL_INLINE bool igl::copyleft::quadprog(
  68. const Eigen::MatrixXd & G,
  69. const Eigen::VectorXd & g0,
  70. const Eigen::MatrixXd & CE,
  71. const Eigen::VectorXd & ce0,
  72. const Eigen::MatrixXd & CI,
  73. const Eigen::VectorXd & ci0,
  74. Eigen::VectorXd& x)
  75. {
  76. using namespace Eigen;
  77. typedef double Scalar;
  78. const auto distance = [](Scalar a, Scalar b)->Scalar
  79. {
  80. Scalar a1, b1, t;
  81. a1 = std::abs(a);
  82. b1 = std::abs(b);
  83. if (a1 > b1)
  84. {
  85. t = (b1 / a1);
  86. return a1 * std::sqrt(1.0 + t * t);
  87. }
  88. else
  89. if (b1 > a1)
  90. {
  91. t = (a1 / b1);
  92. return b1 * std::sqrt(1.0 + t * t);
  93. }
  94. return a1 * std::sqrt(2.0);
  95. };
  96. const auto compute_d = [](VectorXd &d, const MatrixXd& J, const VectorXd& np)
  97. {
  98. d = J.adjoint() * np;
  99. };
  100. const auto update_z =
  101. [](VectorXd& z, const MatrixXd& J, const VectorXd& d, int iq)
  102. {
  103. z = J.rightCols(z.size()-iq) * d.tail(d.size()-iq);
  104. };
  105. const auto update_r =
  106. [](const MatrixXd& R, VectorXd& r, const VectorXd& d, int iq)
  107. {
  108. r.head(iq) =
  109. R.topLeftCorner(iq,iq).triangularView<Upper>().solve(d.head(iq));
  110. };
  111. const auto add_constraint = [&distance](
  112. MatrixXd& R,
  113. MatrixXd& J,
  114. VectorXd& d,
  115. int& iq,
  116. double& R_norm)->bool
  117. {
  118. int n=J.rows();
  119. #ifdef TRACE_SOLVER
  120. std::cerr << "Add constraint " << iq << '/';
  121. #endif
  122. int i, j, k;
  123. double cc, ss, h, t1, t2, xny;
  124. /* we have to find the Givens rotation which will reduce the element
  125. d(j) to zero.
  126. if it is already zero we don't have to do anything, except of
  127. decreasing j */
  128. for (j = n - 1; j >= iq + 1; j--)
  129. {
  130. /* The Givens rotation is done with the matrix (cc cs, cs -cc).
  131. If cc is one, then element (j) of d is zero compared with element
  132. (j - 1). Hence we don't have to do anything.
  133. If cc is zero, then we just have to switch column (j) and column (j - 1)
  134. of J. Since we only switch columns in J, we have to be careful how we
  135. update d depending on the sign of gs.
  136. Otherwise we have to apply the Givens rotation to these columns.
  137. The i - 1 element of d has to be updated to h. */
  138. cc = d(j - 1);
  139. ss = d(j);
  140. h = distance(cc, ss);
  141. if (h == 0.0)
  142. continue;
  143. d(j) = 0.0;
  144. ss = ss / h;
  145. cc = cc / h;
  146. if (cc < 0.0)
  147. {
  148. cc = -cc;
  149. ss = -ss;
  150. d(j - 1) = -h;
  151. }
  152. else
  153. d(j - 1) = h;
  154. xny = ss / (1.0 + cc);
  155. for (k = 0; k < n; k++)
  156. {
  157. t1 = J(k,j - 1);
  158. t2 = J(k,j);
  159. J(k,j - 1) = t1 * cc + t2 * ss;
  160. J(k,j) = xny * (t1 + J(k,j - 1)) - t2;
  161. }
  162. }
  163. /* update the number of constraints added*/
  164. iq++;
  165. /* To update R we have to put the iq components of the d vector
  166. into column iq - 1 of R
  167. */
  168. R.col(iq-1).head(iq) = d.head(iq);
  169. #ifdef TRACE_SOLVER
  170. std::cerr << iq << std::endl;
  171. #endif
  172. if (std::abs(d(iq - 1)) <= std::numeric_limits<double>::epsilon() * R_norm)
  173. {
  174. // problem degenerate
  175. return false;
  176. }
  177. R_norm = std::max<double>(R_norm, std::abs(d(iq - 1)));
  178. return true;
  179. };
  180. const auto delete_constraint = [&distance](
  181. MatrixXd& R,
  182. MatrixXd& J,
  183. VectorXi& A,
  184. VectorXd& u,
  185. int p,
  186. int& iq,
  187. int l)
  188. {
  189. int n = R.rows();
  190. #ifdef TRACE_SOLVER
  191. std::cerr << "Delete constraint " << l << ' ' << iq;
  192. #endif
  193. int i, j, k, qq;
  194. double cc, ss, h, xny, t1, t2;
  195. /* Find the index qq for active constraint l to be removed */
  196. for (i = p; i < iq; i++)
  197. if (A(i) == l)
  198. {
  199. qq = i;
  200. break;
  201. }
  202. /* remove the constraint from the active set and the duals */
  203. for (i = qq; i < iq - 1; i++)
  204. {
  205. A(i) = A(i + 1);
  206. u(i) = u(i + 1);
  207. R.col(i) = R.col(i+1);
  208. }
  209. A(iq - 1) = A(iq);
  210. u(iq - 1) = u(iq);
  211. A(iq) = 0;
  212. u(iq) = 0.0;
  213. for (j = 0; j < iq; j++)
  214. R(j,iq - 1) = 0.0;
  215. /* constraint has been fully removed */
  216. iq--;
  217. #ifdef TRACE_SOLVER
  218. std::cerr << '/' << iq << std::endl;
  219. #endif
  220. if (iq == 0)
  221. return;
  222. for (j = qq; j < iq; j++)
  223. {
  224. cc = R(j,j);
  225. ss = R(j + 1,j);
  226. h = distance(cc, ss);
  227. if (h == 0.0)
  228. continue;
  229. cc = cc / h;
  230. ss = ss / h;
  231. R(j + 1,j) = 0.0;
  232. if (cc < 0.0)
  233. {
  234. R(j,j) = -h;
  235. cc = -cc;
  236. ss = -ss;
  237. }
  238. else
  239. R(j,j) = h;
  240. xny = ss / (1.0 + cc);
  241. for (k = j + 1; k < iq; k++)
  242. {
  243. t1 = R(j,k);
  244. t2 = R(j + 1,k);
  245. R(j,k) = t1 * cc + t2 * ss;
  246. R(j + 1,k) = xny * (t1 + R(j,k)) - t2;
  247. }
  248. for (k = 0; k < n; k++)
  249. {
  250. t1 = J(k,j);
  251. t2 = J(k,j + 1);
  252. J(k,j) = t1 * cc + t2 * ss;
  253. J(k,j + 1) = xny * (J(k,j) + t1) - t2;
  254. }
  255. }
  256. };
  257. int i, j, k, l; /* indices */
  258. int ip, me, mi;
  259. int n=g0.size(); int p=ce0.size(); int m=ci0.size();
  260. MatrixXd R(G.rows(),G.cols()), J(G.rows(),G.cols());
  261. LLT<MatrixXd,Lower> chol(G.cols());
  262. VectorXd s(m+p), z(n), r(m + p), d(n), np(n), u(m + p);
  263. VectorXd x_old(n), u_old(m + p);
  264. double f_value, psi, c1, c2, sum, ss, R_norm;
  265. const double inf = std::numeric_limits<double>::infinity();
  266. double t, t1, t2; /* t is the step length, which is the minimum of the partial step length t1
  267. * and the full step length t2 */
  268. VectorXi A(m + p), A_old(m + p), iai(m + p);
  269. int q;
  270. int iq, iter = 0;
  271. std::vector<bool> iaexcl(m + p);
  272. me = p; /* number of equality constraints */
  273. mi = m; /* number of inequality constraints */
  274. q = 0; /* size of the active set A (containing the indices of the active constraints) */
  275. /*
  276. * Preprocessing phase
  277. */
  278. /* compute the trace of the original matrix G */
  279. c1 = G.trace();
  280. /* decompose the matrix G in the form LL^T */
  281. chol.compute(G);
  282. /* initialize the matrix R */
  283. d.setZero();
  284. R.setZero();
  285. R_norm = 1.0; /* this variable will hold the norm of the matrix R */
  286. /* compute the inverse of the factorized matrix G^-1, this is the initial value for H */
  287. // J = L^-T
  288. J.setIdentity();
  289. J = chol.matrixU().solve(J);
  290. c2 = J.trace();
  291. #ifdef TRACE_SOLVER
  292. print_matrix("J", J, n);
  293. #endif
  294. /* c1 * c2 is an estimate for cond(G) */
  295. /*
  296. * Find the unconstrained minimizer of the quadratic form 0.5 * x G x + g0 x
  297. * this is a feasible point in the dual space
  298. * x = G^-1 * g0
  299. */
  300. x = chol.solve(g0);
  301. x = -x;
  302. /* and compute the current solution value */
  303. f_value = 0.5 * g0.dot(x);
  304. #ifdef TRACE_SOLVER
  305. std::cerr << "Unconstrained solution: " << f_value << std::endl;
  306. print_vector("x", x, n);
  307. #endif
  308. /* Add equality constraints to the working set A */
  309. iq = 0;
  310. for (i = 0; i < me; i++)
  311. {
  312. np = CE.col(i);
  313. compute_d(d, J, np);
  314. update_z(z, J, d, iq);
  315. update_r(R, r, d, iq);
  316. #ifdef TRACE_SOLVER
  317. print_matrix("R", R, iq);
  318. print_vector("z", z, n);
  319. print_vector("r", r, iq);
  320. print_vector("d", d, n);
  321. #endif
  322. /* compute full step length t2: i.e., the minimum step in primal space s.t. the contraint
  323. becomes feasible */
  324. t2 = 0.0;
  325. if (std::abs(z.dot(z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0
  326. t2 = (-np.dot(x) - ce0(i)) / z.dot(np);
  327. x += t2 * z;
  328. /* set u = u+ */
  329. u(iq) = t2;
  330. u.head(iq) -= t2 * r.head(iq);
  331. /* compute the new solution value */
  332. f_value += 0.5 * (t2 * t2) * z.dot(np);
  333. A(i) = -i - 1;
  334. if (!add_constraint(R, J, d, iq, R_norm))
  335. {
  336. // FIXME: it should raise an error
  337. // Equality constraints are linearly dependent
  338. return false;
  339. }
  340. }
  341. /* set iai = K \ A */
  342. for (i = 0; i < mi; i++)
  343. iai(i) = i;
  344. l1: iter++;
  345. #ifdef TRACE_SOLVER
  346. print_vector("x", x, n);
  347. #endif
  348. /* step 1: choose a violated constraint */
  349. for (i = me; i < iq; i++)
  350. {
  351. ip = A(i);
  352. iai(ip) = -1;
  353. }
  354. /* compute s(x) = ci^T * x + ci0 for all elements of K \ A */
  355. ss = 0.0;
  356. psi = 0.0; /* this value will contain the sum of all infeasibilities */
  357. ip = 0; /* ip will be the index of the chosen violated constraint */
  358. for (i = 0; i < mi; i++)
  359. {
  360. iaexcl[i] = true;
  361. sum = CI.col(i).dot(x) + ci0(i);
  362. s(i) = sum;
  363. psi += std::min(0.0, sum);
  364. }
  365. #ifdef TRACE_SOLVER
  366. print_vector("s", s, mi);
  367. #endif
  368. if (std::abs(psi) <= mi * std::numeric_limits<double>::epsilon() * c1 * c2* 100.0)
  369. {
  370. /* numerically there are not infeasibilities anymore */
  371. q = iq;
  372. return true;
  373. }
  374. /* save old values for u, x and A */
  375. u_old.head(iq) = u.head(iq);
  376. A_old.head(iq) = A.head(iq);
  377. x_old = x;
  378. l2: /* Step 2: check for feasibility and determine a new S-pair */
  379. for (i = 0; i < mi; i++)
  380. {
  381. if (s(i) < ss && iai(i) != -1 && iaexcl[i])
  382. {
  383. ss = s(i);
  384. ip = i;
  385. }
  386. }
  387. if (ss >= 0.0)
  388. {
  389. q = iq;
  390. return true;
  391. }
  392. /* set np = n(ip) */
  393. np = CI.col(ip);
  394. /* set u = (u 0)^T */
  395. u(iq) = 0.0;
  396. /* add ip to the active set A */
  397. A(iq) = ip;
  398. #ifdef TRACE_SOLVER
  399. std::cerr << "Trying with constraint " << ip << std::endl;
  400. print_vector("np", np, n);
  401. #endif
  402. l2a:/* Step 2a: determine step direction */
  403. /* compute z = H np: the step direction in the primal space (through J, see the paper) */
  404. compute_d(d, J, np);
  405. update_z(z, J, d, iq);
  406. /* compute N* np (if q > 0): the negative of the step direction in the dual space */
  407. update_r(R, r, d, iq);
  408. #ifdef TRACE_SOLVER
  409. std::cerr << "Step direction z" << std::endl;
  410. print_vector("z", z, n);
  411. print_vector("r", r, iq + 1);
  412. print_vector("u", u, iq + 1);
  413. print_vector("d", d, n);
  414. print_ivector("A", A, iq + 1);
  415. #endif
  416. /* Step 2b: compute step length */
  417. l = 0;
  418. /* Compute t1: partial step length (maximum step in dual space without violating dual feasibility */
  419. t1 = inf; /* +inf */
  420. /* find the index l s.t. it reaches the minimum of u+(x) / r */
  421. for (k = me; k < iq; k++)
  422. {
  423. double tmp;
  424. if (r(k) > 0.0 && ((tmp = u(k) / r(k)) < t1) )
  425. {
  426. t1 = tmp;
  427. l = A(k);
  428. }
  429. }
  430. /* Compute t2: full step length (minimum step in primal space such that the constraint ip becomes feasible */
  431. if (std::abs(z.dot(z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0
  432. t2 = -s(ip) / z.dot(np);
  433. else
  434. t2 = inf; /* +inf */
  435. /* the step is chosen as the minimum of t1 and t2 */
  436. t = std::min(t1, t2);
  437. #ifdef TRACE_SOLVER
  438. std::cerr << "Step sizes: " << t << " (t1 = " << t1 << ", t2 = " << t2 << ") ";
  439. #endif
  440. /* Step 2c: determine new S-pair and take step: */
  441. /* case (i): no step in primal or dual space */
  442. if (t >= inf)
  443. {
  444. /* QPP is infeasible */
  445. // FIXME: unbounded to raise
  446. q = iq;
  447. return false;
  448. }
  449. /* case (ii): step in dual space */
  450. if (t2 >= inf)
  451. {
  452. /* set u = u + t * [-r 1) and drop constraint l from the active set A */
  453. u.head(iq) -= t * r.head(iq);
  454. u(iq) += t;
  455. iai(l) = l;
  456. delete_constraint(R, J, A, u, p, iq, l);
  457. #ifdef TRACE_SOLVER
  458. std::cerr << " in dual space: "
  459. << f_value << std::endl;
  460. print_vector("x", x, n);
  461. print_vector("z", z, n);
  462. print_ivector("A", A, iq + 1);
  463. #endif
  464. goto l2a;
  465. }
  466. /* case (iii): step in primal and dual space */
  467. x += t * z;
  468. /* update the solution value */
  469. f_value += t * z.dot(np) * (0.5 * t + u(iq));
  470. u.head(iq) -= t * r.head(iq);
  471. u(iq) += t;
  472. #ifdef TRACE_SOLVER
  473. std::cerr << " in both spaces: "
  474. << f_value << std::endl;
  475. print_vector("x", x, n);
  476. print_vector("u", u, iq + 1);
  477. print_vector("r", r, iq + 1);
  478. print_ivector("A", A, iq + 1);
  479. #endif
  480. if (t == t2)
  481. {
  482. #ifdef TRACE_SOLVER
  483. std::cerr << "Full step has taken " << t << std::endl;
  484. print_vector("x", x, n);
  485. #endif
  486. /* full step has taken */
  487. /* add constraint ip to the active set*/
  488. if (!add_constraint(R, J, d, iq, R_norm))
  489. {
  490. iaexcl[ip] = false;
  491. delete_constraint(R, J, A, u, p, iq, ip);
  492. #ifdef TRACE_SOLVER
  493. print_matrix("R", R, n);
  494. print_ivector("A", A, iq);
  495. #endif
  496. for (i = 0; i < m; i++)
  497. iai(i) = i;
  498. for (i = 0; i < iq; i++)
  499. {
  500. A(i) = A_old(i);
  501. iai(A(i)) = -1;
  502. u(i) = u_old(i);
  503. }
  504. x = x_old;
  505. goto l2; /* go to step 2 */
  506. }
  507. else
  508. iai(ip) = -1;
  509. #ifdef TRACE_SOLVER
  510. print_matrix("R", R, n);
  511. print_ivector("A", A, iq);
  512. #endif
  513. goto l1;
  514. }
  515. /* a patial step has taken */
  516. #ifdef TRACE_SOLVER
  517. std::cerr << "Partial step has taken " << t << std::endl;
  518. print_vector("x", x, n);
  519. #endif
  520. /* drop constraint l */
  521. iai(l) = l;
  522. delete_constraint(R, J, A, u, p, iq, l);
  523. #ifdef TRACE_SOLVER
  524. print_matrix("R", R, n);
  525. print_ivector("A", A, iq);
  526. #endif
  527. s(ip) = CI.col(ip).dot(x) + ci0(ip);
  528. #ifdef TRACE_SOLVER
  529. print_vector("s", s, mi);
  530. #endif
  531. goto l2a;
  532. }