You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
6.2 KiB

8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
  1. from pims.base_frames import FramesSequenceND
  2. from nd2reader.exceptions import EmptyFileError
  3. from nd2reader.parser import Parser
  4. import numpy as np
  5. class ND2Reader(FramesSequenceND):
  6. """PIMS wrapper for the ND2 parser.
  7. This is the main class: use this to process your .nd2 files.
  8. """
  9. class_priority = 12
  10. def __init__(self, filename):
  11. super(self.__class__, self).__init__()
  12. self.filename = filename
  13. # first use the parser to parse the file
  14. self._fh = open(filename, "rb")
  15. self._parser = Parser(self._fh)
  16. # Setup metadata
  17. self.metadata = self._parser.metadata
  18. # Set data type
  19. self._dtype = self._parser.get_dtype_from_metadata()
  20. # Setup the axes
  21. self._setup_axes()
  22. # Other properties
  23. self._timesteps = None
  24. @classmethod
  25. def class_exts(cls):
  26. """Let PIMS open function use this reader for opening .nd2 files
  27. """
  28. return {'nd2'} | super(ND2Reader, cls).class_exts()
  29. def close(self):
  30. """Correctly close the file handle
  31. """
  32. if self._fh is not None:
  33. self._fh.close()
  34. def _get_default(self, coord):
  35. try:
  36. return self.default_coords[coord]
  37. except KeyError:
  38. return 0
  39. def get_frame_2D(self, c=0, t=0, z=0, x=0, y=0, v=0):
  40. """Fallback function for backwards compatibility
  41. """
  42. return get_frame_vczyx(v=v, c=c, t=t, z=z, x=x, y=y)
  43. def get_frame_vczyx(self, v=None, c=None, t=None, z=None, x=None, y=None):
  44. x = self.metadata["width"] if x <= 0 else x
  45. y = self.metadata["height"] if y <= 0 else y
  46. result = []
  47. for v in self._get_possible_coords('v', v):
  48. for c in self._get_possible_coords('c', c):
  49. for z in self._get_possible_coords('z', z):
  50. result.append(self._parser.get_image_by_attributes(t, v, c, z, y, x))
  51. return np.squeeze(np.array(result, dtype=self._dtype))
  52. def _get_possible_coords(self, dim, default):
  53. if dim in self.sizes:
  54. return [default] if default is not None else range(self.sizes[dim])
  55. return [None]
  56. @property
  57. def parser(self):
  58. """
  59. Returns the parser object.
  60. Returns:
  61. Parser: the parser object
  62. """
  63. return self._parser
  64. @property
  65. def pixel_type(self):
  66. """Return the pixel data type
  67. Returns:
  68. dtype: the pixel data type
  69. """
  70. return self._dtype
  71. @property
  72. def timesteps(self):
  73. """Get the timesteps of the experiment
  74. Returns:
  75. np.ndarray: an array of times in milliseconds.
  76. """
  77. if self._timesteps is None:
  78. return self.get_timesteps()
  79. return self._timesteps
  80. @property
  81. def events(self):
  82. """Get the events of the experiment
  83. Returns:
  84. iterator of events as dict
  85. """
  86. return self._get_metadata_property("events")
  87. @property
  88. def frame_rate(self):
  89. """The (average) frame rate
  90. Returns:
  91. float: the (average) frame rate in frames per second
  92. """
  93. total_duration = 0.0
  94. for loop in self.metadata['experiment']['loops']:
  95. total_duration += loop['duration']
  96. if total_duration == 0:
  97. raise ValueError('Total measurement duration could not be determined from loops')
  98. return self.metadata['num_frames'] / (total_duration/1000.0)
  99. def _get_metadata_property(self, key, default=None):
  100. if self.metadata is None:
  101. return default
  102. if key not in self.metadata:
  103. return default
  104. if self.metadata[key] is None:
  105. return default
  106. return self.metadata[key]
  107. def _setup_axes(self):
  108. """Setup the xyctz axes, iterate over t axis by default
  109. """
  110. self._init_axis_if_exists('x', self._get_metadata_property("width", default=0))
  111. self._init_axis_if_exists('y', self._get_metadata_property("height", default=0))
  112. self._init_axis_if_exists('c', len(self._get_metadata_property("channels", default=[])), min_size=2)
  113. self._init_axis_if_exists('t', len(self._get_metadata_property("frames", default=[])))
  114. self._init_axis_if_exists('z', len(self._get_metadata_property("z_levels", default=[])), min_size=2)
  115. self._init_axis_if_exists('v', len(self._get_metadata_property("fields_of_view", default=[])), min_size=2)
  116. if len(self.sizes) == 0:
  117. raise EmptyFileError("No axes were found for this .nd2 file.")
  118. # provide the default
  119. self.iter_axes = self._guess_default_iter_axis()
  120. self._register_get_frame(self.get_frame_vczyx, 'vczyx')
  121. self._register_get_frame(self.get_frame_vczyx, 'vzyx')
  122. self._register_get_frame(self.get_frame_vczyx, 'vcyx')
  123. self._register_get_frame(self.get_frame_vczyx, 'vyx')
  124. self._register_get_frame(self.get_frame_vczyx, 'czyx')
  125. self._register_get_frame(self.get_frame_vczyx, 'cyx')
  126. self._register_get_frame(self.get_frame_vczyx, 'zyx')
  127. self._register_get_frame(self.get_frame_vczyx, 'yx')
  128. def _init_axis_if_exists(self, axis, size, min_size=1):
  129. if size >= min_size:
  130. self._init_axis(axis, size)
  131. def _guess_default_iter_axis(self):
  132. """
  133. Guesses the default axis to iterate over based on axis sizes.
  134. Returns:
  135. the axis to iterate over
  136. """
  137. priority = ['t', 'z', 'c', 'v']
  138. found_axes = []
  139. for axis in priority:
  140. try:
  141. current_size = self.sizes[axis]
  142. except KeyError:
  143. continue
  144. if current_size > 1:
  145. return axis
  146. found_axes.append(axis)
  147. return found_axes[0]
  148. def get_timesteps(self):
  149. """Get the timesteps of the experiment
  150. Returns:
  151. np.ndarray: an array of times in milliseconds.
  152. """
  153. if self._timesteps is not None and len(self._timesteps) > 0:
  154. return self._timesteps
  155. self._timesteps = np.array(list(self._parser._raw_metadata.acquisition_times), dtype=np.float) * 1000.0
  156. return self._timesteps