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.

199 lines
5.5 KiB

8 years ago
8 years ago
8 years ago
8 years ago
  1. from pims.base_frames import FramesSequenceND, Frame
  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):
  40. """Gets a given frame using the parser
  41. Args:
  42. x: The x-index (pims expects this)
  43. y: The y-index (pims expects this)
  44. c: The color channel number
  45. t: The frame number
  46. z: The z stack number
  47. Returns:
  48. numpy.ndarray: The requested frame
  49. """
  50. try:
  51. c_name = self.metadata["channels"][c]
  52. except KeyError:
  53. c_name = self.metadata["channels"][0]
  54. x = self.metadata["width"] if x <= 0 else x
  55. y = self.metadata["height"] if y <= 0 else y
  56. return self._parser.get_image_by_attributes(t, 0, c_name, z, y, x)
  57. @property
  58. def parser(self):
  59. """
  60. Returns the parser object.
  61. Returns:
  62. Parser: the parser object
  63. """
  64. return self._parser
  65. @property
  66. def pixel_type(self):
  67. """Return the pixel data type
  68. Returns:
  69. dtype: the pixel data type
  70. """
  71. return self._dtype
  72. @property
  73. def timesteps(self):
  74. """Get the timesteps of the experiment
  75. Returns:
  76. np.ndarray: an array of times in milliseconds.
  77. """
  78. if self._timesteps is None:
  79. return self.get_timesteps()
  80. return self._timesteps
  81. @property
  82. def frame_rate(self):
  83. """The (average) frame rate
  84. Returns:
  85. float: the (average) frame rate in frames per second
  86. """
  87. return 1000. / np.mean(np.diff(self.timesteps))
  88. def _get_metadata_property(self, key, default=None):
  89. if self.metadata is None:
  90. return default
  91. if key not in self.metadata:
  92. return default
  93. if self.metadata[key] is None:
  94. return default
  95. return self.metadata[key]
  96. def _setup_axes(self):
  97. """Setup the xyctz axes, iterate over t axis by default
  98. """
  99. self._init_axis_if_exists('x', self._get_metadata_property("width", default=0))
  100. self._init_axis_if_exists('y', self._get_metadata_property("height", default=0))
  101. self._init_axis_if_exists('c', len(self._get_metadata_property("channels", default=[])), min_size=2)
  102. self._init_axis_if_exists('t', len(self._get_metadata_property("frames", default=[])))
  103. self._init_axis_if_exists('z', len(self._get_metadata_property("z_levels", default=[])), min_size=2)
  104. if len(self.sizes) == 0:
  105. raise EmptyFileError("No axes were found for this .nd2 file.")
  106. # provide the default
  107. self.iter_axes = self._guess_default_iter_axis()
  108. def _init_axis_if_exists(self, axis, size, min_size=1):
  109. if size >= min_size:
  110. self._init_axis(axis, size)
  111. def _guess_default_iter_axis(self):
  112. """
  113. Guesses the default axis to iterate over based on axis sizes.
  114. Returns:
  115. the axis to iterate over
  116. """
  117. priority = ['t', 'z', 'c']
  118. found_axes = []
  119. for axis in priority:
  120. try:
  121. current_size = self.sizes[axis]
  122. except KeyError:
  123. continue
  124. if current_size > 1:
  125. return axis
  126. found_axes.append(axis)
  127. return found_axes[0]
  128. def get_timesteps(self):
  129. """Get the timesteps of the experiment
  130. Returns:
  131. np.ndarray: an array of times in milliseconds.
  132. """
  133. if self._timesteps is not None:
  134. return self._timesteps
  135. timesteps = np.array([])
  136. current_time = 0.0
  137. for loop in self.metadata['experiment']['loops']:
  138. if loop['stimulation']:
  139. continue
  140. if loop['sampling_interval'] == 0:
  141. # This is a loop were no data is acquired
  142. current_time += loop['duration']
  143. continue
  144. timesteps = np.concatenate(
  145. (timesteps, np.arange(current_time, current_time + loop['duration'], loop['sampling_interval'])))
  146. current_time += loop['duration']
  147. # if experiment did not finish, number of timesteps is wrong. Take correct amount of leading timesteps.
  148. self._timesteps = timesteps[:self.metadata['num_frames']]
  149. return self._timesteps