iglhelpers.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # This file is part of libigl, a simple c++ geometry processing library.
  2. #
  3. # Copyright (C) 2017 Sebastian Koch <s.koch@tu-berlin.de> and Daniele Panozzo <daniele.panozzo@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. import numpy as np
  9. import scipy.sparse as sparse
  10. import pyigl as igl
  11. def p2e(m):
  12. if isinstance(m, np.ndarray):
  13. if not (m.flags['C_CONTIGUOUS'] or m.flags['F_CONTIGUOUS']):
  14. raise TypeError('p2e support either c-order or f-order')
  15. if m.dtype.type in [np.int32, np.int64]:
  16. return igl.eigen.MatrixXi(m.astype(np.int32))
  17. elif m.dtype.type in [np.float64, np.float32]:
  18. return igl.eigen.MatrixXd(m.astype(np.float64))
  19. elif m.dtype.type == np.bool:
  20. return igl.eigen.MatrixXb(m)
  21. raise TypeError("p2e only support dtype float64/32, int64/32 and bool")
  22. if sparse.issparse(m):
  23. # convert in a dense matrix with triples
  24. coo = m.tocoo()
  25. triplets = np.vstack((coo.row, coo.col, coo.data)).T
  26. triples_eigen_wrapper = igl.eigen.MatrixXd(triplets)
  27. if m.dtype.type == np.int32:
  28. t = igl.eigen.SparseMatrixi()
  29. t.fromcoo(triples_eigen_wrapper)
  30. return t
  31. elif m.dtype.type == np.float64:
  32. t = igl.eigen.SparseMatrixd()
  33. t.fromCOO(triples_eigen_wrapper)
  34. return t
  35. raise TypeError("p2e only support numpy.array or scipy.sparse")
  36. def e2p(m):
  37. if isinstance(m, igl.eigen.MatrixXd):
  38. return np.array(m, dtype='float64', order='C')
  39. elif isinstance(m, igl.eigen.MatrixXi):
  40. return np.array(m, dtype='int32', order='C')
  41. elif isinstance(m, igl.eigen.MatrixXb):
  42. return np.array(m, dtype='bool', order='C')
  43. elif isinstance(m, igl.eigen.SparseMatrixd):
  44. coo = np.array(m.toCOO())
  45. I = coo[:, 0]
  46. J = coo[:, 1]
  47. V = coo[:, 2]
  48. return sparse.coo_matrix((V,(I,J)), shape=(m.rows(),m.cols()), dtype='float64')
  49. elif isinstance(m, igl.eigen.SparseMatrixi):
  50. coo = np.array(m.toCOO())
  51. I = coo[:, 0]
  52. J = coo[:, 1]
  53. V = coo[:, 2]
  54. return sparse.coo_matrix((V,(I,J)), shape=(m.rows(),m.cols()), dtype='int32')
  55. def printMatrixSizes(x,xn):
  56. print(xn + " (" + str(x.rows()) + "," + str(x.cols()) + ")")