MatlabWorkspace.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <[email protected]>
  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. /// Class which contains data of a matlab workspace which can be written to a
  20. /// .mat file and loaded from matlab
  21. ///
  22. /// This depends on matlab at compile time (though it shouldn't necessarily
  23. /// have to) but it does not depend on running the matlab engine at run-time.
  24. ///
  25. /// \bug Treats all matrices as doubles (this may actually be desired
  26. /// for some "index" matrices since matlab's sparse command takes doubles
  27. /// rather than int class matrices). It is of course not desired when dealing
  28. /// with logicals or uint's for images.
  29. ///
  30. class MatlabWorkspace
  31. {
  32. private:
  33. /// List of names
  34. /// \bug Why not use a map? Any reason to allow duplicate names?
  35. std::vector<std::string> names;
  36. /// List of data pointers
  37. std::vector<mxArray*> data;
  38. public:
  39. MatlabWorkspace();
  40. ~MatlabWorkspace();
  41. /// Clear names and data of variables in workspace
  42. inline void clear();
  43. /// Save current list of variables
  44. ///
  45. /// @param[in] path path to .mat file
  46. /// @return true on success, false on failure
  47. inline bool write(const std::string & path) const;
  48. /// Load list of variables from .mat file
  49. ///
  50. /// @param[in] path path to .mat file
  51. /// @return true on success, false on failure
  52. inline bool read(const std::string & path);
  53. /// Assign data to a variable name in the workspace
  54. ///
  55. /// @tparam DerivedM eigen matrix (e.g. Eigen::MatrixXd)
  56. /// @param[in] M data (usually a matrix)
  57. /// @param[in] name variable name to save into work space
  58. /// @return true on success, false on failure
  59. ///
  60. /// \bug Assumes DerivedM is using column major ordering
  61. template <typename DerivedM>
  62. inline MatlabWorkspace& save(
  63. const Eigen::MatrixBase<DerivedM>& M,
  64. const std::string & name);
  65. /// \overload
  66. /// @tparam MT sparse matrix type (e.g. double)
  67. template <typename MT>
  68. inline MatlabWorkspace& save(
  69. const Eigen::SparseMatrix<MT>& M,
  70. const std::string & name);
  71. /// \overload
  72. /// @tparam ScalarM scalar type, e.g. double
  73. template <typename ScalarM>
  74. inline MatlabWorkspace& save(
  75. const std::vector<std::vector<ScalarM> > & vM,
  76. const std::string & name);
  77. /// \overload
  78. /// @tparam ScalarV scalar type, e.g. double
  79. template <typename ScalarV>
  80. inline MatlabWorkspace& save(
  81. const std::vector<ScalarV> & vV,
  82. const std::string & name);
  83. /// @tparam Q quaternion type
  84. ///
  85. /// NOTE: Eigen stores quaternions coefficients as (i,j,k,1), but most of
  86. /// our matlab code stores them as (1,i,j,k) This takes a quaternion and
  87. /// saves it as a (1,i,j,k) row vector
  88. template <typename Q>
  89. inline MatlabWorkspace& save(
  90. const Eigen::Quaternion<Q> & q,
  91. const std::string & name);
  92. /// \overload
  93. inline MatlabWorkspace& save(
  94. const double d,
  95. const std::string & name);
  96. /// Same as save() but adds 1 to each element, useful for saving "index"
  97. /// matrices like lists of faces or elements
  98. /// @tparam DerivedM eigen matrix (e.g. Eigen::MatrixXd)
  99. template <typename DerivedM>
  100. inline MatlabWorkspace& save_index(
  101. const Eigen::DenseBase<DerivedM>& M,
  102. const std::string & name);
  103. /// \overload
  104. /// @tparam MT sparse matrix type (e.g. double)
  105. template <typename ScalarM>
  106. inline MatlabWorkspace& save_index(
  107. const std::vector<std::vector<ScalarM> > & vM,
  108. const std::string & name);
  109. /// \overload
  110. /// @tparam ScalarV scalar type, e.g. double
  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. /// \bug Outputs the first found (not necessarily unique lists).
  118. ///
  119. /// @tparam DerivedM eigen matrix (e.g. Eigen::MatrixXd)
  120. /// @param[in] name exact name of matrix as string
  121. /// @param[out] M matrix
  122. /// @return true only if found.
  123. template <typename DerivedM>
  124. inline bool find(
  125. const std::string & name,
  126. Eigen::PlainObjectBase<DerivedM>& M);
  127. /// \overload
  128. /// @tparam MT sparse matrix type (e.g. double)
  129. template <typename MT>
  130. inline bool find(
  131. const std::string & name,
  132. Eigen::SparseMatrix<MT>& M);
  133. /// \overload
  134. inline bool find(
  135. const std::string & name,
  136. double & d);
  137. /// \overload
  138. inline bool find(
  139. const std::string & name,
  140. int & v);
  141. /// Subtracts 1 from all entries
  142. /// @tparam DerivedM eigen matrix (e.g. Eigen::MatrixXd)
  143. /// @param[in] name exact name of matrix as string
  144. /// @param[out] M matrix
  145. template <typename DerivedM>
  146. inline bool find_index(
  147. const std::string & name,
  148. Eigen::PlainObjectBase<DerivedM>& M);
  149. };
  150. }
  151. }
  152. // Implementation
  153. // Be sure that this is not compiled into libigl.a
  154. // http://stackoverflow.com/a/3318993/148668
  155. // IGL
  156. #include "igl/list_to_matrix.h"
  157. // MATLAB
  158. #include "mat.h"
  159. // STL
  160. #include <iostream>
  161. #include <algorithm>
  162. #include <vector>
  163. inline igl::matlab::MatlabWorkspace::MatlabWorkspace():
  164. names(),
  165. data()
  166. {
  167. }
  168. inline igl::matlab::MatlabWorkspace::~MatlabWorkspace()
  169. {
  170. // clean up data
  171. clear();
  172. }
  173. inline void igl::matlab::MatlabWorkspace::clear()
  174. {
  175. for_each(data.begin(),data.end(),&mxDestroyArray);
  176. data.clear();
  177. names.clear();
  178. }
  179. inline bool igl::matlab::MatlabWorkspace::write(const std::string & path) const
  180. {
  181. MATFile * mat_file = matOpen(path.c_str(), "w");
  182. if(mat_file == NULL)
  183. {
  184. fprintf(stderr,"Error opening file %s\n",path.c_str());
  185. return false;
  186. }
  187. assert(names.size() == data.size());
  188. // loop over names and data
  189. for(int i = 0;i < (int)names.size(); i++)
  190. {
  191. // Put variable as LOCAL variable
  192. int status = matPutVariable(mat_file,names[i].c_str(), data[i]);
  193. if(status != 0)
  194. {
  195. std::cerr<<"^MatlabWorkspace::save Error: matPutVariable ("<<names[i]<<
  196. ") failed"<<std::endl;
  197. return false;
  198. }
  199. }
  200. if(matClose(mat_file) != 0)
  201. {
  202. fprintf(stderr,"Error closing file %s\n",path.c_str());
  203. return false;
  204. }
  205. return true;
  206. }
  207. inline bool igl::matlab::MatlabWorkspace::read(const std::string & path)
  208. {
  209. MATFile * mat_file;
  210. mat_file = matOpen(path.c_str(), "r");
  211. if (mat_file == NULL)
  212. {
  213. std::cerr<<"Error: failed to open "<<path<<std::endl;
  214. return false;
  215. }
  216. int ndir;
  217. const char ** dir = (const char **)matGetDir(mat_file, &ndir);
  218. if (dir == NULL) {
  219. std::cerr<<"Error reading directory of file "<< path<<std::endl;
  220. return false;
  221. }
  222. mxFree(dir);
  223. // Must close and reopen
  224. if(matClose(mat_file) != 0)
  225. {
  226. std::cerr<<"Error: failed to close file "<<path<<std::endl;
  227. return false;
  228. }
  229. mat_file = matOpen(path.c_str(), "r");
  230. if (mat_file == NULL)
  231. {
  232. std::cerr<<"Error: failed to open "<<path<<std::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. std::cerr<<"Error: matGetNextVariable failed in "<<path<<std::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. std::cerr<<"Error: failed to close file "<<path<<std::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::MatrixBase<DerivedM>& M,
  269. const std::string & name)
  270. {
  271. const int m = M.rows();
  272. const int n = M.cols();
  273. mxArray * mx_data = mxCreateDoubleMatrix(m,n,mxREAL);
  274. data.push_back(mx_data);
  275. names.push_back(name);
  276. // Copy data immediately
  277. // Use Eigen's map and cast to copy
  278. Eigen::Map< Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> >
  279. map(mxGetPr(mx_data),m,n);
  280. map = M.template cast<double>();
  281. return *this;
  282. }
  283. // Treat everything as a double
  284. template <typename MT>
  285. inline igl::matlab::MatlabWorkspace& igl::matlab::MatlabWorkspace::save(
  286. const Eigen::SparseMatrix<MT>& M,
  287. const std::string & name)
  288. {
  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::DenseBase<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. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  389. if(i>=(int)names.size())
  390. {
  391. return false;
  392. }
  393. assert(i<=(int)data.size());
  394. mxArray * mx_data = data[i];
  395. assert(!mxIsSparse(mx_data));
  396. assert(mxGetNumberOfDimensions(mx_data) == 2);
  397. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  398. const int m = mxGetM(mx_data);
  399. const int n = mxGetN(mx_data);
  400. // Handle vectors: in the sense that anything found becomes a column vector,
  401. // whether it was column vector, row vector or matrix
  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. assert(mxGetNumberOfElements(mx_data) == M.size());
  411. // Use Eigen's map and cast to copy
  412. M = Eigen::Map< Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> >
  413. (mxGetPr(mx_data),M.rows(),M.cols()).cast<typename DerivedM::Scalar>();
  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. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  422. if(i>=(int)names.size())
  423. {
  424. return false;
  425. }
  426. assert(i<=(int)data.size());
  427. mxArray * mx_data = data[i];
  428. // Handle boring case where matrix is actually an empty dense matrix
  429. if(mxGetNumberOfElements(mx_data) == 0)
  430. {
  431. M.resize(0,0);
  432. return true;
  433. }
  434. assert(mxIsSparse(mx_data));
  435. assert(mxGetNumberOfDimensions(mx_data) == 2);
  436. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  437. const int m = mxGetM(mx_data);
  438. const int n = mxGetN(mx_data);
  439. // TODO: It should be possible to directly load the data into the sparse
  440. // matrix without going through the triplets
  441. // Copy data immediately
  442. double * pr = mxGetPr(mx_data);
  443. mwIndex * ir = mxGetIr(mx_data);
  444. mwIndex * jc = mxGetJc(mx_data);
  445. vector<Eigen::Triplet<MT> > MIJV;
  446. const int nnz = mxGetNzmax(mx_data);
  447. MIJV.reserve(nnz);
  448. // Iterate over outside
  449. int k = 0;
  450. for(int j=0; j<n;j++)
  451. {
  452. // Iterate over inside
  453. while(k<(int)jc[j+1])
  454. {
  455. //cout<<ir[k]<<" "<<j<<" "<<pr[k]<<endl;
  456. assert((int)ir[k]<m);
  457. assert((int)j<n);
  458. MIJV.push_back(Eigen::Triplet<MT >(ir[k],j,pr[k]));
  459. k++;
  460. }
  461. }
  462. M.resize(m,n);
  463. M.setFromTriplets(MIJV.begin(),MIJV.end());
  464. return true;
  465. }
  466. inline bool igl::matlab::MatlabWorkspace::find(
  467. const std::string & name,
  468. int & v)
  469. {
  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. const int i = std::find(names.begin(), names.end(), name)-names.begin();
  492. if(i>=(int)names.size())
  493. {
  494. return false;
  495. }
  496. assert(i<=(int)data.size());
  497. mxArray * mx_data = data[i];
  498. assert(!mxIsSparse(mx_data));
  499. assert(mxGetNumberOfDimensions(mx_data) == 2);
  500. //cout<<name<<": "<<mxGetM(mx_data)<<" "<<mxGetN(mx_data)<<endl;
  501. assert(mxGetNumberOfElements(mx_data) == 1);
  502. copy(
  503. mxGetPr(mx_data),
  504. mxGetPr(mx_data)+mxGetNumberOfElements(mx_data),
  505. &d);
  506. return true;
  507. }
  508. template <typename DerivedM>
  509. inline bool igl::matlab::MatlabWorkspace::find_index(
  510. const std::string & name,
  511. Eigen::PlainObjectBase<DerivedM>& M)
  512. {
  513. if(!find(name,M))
  514. {
  515. return false;
  516. }
  517. M.array() -= 1;
  518. return true;
  519. }
  520. //template <typename Data>
  521. //bool igl::matlab::MatlabWorkspace::save(const Data & M, const std::string & name)
  522. //{
  523. // using namespace std;
  524. // // If I don't know the type then I can't save it
  525. // std::cerr<<"^MatlabWorkspace::save Error: Unknown data type. "<<
  526. // name<<" not saved."<<std::endl;
  527. // return false;
  528. //}
  529. #endif