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.

368 lines
14 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. # -*- coding: utf-8 -*-
  2. import array
  3. from datetime import datetime
  4. import numpy as np
  5. import re
  6. import struct
  7. import six
  8. class Nd2Parser(object):
  9. """
  10. Reads .nd2 files, provides an interface to the metadata, and generates numpy arrays from the image data.
  11. You should not ever need to instantiate this class manually unless you're a developer.
  12. """
  13. CHUNK_HEADER = 0xabeceda
  14. CHUNK_MAP_START = six.b("ND2 FILEMAP SIGNATURE NAME 0001!")
  15. CHUNK_MAP_END = six.b("ND2 CHUNK MAP SIGNATURE 0000001!")
  16. def __init__(self, filename):
  17. self._filename = filename
  18. self._fh = None
  19. self._channels = None
  20. self._channel_count = None
  21. self._chunk_map_start_location = None
  22. self._cursor_position = 0
  23. self._dimension_text = None
  24. self._fields_of_view = None
  25. self._label_map = {}
  26. self.metadata = {}
  27. self._read_map()
  28. self._time_indexes = None
  29. self._parse_metadata()
  30. self._z_levels = None
  31. @property
  32. def _file_handle(self):
  33. if self._fh is None:
  34. self._fh = open(self._filename, "rb")
  35. return self._fh
  36. def _get_raw_image_data(self, image_group_number, channel_offset):
  37. """
  38. Reads the raw bytes and the timestamp of an image.
  39. :param image_group_number: groups are made of images with the same time index, field of view and z-level.
  40. :type image_group_number: int
  41. :param channel_offset: the offset in the array where the bytes for this image are found.
  42. :type channel_offset: int
  43. :return: (int, array.array()) or None
  44. """
  45. chunk = self._label_map[six.b("ImageDataSeq|%d!" % image_group_number)]
  46. data = self._read_chunk(chunk)
  47. # All images in the same image group share the same timestamp! So if you have complicated image data,
  48. # your timestamps may not be entirely accurate. Practically speaking though, they'll only be off by a few
  49. # seconds unless you're doing something super weird.
  50. timestamp = struct.unpack("d", data[:8])[0]
  51. image_group_data = array.array("H", data)
  52. image_data_start = 4 + channel_offset
  53. # The images for the various channels are interleaved within the same array. For example, the second image
  54. # of a four image group will be composed of bytes 2, 6, 10, etc. If you understand why someone would design
  55. # a data structure that way, please send the author of this library a message.
  56. image_data = image_group_data[image_data_start::len(self.channels)]
  57. # Skip images that are all zeros! This is important, since NIS Elements creates blank "gap" images if you
  58. # don't have the same number of images each cycle. We discovered this because we only took GFP images every
  59. # other cycle to reduce phototoxicity, but NIS Elements still allocated memory as if we were going to take
  60. # them every cycle.
  61. if np.any(image_data):
  62. return timestamp, image_data
  63. return None
  64. @property
  65. def _dimensions(self):
  66. """
  67. While there are metadata values that represent a lot of what we want to capture, they seem to be unreliable.
  68. Sometimes certain elements don't exist, or change their data type randomly. However, the human-readable text
  69. is always there and in the same exact format, so we just parse that instead.
  70. :rtype: str
  71. """
  72. if self._dimension_text is None:
  73. for line in self.metadata[six.b('ImageTextInfo')][six.b('SLxImageTextInfo')].values():
  74. if six.b("Dimensions:") in line:
  75. metadata = line
  76. break
  77. else:
  78. raise ValueError("Could not parse metadata dimensions!")
  79. for line in metadata.split(six.b("\r\n")):
  80. if line.startswith(six.b("Dimensions:")):
  81. self._dimension_text = line
  82. break
  83. else:
  84. raise ValueError("Could not parse metadata dimensions!")
  85. return self._dimension_text
  86. @property
  87. def channels(self):
  88. """
  89. These are labels created by the NIS Elements user. Typically they may a short description of the filter cube
  90. used (e.g. "bright field", "GFP", etc.)
  91. :rtype: str
  92. """
  93. if not self._channels:
  94. self._channels = []
  95. metadata = self.metadata[six.b('ImageMetadataSeq')][six.b('SLxPictureMetadata')][six.b('sPicturePlanes')]
  96. try:
  97. validity = self.metadata[six.b('ImageMetadata')][six.b('SLxExperiment')][six.b('ppNextLevelEx')][six.b('')][0][six.b('ppNextLevelEx')][six.b('')][0][six.b('pItemValid')]
  98. except KeyError:
  99. # If none of the channels have been deleted, there is no validity list, so we just make one
  100. validity = [True for _ in metadata]
  101. # Channel information is contained in dictionaries with the keys a0, a1...an where the number
  102. # indicates the order in which the channel is stored. So by sorting the dicts alphabetically
  103. # we get the correct order.
  104. for (label, chan), valid in zip(sorted(metadata[six.b('sPlaneNew')].items()), validity):
  105. if not valid:
  106. continue
  107. self._channels.append(chan[six.b('sDescription')].decode("utf8"))
  108. return self._channels
  109. def _calculate_image_group_number(self, time_index, fov, z_level):
  110. """
  111. Images are grouped together if they share the same time index, field of view, and z-level.
  112. :type time_index: int
  113. :type fov: int
  114. :type z_level: int
  115. :rtype: int
  116. """
  117. return time_index * len(self.fields_of_view) * len(self.z_levels) + (fov * len(self.z_levels) + z_level)
  118. @property
  119. def _channel_offset(self):
  120. """
  121. Image data is interleaved for each image set. That is, if there are four images in a set, the first image
  122. will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth.
  123. :rtype: dict
  124. """
  125. channel_offset = {}
  126. for n, channel in enumerate(self._channels):
  127. channel_offset[channel] = n
  128. return channel_offset
  129. @property
  130. def _absolute_start(self):
  131. """
  132. The date and time when acquisition began.
  133. :rtype: datetime.datetime()
  134. """
  135. for line in self.metadata[six.b('ImageTextInfo')][six.b('SLxImageTextInfo')].values():
  136. line = line.decode("utf8")
  137. absolute_start_12 = None
  138. absolute_start_24 = None
  139. # ND2s seem to randomly switch between 12- and 24-hour representations.
  140. try:
  141. absolute_start_24 = datetime.strptime(line, "%m/%d/%Y %H:%M:%S")
  142. except (TypeError, ValueError):
  143. pass
  144. try:
  145. absolute_start_12 = datetime.strptime(line, "%m/%d/%Y %I:%M:%S %p")
  146. except (TypeError, ValueError):
  147. pass
  148. if not absolute_start_12 and not absolute_start_24:
  149. continue
  150. return absolute_start_12 if absolute_start_12 else absolute_start_24
  151. raise ValueError("This ND2 has no recorded start time. This is probably a bug.")
  152. def _parse_dimension_text(self, pattern):
  153. try:
  154. count = int(re.match(pattern, self._dimensions).group(1))
  155. except AttributeError:
  156. return [0]
  157. except TypeError:
  158. count = int(re.match(pattern, self._dimensions.decode("utf8")).group(1))
  159. return list(range(count))
  160. else:
  161. return list(range(count))
  162. @property
  163. def fields_of_view(self):
  164. """
  165. The metadata contains information about fields of view, but it contains it even if some fields
  166. of view were cropped. We can't find anything that states which fields of view are actually
  167. in the image data, so we have to calculate it. There probably is something somewhere, since
  168. NIS Elements can figure it out, but we haven't found it yet.
  169. :rtype: int
  170. """
  171. if self._fields_of_view is None:
  172. self._fields_of_view = self._parse_dimension_text(r""".*?XY\((\d+)\).*?""")
  173. return self._fields_of_view
  174. @property
  175. def time_indexes(self):
  176. """
  177. The number of cycles.
  178. :rtype: int
  179. """
  180. if self._time_indexes is None:
  181. self._time_indexes = self._parse_dimension_text(r""".*?T'\((\d+)\).*?""")
  182. return self._time_indexes
  183. @property
  184. def z_levels(self):
  185. """
  186. The different levels in the Z-plane. Just a sequence from 0 to n.
  187. :rtype: int
  188. """
  189. if self._z_levels is None:
  190. self._z_levels = self._parse_dimension_text(r""".*?Z\((\d+)\).*?""")
  191. return self._z_levels
  192. @property
  193. def _image_count(self):
  194. """
  195. The total number of images in the ND2. Warning: this may be inaccurate as it includes "gap" images.
  196. :rtype: int
  197. """
  198. return self.metadata[six.b('ImageAttributes')][six.b('SLxImageAttributes')][six.b('uiSequenceCount')]
  199. def _parse_metadata(self):
  200. """
  201. Reads all metadata.
  202. """
  203. for label in self._label_map.keys():
  204. if label.endswith(six.b("LV!")) or six.b("LV|") in label:
  205. data = self._read_chunk(self._label_map[label])
  206. stop = label.index(six.b("LV"))
  207. self.metadata[label[:stop]] = self._read_metadata(data, 1)
  208. def _read_map(self):
  209. """
  210. Every label ends with an exclamation point, however, we can't directly search for those to find all the labels
  211. as some of the bytes contain the value 33, which is the ASCII code for "!". So we iteratively find each label,
  212. grab the subsequent data (always 16 bytes long), advance to the next label and repeat.
  213. """
  214. self._file_handle.seek(-8, 2)
  215. chunk_map_start_location = struct.unpack("Q", self._file_handle.read(8))[0]
  216. self._file_handle.seek(chunk_map_start_location)
  217. raw_text = self._file_handle.read(-1)
  218. label_start = raw_text.index(Nd2Parser.CHUNK_MAP_START) + 32
  219. while True:
  220. data_start = raw_text.index(six.b("!"), label_start) + 1
  221. key = raw_text[label_start: data_start]
  222. location, length = struct.unpack("QQ", raw_text[data_start: data_start + 16])
  223. if key == Nd2Parser.CHUNK_MAP_END:
  224. # We've reached the end of the chunk map
  225. break
  226. self._label_map[key] = location
  227. label_start = data_start + 16
  228. def _read_chunk(self, chunk_location):
  229. """
  230. Gets the data for a given chunk pointer
  231. """
  232. self._file_handle.seek(chunk_location)
  233. # The chunk metadata is always 16 bytes long
  234. chunk_metadata = self._file_handle.read(16)
  235. header, relative_offset, data_length = struct.unpack("IIQ", chunk_metadata)
  236. if header != Nd2Parser.CHUNK_HEADER:
  237. raise ValueError("The ND2 file seems to be corrupted.")
  238. # We start at the location of the chunk metadata, skip over the metadata, and then proceed to the
  239. # start of the actual data field, which is at some arbitrary place after the metadata.
  240. self._file_handle.seek(chunk_location + 16 + relative_offset)
  241. return self._file_handle.read(data_length)
  242. def _parse_unsigned_char(self, data):
  243. return struct.unpack("B", data.read(1))[0]
  244. def _parse_unsigned_int(self, data):
  245. return struct.unpack("I", data.read(4))[0]
  246. def _parse_unsigned_long(self, data):
  247. return struct.unpack("Q", data.read(8))[0]
  248. def _parse_double(self, data):
  249. return struct.unpack("d", data.read(8))[0]
  250. def _parse_string(self, data):
  251. value = data.read(2)
  252. while not value.endswith(six.b("\x00\x00")):
  253. # the string ends at the first instance of \x00\x00
  254. value += data.read(2)
  255. return value.decode("utf16")[:-1].encode("utf8")
  256. def _parse_char_array(self, data):
  257. array_length = struct.unpack("Q", data.read(8))[0]
  258. return array.array("B", data.read(array_length))
  259. def _parse_metadata_item(self, data):
  260. """
  261. Reads hierarchical data, analogous to a Python dict.
  262. """
  263. new_count, length = struct.unpack("<IQ", data.read(12))
  264. length -= data.tell() - self._cursor_position
  265. next_data_length = data.read(length)
  266. value = self._read_metadata(next_data_length, new_count)
  267. # Skip some offsets
  268. data.read(new_count * 8)
  269. return value
  270. def _get_value(self, data, data_type):
  271. """
  272. ND2s use various codes to indicate different data types, which we translate here.
  273. """
  274. parser = {1: self._parse_unsigned_char,
  275. 2: self._parse_unsigned_int,
  276. 3: self._parse_unsigned_int,
  277. 5: self._parse_unsigned_long,
  278. 6: self._parse_double,
  279. 8: self._parse_string,
  280. 9: self._parse_char_array,
  281. 11: self._parse_metadata_item}
  282. return parser[data_type](data)
  283. def _read_metadata(self, data, count):
  284. """
  285. Iterates over each element some section of the metadata and parses it.
  286. """
  287. data = six.BytesIO(data)
  288. metadata = {}
  289. for _ in range(count):
  290. self._cursor_position = data.tell()
  291. header = data.read(2)
  292. if not header:
  293. # We've reached the end of some hierarchy of data
  294. break
  295. if six.PY3:
  296. header = header.decode("utf8")
  297. data_type, name_length = map(ord, header)
  298. name = data.read(name_length * 2).decode("utf16")[:-1].encode("utf8")
  299. value = self._get_value(data, data_type)
  300. if name not in metadata.keys():
  301. metadata[name] = value
  302. else:
  303. if not isinstance(metadata[name], list):
  304. # We have encountered this key exactly once before. Since we're seeing it again, we know we
  305. # need to convert it to a list before proceeding.
  306. metadata[name] = [metadata[name]]
  307. # We've encountered this key before so we're guaranteed to be dealing with a list. Thus we append
  308. # the value to the already-existing list.
  309. metadata[name].append(value)
  310. return metadata