MatlabWorkspace.h 16 KB

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