MatlabWorkspace.h 12 KB

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