numeric.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #==============================================================================
  2. #
  3. # Program: ParaView
  4. # Module: numeric.py
  5. #
  6. # Copyright (c) Kitware, Inc.
  7. # All rights reserved.
  8. # See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
  9. #
  10. # This software is distributed WITHOUT ANY WARRANTY; without even
  11. # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  12. # PURPOSE. See the above copyright notice for more information.
  13. #
  14. #==============================================================================
  15. r"""
  16. This module provides functions to vtk data arrays to NumPy arrays.
  17. """
  18. __num_py_available__ = False
  19. try:
  20. import numpy
  21. __num_py_available__ = True
  22. except:
  23. raise """NumPy module "numpy" is not accessible. Please make sure
  24. that NumPy is installed correctly."""
  25. # These types are returned by GetDataType to indicate data type.
  26. VTK_VOID = 0
  27. VTK_BIT = 1
  28. VTK_CHAR = 2
  29. VTK_UNSIGNED_CHAR = 3
  30. VTK_SHORT = 4
  31. VTK_UNSIGNED_SHORT = 5
  32. VTK_INT = 6
  33. VTK_UNSIGNED_INT = 7
  34. VTK_LONG = 8
  35. VTK_UNSIGNED_LONG = 9
  36. VTK_FLOAT =10
  37. VTK_DOUBLE =11
  38. VTK_ID_TYPE =12
  39. __typeDict = { VTK_CHAR:numpy.int8,
  40. VTK_UNSIGNED_CHAR:numpy.uint8,
  41. VTK_SHORT:numpy.int16,
  42. VTK_UNSIGNED_SHORT:numpy.int16,
  43. VTK_INT:numpy.int32,
  44. VTK_FLOAT:numpy.float32,
  45. VTK_DOUBLE:numpy.float64 }
  46. def fromvtkarray(vtkarray):
  47. """This function takes a vtkDataArray of any type and converts it to a
  48. NumPy array of appropriate type and dimensions."""
  49. global __typeDict__
  50. global __num_py_available__
  51. if not __num_py_available__:
  52. raise "NumPy module is not available."
  53. #create a numpy array of the correct type.
  54. vtktype = vtkarray.GetDataType()
  55. if vtktype not in __typeDict:
  56. raise "Cannot convert data arrays of the type %s" \
  57. % vtkarray.GetDataTypeAsString()
  58. # size = num_comps * num_tuples
  59. # imArray = numpy.empty((size,), type)
  60. # vtkarray.ExportToVoidPointer(imArray)
  61. type = __typeDict[vtktype]
  62. pyarray = numpy.frombuffer(vtkarray, dtype=type)
  63. # re-shape the array to current number of rows and columns.
  64. num_tuples = vtkarray.GetNumberOfTuples()
  65. num_comps = vtkarray.GetNumberOfComponents()
  66. pyarray = numpy.reshape(pyarray, (num_tuples, num_comps))
  67. return pyarray