MatlabWorkspace.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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::PlainObjectBase<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. // Q: Won't this be incorrect for integers?
  279. copy(M.data(),M.data()+M.size(),mxGetPr(mx_data));
  280. return *this;
  281. }
  282. // Treat everything as a double
  283. template <typename MT>
  284. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save(
  285. const Eigen::SparseMatrix<MT>& M,
  286. const std::string & name)
  287. {
  288. using namespace std;
  289. const int m = M.rows();
  290. const int n = M.cols();
  291. // THIS WILL NOT WORK FOR ROW-MAJOR
  292. assert(n==M.outerSize());
  293. const int nzmax = M.nonZeros();
  294. mxArray * mx_data = mxCreateSparse(m, n, nzmax, mxREAL);
  295. data.push_back(mx_data);
  296. names.push_back(name);
  297. // Copy data immediately
  298. double * pr = mxGetPr(mx_data);
  299. mwIndex * ir = mxGetIr(mx_data);
  300. mwIndex * jc = mxGetJc(mx_data);
  301. // Iterate over outside
  302. int k = 0;
  303. for(int j=0; j<M.outerSize();j++)
  304. {
  305. jc[j] = k;
  306. // Iterate over inside
  307. for(typename Eigen::SparseMatrix<MT>::InnerIterator it (M,j); it; ++it)
  308. {
  309. pr[k] = it.value();
  310. ir[k] = it.row();
  311. k++;
  312. }
  313. }
  314. jc[M.outerSize()] = k;
  315. return *this;
  316. }
  317. template <typename ScalarM>
  318. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save(
  319. const std::vector<std::vector<ScalarM> > & vM,
  320. const std::string & name)
  321. {
  322. Eigen::MatrixXd M;
  323. list_to_matrix(vM,M);
  324. return this->save(M,name);
  325. }
  326. template <typename ScalarV>
  327. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save(
  328. const std::vector<ScalarV> & vV,
  329. const std::string & name)
  330. {
  331. Eigen::MatrixXd V;
  332. list_to_matrix(vV,V);
  333. return this->save(V,name);
  334. }
  335. template <typename Q>
  336. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save(
  337. const Eigen::Quaternion<Q> & q,
  338. const std::string & name)
  339. {
  340. Eigen::Matrix<Q,1,4> qm;
  341. qm(0,0) = q.w();
  342. qm(0,1) = q.x();
  343. qm(0,2) = q.y();
  344. qm(0,3) = q.z();
  345. return save(qm,name);
  346. }
  347. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save(
  348. const double d,
  349. const std::string & name)
  350. {
  351. Eigen::VectorXd v(1);
  352. v(0) = d;
  353. return save(v,name);
  354. }
  355. template <typename DerivedM>
  356. inline igl::matlab::MatlabWorkspace&
  357. igl::matlab::MatlabWorkspace::save_index(
  358. const Eigen::PlainObjectBase<DerivedM>& M,
  359. const std::string & name)
  360. {
  361. DerivedM Mp1 = M;
  362. Mp1.array() += 1;
  363. return this->save(Mp1,name);
  364. }
  365. template <typename ScalarM>
  366. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save_index(
  367. const std::vector<std::vector<ScalarM> > & vM,
  368. const std::string & name)
  369. {
  370. Eigen::MatrixXd M;
  371. list_to_matrix(vM,M);
  372. return this->save_index(M,name);
  373. }
  374. template <typename ScalarV>
  375. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save_index(
  376. const std::vector<ScalarV> & vV,
  377. const std::string & name)
  378. {
  379. Eigen::MatrixXd V;
  380. list_to_matrix(vV,V);
  381. return this->save_index(V,name);
  382. }
  383. template <typename DerivedM>
  384. inline bool igl::matlab::MatlabWorkspace::find(
  385. const std::string & name,
  386. Eigen::PlainObjectBase<DerivedM>& M)
  387. {
  388. using namespace std;
  389. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  390. if(i>=(int)names.size())
  391. {
  392. return false;
  393. }
  394. assert(i<=(int)data.size());
  395. mxArray * mx_data = data[i];
  396. assert(!mxIsSparse(mx_data));
  397. assert(mxGetNumberOfDimensions(mx_data) == 2);
  398. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  399. const int m = mxGetM(mx_data);
  400. const int n = mxGetN(mx_data);
  401. // Handle vectors
  402. if(DerivedM::IsVectorAtCompileTime)
  403. {
  404. assert(m==1 || n==1 || (m==0 && n==0));
  405. M.resize(m*n,1);
  406. }else
  407. {
  408. M.resize(m,n);
  409. }
  410. copy(
  411. mxGetPr(mx_data),
  412. mxGetPr(mx_data)+mxGetNumberOfElements(mx_data),
  413. M.data());
  414. return true;
  415. }
  416. template <typename MT>
  417. inline bool igl::matlab::MatlabWorkspace::find(
  418. const std::string & name,
  419. Eigen::SparseMatrix<MT>& M)
  420. {
  421. using namespace std;
  422. using namespace Eigen;
  423. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  424. if(i>=(int)names.size())
  425. {
  426. return false;
  427. }
  428. assert(i<=(int)data.size());
  429. mxArray * mx_data = data[i];
  430. // Handle boring case where matrix is actually an empty dense matrix
  431. if(mxGetNumberOfElements(mx_data) == 0)
  432. {
  433. M.resize(0,0);
  434. return true;
  435. }
  436. assert(mxIsSparse(mx_data));
  437. assert(mxGetNumberOfDimensions(mx_data) == 2);
  438. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  439. const int m = mxGetM(mx_data);
  440. const int n = mxGetN(mx_data);
  441. // Copy data immediately
  442. double * pr = mxGetPr(mx_data);
  443. mwIndex * ir = mxGetIr(mx_data);
  444. mwIndex * jc = mxGetJc(mx_data);
  445. vector<Triplet<MT> > MIJV;
  446. MIJV.reserve(mxGetNumberOfElements(mx_data));
  447. // Iterate over outside
  448. int k = 0;
  449. for(int j=0; j<n;j++)
  450. {
  451. // Iterate over inside
  452. while(k<(int)jc[j+1])
  453. {
  454. //cout<<ir[k]<<" "<<j<<" "<<pr[k]<<endl;
  455. assert((int)ir[k]<m);
  456. assert((int)j<n);
  457. MIJV.push_back(Triplet<MT >(ir[k],j,pr[k]));
  458. k++;
  459. }
  460. }
  461. M.resize(m,n);
  462. M.setFromTriplets(MIJV.begin(),MIJV.end());
  463. return true;
  464. }
  465. inline bool igl::matlab::MatlabWorkspace::find(
  466. const std::string & name,
  467. int & v)
  468. {
  469. using namespace std;
  470. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  471. if(i>=(int)names.size())
  472. {
  473. return false;
  474. }
  475. assert(i<=(int)data.size());
  476. mxArray * mx_data = data[i];
  477. assert(!mxIsSparse(mx_data));
  478. assert(mxGetNumberOfDimensions(mx_data) == 2);
  479. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  480. assert(mxGetNumberOfElements(mx_data) == 1);
  481. copy(
  482. mxGetPr(mx_data),
  483. mxGetPr(mx_data)+mxGetNumberOfElements(mx_data),
  484. &v);
  485. return true;
  486. }
  487. inline bool igl::matlab::MatlabWorkspace::find(
  488. const std::string & name,
  489. double & d)
  490. {
  491. using namespace std;
  492. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  493. if(i>=(int)names.size())
  494. {
  495. return false;
  496. }
  497. assert(i<=(int)data.size());
  498. mxArray * mx_data = data[i];
  499. assert(!mxIsSparse(mx_data));
  500. assert(mxGetNumberOfDimensions(mx_data) == 2);
  501. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  502. assert(mxGetNumberOfElements(mx_data) == 1);
  503. copy(
  504. mxGetPr(mx_data),
  505. mxGetPr(mx_data)+mxGetNumberOfElements(mx_data),
  506. &d);
  507. return true;
  508. }
  509. template <typename DerivedM>
  510. inline bool igl::matlab::MatlabWorkspace::find_index(
  511. const std::string & name,
  512. Eigen::PlainObjectBase<DerivedM>& M)
  513. {
  514. if(!find(name,M))
  515. {
  516. return false;
  517. }
  518. M.array() -= 1;
  519. return true;
  520. }
  521. //template <typename Data>
  522. //bool igl::matlab::MatlabWorkspace::save(const Data & M, const std::string & name)
  523. //{
  524. // using namespace std;
  525. // // If I don't know the type then I can't save it
  526. // cerr<<"^MatlabWorkspace::save Error: Unknown data type. "<<
  527. // name<<" not saved."<<endl;
  528. // return false;
  529. //}
  530. #endif