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.

248 lines
6.3 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. import struct
  2. import array
  3. from datetime import datetime
  4. import six
  5. import re
  6. from nd2reader.exceptions import InvalidVersionError
  7. def get_version(fh):
  8. """Determines what version the ND2 is.
  9. Args:
  10. fh: File handle of the .nd2 file
  11. Returns:
  12. tuple: Major and minor version
  13. """
  14. # the first 16 bytes seem to have no meaning, so we skip them
  15. fh.seek(16)
  16. # the next 38 bytes contain the string that we want to parse. Unlike most of the ND2, this is in UTF-8
  17. data = fh.read(38).decode("utf8")
  18. return parse_version(data)
  19. def parse_version(data):
  20. """Parses a string with the version data in it.
  21. Args:
  22. data (unicode): the 19th through 54th byte of the ND2, representing the version
  23. Returns:
  24. tuple: Major and minor version
  25. """
  26. match = re.search(r"""^ND2 FILE SIGNATURE CHUNK NAME01!Ver(?P<major>\d)\.(?P<minor>\d)$""", data)
  27. if match:
  28. # We haven't seen a lot of ND2s but the ones we have seen conform to this
  29. return int(match.group('major')), int(match.group('minor'))
  30. raise InvalidVersionError("The version of the ND2 you specified is not supported.")
  31. def read_chunk(fh, chunk_location):
  32. """Reads a piece of data given the location of its pointer.
  33. Args:
  34. fh: an open file handle to the ND2
  35. chunk_location (int): location to read
  36. Returns:
  37. bytes: the data at the chunk location
  38. """
  39. if chunk_location is None:
  40. return None
  41. fh.seek(chunk_location)
  42. # The chunk metadata is always 16 bytes long
  43. chunk_metadata = fh.read(16)
  44. header, relative_offset, data_length = struct.unpack("IIQ", chunk_metadata)
  45. if header != 0xabeceda:
  46. raise ValueError("The ND2 file seems to be corrupted.")
  47. # We start at the location of the chunk metadata, skip over the metadata, and then proceed to the
  48. # start of the actual data field, which is at some arbitrary place after the metadata.
  49. fh.seek(chunk_location + 16 + relative_offset)
  50. return fh.read(data_length)
  51. def read_array(fh, kind, chunk_location):
  52. """
  53. Args:
  54. fh:
  55. kind:
  56. chunk_location:
  57. Returns:
  58. """
  59. kinds = {'double': 'd',
  60. 'int': 'i',
  61. 'float': 'f'}
  62. if kind not in kinds:
  63. raise ValueError('You attempted to read an array of an unknown type.')
  64. raw_data = read_chunk(fh, chunk_location)
  65. if raw_data is None:
  66. return None
  67. return array.array(kinds[kind], raw_data)
  68. def _parse_unsigned_char(data):
  69. return struct.unpack("B", data.read(1))[0]
  70. def _parse_unsigned_int(data):
  71. return struct.unpack("I", data.read(4))[0]
  72. def _parse_unsigned_long(data):
  73. return struct.unpack("Q", data.read(8))[0]
  74. def _parse_double(data):
  75. return struct.unpack("d", data.read(8))[0]
  76. def _parse_string(data):
  77. value = data.read(2)
  78. while not value.endswith(six.b("\x00\x00")):
  79. # the string ends at the first instance of \x00\x00
  80. value += data.read(2)
  81. return value.decode("utf16")[:-1].encode("utf8")
  82. def _parse_char_array(data):
  83. array_length = struct.unpack("Q", data.read(8))[0]
  84. return array.array("B", data.read(array_length))
  85. def parse_date(text_info):
  86. """
  87. The date and time when acquisition began.
  88. Args:
  89. text_info:
  90. Returns:
  91. """
  92. for line in text_info.values():
  93. line = line.decode("utf8")
  94. # ND2s seem to randomly switch between 12- and 24-hour representations.
  95. try:
  96. absolute_start = datetime.strptime(line, "%m/%d/%Y %H:%M:%S")
  97. except (TypeError, ValueError):
  98. try:
  99. absolute_start = datetime.strptime(line, "%m/%d/%Y %I:%M:%S %p")
  100. except (TypeError, ValueError):
  101. absolute_start = None
  102. return absolute_start
  103. def _parse_metadata_item(data, cursor_position):
  104. """Reads hierarchical data, analogous to a Python dict.
  105. Args:
  106. data:
  107. cursor_position:
  108. Returns:
  109. """
  110. new_count, length = struct.unpack("<IQ", data.read(12))
  111. length -= data.tell() - cursor_position
  112. next_data_length = data.read(length)
  113. value = read_metadata(next_data_length, new_count)
  114. # Skip some offsets
  115. data.read(new_count * 8)
  116. return value
  117. def _get_value(data, data_type, cursor_position):
  118. """ND2s use various codes to indicate different data types, which we translate here.
  119. Args:
  120. data:
  121. data_type:
  122. cursor_position:
  123. Returns:
  124. """
  125. parser = {1: _parse_unsigned_char,
  126. 2: _parse_unsigned_int,
  127. 3: _parse_unsigned_int,
  128. 5: _parse_unsigned_long,
  129. 6: _parse_double,
  130. 8: _parse_string,
  131. 9: _parse_char_array,
  132. 11: _parse_metadata_item}
  133. return parser[data_type](data) if data_type < 11 else parser[data_type](data, cursor_position)
  134. def read_metadata(data, count):
  135. """
  136. Iterates over each element some section of the metadata and parses it.
  137. Args:
  138. data:
  139. count:
  140. Returns:
  141. """
  142. if data is None:
  143. return None
  144. data = six.BytesIO(data)
  145. metadata = {}
  146. for _ in range(count):
  147. cursor_position = data.tell()
  148. header = data.read(2)
  149. if not header:
  150. # We've reached the end of some hierarchy of data
  151. break
  152. if six.PY3:
  153. header = header.decode("utf8")
  154. data_type, name_length = map(ord, header)
  155. name = data.read(name_length * 2).decode("utf16")[:-1].encode("utf8")
  156. value = _get_value(data, data_type, cursor_position)
  157. metadata = _add_to_metadata(metadata, name, value)
  158. return metadata
  159. def _add_to_metadata(metadata, name, value):
  160. """
  161. Add the name value pair to the metadata dict
  162. Args:
  163. metadata:
  164. name:
  165. value:
  166. Returns:
  167. """
  168. if name not in metadata.keys():
  169. metadata[name] = value
  170. else:
  171. if not isinstance(metadata[name], list):
  172. # We have encountered this key exactly once before. Since we're seeing it again, we know we
  173. # need to convert it to a list before proceeding.
  174. metadata[name] = [metadata[name]]
  175. # We've encountered this key before so we're guaranteed to be dealing with a list. Thus we append
  176. # the value to the already-existing list.
  177. metadata[name].append(value)
  178. return metadata