iglhelpers.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import numpy as np
  2. import scipy.sparse as sparse
  3. import pyigl as igl
  4. def p2e(m):
  5. if isinstance(m, np.ndarray):
  6. if not m.flags['C_CONTIGUOUS']:
  7. raise TypeError("p2e only support C-contiguous order")
  8. if m.dtype.type == np.int32:
  9. return igl.eigen.MatrixXi(m)
  10. elif m.dtype.type == np.float64:
  11. return igl.eigen.MatrixXd(m)
  12. elif m.dtype.type == np.bool:
  13. return igl.eigen.MatrixXb(m)
  14. raise TypeError("p2e only support dtype float64, int32 and bool")
  15. if sparse.issparse(m):
  16. # convert in a dense matrix with triples
  17. coo = m.tocoo()
  18. triplets = np.vstack((coo.row, coo.col, coo.data)).T
  19. triples_eigen_wrapper = igl.eigen.MatrixXd(triplets)
  20. if m.dtype.type == np.int32:
  21. t = igl.eigen.SparseMatrixi()
  22. t.fromcoo(triples_eigen_wrapper)
  23. return t
  24. elif m.dtype.type == np.float64:
  25. t = igl.eigen.SparseMatrixd()
  26. t.fromCOO(triples_eigen_wrapper)
  27. return t
  28. raise TypeError("p2e only support numpy.array or scipy.sparse")
  29. def e2p(m):
  30. if isinstance(m, igl.eigen.MatrixXd):
  31. return np.array(m, dtype='float64', order='C')
  32. elif isinstance(m, igl.eigen.MatrixXi):
  33. return np.array(m, dtype='int32', order='C')
  34. elif isinstance(m, igl.eigen.MatrixXb):
  35. return np.array(m, dtype='bool', order='C')
  36. elif isinstance(m, igl.eigen.SparseMatrixd):
  37. coo = np.array(m.toCOO())
  38. I = coo[:, 0]
  39. J = coo[:, 1]
  40. V = coo[:, 2]
  41. return sparse.coo_matrix((V,(I,J)), shape=(m.rows(),m.cols()), dtype='float64')
  42. elif isinstance(m, igl.eigen.SparseMatrixi):
  43. coo = np.array(m.toCOO())
  44. I = coo[:, 0]
  45. J = coo[:, 1]
  46. V = coo[:, 2]
  47. return sparse.coo_matrix((V,(I,J)), shape=(m.rows(),m.cols()), dtype='int32')
  48. def printMatrixSizes(x,xn):
  49. print(xn + " (" + str(x.rows()) + "," + str(x.cols()) + ")")