MatlabWorkspace.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 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. #ifndef IGL_WRITE_MATLAB_WORKSPACE
  9. #define IGL_WRITE_MATLAB_WORKSPACE
  10. #include <Eigen/Dense>
  11. #include <Eigen/Sparse>
  12. #include <mat.h>
  13. #include <string>
  14. #include <vector>
  15. namespace igl
  16. {
  17. // It would be really great to replicate this for a simple XML-based
  18. // workspace.
  19. //
  20. // Class which contains data of a matlab workspace which can be written to a
  21. // .mat file and loaded from matlab
  22. //
  23. // This depends on matlab at compile time (though it shouldn't necessarily
  24. // have to) but it does not depend on running the matlab engine at run-time.
  25. //
  26. // Known bugs: Treats all matrices as doubles (this may actually be desired
  27. // for some "index" matrices since matlab's sparse command takes doubles
  28. // rather than int class matrices). It is of course not desired when dealing
  29. // with logicals or uint's for images.
  30. class MatlabWorkspace
  31. {
  32. private:
  33. // KNOWN BUG: Why not use a map? Any reason to allow duplicate names?
  34. //
  35. // List of names
  36. std::vector<std::string> names;
  37. // List of data pointers
  38. std::vector<mxArray*> data;
  39. public:
  40. MatlabWorkspace();
  41. ~MatlabWorkspace();
  42. // Clear names and data of variables in workspace
  43. inline void clear();
  44. // Save current list of variables
  45. //
  46. // Inputs:
  47. // path path to .mat file
  48. // Returns true on success, false on failure
  49. inline bool write(const std::string & path) const;
  50. // Load list of variables from .mat file
  51. //
  52. // Inputs:
  53. // path path to .mat file
  54. // Returns true on success, false on failure
  55. inline bool read(const std::string & path);
  56. // Assign data to a variable name in the workspace
  57. //
  58. // Template:
  59. // DerivedM eigen matrix (e.g. MatrixXd)
  60. // Inputs:
  61. // M data (usually a matrix)
  62. // name variable name to save into work space
  63. // Returns true on success, false on failure
  64. //
  65. // Known Bugs: Assumes Eigen is using column major ordering
  66. template <typename DerivedM>
  67. inline MatlabWorkspace& save(
  68. const Eigen::PlainObjectBase<DerivedM>& M,
  69. const std::string & name);
  70. // Template:
  71. // MT sparse matrix type (e.g. double)
  72. template <typename MT>
  73. inline MatlabWorkspace& save(
  74. const Eigen::SparseMatrix<MT>& M,
  75. const std::string & name);
  76. // Templates:
  77. // ScalarM scalar type, e.g. double
  78. template <typename ScalarM>
  79. inline MatlabWorkspace& save(
  80. const std::vector<std::vector<ScalarM> > & vM,
  81. const std::string & name);
  82. // Templates:
  83. // ScalarV scalar type, e.g. double
  84. template <typename ScalarV>
  85. inline MatlabWorkspace& save(
  86. const std::vector<ScalarV> & vV,
  87. const std::string & name);
  88. // NOTE: Eigen stores quaternions coefficients as (i,j,k,1), but most of
  89. // our matlab code stores them as (1,i,j,k) This takes a quaternion and
  90. // saves it as a (1,i,j,k) row vector
  91. //
  92. // Templates:
  93. // Q quaternion type
  94. template <typename Q>
  95. inline MatlabWorkspace& save(
  96. const Eigen::Quaternion<Q> & q,
  97. const std::string & name);
  98. inline MatlabWorkspace& save(
  99. const double d,
  100. const std::string & name);
  101. // Same as save() but adds 1 to each element, useful for saving "index"
  102. // matrices like lists of faces or elements
  103. template <typename DerivedM>
  104. inline MatlabWorkspace& save_index(
  105. const Eigen::PlainObjectBase<DerivedM>& M,
  106. const std::string & name);
  107. template <typename ScalarM>
  108. inline MatlabWorkspace& save_index(
  109. const std::vector<std::vector<ScalarM> > & vM,
  110. const std::string & name);
  111. template <typename ScalarV>
  112. inline MatlabWorkspace& save_index(
  113. const std::vector<ScalarV> & vV,
  114. const std::string & name);
  115. // Find a certain matrix by name.
  116. //
  117. // KNOWN BUG: Outputs the first found (not necessarily unique lists).
  118. //
  119. // Template:
  120. // DerivedM eigen matrix (e.g. MatrixXd)
  121. // Inputs:
  122. // name exact name of matrix as string
  123. // Outputs:
  124. // M matrix
  125. // Returns true only if found.
  126. template <typename DerivedM>
  127. inline bool find(
  128. const std::string & name,
  129. Eigen::PlainObjectBase<DerivedM>& M);
  130. template <typename MT>
  131. inline bool find(
  132. const std::string & name,
  133. Eigen::SparseMatrix<MT>& M);
  134. inline bool find(
  135. const std::string & name,
  136. double & d);
  137. inline bool find(
  138. const std::string & name,
  139. int & v);
  140. // Subtracts 1 from all entries
  141. template <typename DerivedM>
  142. inline bool find_index(
  143. const std::string & name,
  144. Eigen::PlainObjectBase<DerivedM>& M);
  145. };
  146. }
  147. // Implementation
  148. // Be sure that this is not compiled into libigl.a
  149. // http://stackoverflow.com/a/3318993/148668
  150. // IGL
  151. #include "igl/list_to_matrix.h"
  152. // MATLAB
  153. #include "mat.h"
  154. // STL
  155. #include <iostream>
  156. #include <algorithm>
  157. #include <vector>
  158. inline igl::MatlabWorkspace::MatlabWorkspace():
  159. names(),
  160. data()
  161. {
  162. }
  163. inline igl::MatlabWorkspace::~MatlabWorkspace()
  164. {
  165. // clean up data
  166. clear();
  167. }
  168. inline void igl::MatlabWorkspace::clear()
  169. {
  170. for_each(data.begin(),data.end(),&mxDestroyArray);
  171. data.clear();
  172. names.clear();
  173. }
  174. inline bool igl::MatlabWorkspace::write(const std::string & path) const
  175. {
  176. using namespace std;
  177. MATFile * mat_file = matOpen(path.c_str(), "w");
  178. assert(names.size() == data.size());
  179. // loop over names and data
  180. for(int i = 0;i < (int)names.size(); i++)
  181. {
  182. // Put variable as LOCAL variable
  183. int status = matPutVariable(mat_file,names[i].c_str(), data[i]);
  184. if(status != 0)
  185. {
  186. cerr<<"^MatlabWorkspace::save Error: matPutVariable ("<<names[i]<<
  187. ") failed"<<endl;
  188. return false;
  189. }
  190. }
  191. if(matClose(mat_file) != 0)
  192. {
  193. fprintf(stderr,"Error closing file %s\n",path.c_str());
  194. return false;
  195. }
  196. return true;
  197. }
  198. inline bool igl::MatlabWorkspace::read(const std::string & path)
  199. {
  200. using namespace std;
  201. MATFile * mat_file;
  202. mat_file = matOpen(path.c_str(), "r");
  203. if (mat_file == NULL)
  204. {
  205. cerr<<"Error: failed to open "<<path<<endl;
  206. return false;
  207. }
  208. int ndir;
  209. const char ** dir = (const char **)matGetDir(mat_file, &ndir);
  210. if (dir == NULL) {
  211. cerr<<"Error reading directory of file "<< path<<endl;
  212. return false;
  213. }
  214. mxFree(dir);
  215. // Must close and reopen
  216. if(matClose(mat_file) != 0)
  217. {
  218. cerr<<"Error: failed to close file "<<path<<endl;
  219. return false;
  220. }
  221. mat_file = matOpen(path.c_str(), "r");
  222. if (mat_file == NULL)
  223. {
  224. cerr<<"Error: failed to open "<<path<<endl;
  225. return false;
  226. }
  227. /* Read in each array. */
  228. for (int i=0; i<ndir; i++)
  229. {
  230. const char * name;
  231. mxArray * mx_data = matGetNextVariable(mat_file, &name);
  232. if (mx_data == NULL)
  233. {
  234. cerr<<"Error: matGetNextVariable failed in "<<path<<endl;
  235. return false;
  236. }
  237. const int dims = mxGetNumberOfDimensions(mx_data);
  238. assert(dims == 2);
  239. if(dims != 2)
  240. {
  241. fprintf(stderr,"Variable '%s' has %d ≠ 2 dimensions. Skipping\n",
  242. name,dims);
  243. mxDestroyArray(mx_data);
  244. continue;
  245. }
  246. // don't destroy
  247. names.push_back(name);
  248. data.push_back(mx_data);
  249. }
  250. if(matClose(mat_file) != 0)
  251. {
  252. cerr<<"Error: failed to close file "<<path<<endl;
  253. return false;
  254. }
  255. return true;
  256. }
  257. // Treat everything as a double
  258. template <typename DerivedM>
  259. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save(
  260. const Eigen::PlainObjectBase<DerivedM>& M,
  261. const std::string & name)
  262. {
  263. using namespace std;
  264. const int m = M.rows();
  265. const int n = M.cols();
  266. mxArray * mx_data = mxCreateDoubleMatrix(m,n,mxREAL);
  267. data.push_back(mx_data);
  268. names.push_back(name);
  269. // Copy data immediately
  270. // Q: Won't this be incorrect for integers?
  271. copy(M.data(),M.data()+M.size(),mxGetPr(mx_data));
  272. return *this;
  273. }
  274. // Treat everything as a double
  275. template <typename MT>
  276. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save(
  277. const Eigen::SparseMatrix<MT>& M,
  278. const std::string & name)
  279. {
  280. using namespace std;
  281. const int m = M.rows();
  282. const int n = M.cols();
  283. // THIS WILL NOT WORK FOR ROW-MAJOR
  284. assert(n==M.outerSize());
  285. const int nzmax = M.nonZeros();
  286. mxArray * mx_data = mxCreateSparse(m, n, nzmax, mxREAL);
  287. data.push_back(mx_data);
  288. names.push_back(name);
  289. // Copy data immediately
  290. double * pr = mxGetPr(mx_data);
  291. mwIndex * ir = mxGetIr(mx_data);
  292. mwIndex * jc = mxGetJc(mx_data);
  293. // Iterate over outside
  294. int k = 0;
  295. for(int j=0; j<M.outerSize();j++)
  296. {
  297. jc[j] = k;
  298. // Iterate over inside
  299. for(typename Eigen::SparseMatrix<MT>::InnerIterator it (M,j); it; ++it)
  300. {
  301. pr[k] = it.value();
  302. ir[k] = it.row();
  303. k++;
  304. }
  305. }
  306. jc[M.outerSize()] = k;
  307. return *this;
  308. }
  309. template <typename ScalarM>
  310. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save(
  311. const std::vector<std::vector<ScalarM> > & vM,
  312. const std::string & name)
  313. {
  314. Eigen::MatrixXd M;
  315. list_to_matrix(vM,M);
  316. return this->save(M,name);
  317. }
  318. template <typename ScalarV>
  319. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save(
  320. const std::vector<ScalarV> & vV,
  321. const std::string & name)
  322. {
  323. Eigen::MatrixXd V;
  324. list_to_matrix(vV,V);
  325. return this->save(V,name);
  326. }
  327. template <typename Q>
  328. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save(
  329. const Eigen::Quaternion<Q> & q,
  330. const std::string & name)
  331. {
  332. Eigen::Matrix<Q,1,4> qm;
  333. qm(0,0) = q.w();
  334. qm(0,1) = q.x();
  335. qm(0,2) = q.y();
  336. qm(0,3) = q.z();
  337. return save(qm,name);
  338. }
  339. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save(
  340. const double d,
  341. const std::string & name)
  342. {
  343. Eigen::VectorXd v(1);
  344. v(0) = d;
  345. return save(v,name);
  346. }
  347. template <typename DerivedM>
  348. inline igl::MatlabWorkspace&
  349. igl::MatlabWorkspace::save_index(
  350. const Eigen::PlainObjectBase<DerivedM>& M,
  351. const std::string & name)
  352. {
  353. DerivedM Mp1 = M;
  354. Mp1.array() += 1;
  355. return this->save(Mp1,name);
  356. }
  357. template <typename ScalarM>
  358. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save_index(
  359. const std::vector<std::vector<ScalarM> > & vM,
  360. const std::string & name)
  361. {
  362. Eigen::MatrixXd M;
  363. list_to_matrix(vM,M);
  364. return this->save_index(M,name);
  365. }
  366. template <typename ScalarV>
  367. inline igl::MatlabWorkspace& igl::MatlabWorkspace::save_index(
  368. const std::vector<ScalarV> & vV,
  369. const std::string & name)
  370. {
  371. Eigen::MatrixXd V;
  372. list_to_matrix(vV,V);
  373. return this->save_index(V,name);
  374. }
  375. template <typename DerivedM>
  376. inline bool igl::MatlabWorkspace::find(
  377. const std::string & name,
  378. Eigen::PlainObjectBase<DerivedM>& M)
  379. {
  380. using namespace std;
  381. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  382. if(i>=(int)names.size())
  383. {
  384. return false;
  385. }
  386. assert(i<=(int)data.size());
  387. mxArray * mx_data = data[i];
  388. assert(!mxIsSparse(mx_data));
  389. assert(mxGetNumberOfDimensions(mx_data) == 2);
  390. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  391. const int m = mxGetM(mx_data);
  392. const int n = mxGetN(mx_data);
  393. // Handle vectors
  394. if(DerivedM::IsVectorAtCompileTime)
  395. {
  396. assert(m==1 || n==1 || (m==0 && n==0));
  397. M.resize(m*n,1);
  398. }else
  399. {
  400. M.resize(m,n);
  401. }
  402. copy(
  403. mxGetPr(mx_data),
  404. mxGetPr(mx_data)+mxGetNumberOfElements(mx_data),
  405. M.data());
  406. return true;
  407. }
  408. template <typename MT>
  409. inline bool igl::MatlabWorkspace::find(
  410. const std::string & name,
  411. Eigen::SparseMatrix<MT>& M)
  412. {
  413. using namespace std;
  414. using namespace Eigen;
  415. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  416. if(i>=(int)names.size())
  417. {
  418. return false;
  419. }
  420. assert(i<=(int)data.size());
  421. mxArray * mx_data = data[i];
  422. // Handle boring case where matrix is actually an empty dense matrix
  423. if(mxGetNumberOfElements(mx_data) == 0)
  424. {
  425. M.resize(0,0);
  426. return true;
  427. }
  428. assert(mxIsSparse(mx_data));
  429. assert(mxGetNumberOfDimensions(mx_data) == 2);
  430. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  431. const int m = mxGetM(mx_data);
  432. const int n = mxGetN(mx_data);
  433. // Copy data immediately
  434. double * pr = mxGetPr(mx_data);
  435. mwIndex * ir = mxGetIr(mx_data);
  436. mwIndex * jc = mxGetJc(mx_data);
  437. vector<Triplet<MT> > MIJV;
  438. MIJV.reserve(mxGetNumberOfElements(mx_data));
  439. // Iterate over outside
  440. int k = 0;
  441. for(int j=0; j<n;j++)
  442. {
  443. // Iterate over inside
  444. while(k<(int)jc[j+1])
  445. {
  446. //cout<<ir[k]<<" "<<j<<" "<<pr[k]<<endl;
  447. assert((int)ir[k]<m);
  448. assert((int)j<n);
  449. MIJV.push_back(Triplet<MT >(ir[k],j,pr[k]));
  450. k++;
  451. }
  452. }
  453. M.resize(m,n);
  454. M.setFromTriplets(MIJV.begin(),MIJV.end());
  455. return true;
  456. }
  457. inline bool igl::MatlabWorkspace::find(
  458. const std::string & name,
  459. int & v)
  460. {
  461. using namespace std;
  462. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  463. if(i>=(int)names.size())
  464. {
  465. return false;
  466. }
  467. assert(i<=(int)data.size());
  468. mxArray * mx_data = data[i];
  469. assert(!mxIsSparse(mx_data));
  470. assert(mxGetNumberOfDimensions(mx_data) == 2);
  471. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  472. assert(mxGetNumberOfElements(mx_data) == 1);
  473. copy(
  474. mxGetPr(mx_data),
  475. mxGetPr(mx_data)+mxGetNumberOfElements(mx_data),
  476. &v);
  477. return true;
  478. }
  479. inline bool igl::MatlabWorkspace::find(
  480. const std::string & name,
  481. double & d)
  482. {
  483. using namespace std;
  484. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  485. if(i>=(int)names.size())
  486. {
  487. return false;
  488. }
  489. assert(i<=(int)data.size());
  490. mxArray * mx_data = data[i];
  491. assert(!mxIsSparse(mx_data));
  492. assert(mxGetNumberOfDimensions(mx_data) == 2);
  493. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  494. assert(mxGetNumberOfElements(mx_data) == 1);
  495. copy(
  496. mxGetPr(mx_data),
  497. mxGetPr(mx_data)+mxGetNumberOfElements(mx_data),
  498. &d);
  499. return true;
  500. }
  501. template <typename DerivedM>
  502. inline bool igl::MatlabWorkspace::find_index(
  503. const std::string & name,
  504. Eigen::PlainObjectBase<DerivedM>& M)
  505. {
  506. if(!find(name,M))
  507. {
  508. return false;
  509. }
  510. M.array() -= 1;
  511. return true;
  512. }
  513. //template <typename Data>
  514. //bool igl::MatlabWorkspace::save(const Data & M, const std::string & name)
  515. //{
  516. // using namespace std;
  517. // // If I don't know the type then I can't save it
  518. // cerr<<"^MatlabWorkspace::save Error: Unknown data type. "<<
  519. // name<<" not saved."<<endl;
  520. // return false;
  521. //}
  522. #endif