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.

379 lines
15 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 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::self._channel_count]
  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. if six.PY3:
  86. return self._dimension_text.decode("utf8")
  87. return self._dimension_text
  88. @property
  89. def channels(self):
  90. """
  91. These are labels created by the NIS Elements user. Typically they may a short description of the filter cube
  92. used (e.g. "bright field", "GFP", etc.)
  93. :rtype: str
  94. """
  95. if not self._channels:
  96. self._channels = []
  97. metadata = self.metadata[six.b('ImageMetadataSeq')][six.b('SLxPictureMetadata')][six.b('sPicturePlanes')]
  98. try:
  99. validity = self.metadata[six.b('ImageMetadata')][six.b('SLxExperiment')][six.b('ppNextLevelEx')][six.b('')][0][six.b('ppNextLevelEx')][six.b('')][0][six.b('pItemValid')]
  100. except KeyError:
  101. # If none of the channels have been deleted, there is no validity list, so we just make one
  102. validity = [True for _ in metadata]
  103. # Channel information is contained in dictionaries with the keys a0, a1...an where the number
  104. # indicates the order in which the channel is stored. So by sorting the dicts alphabetically
  105. # we get the correct order.
  106. for (label, chan), valid in zip(sorted(metadata[six.b('sPlaneNew')].items()), validity):
  107. if not valid:
  108. continue
  109. self._channels.append(chan[six.b('sDescription')].decode("utf8"))
  110. return self._channels
  111. def _calculate_image_group_number(self, time_index, fov, z_level):
  112. """
  113. Images are grouped together if they share the same time index, field of view, and z-level.
  114. :type time_index: int
  115. :type fov: int
  116. :type z_level: int
  117. :rtype: int
  118. """
  119. return time_index * len(self.fields_of_view) * len(self.z_levels) + (fov * len(self.z_levels) + z_level)
  120. @property
  121. def _channel_offset(self):
  122. """
  123. Image data is interleaved for each image set. That is, if there are four images in a set, the first image
  124. will consist of pixels 1, 5, 9, etc, the second will be pixels 2, 6, 10, and so forth.
  125. :rtype: dict
  126. """
  127. channel_offset = {}
  128. for n, channel in enumerate(self._channels):
  129. channel_offset[channel] = n
  130. return channel_offset
  131. @property
  132. def _absolute_start(self):
  133. """
  134. The date and time when acquisition began.
  135. :rtype: datetime.datetime()
  136. """
  137. for line in self.metadata[six.b('ImageTextInfo')][six.b('SLxImageTextInfo')].values():
  138. line = line.decode("utf8")
  139. absolute_start_12 = None
  140. absolute_start_24 = None
  141. # ND2s seem to randomly switch between 12- and 24-hour representations.
  142. try:
  143. absolute_start_24 = datetime.strptime(line, "%m/%d/%Y %H:%M:%S")
  144. except (TypeError, ValueError):
  145. pass
  146. try:
  147. absolute_start_12 = datetime.strptime(line, "%m/%d/%Y %I:%M:%S %p")
  148. except (TypeError, ValueError):
  149. pass
  150. if not absolute_start_12 and not absolute_start_24:
  151. continue
  152. return absolute_start_12 if absolute_start_12 else absolute_start_24
  153. raise ValueError("This ND2 has no recorded start time. This is probably a bug.")
  154. def _parse_dimension_text(self, pattern):
  155. try:
  156. count = int(re.match(pattern, self._dimensions).group(1))
  157. except AttributeError:
  158. return [0]
  159. else:
  160. return range(count)
  161. @property
  162. def channel_count(self):
  163. """
  164. The number of different channels used, including bright field.
  165. :rtype: int
  166. """
  167. if self._channel_count is None:
  168. self._channel_count = self._parse_dimension_text(r""".*?λ\((\d+)\).*?""")
  169. return self._channel_count
  170. @property
  171. def fields_of_view(self):
  172. """
  173. The metadata contains information about fields of view, but it contains it even if some fields
  174. of view were cropped. We can't find anything that states which fields of view are actually
  175. in the image data, so we have to calculate it. There probably is something somewhere, since
  176. NIS Elements can figure it out, but we haven't found it yet.
  177. :rtype: int
  178. """
  179. if self._fields_of_view is None:
  180. self._fields_of_view = self._parse_dimension_text(r""".*?XY\((\d+)\).*?""")
  181. return self._fields_of_view
  182. @property
  183. def time_indexes(self):
  184. """
  185. The number of cycles.
  186. :rtype: int
  187. """
  188. if self._time_indexes is None:
  189. self._time_indexes = self._parse_dimension_text(r""".*?T'\((\d+)\).*?""")
  190. return self._time_indexes
  191. @property
  192. def z_levels(self):
  193. """
  194. The different levels in the Z-plane. Just a sequence from 0 to n.
  195. :rtype: int
  196. """
  197. if self._z_levels is None:
  198. self._z_levels = self._parse_dimension_text(r""".*?Z\((\d+)\).*?""")
  199. return self._z_levels
  200. @property
  201. def _image_count(self):
  202. """
  203. The total number of images in the ND2. Warning: this may be inaccurate as it includes "gap" images.
  204. :rtype: int
  205. """
  206. return self.metadata[six.b('ImageAttributes')][six.b('SLxImageAttributes')][six.b('uiSequenceCount')]
  207. def _parse_metadata(self):
  208. """
  209. Reads all metadata.
  210. """
  211. for label in self._label_map.keys():
  212. if label.endswith(six.b("LV!")) or six.b("LV|") in label:
  213. data = self._read_chunk(self._label_map[label])
  214. stop = label.index(six.b("LV"))
  215. self.metadata[label[:stop]] = self._read_metadata(data, 1)
  216. def _read_map(self):
  217. """
  218. Every label ends with an exclamation point, however, we can't directly search for those to find all the labels
  219. as some of the bytes contain the value 33, which is the ASCII code for "!". So we iteratively find each label,
  220. grab the subsequent data (always 16 bytes long), advance to the next label and repeat.
  221. """
  222. self._file_handle.seek(-8, 2)
  223. chunk_map_start_location = struct.unpack("Q", self._file_handle.read(8))[0]
  224. self._file_handle.seek(chunk_map_start_location)
  225. raw_text = self._file_handle.read(-1)
  226. label_start = raw_text.index(Nd2Parser.CHUNK_MAP_START) + 32
  227. while True:
  228. data_start = raw_text.index(six.b("!"), label_start) + 1
  229. key = raw_text[label_start: data_start]
  230. location, length = struct.unpack("QQ", raw_text[data_start: data_start + 16])
  231. if key == Nd2Parser.CHUNK_MAP_END:
  232. # We've reached the end of the chunk map
  233. break
  234. self._label_map[key] = location
  235. label_start = data_start + 16
  236. def _read_chunk(self, chunk_location):
  237. """
  238. Gets the data for a given chunk pointer
  239. """
  240. self._file_handle.seek(chunk_location)
  241. # The chunk metadata is always 16 bytes long
  242. chunk_metadata = self._file_handle.read(16)
  243. header, relative_offset, data_length = struct.unpack("IIQ", chunk_metadata)
  244. if header != Nd2Parser.CHUNK_HEADER:
  245. raise ValueError("The ND2 file seems to be corrupted.")
  246. # We start at the location of the chunk metadata, skip over the metadata, and then proceed to the
  247. # start of the actual data field, which is at some arbitrary place after the metadata.
  248. self._file_handle.seek(chunk_location + 16 + relative_offset)
  249. return self._file_handle.read(data_length)
  250. def _parse_unsigned_char(self, data):
  251. return struct.unpack("B", data.read(1))[0]
  252. def _parse_unsigned_int(self, data):
  253. return struct.unpack("I", data.read(4))[0]
  254. def _parse_unsigned_long(self, data):
  255. return struct.unpack("Q", data.read(8))[0]
  256. def _parse_double(self, data):
  257. return struct.unpack("d", data.read(8))[0]
  258. def _parse_string(self, data):
  259. value = data.read(2)
  260. while not value.endswith(six.b("\x00\x00")):
  261. # the string ends at the first instance of \x00\x00
  262. value += data.read(2)
  263. return value.decode("utf16")[:-1].encode("utf8")
  264. def _parse_char_array(self, data):
  265. array_length = struct.unpack("Q", data.read(8))[0]
  266. return array.array("B", data.read(array_length))
  267. def _parse_metadata_item(self, data):
  268. """
  269. Reads hierarchical data, analogous to a Python dict.
  270. """
  271. new_count, length = struct.unpack("<IQ", data.read(12))
  272. length -= data.tell() - self._cursor_position
  273. next_data_length = data.read(length)
  274. value = self._read_metadata(next_data_length, new_count)
  275. # Skip some offsets
  276. data.read(new_count * 8)
  277. return value
  278. def _get_value(self, data, data_type):
  279. """
  280. ND2s use various codes to indicate different data types, which we translate here.
  281. """
  282. parser = {1: self._parse_unsigned_char,
  283. 2: self._parse_unsigned_int,
  284. 3: self._parse_unsigned_int,
  285. 5: self._parse_unsigned_long,
  286. 6: self._parse_double,
  287. 8: self._parse_string,
  288. 9: self._parse_char_array,
  289. 11: self._parse_metadata_item}
  290. return parser[data_type](data)
  291. def _read_metadata(self, data, count):
  292. """
  293. Iterates over each element some section of the metadata and parses it.
  294. """
  295. data = six.BytesIO(data)
  296. metadata = {}
  297. for _ in range(count):
  298. self._cursor_position = data.tell()
  299. header = data.read(2)
  300. if not header:
  301. # We've reached the end of some hierarchy of data
  302. break
  303. if six.PY3:
  304. header = header.decode("utf8")
  305. data_type, name_length = map(ord, header)
  306. name = data.read(name_length * 2).decode("utf16")[:-1].encode("utf8")
  307. value = self._get_value(data, data_type)
  308. if name not in metadata.keys():
  309. metadata[name] = value
  310. else:
  311. if not isinstance(metadata[name], list):
  312. # We have encountered this key exactly once before. Since we're seeing it again, we know we
  313. # need to convert it to a list before proceeding.
  314. metadata[name] = [metadata[name]]
  315. # We've encountered this key before so we're guaranteed to be dealing with a list. Thus we append
  316. # the value to the already-existing list.
  317. metadata[name].append(value)
  318. return metadata