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.

314 lines
12 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
  1. import array
  2. import numpy as np
  3. import struct
  4. from StringIO import StringIO
  5. from collections import namedtuple
  6. import logging
  7. from nd2reader.model import Channel, ImageSet, Image
  8. log = logging.getLogger("nd2reader")
  9. log.setLevel(logging.DEBUG)
  10. chunk = namedtuple('Chunk', ['location', 'length'])
  11. field_of_view = namedtuple('FOV', ['number', 'x', 'y', 'z', 'pfs_offset'])
  12. class BaseNd2(object):
  13. def __init__(self, filename):
  14. self._reader = Nd2Reader(filename)
  15. self._channel_offset = None
  16. @property
  17. def height(self):
  18. return self._metadata['ImageAttributes']['SLxImageAttributes']['uiHeight']
  19. @property
  20. def width(self):
  21. return self._metadata['ImageAttributes']['SLxImageAttributes']['uiWidth']
  22. @property
  23. def channels(self):
  24. metadata = self._metadata['ImageMetadataSeq']['SLxPictureMetadata']['sPicturePlanes']
  25. try:
  26. validity = self._metadata['ImageMetadata']['SLxExperiment']['ppNextLevelEx'][''][0]['ppNextLevelEx'][''][0]['pItemValid']
  27. except KeyError:
  28. # If none of the channels have been deleted, there is no validity list, so we just make one
  29. validity = [True for i in metadata]
  30. # Channel information is contained in dictionaries with the keys a0, a1...an where the number
  31. # indicates the order in which the channel is stored. So by sorting the dicts alphabetically
  32. # we get the correct order.
  33. for (label, chan), valid in zip(sorted(metadata['sPlaneNew'].items()), validity):
  34. if not valid:
  35. continue
  36. name = chan['sDescription']
  37. exposure_time = metadata['sSampleSetting'][label]['dExposureTime']
  38. camera = metadata['sSampleSetting'][label]['pCameraSetting']['CameraUserName']
  39. yield Channel(name, camera, exposure_time)
  40. @property
  41. def _image_count(self):
  42. return self._metadata['ImageAttributes']['SLxImageAttributes']['uiSequenceCount']
  43. @property
  44. def _sequence_count(self):
  45. return self._metadata['ImageEvents']['RLxExperimentRecord']['uiCount']
  46. @property
  47. def timepoint_count(self):
  48. return self._image_count / self.field_of_view_count / self.z_level_count
  49. @property
  50. def z_level_count(self):
  51. return self._image_count / self._sequence_count
  52. @property
  53. def field_of_view_count(self):
  54. """
  55. The metadata contains information about fields of view, but it contains it even if some fields
  56. of view were cropped. We can't find anything that states which fields of view are actually
  57. in the image data, so we have to calculate it. There probably is something somewhere, since
  58. NIS Elements can figure it out, but we haven't found it yet.
  59. """
  60. return sum(self._metadata['ImageMetadata']['SLxExperiment']['ppNextLevelEx'][''][0]['pItemValid'])
  61. @property
  62. def channel_count(self):
  63. return self._reader.channel_count
  64. @property
  65. def channel_offset(self):
  66. if self._channel_offset is None:
  67. self._channel_offset = {}
  68. for n, channel in enumerate(self.channels):
  69. self._channel_offset[channel.name] = n
  70. return self._channel_offset
  71. @property
  72. def _metadata(self):
  73. return self._reader.metadata
  74. def _calculate_image_set_number(self, timepoint, fov, z_level):
  75. return timepoint * self.field_of_view_count * self.z_level_count + (fov * self.z_level_count + z_level)
  76. class Nd2Reader(object):
  77. """
  78. Reads .nd2 files, provides an interface to the metadata, and generates numpy arrays from the image data.
  79. """
  80. def __init__(self, filename):
  81. self._filename = filename
  82. self._file_handler = None
  83. self._chunk_map_start_location = None
  84. self._label_map = {}
  85. self._metadata = {}
  86. self._read_map()
  87. self._parse_dict_data()
  88. @property
  89. def fh(self):
  90. if self._file_handler is None:
  91. self._file_handler = open(self._filename, "rb")
  92. return self._file_handler
  93. @property
  94. def channel_count(self):
  95. return self._metadata['ImageAttributes']["SLxImageAttributes"]["uiComp"]
  96. def get_raw_image_data(self, image_set_number, channel_offset):
  97. chunk = self._label_map["ImageDataSeq|%d!" % image_set_number]
  98. data = self._read_chunk(chunk.location)
  99. timestamp = struct.unpack("d", data[:8])[0]
  100. # The images for the various channels are interleaved within each other. Yes, this is an incredibly unintuitive and nonsensical way
  101. # to store data.
  102. image_data = array.array("H", data)
  103. image_data_start = 4 + channel_offset
  104. return timestamp, image_data[image_data_start::self.channel_count]
  105. def _parse_dict_data(self):
  106. # TODO: Don't like this name
  107. for label in self._top_level_dict_labels:
  108. chunk_location = self._label_map[label].location
  109. data = self._read_chunk(chunk_location)
  110. stop = label.index("LV")
  111. self._metadata[label[:stop]] = self.read_lv_encoding(data, 1)
  112. @property
  113. def metadata(self):
  114. return self._metadata
  115. @property
  116. def _top_level_dict_labels(self):
  117. # TODO: I don't like this name either
  118. for label in self._label_map.keys():
  119. if label.endswith("LV!") or "LV|" in label:
  120. yield label
  121. def _read_map(self):
  122. """
  123. Every label ends with an exclamation point, however, we can't directly search for those to find all the labels
  124. as some of the bytes contain the value 33, which is the ASCII code for "!". So we iteratively find each label,
  125. grab the subsequent data (always 16 bytes long), advance to the next label and repeat.
  126. """
  127. raw_text = self._get_raw_chunk_map_text()
  128. label_start = self._find_first_label_offset(raw_text)
  129. while True:
  130. data_start = self._get_data_start(label_start, raw_text)
  131. label, value = self._extract_map_key(label_start, data_start, raw_text)
  132. if label == "ND2 CHUNK MAP SIGNATURE 0000001!":
  133. # We've reached the end of the chunk map
  134. break
  135. self._label_map[label] = value
  136. label_start = data_start + 16
  137. @staticmethod
  138. def _find_first_label_offset(raw_text):
  139. """
  140. The chunk map starts with some number of (seemingly) useless bytes, followed
  141. by "ND2 FILEMAP SIGNATURE NAME 0001!". We return the location of the first character after this sequence,
  142. which is the actual beginning of the chunk map.
  143. """
  144. return raw_text.index("ND2 FILEMAP SIGNATURE NAME 0001!") + 32
  145. @staticmethod
  146. def _get_data_start(label_start, raw_text):
  147. """
  148. The data for a given label begins immediately after the first exclamation point
  149. """
  150. return raw_text.index("!", label_start) + 1
  151. @staticmethod
  152. def _extract_map_key(label_start, data_start, raw_text):
  153. """
  154. Chunk map entries are a string label of arbitrary length followed by 16 bytes of data, which represent
  155. the byte offset from the beginning of the file where that data can be found.
  156. """
  157. key = raw_text[label_start: data_start]
  158. location, length = struct.unpack("QQ", raw_text[data_start: data_start + 16])
  159. return key, chunk(location=location, length=length)
  160. @property
  161. def chunk_map_start_location(self):
  162. """
  163. The position in bytes from the beginning of the file where the chunk map begins.
  164. The chunk map is a series of string labels followed by the position (in bytes) of the respective data.
  165. """
  166. if self._chunk_map_start_location is None:
  167. # Put the cursor 8 bytes before the end of the file
  168. self.fh.seek(-8, 2)
  169. # Read the last 8 bytes of the file
  170. self._chunk_map_start_location = struct.unpack("Q", self.fh.read(8))[0]
  171. return self._chunk_map_start_location
  172. def _read_chunk(self, chunk_location):
  173. """
  174. Gets the data for a given chunk pointer
  175. """
  176. self.fh.seek(chunk_location)
  177. chunk_data = self._read_chunk_metadata()
  178. header, relative_offset, data_length = self._parse_chunk_metadata(chunk_data)
  179. return self._read_chunk_data(chunk_location, relative_offset, data_length)
  180. def _read_chunk_metadata(self):
  181. """
  182. Gets the chunks metadata, which is always 16 bytes
  183. """
  184. return self.fh.read(16)
  185. def _read_chunk_data(self, chunk_location, relative_offset, data_length):
  186. """
  187. Reads the actual data for a given chunk
  188. """
  189. # We start at the location of the chunk metadata, skip over the metadata, and then proceed to the
  190. # start of the actual data field, which is at some arbitrary place after the metadata.
  191. self.fh.seek(chunk_location + 16 + relative_offset)
  192. return self.fh.read(data_length)
  193. @staticmethod
  194. def _parse_chunk_metadata(chunk_data):
  195. """
  196. Finds out everything about a given chunk. Every chunk begins with the same value, so if that's ever
  197. different we can assume the file has suffered some kind of damage.
  198. """
  199. header, relative_offset, data_length = struct.unpack("IIQ", chunk_data)
  200. if header != 0xabeceda:
  201. raise ValueError("The ND2 file seems to be corrupted.")
  202. return header, relative_offset, data_length
  203. def _get_raw_chunk_map_text(self):
  204. """
  205. Reads the entire chunk map and returns it as a string.
  206. """
  207. self.fh.seek(self.chunk_map_start_location)
  208. return self.fh.read(-1)
  209. @staticmethod
  210. def as_numpy_array(arr):
  211. return np.frombuffer(arr)
  212. def _z_level_count(self):
  213. """read the microscope coordinates and temperatures
  214. Missing: get chunknames and types from xml metadata"""
  215. res = {}
  216. name = "CustomData|Z!"
  217. st = self._read_chunk(self._label_map[name].location)
  218. res = array.array("d", st)
  219. return len(res)
  220. def read_lv_encoding(self, data, count):
  221. data = StringIO(data)
  222. res = {}
  223. total_count = 0
  224. for c in range(count):
  225. lastpos = data.tell()
  226. total_count += 1
  227. hdr = data.read(2)
  228. if not hdr:
  229. break
  230. typ = ord(hdr[0])
  231. bname = data.read(2*ord(hdr[1]))
  232. name = bname.decode("utf16")[:-1].encode("utf8")
  233. if typ == 1:
  234. value, = struct.unpack("B", data.read(1))
  235. elif typ in [2, 3]:
  236. value, = struct.unpack("I", data.read(4))
  237. elif typ == 5:
  238. value, = struct.unpack("Q", data.read(8))
  239. elif typ == 6:
  240. value, = struct.unpack("d", data.read(8))
  241. elif typ == 8:
  242. value = data.read(2)
  243. while value[-2:] != "\x00\x00":
  244. value += data.read(2)
  245. value = value.decode("utf16")[:-1].encode("utf8")
  246. elif typ == 9:
  247. cnt, = struct.unpack("Q", data.read(8))
  248. value = array.array("B", data.read(cnt))
  249. elif typ == 11:
  250. newcount, length = struct.unpack("<IQ", data.read(12))
  251. length -= data.tell()-lastpos
  252. nextdata = data.read(length)
  253. value = self.read_lv_encoding(nextdata, newcount)
  254. # Skip some offsets
  255. data.read(newcount * 8)
  256. else:
  257. assert 0, "%s hdr %x:%x unknown" % (name, ord(hdr[0]), ord(hdr[1]))
  258. if not name in res:
  259. res[name] = value
  260. else:
  261. if not isinstance(res[name], list):
  262. res[name] = [res[name]]
  263. res[name].append(value)
  264. x = data.read()
  265. assert not x, "skip %d %s" % (len(x), repr(x[:30]))
  266. return res