00001 /*************************************************************************** 00002 * Copyright (c) Konstantinos Poulios (logari81@gmail.com) 2011 * 00003 * * 00004 * This file is part of the FreeCAD CAx development system. * 00005 * * 00006 * This library is free software; you can redistribute it and/or * 00007 * modify it under the terms of the GNU Library General Public * 00008 * License as published by the Free Software Foundation; either * 00009 * version 2 of the License, or (at your option) any later version. * 00010 * * 00011 * This library is distributed in the hope that it will be useful, * 00012 * but WITHOUT ANY WARRANTY; without even the implied warranty of * 00013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * 00014 * GNU Library General Public License for more details. * 00015 * * 00016 * You should have received a copy of the GNU Library General Public * 00017 * License along with this library; see the file COPYING.LIB. If not, * 00018 * write to the Free Software Foundation, Inc., 59 Temple Place, * 00019 * Suite 330, Boston, MA 02111-1307, USA * 00020 * * 00021 ***************************************************************************/ 00022 #include <iostream> 00023 #include <Eigen/QR> 00024 00025 using namespace Eigen; 00026 00027 // minimizes ( 0.5 * x^T * H * x + g^T * x ) under the condition ( A*x + c = 0 ) 00028 // it returns the solution in x, the row-space of A in Y, and the null space of A in Z 00029 int qp_eq(MatrixXd &H, VectorXd &g, MatrixXd &A, VectorXd &c, 00030 VectorXd &x, MatrixXd &Y, MatrixXd &Z) 00031 { 00032 FullPivHouseholderQR<MatrixXd> qrAT(A.transpose()); 00033 MatrixXd Q = qrAT.matrixQ (); 00034 00035 size_t params_num = qrAT.rows(); 00036 size_t constr_num = qrAT.cols(); 00037 size_t rank = qrAT.rank(); 00038 00039 if (rank != constr_num || constr_num > params_num) 00040 return -1; 00041 00042 // A^T = Q*R*P^T = Q1*R1*P^T 00043 // Q = [Q1,Q2], R=[R1;0] 00044 // Y = Q1 * inv(R^T) * P^T 00045 // Z = Q2 00046 Y = qrAT.matrixQR().topRows(constr_num) 00047 .triangularView<Upper>() 00048 .transpose() 00049 .solve<OnTheRight>(Q.leftCols(rank)) 00050 * qrAT.colsPermutation().transpose(); 00051 if (params_num == rank) 00052 x = - Y * c; 00053 else { 00054 Z = Q.rightCols(params_num-rank); 00055 00056 MatrixXd ZTHZ = Z.transpose() * H * Z; 00057 VectorXd rhs = Z.transpose() * (H * Y * c - g); 00058 00059 VectorXd y = ZTHZ.colPivHouseholderQr().solve(rhs); 00060 00061 x = - Y * c + Z * y; 00062 } 00063 00064 return 0; 00065 }